mirror of
https://github.com/cocos/cocos4.git
synced 2026-11-20 23:52:40 +08:00
Merge branch 'v3.7.3' into develop_merge_v3.7.3
This commit is contained in:
+7
-1
@@ -369,6 +369,12 @@
|
||||
"ccGlobal": true,
|
||||
"internal": false
|
||||
},
|
||||
"WECHAT_MINI_PROGRAM": {
|
||||
"comment": "Running in the Wechat's mini program.",
|
||||
"type": "boolean",
|
||||
"value": false,
|
||||
"internal": false
|
||||
},
|
||||
"BAIDU": {
|
||||
"comment": "Running in the baidu's mini game.",
|
||||
"type": "boolean",
|
||||
@@ -511,7 +517,7 @@
|
||||
"MINIGAME": {
|
||||
"comment": "Running in mini game.",
|
||||
"type": "boolean",
|
||||
"value": "$WECHAT || $BAIDU || $XIAOMI || $ALIPAY || $TAOBAO || $TAOBAO_MINIGAME || $BYTEDANCE",
|
||||
"value": "$WECHAT || $WECHAT_MINI_PROGRAM || $BAIDU || $XIAOMI || $ALIPAY || $TAOBAO || $TAOBAO_MINIGAME || $BYTEDANCE",
|
||||
"ccGlobal": true,
|
||||
"internal": false
|
||||
},
|
||||
|
||||
@@ -24,7 +24,7 @@
|
||||
|
||||
// @ts-check
|
||||
import { ccclass, override } from 'cc.decorator';
|
||||
import { EDITOR, ALIPAY, XIAOMI, JSB, TEST, BAIDU, TAOBAO } from 'internal:constants';
|
||||
import { EDITOR, ALIPAY, XIAOMI, JSB, TEST, BAIDU, TAOBAO, TAOBAO_MINIGAME, WECHAT_MINI_PROGRAM } from 'internal:constants';
|
||||
import { Device, Format, FormatFeatureBit, deviceManager } from '../../gfx';
|
||||
import { Asset } from './asset';
|
||||
import { PixelFormat } from './asset-enum';
|
||||
@@ -163,7 +163,7 @@ function fetchImageSource (imageSource: ImageSource) {
|
||||
|
||||
// 返回该图像源是否是平台提供的图像对象。
|
||||
function isNativeImage (imageSource: ImageSource): imageSource is (HTMLImageElement | HTMLCanvasElement | ImageBitmap) {
|
||||
if (ALIPAY || TAOBAO || XIAOMI || BAIDU) {
|
||||
if (ALIPAY || TAOBAO || TAOBAO_MINIGAME || XIAOMI || BAIDU || WECHAT_MINI_PROGRAM) {
|
||||
// We're unable to grab the constructors of Alipay native image or canvas object.
|
||||
return !('_data' in imageSource);
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { EDITOR, TEST, VIVO, WECHAT } from 'internal:constants';
|
||||
import { EDITOR, TEST, VIVO, WECHAT, WECHAT_MINI_PROGRAM } from 'internal:constants';
|
||||
import { ccclass, serializable } from 'cc.decorator';
|
||||
import { TextureType, TextureInfo, TextureViewInfo, BufferTextureCopy } from '../../gfx';
|
||||
import { ImageAsset } from './image-asset';
|
||||
@@ -190,7 +190,7 @@ export class TextureCube extends SimpleTexture {
|
||||
}
|
||||
//In ios wechat mini-game platform drawImage and getImageData can not get correct data,so upload to gfxTexture than use readPixels to get data
|
||||
//The performance of upload to gfxTexture and readPixels is not good, so only use this way in the ios wechat mini-game platform
|
||||
if ((WECHAT && sys.os === OS.IOS) || VIVO) {
|
||||
if (((WECHAT || WECHAT_MINI_PROGRAM) && sys.os === OS.IOS) || VIVO) {
|
||||
this._uploadAtlas();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
|
||||
import { systemInfo } from 'pal/system-info';
|
||||
import { screenAdapter } from 'pal/screen-adapter';
|
||||
import { WECHAT } from 'internal:constants';
|
||||
import { WECHAT, WECHAT_MINI_PROGRAM } from 'internal:constants';
|
||||
import { legacyCC } from '../global-exports';
|
||||
import { Rect } from '../math/rect';
|
||||
import { Vec2 } from '../math/vec2';
|
||||
@@ -322,7 +322,7 @@ export const sys = {
|
||||
};
|
||||
}
|
||||
|
||||
if (WECHAT) {
|
||||
if (WECHAT || WECHAT_MINI_PROGRAM) {
|
||||
this.__isWebIOS14OrIPadOS14Env = (sys.os === OS.IOS || sys.os === OS.OSX) && GameGlobal?.isIOSHighPerformanceMode
|
||||
&& /(OS 1((4\.[0-9])|(5\.[0-3])))|(Version\/1((4\.[0-9])|(5\.[0-3])))/.test(window.navigator.userAgent);
|
||||
} else {
|
||||
|
||||
+14
-6
@@ -418,8 +418,8 @@ export class Game extends EventTarget {
|
||||
* @en The delta time since last frame, unit: s.
|
||||
* @zh 获取上一帧的增量时间,以秒为单位。
|
||||
*/
|
||||
public get deltaTime () {
|
||||
return this._deltaTime;
|
||||
public get deltaTime (): number {
|
||||
return this._useFixedDeltaTime ? this.frameTime / 1000 : this._deltaTime;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -460,6 +460,7 @@ export class Game extends EventTarget {
|
||||
private _initTime = 0;
|
||||
private _startTime = 0;
|
||||
private _deltaTime = 0.0;
|
||||
private _useFixedDeltaTime = false;
|
||||
private _shouldLoadLaunchScene = true;
|
||||
|
||||
/**
|
||||
@@ -537,7 +538,7 @@ export class Game extends EventTarget {
|
||||
* @zh 以固定帧间隔执行一帧游戏循环,帧间隔与设定的帧率匹配。
|
||||
*/
|
||||
public step () {
|
||||
director.tick(this.frameTime / 1000);
|
||||
director.tick(this._calculateDT(true));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -985,7 +986,14 @@ export class Game extends EventTarget {
|
||||
|
||||
// @Methods
|
||||
|
||||
private _calculateDT () {
|
||||
private _calculateDT (useFixedDeltaTime: boolean) {
|
||||
this._useFixedDeltaTime = useFixedDeltaTime;
|
||||
|
||||
if (useFixedDeltaTime) {
|
||||
this._startTime = performance.now();
|
||||
return this.frameTime / 1000;
|
||||
}
|
||||
|
||||
const now = performance.now();
|
||||
this._deltaTime = now > this._startTime ? (now - this._startTime) / 1000 : 0;
|
||||
if (this._deltaTime > Game.DEBUG_DT_THRESHOLD) {
|
||||
@@ -998,7 +1006,7 @@ export class Game extends EventTarget {
|
||||
private _updateCallback () {
|
||||
if (!this._inited) return;
|
||||
if (!SplashScreen.instance.isFinished) {
|
||||
SplashScreen.instance.update(this._calculateDT());
|
||||
SplashScreen.instance.update(this._calculateDT(false));
|
||||
} else if (this._shouldLoadLaunchScene) {
|
||||
this._shouldLoadLaunchScene = false;
|
||||
const launchScene = settings.querySettings(Settings.Category.LAUNCH, 'launchScene');
|
||||
@@ -1016,7 +1024,7 @@ export class Game extends EventTarget {
|
||||
this.onStart?.();
|
||||
}
|
||||
} else {
|
||||
director.tick(this._calculateDT());
|
||||
director.tick(this._calculateDT(false));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { EDITOR, TAOBAO, TAOBAO_MINIGAME } from 'internal:constants';
|
||||
import { EDITOR, TAOBAO } from 'internal:constants';
|
||||
import { Material } from '../asset/assets/material';
|
||||
import { clamp01, Mat4, Vec2, Settings, settings, sys, cclegacy, easing, preTransforms } from '../core';
|
||||
import {
|
||||
@@ -125,7 +125,7 @@ export class SplashScreen {
|
||||
this._curTime = 0;
|
||||
|
||||
// TODO: Image can't load with base64 data on Taobao platform.
|
||||
if (EDITOR || TAOBAO || TAOBAO_MINIGAME || this.settings.base64src === '' || this.settings.totalTime <= 0) {
|
||||
if (EDITOR || TAOBAO || this.settings.base64src === '' || this.settings.totalTime <= 0) {
|
||||
this.settings.totalTime = 0;
|
||||
} else {
|
||||
this.device = cclegacy.director.root!.device;
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { ALIPAY, RUNTIME_BASED, BYTEDANCE, WECHAT, LINKSURE, QTT, COCOSPLAY, HUAWEI, EDITOR, VIVO, TAOBAO, TAOBAO_MINIGAME } from 'internal:constants';
|
||||
import { ALIPAY, RUNTIME_BASED, BYTEDANCE, WECHAT, LINKSURE, QTT, COCOSPLAY, HUAWEI, EDITOR, VIVO, TAOBAO, TAOBAO_MINIGAME, WECHAT_MINI_PROGRAM } from 'internal:constants';
|
||||
import { systemInfo } from 'pal/system-info';
|
||||
import { WebGLCommandAllocator } from './webgl-command-allocator';
|
||||
import { WebGLStateCache } from './webgl-state-cache';
|
||||
@@ -155,13 +155,13 @@ export function getExtensions (gl: WebGLRenderingContext) {
|
||||
|
||||
// some earlier version of iOS and android wechat implement gl.detachShader incorrectly
|
||||
if ((systemInfo.os === OS.IOS && systemInfo.osMainVersion <= 10)
|
||||
|| (WECHAT && systemInfo.os === OS.ANDROID)) {
|
||||
|| ((WECHAT || WECHAT_MINI_PROGRAM) && systemInfo.os === OS.ANDROID)) {
|
||||
res.destroyShadersImmediately = false;
|
||||
}
|
||||
|
||||
// getUniformLocation has always been problematic because the
|
||||
// paradigm differs from GLES, and many platforms get it wrong [eyerolling]
|
||||
if (WECHAT) {
|
||||
if (WECHAT || WECHAT_MINI_PROGRAM) {
|
||||
// wEcHaT just returns { id: -1 } for inactive names
|
||||
res.isLocationActive = (glLoc: unknown): glLoc is WebGLUniformLocation => !!glLoc && (glLoc as { id: number }).id !== -1;
|
||||
}
|
||||
@@ -171,7 +171,7 @@ export function getExtensions (gl: WebGLRenderingContext) {
|
||||
}
|
||||
|
||||
// compressedTexSubImage2D too
|
||||
if (WECHAT) {
|
||||
if (WECHAT || WECHAT_MINI_PROGRAM) {
|
||||
res.noCompressedTexSubImage2D = true;
|
||||
}
|
||||
|
||||
|
||||
@@ -1987,7 +1987,8 @@ export function WebGL2CmdFuncBeginRenderPass (
|
||||
gl.colorMask(true, true, true, true);
|
||||
}
|
||||
|
||||
if (!gpuFramebuffer.isOffscreen) {
|
||||
// We-chat mini-game, glClearBufferfv get INVALID_ENUM. MRT may not be supported. use clearColor instead.
|
||||
if (gpuRenderPass.colorAttachments.length === 1) {
|
||||
const clearColor = clearColors[0];
|
||||
gl.clearColor(clearColor.x, clearColor.y, clearColor.z, clearColor.w);
|
||||
clears |= gl.COLOR_BUFFER_BIT;
|
||||
|
||||
@@ -180,7 +180,6 @@ export class ParticleSystem extends ModelRenderer {
|
||||
*/
|
||||
@type(CurveRange)
|
||||
@serializable
|
||||
@range([-2 * Math.PI, 2 * Math.PI])
|
||||
@radian
|
||||
@displayOrder(12)
|
||||
@tooltip('i18n:particle_system.startRotationX')
|
||||
@@ -193,7 +192,6 @@ export class ParticleSystem extends ModelRenderer {
|
||||
*/
|
||||
@type(CurveRange)
|
||||
@serializable
|
||||
@range([-2 * Math.PI, 2 * Math.PI])
|
||||
@radian
|
||||
@displayOrder(12)
|
||||
@tooltip('i18n:particle_system.startRotationY')
|
||||
@@ -206,7 +204,6 @@ export class ParticleSystem extends ModelRenderer {
|
||||
*/
|
||||
@type(CurveRange)
|
||||
@formerlySerializedAs('startRotation')
|
||||
@range([-2 * Math.PI, 2 * Math.PI])
|
||||
@radian
|
||||
@displayOrder(12)
|
||||
@tooltip('i18n:particle_system.startRotationZ')
|
||||
|
||||
@@ -24,7 +24,7 @@
|
||||
|
||||
// eslint-disable-next-line import/no-extraneous-dependencies
|
||||
import bulletModule, { bulletType } from '@cocos/bullet';
|
||||
import { WECHAT, RUNTIME_BASED } from 'internal:constants';
|
||||
import { WECHAT, RUNTIME_BASED, WECHAT_MINI_PROGRAM } from 'internal:constants';
|
||||
import { game } from '../../game';
|
||||
import { sys } from '../../core';
|
||||
import { pageSize, pageCount, importFunc } from './bullet-env';
|
||||
@@ -117,7 +117,7 @@ export function waitForAmmoInstantiation () {
|
||||
}, errorReport);
|
||||
}
|
||||
|
||||
if (WECHAT || RUNTIME_BASED) {
|
||||
if (WECHAT || WECHAT_MINI_PROGRAM || RUNTIME_BASED) {
|
||||
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
|
||||
const wasmFilePath = `cocos-js/${module}` as any;
|
||||
instantiateWasm(wasmFilePath);
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
*/
|
||||
|
||||
import { ccclass, help, menu, executionOrder, requireComponent, tooltip, serializable } from 'cc.decorator';
|
||||
import { EDITOR, WECHAT } from 'internal:constants';
|
||||
import { EDITOR, WECHAT, WECHAT_MINI_PROGRAM } from 'internal:constants';
|
||||
import { minigame } from 'pal/minigame';
|
||||
import { screenAdapter } from 'pal/screen-adapter';
|
||||
import { Component } from '../scene-graph/component';
|
||||
@@ -153,7 +153,7 @@ export class SubContextView extends Component {
|
||||
const sharedCanvas = this._openDataContext.canvas;
|
||||
let designWidth = this._designResolutionSize.width;
|
||||
let designHeight = this._designResolutionSize.height;
|
||||
if (WECHAT) {
|
||||
if (WECHAT || WECHAT_MINI_PROGRAM) {
|
||||
// HACK: on WeChat platform, at least one side of the width and height of sharedCanvas is greater than 513
|
||||
// When the sharedCanvas is smaller than this size, the rendering doesn't work.
|
||||
const minimumSize = 513;
|
||||
|
||||
@@ -201,7 +201,7 @@ float CCGetLinearDepth(vec3 worldPos) {
|
||||
|
||||
|
||||
//////////////////////////////////////////////////////////Main Functions
|
||||
float CCSpotShadowFactorBase(out vec4 shadowNDCPosWithBias, vec4 shadowPos, vec3 worldPos, vec2 shadowBias)
|
||||
float CCSpotShadowFactorBase(out vec4 shadowPosWithDepthBias, vec4 shadowPos, vec3 worldPos, vec2 shadowBias)
|
||||
{
|
||||
float pcf = cc_shadowWHPBInfo.z;
|
||||
vec4 pos = vec4(1.0);
|
||||
@@ -222,11 +222,11 @@ float CCGetLinearDepth(vec3 worldPos) {
|
||||
realtimeShadow = CCGetSpotLightShadowFactorHard(pos, worldPos);
|
||||
}
|
||||
|
||||
shadowNDCPosWithBias = pos;
|
||||
shadowPosWithDepthBias = pos;
|
||||
return mix(realtimeShadow, 1.0, cc_shadowNFLSInfo.w);
|
||||
}
|
||||
|
||||
float CCShadowFactorBase(out vec4 shadowNDCPosWithBias, vec4 shadowPos, vec3 N, vec2 shadowBias)
|
||||
float CCShadowFactorBase(out vec4 shadowPosWithDepthBias, vec4 shadowPos, vec3 N, vec2 shadowBias)
|
||||
{
|
||||
vec4 pos = ApplyShadowDepthBias_FaceNormal(shadowPos, N, shadowBias.y, cc_matLightView, cc_shadowProjInfo.xy);
|
||||
pos = ApplyShadowDepthBias_Orthographic(pos, shadowBias.x, cc_shadowProjDepthInfo.x, cc_shadowProjDepthInfo.y);
|
||||
@@ -245,7 +245,7 @@ float CCGetLinearDepth(vec3 worldPos) {
|
||||
realtimeShadow = CCGetDirLightShadowFactorHard(pos);
|
||||
#endif
|
||||
|
||||
shadowNDCPosWithBias = pos;
|
||||
shadowPosWithDepthBias = pos;
|
||||
return mix(realtimeShadow, 1.0, cc_shadowNFLSInfo.w);
|
||||
}
|
||||
|
||||
@@ -344,7 +344,7 @@ float CCGetLinearDepth(vec3 worldPos) {
|
||||
}
|
||||
|
||||
// output csmPos is non-biased position that can be used for sampling shadow map after homogeneous divid
|
||||
float CCCSMFactorBase(out vec4 csmPos, out vec4 csmNDCPosWithBias, vec3 worldPos, vec3 N, vec2 shadowBias)
|
||||
float CCCSMFactorBase(out vec4 csmPos, out vec4 csmPosWithBias, vec3 worldPos, vec3 N, vec2 shadowBias)
|
||||
{
|
||||
bool isTransitionArea = false;
|
||||
highp float ratio = 0.0;
|
||||
@@ -361,7 +361,7 @@ float CCGetLinearDepth(vec3 worldPos) {
|
||||
|
||||
vec4 pos = ApplyShadowDepthBias_FaceNormal(csmPos, N, shadowBias.y, shadowViewDir0, shadowViewDir1, shadowViewDir2, shadowProjInfo.xy);
|
||||
pos = ApplyShadowDepthBias_Orthographic(pos, shadowBias.x, shadowProjDepthInfo.x, shadowProjDepthInfo.y);
|
||||
csmNDCPosWithBias = pos;
|
||||
csmPosWithBias = pos;
|
||||
|
||||
float realtimeShadow = 1.0;
|
||||
#if CC_DIR_SHADOW_PCF_TYPE == CC_SHADOW_PCF_SOFT_5X
|
||||
@@ -413,26 +413,26 @@ float CCGetLinearDepth(vec3 worldPos) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
float CCCSMFactorBase(out vec4 csmPos, out vec4 csmNDCPosWithBias, vec3 worldPos, vec3 N, vec2 shadowBias) {
|
||||
float CCCSMFactorBase(out vec4 csmPos, out vec4 csmPosWithBias, vec3 worldPos, vec3 N, vec2 shadowBias) {
|
||||
csmPos = cc_matLightViewProj * vec4(worldPos, 1.0);
|
||||
return CCShadowFactorBase(csmNDCPosWithBias, csmPos, N, shadowBias);
|
||||
return CCShadowFactorBase(csmPosWithBias, csmPos, N, shadowBias);
|
||||
}
|
||||
#endif
|
||||
|
||||
// compatible version
|
||||
float CCShadowFactorBase(vec4 shadowPos, vec3 N, vec2 shadowBias) {
|
||||
vec4 shadowNDCPosWithBias;
|
||||
return CCShadowFactorBase(shadowNDCPosWithBias, shadowPos, N, shadowBias);
|
||||
vec4 shadowPosWithDepthBias;
|
||||
return CCShadowFactorBase(shadowPosWithDepthBias, shadowPos, N, shadowBias);
|
||||
}
|
||||
|
||||
float CCCSMFactorBase(vec3 worldPos, vec3 N, vec2 shadowBias) {
|
||||
vec4 csmPos, csmNDCPosWithBias;
|
||||
return CCCSMFactorBase(csmPos, csmNDCPosWithBias, worldPos, N, shadowBias);
|
||||
vec4 csmPos, csmPosWithBias;
|
||||
return CCCSMFactorBase(csmPos, csmPosWithBias, worldPos, N, shadowBias);
|
||||
}
|
||||
|
||||
float CCSpotShadowFactorBase(vec4 shadowPos, vec3 worldPos, vec2 shadowBias)
|
||||
{
|
||||
vec4 shadowNDCPosWithBias;
|
||||
return CCSpotShadowFactorBase(shadowNDCPosWithBias, shadowPos, worldPos, shadowBias);
|
||||
vec4 shadowPosWithDepthBias;
|
||||
return CCSpotShadowFactorBase(shadowPosWithDepthBias, shadowPos, worldPos, shadowBias);
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -28,7 +28,7 @@
|
||||
#pragma define equalf(data1, data2) (abs(float(data1) - float(data2)) < EPSILON)
|
||||
#pragma define equalf_lowp(data1, data2) (abs(float(data1) - float(data2)) < EPSILON_LOWP)
|
||||
#pragma define equalf_epsilon(data1, data2, epsilonValue) (abs(float(data1) - float(data2)) < epsilonValue)
|
||||
void clip(float value) { if(value < 0.0) discard; }
|
||||
#pragma define clip(value) if(value < 0.0) discard;
|
||||
|
||||
// runtime constants
|
||||
#pragma define-meta CC_DEVICE_SUPPORT_FLOAT_TEXTURE default(1)
|
||||
@@ -67,3 +67,6 @@ void clip(float value) { if(value < 0.0) discard; }
|
||||
#define IS_SPOT_LIGHT(light_type) equalf_lowp(light_type, LIGHT_TYPE_SPOT)
|
||||
#define IS_POINT_LIGHT(light_type) equalf_lowp(light_type, LIGHT_TYPE_POINT)
|
||||
#define IS_RANGED_DIRECTIONAL_LIGHT(light_type) equalf_lowp(light_type, LIGHT_TYPE_RANGED_DIRECTIONAL)
|
||||
|
||||
// Material
|
||||
#define SURFACES_MAX_TRANSMIT_DEPTH_VALUE 999999.0
|
||||
|
||||
@@ -29,6 +29,9 @@ void GetAnisotropicRoughness(float roughness, float anisotropyShape, out float r
|
||||
roughnessY = saturate(r2);
|
||||
}
|
||||
|
||||
// How to get an anisotropic offset along T/B:
|
||||
// 1. accurate: rotation TBN basis, let N intend to T/B, such as flow map as normalmap, output vec3(0, delta, 1) instead of vec3(0, 0, 1)
|
||||
// 2. not accurate: H intend to V, and passed to this function
|
||||
float D_GGXAniso(float RoughnessX, float RoughnessY, float NoH, vec3 H, vec3 X, vec3 Y)
|
||||
{
|
||||
float mx = max(EPSILON_LOWP, RoughnessX * RoughnessX);
|
||||
|
||||
@@ -12,3 +12,12 @@ float CalculateFresnelCoefficient(float ior, float NoVSat)
|
||||
next *= next;
|
||||
return 0.5 * prev * (1.0 + next);
|
||||
}
|
||||
|
||||
vec3 CalculateScattering(vec3 unscatteredColor, float distance, float outScatterExtinctCoef, float inScatterExtinctCoef, float inScatterCoef, vec3 inScatterColor, vec3 outScatterColor)
|
||||
{
|
||||
vec2 e = vec2(outScatterExtinctCoef, inScatterExtinctCoef * inScatterCoef);
|
||||
vec2 extinction = exp(-e * distance);
|
||||
vec3 inScattered = (1.0 - extinction.y) * inScatterColor;
|
||||
vec3 outScattered = unscatteredColor * extinction.x * outScatterColor;
|
||||
return outScattered + inScattered;
|
||||
}
|
||||
|
||||
@@ -96,3 +96,12 @@ void RotateTangentAndBinormal(inout vec3 tangent, inout vec3 binormal, vec3 norm
|
||||
tangent = normalize(tangentNew);
|
||||
// tangent = cross(binormal, normal);
|
||||
}
|
||||
|
||||
// fast rotation for anisotropic offset
|
||||
// rotationAngle: -1 - +1
|
||||
void RotateNormalAndBinormal(inout vec3 binormal, inout vec3 normal, in vec3 tangent, float rotationAngle)
|
||||
{
|
||||
normal += (binormal - normal) * rotationAngle;
|
||||
normal = normalize(normal);
|
||||
binormal = normalize(cross(tangent, normal));
|
||||
}
|
||||
|
||||
@@ -14,6 +14,27 @@ float SampleShadowMap (vec3 shadowNDCPos, highp sampler2D shadowMap)
|
||||
#endif
|
||||
}
|
||||
|
||||
// return averaged depth
|
||||
float SampleShadowMapSoft (vec3 shadowNDCPos, highp sampler2D shadowMap, vec2 shadowMapResolution)
|
||||
{
|
||||
vec2 oneTap = 1.0 / shadowMapResolution;
|
||||
vec2 shadowNDCPos_offset = shadowNDCPos.xy + oneTap;
|
||||
|
||||
float block0 = SampleShadowMap(vec3(shadowNDCPos.x, shadowNDCPos.y, shadowNDCPos.z), shadowMap);
|
||||
float block1 = SampleShadowMap(vec3(shadowNDCPos_offset.x, shadowNDCPos.y, shadowNDCPos.z), shadowMap);
|
||||
float block2 = SampleShadowMap(vec3(shadowNDCPos.x, shadowNDCPos_offset.y, shadowNDCPos.z), shadowMap);
|
||||
float block3 = SampleShadowMap(vec3(shadowNDCPos_offset.x, shadowNDCPos_offset.y, shadowNDCPos.z), shadowMap);
|
||||
|
||||
float coefX = mod(shadowNDCPos.x, oneTap.x) * shadowMapResolution.x;
|
||||
float resultX = mix(block0, block1, coefX);
|
||||
float resultY = mix(block2, block3, coefX);
|
||||
float coefY = mod(shadowNDCPos.y, oneTap.y) * shadowMapResolution.y;
|
||||
|
||||
return mix(resultX, resultY, coefY);
|
||||
}
|
||||
|
||||
|
||||
|
||||
float NativePCFShadowFactorHard (vec3 shadowNDCPos, highp sampler2D shadowMap, vec2 shadowMapResolution)
|
||||
{
|
||||
#if CC_SHADOWMAP_FORMAT == SHADOWMAP_FORMAT_RGBA8
|
||||
|
||||
+11
-7
@@ -3,6 +3,7 @@ struct LightingIntermediateData
|
||||
vec3 N, H, L, V; // normalized
|
||||
float distToLight, distToLightSqr; // (pos->light)^2
|
||||
float distToCamera, distToCameraSqr; // pos->camera
|
||||
float angleAttenuation, distAttenuation;
|
||||
|
||||
float NoL, NoV, NoH;//, VoH;
|
||||
float NoLSat, NoVSat, NoHSat;//, VoHSat; // clamped to 0-1
|
||||
@@ -22,12 +23,12 @@ struct LightingIntermediateData
|
||||
#endif
|
||||
|
||||
#if CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE
|
||||
vec4 shadowPosAndDepth; //xy: shadowmap uv, z: camera depth from pixel LVP, w: camera depth from shadowmap
|
||||
vec4 transmitDiffuseParams; //zw: min/max DepthWS for shadowmap and 0 means disable shadow transmit, x: transmit irradiance apply shadow, y: additional transmit depth mask, 可补充shadowmap cover不到的地方,也可以在minmax屏蔽掉shadowmap之后给专门的薄片穿透
|
||||
vec4 shadowPosAndDepth; //xy: shadowmap uv, z: camera depth from pixel LVP, w: camera depth from shadowmap, (z == w && z > 999998.0) means disable get distance from shadowmap
|
||||
vec4 transmitDiffuseParams; //zw: min/max DepthWS for shadowmap, x: transmit irradiance apply shadow, y: additional transmit mask, for shadowmap uncovered area
|
||||
#endif
|
||||
#if CC_SURFACES_LIGHTING_TRANSMIT_SPECULAR || CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE
|
||||
vec4 transmitParams; // xy: extinction coef for out/in-scattering, z: in-scattering coef, w: transmit distance(water depth, leaf thickness)
|
||||
vec3 inScatteringLightColor;
|
||||
vec4 transmitScatteringParams; // xy: extinction coef for out/in-scattering, z: in-scattering coef, w: transmit distance(water depth, leaf thickness)
|
||||
vec3 outScatteringColor, inScatteringColor;
|
||||
#endif
|
||||
#if CC_SURFACES_LIGHTING_TT
|
||||
vec3 baseColorTT;
|
||||
@@ -53,6 +54,8 @@ void CCSurfacesLightingGetIntermediateData_PerPixel(inout LightingIntermediateDa
|
||||
data.distToCamera = sqrt(data.distToCameraSqr);
|
||||
data.V /= data.distToCamera;
|
||||
|
||||
data.angleAttenuation = data.distAttenuation = 1.0;
|
||||
|
||||
data.NoV = dot(data.N, data.V);
|
||||
data.NoVSat = max(data.NoV, 0.0);
|
||||
data.NoVAbsSat = max(abs(data.NoV), 0.0);
|
||||
@@ -65,11 +68,12 @@ void CCSurfacesLightingGetIntermediateData_PerPixel(inout LightingIntermediateDa
|
||||
data.anisotropyShape = anisotropyShape;
|
||||
#endif
|
||||
#if CC_SURFACES_LIGHTING_TRANSMIT_SPECULAR || CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE
|
||||
data.inScatteringLightColor = vec3(0.0);
|
||||
data.transmitParams = vec4(0.0);
|
||||
data.outScatteringColor = vec3(1.0);
|
||||
data.inScatteringColor = vec3(0.0);
|
||||
data.transmitScatteringParams = vec4(0.0);
|
||||
#endif
|
||||
#if CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE
|
||||
data.shadowPosAndDepth = vec4(0.0, 0.0, 999999.0, 999999.0);
|
||||
data.shadowPosAndDepth = vec4(0.0, 0.0, SURFACES_MAX_TRANSMIT_DEPTH_VALUE, SURFACES_MAX_TRANSMIT_DEPTH_VALUE);
|
||||
#endif
|
||||
#if CC_SURFACES_LIGHTING_TT
|
||||
data.baseColorTT = vec3(0.0);
|
||||
|
||||
@@ -1,8 +1,41 @@
|
||||
// invoked by lighting-models/model-functions/XXX
|
||||
#ifndef CC_SURFACES_LIGHTING_MODIFY_SKIN_DIFFUSE_LIGHTING
|
||||
vec3 SurfacesLightingModifySkinDiffuseLighting(in LightingIntermediateData lightingData, in float ssssCurvature)
|
||||
#include <surfaces/data-structures/standard>
|
||||
#include <lighting-models/includes/standard>
|
||||
|
||||
#if USE_PREINTEGRATED_SKIN
|
||||
uniform sampler2D preIntegratedSkinMap; // engine internal assets
|
||||
#endif
|
||||
|
||||
#define CC_SURFACES_LIGHTING_MODIFY_FINAL_RESULT
|
||||
void SurfacesLightingModifyFinalResult(inout LightingResult result, in LightingIntermediateData lightingData, in SurfacesMaterialData surfaceData, in LightingMiscData miscData)
|
||||
{
|
||||
// if user do not sample PreIntegratedSSS tex, fallback to default light model
|
||||
return vec3(lightingData.NoL);
|
||||
#if CC_SURFACES_LIGHTING_SSS
|
||||
float sssIntensity = surfaceData.sssParams.x;
|
||||
float sssCurvature = surfaceData.sssParams.y;
|
||||
float sssColoration = surfaceData.sssParams.z;
|
||||
float cavity = surfaceData.sssParams.w;
|
||||
|
||||
// update lighting data for diffuse calculations
|
||||
LightingIntermediateData lightingData3S = lightingData;
|
||||
lightingData3S.N = FSInput_worldNormal;
|
||||
lightingData3S.NoL = dot(lightingData3S.N, -miscData.lightDir);
|
||||
lightingData3S.NoL = mix(lightingData.NoL, lightingData3S.NoL, sssIntensity);
|
||||
lightingData3S.NoLSat = saturate(lightingData3S.NoL);
|
||||
|
||||
float multiplier = lightingData.distAttenuation * lightingData.angleAttenuation;
|
||||
#if USE_PREINTEGRATED_SKIN
|
||||
result.directDiffuse = texture(preIntegratedSkinMap, vec2(lightingData3S.NoL * 0.5 + 0.5, sssCurvature)).rgb;
|
||||
vec3 color = result.directDiffuse / (EPSILON_LOWP + max(max(result.directDiffuse.r, result.directDiffuse.g), result.directDiffuse.b));
|
||||
result.directDiffuse *= pow(color, vec3(sssColoration));
|
||||
result.directDiffuse *= miscData.lightColorAndIntensity.rgb * miscData.lightColorAndIntensity.w * DiffuseCoefficient_EnergyConservation;
|
||||
#else
|
||||
result.directDiffuse = CalculateDirectDiffuse(lightingData3S, miscData.lightColorAndIntensity) * multiplier;
|
||||
#endif
|
||||
|
||||
result.directSpecular *= cavity;
|
||||
|
||||
#if !CC_FORWARD_ADD
|
||||
result.environmentDiffuse = CalculateEnvironmentDiffuse(lightingData3S, cc_ambientSky.w);
|
||||
result.environmentSpecular *= cavity;
|
||||
#endif
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -1,241 +1,260 @@
|
||||
#if (CC_PIPELINE_TYPE == CC_PIPELINE_TYPE_FORWARD || CC_FORCE_FORWARD_SHADING)
|
||||
#if CC_FORWARD_ADD && !CC_ENABLE_CLUSTERED_LIGHT_CULLING
|
||||
void CCSurfacesLighting(inout LightingResult lightingResultAccumulated, in SurfacesMaterialData surfaceData, in vec2 shadowBias)
|
||||
{
|
||||
vec3 worldPos;
|
||||
HIGHP_VALUE_FROM_STRUCT_DEFINED(worldPos, surfaceData.worldPos);
|
||||
|
||||
CCSurfacesInitializeLightingResult(lightingResultAccumulated);
|
||||
|
||||
LightingIntermediateData lightingData;
|
||||
CCSurfacesInitializeLightingIntermediateData(lightingData, surfaceData);
|
||||
|
||||
LightingResult lightingResult;
|
||||
CCSurfacesLightingInitializeColorWithLighting(lightingResult.diffuseColorWithLighting, lightingResult.specularColorWithLighting, surfaceData, lightingData);
|
||||
lightingResultAccumulated.diffuseColorWithLighting = lightingResult.diffuseColorWithLighting;
|
||||
lightingResultAccumulated.specularColorWithLighting = lightingResult.specularColorWithLighting;
|
||||
|
||||
#if CC_SURFACES_LIGHTING_TRT
|
||||
vec3 diff;
|
||||
SurfacesMaterialData surfaceDataTRT;
|
||||
CCSurfacesGetSurfacesMaterialDataTRT(surfaceDataTRT, surfaceData);
|
||||
CCSurfacesLightingInitializeColorWithLighting(diff, lightingResultAccumulated.specularColorWithLightingTRT, surfaceDataTRT, lightingData);
|
||||
#endif
|
||||
|
||||
int numLights = CC_PIPELINE_TYPE == CC_PIPELINE_TYPE_FORWARD ? LIGHTS_PER_PASS : int(cc_lightDir[0].w);
|
||||
for (int i = 0; i < LIGHTS_PER_PASS; i++) {
|
||||
if (i >= numLights) break;
|
||||
|
||||
vec3 lightDirWithLength = IS_RANGED_DIRECTIONAL_LIGHT(cc_lightPos[i].w) ? -normalize(cc_lightDir[i].xyz) : cc_lightPos[i].xyz - worldPos;
|
||||
CCSurfacesLightingCalculateIntermediateData_PerLight(lightingData, surfaceData, lightDirWithLength);
|
||||
CCSurfacesLightingCalculateColorWithLighting(lightingResult.diffuseColorWithLighting, lightingResult.specularColorWithLighting, surfaceData, lightingData);
|
||||
|
||||
vec3 diffuseLighting, specularLighting;
|
||||
CCSurfacesLightingCalculateDirect(diffuseLighting, specularLighting, lightingData, cc_lightColor[i]);
|
||||
|
||||
float fresnel = 1.0;
|
||||
#if CC_SURFACES_LIGHTING_USE_FRESNEL
|
||||
fresnel = lightingResult.fresnel = CCSurfaceLightingCalculateFresnel(lightingData);
|
||||
#endif
|
||||
|
||||
// shadows
|
||||
float shadow = 1.0;
|
||||
#if CC_RECEIVE_SHADOW && CC_SHADOW_TYPE == CC_SHADOW_MAP
|
||||
if (IS_SPOT_LIGHT(cc_lightPos[i].w) && cc_lightSizeRangeAngle[i].w > 0.0) {
|
||||
vec4 shadowPos = vec4(0.0), shadowNDCPosWithBias = vec4(0.0);
|
||||
if (CCSurfacesLightingEnableShadow(lightingData.NoL)) {
|
||||
shadowPos = cc_matLightViewProj * vec4(surfaceData.worldPos, 1.0);
|
||||
shadow = CCSpotShadowFactorBase(shadowNDCPosWithBias, shadowPos, worldPos, shadowBias);
|
||||
}
|
||||
#if CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE
|
||||
#if CC_SURFACES_LIGHTING_USE_SHADOWMAP_TRANSMIT
|
||||
lightingData.shadowPosAndDepth.xy = shadowNDCPosWithBias.xy;
|
||||
lightingData.shadowPosAndDepth.z = shadowPos.z;
|
||||
lightingData.shadowPosAndDepth.w = GetViewSpaceDepthFromNDCDepth_Perspective(SampleShadowMap(shadowNDCPosWithBias.xyz, cc_spotShadowMap), shadowNDCPosWithBias.w, cc_shadowInvProjDepthInfo.x, cc_shadowInvProjDepthInfo.y);
|
||||
#else
|
||||
lightingData.transmitDiffuseParams.zw = vec2(0.0);
|
||||
#endif
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
#if CC_USE_DEBUG_VIEW == CC_SURFACES_DEBUG_VIEW_COMPOSITE_AND_MISC
|
||||
if (!IS_DEBUG_VIEW_COMPOSITE_ENABLE_SHADOW) {
|
||||
shadow = 1.0;
|
||||
}
|
||||
#endif
|
||||
|
||||
lightingResult.shadow = shadow;
|
||||
|
||||
// attenuations
|
||||
float distAtt = 1.0;
|
||||
if(IS_RANGED_DIRECTIONAL_LIGHT(cc_lightPos[i].w)) {
|
||||
distAtt = GetOutOfRange(worldPos, cc_lightPos[i].xyz, cc_lightDir[i].xyz, cc_lightSizeRangeAngle[i].xyz, cc_lightBoundingSizeVS[i].xyz);
|
||||
} else {
|
||||
distAtt = CCSurfacesLightingCalculateDistanceAttenuation(lightingData, cc_lightSizeRangeAngle[i], cc_lightPos[i].w);
|
||||
}
|
||||
|
||||
float angleAtt = 1.0;
|
||||
if (IS_SPOT_LIGHT(cc_lightPos[i].w)) {
|
||||
angleAtt = CCSurfacesLightingCalculateAngleAttenuation(lightingData, cc_lightSizeRangeAngle[i], -cc_lightDir[i].xyz);
|
||||
}
|
||||
|
||||
float multiplier = distAtt * angleAtt;
|
||||
|
||||
// output
|
||||
lightingResult.directDiffuse = diffuseLighting * multiplier;
|
||||
lightingResult.directSpecular = specularLighting * multiplier * fresnel;
|
||||
|
||||
#if CC_SURFACES_LIGHTING_TRANSMIT_SPECULAR
|
||||
vec3 transmitSpecularLighting;
|
||||
CCSurfacesLightingCalculateDirectTransmitSpecular(transmitSpecularLighting, lightingData, cc_lightColor[i]);
|
||||
lightingResult.directTransmitSpecular = transmitSpecularLighting * multiplier * (1.0 - fresnel);
|
||||
#endif
|
||||
|
||||
#if CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE
|
||||
lightingResult.directTransmitDiffuse = CCSurfacesLightingCalculateDirectTransmitDiffuse(lightingResult, lightingData, cc_lightColor[i]);
|
||||
#endif
|
||||
|
||||
#if CC_SURFACES_LIGHTING_TRT
|
||||
LightingIntermediateData lightingDataTRT;
|
||||
CCSurfacesGetLightingIntermediateDataTRT(lightingDataTRT, lightingData, surfaceData);
|
||||
CCSurfacesLightingCalculateDirectTRT(lightingResult.directTRT, lightingDataTRT, cc_lightColor[i]);
|
||||
lightingResult.directTRT *= multiplier * fresnel;
|
||||
// lightingResult.directTRT -= lightingResult.directSpecular;
|
||||
#endif
|
||||
|
||||
#if CC_SURFACES_LIGHTING_TT
|
||||
CCSurfacesLightingCalculateDirectTT(lightingResult, lightingData, cc_lightColor[i]);
|
||||
#endif
|
||||
|
||||
|
||||
// user-defined lighting model
|
||||
#ifdef CC_SURFACES_LIGHTING_MODIFY_FINAL_RESULT
|
||||
LightingMiscData miscData;
|
||||
miscData.lightType = cc_lightPos[i].w;
|
||||
miscData.lightPos = cc_lightPos[i].xyz;
|
||||
miscData.lightDir = cc_lightDir[i].xyz;
|
||||
miscData.lightColorAndIntensity = cc_lightColor[i];
|
||||
miscData.lightSizeRangeAngle = cc_lightSizeRangeAngle[i];
|
||||
SurfacesLightingModifyFinalResult(lightingResult, lightingData, surfaceData, miscData);
|
||||
#endif
|
||||
|
||||
// accumulate per-light results
|
||||
CCSurfacesAccumulateLightingResult(lightingResultAccumulated, lightingResult);
|
||||
}
|
||||
}
|
||||
#else
|
||||
void CCSurfacesLighting(inout LightingResult lightingResult, in SurfacesMaterialData surfaceData, in vec2 shadowBias)
|
||||
{
|
||||
LightingIntermediateData lightingData;
|
||||
CCSurfacesInitializeLightingIntermediateData(lightingData, surfaceData);
|
||||
CCSurfacesInitializeLightingResult(lightingResult, surfaceData);
|
||||
|
||||
CCSurfacesLightingInitializeColorWithLighting(lightingResult.diffuseColorWithLighting, lightingResult.specularColorWithLighting, surfaceData, lightingData);
|
||||
|
||||
CCSurfacesLightingCalculateIntermediateData_PerLight(lightingData, surfaceData, -cc_mainLitDir.xyz);
|
||||
|
||||
// CCSurfacesLightingCalculateShadow:
|
||||
lightingResult.shadow = 1.0;
|
||||
#if CC_RECEIVE_SHADOW && CC_SHADOW_TYPE == CC_SHADOW_MAP
|
||||
if (cc_mainLitDir.w > 0.0) {
|
||||
vec4 shadowPos = vec4(0.0), shadowNDCPosWithBias = vec4(0.0);
|
||||
if (CCSurfacesLightingEnableShadow(lightingData.NoL)) {
|
||||
#if CC_DIR_LIGHT_SHADOW_TYPE == CC_DIR_LIGHT_SHADOW_CASCADED
|
||||
lightingResult.shadow = CCCSMFactorBase(shadowPos, shadowNDCPosWithBias, surfaceData.worldPos, lightingData.N, shadowBias);
|
||||
#endif
|
||||
#if CC_DIR_LIGHT_SHADOW_TYPE == CC_DIR_LIGHT_SHADOW_UNIFORM
|
||||
shadowPos = cc_matLightViewProj * vec4(surfaceData.worldPos, 1.0);
|
||||
lightingResult.shadow = CCShadowFactorBase(shadowPos, lightingData.N, shadowBias);
|
||||
#endif
|
||||
}
|
||||
#if CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE
|
||||
#if CC_SURFACES_LIGHTING_USE_SHADOWMAP_TRANSMIT
|
||||
lightingData.shadowPosAndDepth.xy = shadowNDCPosWithBias.xy;
|
||||
lightingData.shadowPosAndDepth.z = shadowPos.z;
|
||||
lightingData.shadowPosAndDepth.w = GetViewSpaceDepthFromNDCDepth_Orthgraphic(SampleShadowMap(shadowNDCPosWithBias.xyz, cc_shadowMap), cc_shadowProjDepthInfo.x, cc_shadowProjDepthInfo.y);
|
||||
#else
|
||||
lightingData.transmitDiffuseParams.zw = vec2(0.0);
|
||||
#endif
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
// CCSurfacesLightingCalculateBaked:
|
||||
lightingResult.lightmapColor = vec3(0.0);
|
||||
#if CC_SURFACES_USE_LIGHT_MAP && !CC_FORWARD_ADD
|
||||
float lightmapShadow, lightmapAO;
|
||||
GetLightMapColor(lightingResult.lightmapColor, lightmapShadow, lightmapAO, cc_lightingMap, FSInput_lightMapUV.xy, FSInput_lightMapUV.z, surfaceData.worldNormal);
|
||||
|
||||
#if CC_SURFACES_USE_LIGHT_MAP == LIGHT_MAP_TYPE_INDIRECT_OCCLUSION
|
||||
lightingResult.shadow *= lightmapShadow;
|
||||
lightingResult.ao *= lightmapAO;
|
||||
#endif
|
||||
#endif
|
||||
|
||||
// dynamic & stationary dir light
|
||||
lightingResult.directDiffuse = lightingResult.directSpecular = vec3(0.0);
|
||||
#if !CC_DISABLE_DIRECTIONAL_LIGHT && !CC_FORWARD_ADD
|
||||
CCSurfacesLightingCalculateColorWithLighting(lightingResult.diffuseColorWithLighting, lightingResult.specularColorWithLighting, surfaceData, lightingData);
|
||||
|
||||
CCSurfacesLightingCalculateDirect(lightingResult.directDiffuse, lightingResult.directSpecular, lightingData, cc_mainLitColor);
|
||||
#endif
|
||||
|
||||
// apply SSR, local probe & global probe
|
||||
CCSurfacesLightingCalculateEnvironment(lightingResult.environmentDiffuse, lightingResult.environmentSpecular, lightingData, cc_ambientSky.w);
|
||||
|
||||
#if CC_SURFACES_LIGHTING_USE_FRESNEL
|
||||
lightingResult.fresnel = CCSurfaceLightingCalculateFresnel(lightingData);
|
||||
#endif
|
||||
|
||||
#if CC_SURFACES_LIGHTING_TRANSMIT_SPECULAR
|
||||
CCSurfacesLightingCalculateDirectTransmitSpecular(lightingResult.directTransmitSpecular, lightingData, cc_mainLitColor);
|
||||
CCSurfacesLightingCalculateEnvironmentTransmitSpecular(lightingResult.environmentTransmitSpecular, lightingData, cc_ambientSky.w);
|
||||
#endif
|
||||
|
||||
#if CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE
|
||||
CCSurfacesLightingCalculateDirectTransmitDiffuse(lightingResult.directTransmitDiffuse, lightingResult, lightingData, cc_mainLitColor);
|
||||
CCSurfacesLightingCalculateEnvironmentTransmitDiffuse(lightingResult.environmentTransmitDiffuse, lightingResult, lightingData, cc_ambientSky.w);
|
||||
#endif
|
||||
|
||||
#if CC_SURFACES_LIGHTING_TRT
|
||||
LightingIntermediateData lightingDataTRT;
|
||||
CCSurfacesGetLightingIntermediateDataTRT(lightingDataTRT, lightingData, surfaceData);
|
||||
CCSurfacesLightingCalculateDirectTRT(lightingResult.directTRT, lightingDataTRT, cc_mainLitColor);
|
||||
CCSurfacesLightingCalculateEnvironmentTRT(lightingResult.environmentTRT, lightingDataTRT, cc_ambientSky.w);
|
||||
// lightingResult.directTRT -= lightingResult.directSpecular;
|
||||
// lightingResult.environmentTRT -= lightingResult.environmentSpecular;
|
||||
|
||||
vec3 diff;
|
||||
SurfacesMaterialData surfaceDataTRT;
|
||||
CCSurfacesGetSurfacesMaterialDataTRT(surfaceDataTRT, surfaceData);
|
||||
CCSurfacesLightingInitializeColorWithLighting(diff, lightingResult.specularColorWithLightingTRT, surfaceDataTRT, lightingDataTRT);
|
||||
#endif
|
||||
|
||||
#if CC_SURFACES_LIGHTING_TT
|
||||
CCSurfacesLightingCalculateDirectTT(lightingResult, lightingData, cc_mainLitColor);
|
||||
#endif
|
||||
|
||||
// apply screen-space shadow and ao
|
||||
// lightingResult.shadow/ao *= XXX;
|
||||
|
||||
// user-defined lighting model
|
||||
#ifdef CC_SURFACES_LIGHTING_MODIFY_FINAL_RESULT
|
||||
LightingMiscData miscData;
|
||||
miscData.lightType = LIGHT_TYPE_DIRECTIONAL;
|
||||
miscData.lightPos = vec3(0.0);
|
||||
miscData.lightDir = cc_mainLitDir.xyz;
|
||||
miscData.lightColorAndIntensity = cc_mainLitColor;
|
||||
miscData.lightSizeRangeAngle = vec4(0.0, 0.0, 0.0, 0.0);
|
||||
SurfacesLightingModifyFinalResult(lightingResult, lightingData, surfaceData, miscData);
|
||||
#endif
|
||||
}
|
||||
#if CC_ENABLE_CLUSTERED_LIGHT_CULLING
|
||||
// #todo: cluster related lighting flow, invoke after CCSurfacesLighting
|
||||
// use same code as additive-pass
|
||||
// void CCSurfacesLighting_Cluster(inout LightingResult lightingResult, in SurfacesMaterialData surfaceData, in vec2 shadowBias)
|
||||
// {
|
||||
// }
|
||||
#endif // cluster lighting
|
||||
#endif // base pass
|
||||
#endif // forward shading
|
||||
#if (CC_PIPELINE_TYPE == CC_PIPELINE_TYPE_FORWARD || CC_FORCE_FORWARD_SHADING)
|
||||
#if CC_FORWARD_ADD && !CC_ENABLE_CLUSTERED_LIGHT_CULLING
|
||||
void CCSurfacesLighting(inout LightingResult lightingResultAccumulated, in SurfacesMaterialData surfaceData, in vec2 shadowBias)
|
||||
{
|
||||
vec3 worldPos;
|
||||
HIGHP_VALUE_FROM_STRUCT_DEFINED(worldPos, surfaceData.worldPos);
|
||||
|
||||
CCSurfacesInitializeLightingResult(lightingResultAccumulated);
|
||||
|
||||
LightingIntermediateData lightingData;
|
||||
CCSurfacesInitializeLightingIntermediateData(lightingData, surfaceData);
|
||||
|
||||
LightingResult lightingResult;
|
||||
CCSurfacesLightingInitializeColorWithLighting(lightingResult.diffuseColorWithLighting, lightingResult.specularColorWithLighting, surfaceData, lightingData);
|
||||
lightingResultAccumulated.diffuseColorWithLighting = lightingResult.diffuseColorWithLighting;
|
||||
lightingResultAccumulated.specularColorWithLighting = lightingResult.specularColorWithLighting;
|
||||
|
||||
#if CC_SURFACES_LIGHTING_TRT
|
||||
vec3 diff;
|
||||
SurfacesMaterialData surfaceDataTRT;
|
||||
CCSurfacesGetSurfacesMaterialDataTRT(surfaceDataTRT, surfaceData);
|
||||
CCSurfacesLightingInitializeColorWithLighting(diff, lightingResultAccumulated.specularColorWithLightingTRT, surfaceDataTRT, lightingData);
|
||||
#endif
|
||||
|
||||
int numLights = CC_PIPELINE_TYPE == CC_PIPELINE_TYPE_FORWARD ? LIGHTS_PER_PASS : int(cc_lightDir[0].w);
|
||||
for (int i = 0; i < LIGHTS_PER_PASS; i++) {
|
||||
if (i >= numLights) break;
|
||||
|
||||
vec3 lightDirWithLength = IS_RANGED_DIRECTIONAL_LIGHT(cc_lightPos[i].w) ? -normalize(cc_lightDir[i].xyz) : cc_lightPos[i].xyz - worldPos;
|
||||
CCSurfacesLightingCalculateIntermediateData_PerLight(lightingData, surfaceData, lightDirWithLength);
|
||||
CCSurfacesLightingCalculateColorWithLighting(lightingResult.diffuseColorWithLighting, lightingResult.specularColorWithLighting, surfaceData, lightingData);
|
||||
|
||||
vec3 diffuseLighting, specularLighting;
|
||||
CCSurfacesLightingCalculateDirect(diffuseLighting, specularLighting, lightingData, cc_lightColor[i]);
|
||||
|
||||
float fresnel = 1.0;
|
||||
#if CC_SURFACES_LIGHTING_USE_FRESNEL
|
||||
fresnel = lightingResult.fresnel = CCSurfaceLightingCalculateFresnel(lightingData);
|
||||
#endif
|
||||
|
||||
// shadows
|
||||
float shadow = 1.0;
|
||||
#if CC_RECEIVE_SHADOW && CC_SHADOW_TYPE == CC_SHADOW_MAP
|
||||
if (IS_SPOT_LIGHT(cc_lightPos[i].w) && cc_lightSizeRangeAngle[i].w > 0.0) {
|
||||
vec4 shadowPos = vec4(0.0), shadowPosWithDepthBias = vec4(0.0);
|
||||
if (CCSurfacesLightingEnableShadow(lightingData.NoL)) {
|
||||
shadowPos = cc_matLightViewProj * vec4(worldPos, 1.0);
|
||||
shadow = CCSpotShadowFactorBase(shadowPosWithDepthBias, shadowPos, worldPos, shadowBias);
|
||||
}
|
||||
#if CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE && CC_SURFACES_LIGHTING_USE_SHADOWMAP_TRANSMIT
|
||||
vec3 shadowNDCPos;
|
||||
bool isExceedShadowMap = !GetShadowNDCPos(shadowNDCPos, shadowPosWithDepthBias);
|
||||
lightingData.shadowPosAndDepth.xy = shadowNDCPos.xy;
|
||||
// notice: view space z value is negative
|
||||
lightingData.shadowPosAndDepth.z = isExceedShadowMap ? 0.0 : GetViewSpaceDepthFromNDCDepth_Perspective(shadowNDCPos.z, shadowPosWithDepthBias.w, cc_shadowInvProjDepthInfo.x, cc_shadowInvProjDepthInfo.y);
|
||||
lightingData.shadowPosAndDepth.w = isExceedShadowMap ? lightingData.shadowPosAndDepth.w : GetViewSpaceDepthFromNDCDepth_Perspective(SampleShadowMapSoft(shadowNDCPos, cc_spotShadowMap, cc_shadowWHPBInfo.xy), shadowPosWithDepthBias.w, cc_shadowInvProjDepthInfo.x, cc_shadowInvProjDepthInfo.y);
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
#if CC_USE_DEBUG_VIEW == CC_SURFACES_DEBUG_VIEW_COMPOSITE_AND_MISC
|
||||
if (!IS_DEBUG_VIEW_COMPOSITE_ENABLE_SHADOW) {
|
||||
shadow = 1.0;
|
||||
}
|
||||
#endif
|
||||
|
||||
lightingResult.shadow = shadow;
|
||||
|
||||
// attenuations
|
||||
float distAtt = 1.0;
|
||||
if(IS_RANGED_DIRECTIONAL_LIGHT(cc_lightPos[i].w)) {
|
||||
distAtt = GetOutOfRange(worldPos, cc_lightPos[i].xyz, cc_lightDir[i].xyz, cc_lightSizeRangeAngle[i].xyz, cc_lightBoundingSizeVS[i].xyz);
|
||||
} else {
|
||||
distAtt = CCSurfacesLightingCalculateDistanceAttenuation(lightingData, cc_lightSizeRangeAngle[i], cc_lightPos[i].w);
|
||||
}
|
||||
|
||||
float angleAtt = 1.0;
|
||||
if (IS_SPOT_LIGHT(cc_lightPos[i].w)) {
|
||||
angleAtt = CCSurfacesLightingCalculateAngleAttenuation(lightingData, cc_lightSizeRangeAngle[i], -cc_lightDir[i].xyz);
|
||||
}
|
||||
|
||||
float multiplier = distAtt * angleAtt;
|
||||
|
||||
// output
|
||||
lightingData.angleAttenuation = angleAtt;
|
||||
lightingData.distAttenuation = distAtt;
|
||||
lightingResult.directDiffuse = diffuseLighting * multiplier;
|
||||
lightingResult.directSpecular = specularLighting * multiplier * fresnel;
|
||||
|
||||
vec4 attenuatedLightColorAndIntensity = vec4(cc_lightColor[i].xyz, cc_lightColor[i].w * multiplier);
|
||||
|
||||
#if CC_SURFACES_LIGHTING_TRANSMIT_SPECULAR
|
||||
vec3 transmitSpecularLighting;
|
||||
CCSurfacesLightingCalculateDirectTransmitSpecular(transmitSpecularLighting, lightingData, attenuatedLightColorAndIntensity);
|
||||
lightingResult.directTransmitSpecular = transmitSpecularLighting * multiplier * (1.0 - fresnel);
|
||||
#endif
|
||||
|
||||
#if CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE
|
||||
LightingIntermediateData lightingDataTD;
|
||||
CCSurfacesGetLightingIntermediateDataTransmitDiffuse(lightingDataTD, lightingData, surfaceData);
|
||||
CCSurfacesLightingCalculateIntermediateData_PerLight(lightingDataTD, surfaceData, lightDirWithLength);
|
||||
CCSurfacesLightingCalculateDirectTransmitDiffuse(lightingResult.directTransmitDiffuse, lightingDataTD, attenuatedLightColorAndIntensity, lightingResult.shadow);
|
||||
#endif
|
||||
|
||||
#if CC_SURFACES_LIGHTING_TRT
|
||||
LightingIntermediateData lightingDataTRT;
|
||||
CCSurfacesGetLightingIntermediateDataTRT(lightingDataTRT, lightingData, surfaceData);
|
||||
CCSurfacesLightingCalculateIntermediateData_PerLight(lightingDataTRT, surfaceData, lightDirWithLength);
|
||||
CCSurfacesLightingCalculateDirectTRT(lightingResult.directTRT, lightingDataTRT, attenuatedLightColorAndIntensity, lightingResult.directSpecular);
|
||||
lightingResult.directTRT *= multiplier * fresnel;
|
||||
#endif
|
||||
|
||||
#if CC_SURFACES_LIGHTING_TT
|
||||
CCSurfacesLightingCalculateDirectTT(lightingResult, lightingData, attenuatedLightColorAndIntensity);
|
||||
#endif
|
||||
|
||||
|
||||
// user-defined lighting model
|
||||
#ifdef CC_SURFACES_LIGHTING_MODIFY_FINAL_RESULT
|
||||
LightingMiscData miscData;
|
||||
miscData.lightType = cc_lightPos[i].w;
|
||||
miscData.lightPos = cc_lightPos[i].xyz;
|
||||
miscData.lightDir = cc_lightDir[i].xyz;
|
||||
miscData.lightColorAndIntensity = cc_lightColor[i];
|
||||
miscData.lightSizeRangeAngle = cc_lightSizeRangeAngle[i];
|
||||
SurfacesLightingModifyFinalResult(lightingResult, lightingData, surfaceData, miscData);
|
||||
#endif
|
||||
|
||||
// accumulate per-light results
|
||||
CCSurfacesAccumulateLightingResult(lightingResultAccumulated, lightingResult);
|
||||
}
|
||||
}
|
||||
#else
|
||||
void CCSurfacesLighting(inout LightingResult lightingResult, in SurfacesMaterialData surfaceData, in vec2 shadowBias)
|
||||
{
|
||||
vec3 worldPos;
|
||||
HIGHP_VALUE_FROM_STRUCT_DEFINED(worldPos, surfaceData.worldPos);
|
||||
|
||||
LightingIntermediateData lightingData;
|
||||
CCSurfacesInitializeLightingIntermediateData(lightingData, surfaceData);
|
||||
CCSurfacesInitializeLightingResult(lightingResult, surfaceData);
|
||||
|
||||
CCSurfacesLightingInitializeColorWithLighting(lightingResult.diffuseColorWithLighting, lightingResult.specularColorWithLighting, surfaceData, lightingData);
|
||||
|
||||
CCSurfacesLightingCalculateIntermediateData_PerLight(lightingData, surfaceData, -cc_mainLitDir.xyz);
|
||||
|
||||
// CCSurfacesLightingCalculateShadow:
|
||||
lightingResult.shadow = 1.0;
|
||||
#if CC_RECEIVE_SHADOW && CC_SHADOW_TYPE == CC_SHADOW_MAP
|
||||
if (cc_mainLitDir.w > 0.0) {
|
||||
vec4 shadowPos = vec4(0.0), shadowPosWithDepthBias = vec4(0.0);
|
||||
vec4 shadowProjDepthInfo = vec4(0.0);
|
||||
vec3 shadowNDCPos;
|
||||
bool isExceedShadowMap = true;
|
||||
if (CCSurfacesLightingEnableShadow(lightingData.NoL)) {
|
||||
#if CC_DIR_LIGHT_SHADOW_TYPE == CC_DIR_LIGHT_SHADOW_CASCADED
|
||||
lightingResult.shadow = CCCSMFactorBase(worldPos, lightingData.N, shadowBias);
|
||||
#if CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE && CC_SURFACES_LIGHTING_USE_SHADOWMAP_TRANSMIT
|
||||
vec4 shadowProjInfo;
|
||||
vec3 shadowViewDir0, shadowViewDir1, shadowViewDir2;
|
||||
isExceedShadowMap = 0 > CCGetCSMLevel(shadowPosWithDepthBias, shadowProjDepthInfo, shadowProjInfo, shadowViewDir0, shadowViewDir1, shadowViewDir2, worldPos);
|
||||
GetShadowNDCPos(shadowNDCPos, shadowPosWithDepthBias);
|
||||
#endif
|
||||
#endif
|
||||
#if CC_DIR_LIGHT_SHADOW_TYPE == CC_DIR_LIGHT_SHADOW_UNIFORM
|
||||
shadowPos = cc_matLightViewProj * vec4(worldPos, 1.0);
|
||||
lightingResult.shadow = CCShadowFactorBase(shadowPosWithDepthBias, shadowPos, lightingData.N, shadowBias);
|
||||
shadowProjDepthInfo = cc_shadowProjDepthInfo;
|
||||
isExceedShadowMap = !GetShadowNDCPos(shadowNDCPos, shadowPosWithDepthBias);
|
||||
#endif
|
||||
}
|
||||
#if CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE && CC_SURFACES_LIGHTING_USE_SHADOWMAP_TRANSMIT
|
||||
lightingData.shadowPosAndDepth.xy = shadowNDCPos.xy;
|
||||
// notice: view space z value is negative
|
||||
lightingData.shadowPosAndDepth.z = isExceedShadowMap ? 0.0 : GetViewSpaceDepthFromNDCDepth_Orthgraphic(shadowNDCPos.z, shadowProjDepthInfo.x, shadowProjDepthInfo.y);
|
||||
lightingData.shadowPosAndDepth.w = isExceedShadowMap ? lightingData.shadowPosAndDepth.w : GetViewSpaceDepthFromNDCDepth_Orthgraphic(SampleShadowMapSoft(shadowNDCPos, cc_shadowMap, cc_shadowWHPBInfo.xy), shadowProjDepthInfo.x, shadowProjDepthInfo.y);
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
// CCSurfacesLightingCalculateBaked:
|
||||
lightingResult.lightmapColor = vec3(0.0);
|
||||
#if CC_SURFACES_USE_LIGHT_MAP && !CC_FORWARD_ADD
|
||||
float lightmapShadow, lightmapAO;
|
||||
GetLightMapColor(lightingResult.lightmapColor, lightmapShadow, lightmapAO, cc_lightingMap, FSInput_lightMapUV.xy, FSInput_lightMapUV.z, surfaceData.worldNormal);
|
||||
|
||||
#if CC_SURFACES_USE_LIGHT_MAP == LIGHT_MAP_TYPE_INDIRECT_OCCLUSION
|
||||
lightingResult.shadow *= lightmapShadow;
|
||||
lightingResult.ao *= lightmapAO;
|
||||
#endif
|
||||
#endif
|
||||
|
||||
// dynamic & stationary dir light
|
||||
lightingResult.directDiffuse = lightingResult.directSpecular = vec3(0.0);
|
||||
#if !CC_DISABLE_DIRECTIONAL_LIGHT && !CC_FORWARD_ADD
|
||||
CCSurfacesLightingCalculateColorWithLighting(lightingResult.diffuseColorWithLighting, lightingResult.specularColorWithLighting, surfaceData, lightingData);
|
||||
|
||||
CCSurfacesLightingCalculateDirect(lightingResult.directDiffuse, lightingResult.directSpecular, lightingData, cc_mainLitColor);
|
||||
#endif
|
||||
|
||||
// apply SSR, local probe & global probe
|
||||
CCSurfacesLightingCalculateEnvironment(lightingResult.environmentDiffuse, lightingResult.environmentSpecular, lightingData, cc_ambientSky.w);
|
||||
|
||||
// apply screen-space shadow and ao
|
||||
// lightingResult.shadow/ao *= XXX;
|
||||
|
||||
#if CC_SURFACES_LIGHTING_USE_FRESNEL
|
||||
lightingResult.fresnel = CCSurfaceLightingCalculateFresnel(lightingData);
|
||||
#endif
|
||||
|
||||
#if CC_SURFACES_LIGHTING_TRANSMIT_SPECULAR
|
||||
CCSurfacesLightingCalculateDirectTransmitSpecular(lightingResult.directTransmitSpecular, lightingData, cc_mainLitColor);
|
||||
CCSurfacesLightingCalculateEnvironmentTransmitSpecular(lightingResult.environmentTransmitSpecular, lightingData, cc_ambientSky.w);
|
||||
#endif
|
||||
|
||||
#if CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE
|
||||
LightingIntermediateData lightingDataTD;
|
||||
CCSurfacesGetLightingIntermediateDataTransmitDiffuse(lightingDataTD, lightingData, surfaceData);
|
||||
CCSurfacesLightingCalculateIntermediateData_PerLight(lightingDataTD, surfaceData, -cc_mainLitDir.xyz);
|
||||
CCSurfacesLightingCalculateDirectTransmitDiffuse(lightingResult.directTransmitDiffuse, lightingDataTD, cc_mainLitColor, lightingResult.shadow);
|
||||
CCSurfacesLightingCalculateEnvironmentTransmitDiffuse(lightingResult.environmentTransmitDiffuse, lightingDataTD, cc_ambientSky.w, lightingResult.ao, -cc_mainLitDir.xyz);
|
||||
#endif
|
||||
|
||||
#if CC_SURFACES_LIGHTING_TRT
|
||||
LightingIntermediateData lightingDataTRT;
|
||||
CCSurfacesGetLightingIntermediateDataTRT(lightingDataTRT, lightingData, surfaceData);
|
||||
CCSurfacesLightingCalculateIntermediateData_PerLight(lightingDataTRT, surfaceData, -cc_mainLitDir.xyz);
|
||||
CCSurfacesLightingCalculateDirectTRT(lightingResult.directTRT, lightingDataTRT, cc_mainLitColor, lightingResult.directSpecular);
|
||||
CCSurfacesLightingCalculateEnvironmentTRT(lightingResult.environmentTRT, lightingDataTRT, cc_ambientSky.w, lightingResult.environmentSpecular);
|
||||
|
||||
vec3 diff;
|
||||
SurfacesMaterialData surfaceDataTRT;
|
||||
CCSurfacesGetSurfacesMaterialDataTRT(surfaceDataTRT, surfaceData);
|
||||
CCSurfacesLightingInitializeColorWithLighting(diff, lightingResult.specularColorWithLightingTRT, surfaceDataTRT, lightingDataTRT);
|
||||
#endif
|
||||
|
||||
#if CC_SURFACES_LIGHTING_TT
|
||||
CCSurfacesLightingCalculateDirectTT(lightingResult, lightingData, cc_mainLitColor);
|
||||
#endif
|
||||
|
||||
// user-defined lighting model
|
||||
#ifdef CC_SURFACES_LIGHTING_MODIFY_FINAL_RESULT
|
||||
LightingMiscData miscData;
|
||||
miscData.lightType = LIGHT_TYPE_DIRECTIONAL;
|
||||
miscData.lightPos = vec3(0.0);
|
||||
miscData.lightDir = cc_mainLitDir.xyz;
|
||||
miscData.lightColorAndIntensity = cc_mainLitColor;
|
||||
miscData.lightSizeRangeAngle = vec4(0.0, 0.0, 0.0, 0.0);
|
||||
SurfacesLightingModifyFinalResult(lightingResult, lightingData, surfaceData, miscData);
|
||||
#endif
|
||||
}
|
||||
#if CC_ENABLE_CLUSTERED_LIGHT_CULLING
|
||||
// #todo: cluster related lighting flow, invoke after CCSurfacesLighting
|
||||
// use same code as additive-pass
|
||||
// void CCSurfacesLighting_Cluster(inout LightingResult lightingResult, in SurfacesMaterialData surfaceData, in vec2 shadowBias)
|
||||
// {
|
||||
// }
|
||||
#endif // cluster lighting
|
||||
#endif // base pass
|
||||
#endif // forward shading
|
||||
|
||||
@@ -6,7 +6,15 @@
|
||||
|
||||
bool CCSurfacesLightingEnableShadow(in float NoL)
|
||||
{
|
||||
#if CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE
|
||||
// for back light shadows
|
||||
return true;
|
||||
#elif CC_SURFACES_LIGHTING_SSS
|
||||
// for over-bumped surfaces
|
||||
return true;
|
||||
#else
|
||||
return NoL > 0.0;
|
||||
#endif
|
||||
}
|
||||
|
||||
float CCSurfacesLightingCalculateDistanceAttenuation(in LightingIntermediateData lightingData, in vec4 lightSizeRangeAngle, in float lightType)
|
||||
@@ -21,13 +29,13 @@ float CCSurfacesLightingCalculateAngleAttenuation(in LightingIntermediateData li
|
||||
|
||||
void CCSurfacesLightingCalculateDirect(out vec3 lightingDiffuse, out vec3 lightingSpecular, in LightingIntermediateData lightingData, in vec4 lightSourceColorAndIntensity)
|
||||
{
|
||||
#if CC_SURFACES_LIGHTING_CALCULATE_DIFFUSE
|
||||
#if !CC_SURFACES_LIGHTING_DISABLE_DIFFUSE
|
||||
lightingDiffuse = CalculateDirectDiffuse(lightingData, lightSourceColorAndIntensity);
|
||||
#else
|
||||
lightingDiffuse = vec3(0.0);
|
||||
#endif
|
||||
|
||||
#if CC_SURFACES_LIGHTING_CALCULATE_SPECULAR
|
||||
#if !CC_SURFACES_LIGHTING_DISABLE_SPECULAR
|
||||
lightingSpecular = CalculateDirectSpecular(lightingData, lightSourceColorAndIntensity);
|
||||
#else
|
||||
lightingSpecular = vec3(0.0);
|
||||
@@ -37,13 +45,13 @@ void CCSurfacesLightingCalculateDirect(out vec3 lightingDiffuse, out vec3 lighti
|
||||
|
||||
void CCSurfacesLightingCalculateEnvironment(out vec3 lightingDiffuse, out vec3 lightingSpecular, in LightingIntermediateData lightingData, float lightIntensity)
|
||||
{
|
||||
#if CC_SURFACES_LIGHTING_CALCULATE_DIFFUSE
|
||||
#if !CC_SURFACES_LIGHTING_DISABLE_DIFFUSE
|
||||
lightingDiffuse = CalculateEnvironmentDiffuse(lightingData, lightIntensity);
|
||||
#else
|
||||
lightingDiffuse = vec3(0.0);
|
||||
#endif
|
||||
|
||||
#if CC_SURFACES_LIGHTING_CALCULATE_SPECULAR
|
||||
#if !CC_SURFACES_LIGHTING_DISABLE_SPECULAR
|
||||
lightingSpecular = CalculateEnvironmentSpecular(lightingData, lightIntensity);
|
||||
#else
|
||||
lightingSpecular = vec3(0.0);
|
||||
@@ -88,36 +96,59 @@ void CCSurfacesLightingCalculateEnvironment(out vec3 lightingDiffuse, out vec3 l
|
||||
envSpec = EnvReflection(cc_environment, R, roughness, cc_ambientGround.w);
|
||||
#endif
|
||||
|
||||
lightingSpecular = envSpec * lightIntensity;
|
||||
|
||||
// scattering
|
||||
float distance = lightingData.transmitParams.w, inScatterCoef = lightingData.transmitParams.z;
|
||||
vec2 e = lightingData.transmitParams.xy;
|
||||
vec2 extinction = exp(-e * distance * vec2(1.0, inScatterCoef));
|
||||
vec3 inScattered = (1.0 - extinction.y) * lightingData.inScatteringLightColor.rgb;
|
||||
lightingSpecular = lightingSpecular * extinction.x + inScattered;
|
||||
lightingSpecular = CalculateScattering(envSpec * lightIntensity, lightingData.transmitScatteringParams.w, lightingData.transmitScatteringParams.x, lightingData.transmitScatteringParams.x, lightingData.transmitScatteringParams.y, lightingData.inScatteringColor.rgb, lightingData.outScatteringColor.rgb);
|
||||
}
|
||||
#endif
|
||||
|
||||
#if CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE
|
||||
void CCSurfacesLightingCalculateDirectTransmitDiffuse(out vec3 transmitDiffuse, in LightingResult lightingResult, in LightingIntermediateData lightingData, in vec4 lightSourceColorAndIntensity)
|
||||
#define objectThickness lightingData.transmitDiffuseParams.x
|
||||
#define transmitMask lightingData.transmitDiffuseParams.y
|
||||
#define envTransmitScale lightingData.transmitDiffuseParams.z
|
||||
#define envFixedDistanceScale lightingData.transmitScatteringParams.w
|
||||
#define transmitDistanceScale lightingData.transmitDiffuseParams.w
|
||||
#define DONOT_USE_SHADOWMAP_DISTANCE (equalf(lightingData.shadowPosAndDepth.z, lightingData.shadowPosAndDepth.w) && equalf(lightingData.shadowPosAndDepth.z, SURFACES_MAX_TRANSMIT_DEPTH_VALUE))
|
||||
// view space depth is negative value, so use shadowMap - current
|
||||
#define SHADOWMAP_DISTANCE max(lightingData.shadowPosAndDepth.w - lightingData.shadowPosAndDepth.z, 0.0)
|
||||
//clamp(lightingData.shadowPosAndDepth.w - lightingData.shadowPosAndDepth.z, lightingData.transmitDiffuseParams.z, lightingData.transmitDiffuseParams.w)
|
||||
|
||||
void CCSurfacesLightingCalculateDirectTransmitDiffuse(out vec3 transmitDiffuse, in LightingIntermediateData lightingData, in vec4 lightSourceColorAndIntensity, float shadow)
|
||||
{
|
||||
vec3 backIrradiance = vec3(saturate(-lightingData.NoL)) * lightSourceColorAndIntensity.rgb * lightSourceColorAndIntensity.w;
|
||||
vec3 transmitDiffuse = backIrradiance * DiffuseCoefficient_EnergyConservation;
|
||||
//todo: add some
|
||||
lightingData.transmitParams;
|
||||
lightingData.transmitDiffuseParams;
|
||||
transmitDiffuse = vec3(0.0);
|
||||
float distance = lightingData.transmitScatteringParams.w;
|
||||
if (!DONOT_USE_SHADOWMAP_DISTANCE)
|
||||
{
|
||||
distance = transmitDistanceScale * SHADOWMAP_DISTANCE;
|
||||
shadow = step(SHADOWMAP_DISTANCE, objectThickness) > 0.0 ? 1.0 : shadow;
|
||||
}
|
||||
|
||||
vec3 backIrradiance = CalculateDirectDiffuse(lightingData, lightSourceColorAndIntensity);
|
||||
backIrradiance *= shadow * transmitMask;
|
||||
transmitDiffuse = CalculateScattering(backIrradiance, distance, lightingData.transmitScatteringParams.x, lightingData.transmitScatteringParams.x, lightingData.transmitScatteringParams.y, lightingData.inScatteringColor.rgb, lightingData.outScatteringColor.rgb);
|
||||
}
|
||||
void CCSurfacesLightingCalculateEnvironmentTransmitDiffuse(out vec3 transmitDiffuse, in LightingResult lightingResult, in LightingIntermediateData lightingData, float lightIntensity)
|
||||
// depend on dir-light shadow direction, if there are some occluders in front of the light source, env transmit will dark
|
||||
void CCSurfacesLightingCalculateEnvironmentTransmitDiffuse(out vec3 transmitDiffuse, in LightingIntermediateData lightingData, float lightIntensity, float ao, vec3 shadowLightDirection)
|
||||
{
|
||||
// negativate lightingData.N before invoking CalculateEnvironmentDiffuse
|
||||
lightingData.N *= -1.0;
|
||||
float distance = lightingData.transmitScatteringParams.w;
|
||||
if (!DONOT_USE_SHADOWMAP_DISTANCE)
|
||||
{
|
||||
float shadowMapDistance = transmitDistanceScale * SHADOWMAP_DISTANCE;
|
||||
float fixedDistance = transmitDistanceScale * envFixedDistanceScale;
|
||||
// lerp between shadowmap distance and fix distance to fix shadow and normal direction not match
|
||||
float lerpCoef = saturate(dot(lightingData.N, shadowLightDirection));
|
||||
distance = mix(fixedDistance, shadowMapDistance, lerpCoef);
|
||||
}
|
||||
|
||||
vec3 backIrradiance = CalculateEnvironmentDiffuse(lightingData, lightIntensity);
|
||||
lightingData.transmitParams;
|
||||
lightingData.transmitDiffuseParams;
|
||||
transmitDiffuse = vec3(0.0); //backIrradiance * lightingResult.ao;
|
||||
}
|
||||
backIrradiance *= ao * transmitMask;
|
||||
transmitDiffuse = CalculateScattering(backIrradiance, distance, lightingData.transmitScatteringParams.x, lightingData.transmitScatteringParams.x, lightingData.transmitScatteringParams.y, lightingData.inScatteringColor.rgb, lightingData.outScatteringColor.rgb);
|
||||
transmitDiffuse *= envTransmitScale;
|
||||
}
|
||||
|
||||
#undef objectThickness
|
||||
#undef transmitMask
|
||||
#undef envTransmitScale
|
||||
#undef envFixedDistanceScale
|
||||
#undef DONOT_USE_SHADOWMAP_DISTANCE
|
||||
#undef SHADOWMAP_DISTANCE
|
||||
#endif
|
||||
|
||||
#if CC_SURFACES_LIGHTING_TRT
|
||||
@@ -130,7 +161,7 @@ void CCSurfacesLightingCalculateEnvironment(out vec3 lightingDiffuse, out vec3 l
|
||||
}
|
||||
#endif
|
||||
|
||||
void CCSurfacesLightingCalculateDirectTRT(out vec3 TRTLighting, in LightingIntermediateData lightingData, in vec4 lightSourceColorAndIntensity)
|
||||
void CCSurfacesLightingCalculateDirectTRT(out vec3 TRTLighting, in LightingIntermediateData lightingData, in vec4 lightSourceColorAndIntensity, in vec3 originalSpecular)
|
||||
{
|
||||
vec3 unused;
|
||||
// light color has less influence
|
||||
@@ -139,9 +170,10 @@ void CCSurfacesLightingCalculateEnvironment(out vec3 lightingDiffuse, out vec3 l
|
||||
vec3 Color = SurfacesLightingGetTRTSpecularColor(brdf, true);
|
||||
// todo: modify Color to add some light color influence
|
||||
TRTLighting *= Color * lightSourceColorAndIntensity.w;
|
||||
// TRTLighting -= originalSpecular;
|
||||
}
|
||||
|
||||
void CCSurfacesLightingCalculateEnvironmentTRT(out vec3 TRTLighting, in LightingIntermediateData lightingData, float lightIntensity)
|
||||
void CCSurfacesLightingCalculateEnvironmentTRT(out vec3 TRTLighting, in LightingIntermediateData lightingData, float lightIntensity, in vec3 originalSpecular)
|
||||
{
|
||||
vec3 unused;
|
||||
// light color has less influence
|
||||
@@ -150,6 +182,7 @@ void CCSurfacesLightingCalculateEnvironment(out vec3 lightingDiffuse, out vec3 l
|
||||
vec3 Color = SurfacesLightingGetTRTSpecularColor(brdf, false);
|
||||
// todo: modify Color to add some light color influence
|
||||
TRTLighting *= Color * lightIntensity;
|
||||
// TRTLighting -= originalSpecular;
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ void CCSurfacesGetFragmentInput(out SurfacesStandardFragmentInput fsInput)
|
||||
// Use macros instead of structure to avoid structure precision issues
|
||||
#define FSInput_worldPos v_worldPos
|
||||
#define FSInput_worldNormal v_normal.xyz
|
||||
#define FSInput_faceSideSign v_normal.w
|
||||
#define FSInput_faceSideSign v_normal.w // physical face side, has no relation to USE_TWO_SIDED
|
||||
#define FSInput_texcoord v_uv
|
||||
|
||||
#if CC_SURFACES_USE_VERTEX_COLOR
|
||||
|
||||
+2
-1
@@ -80,7 +80,8 @@ void main() {
|
||||
|
||||
// only base pass or direct lighting is enabled in add pass
|
||||
#if CC_FORWARD_ADD
|
||||
if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_DIRECT_DIFFUSE) || IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_DIRECT_SPECULAR) || IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_DIRECT_ALL))
|
||||
if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_DIRECT_DIFFUSE) || IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_DIRECT_SPECULAR) || IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_DIRECT_ALL) ||
|
||||
IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_TRANSMIT_DIRECT_DIFFUSE) || IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_TRANSMIT_DIRECT_SPECULAR) || IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_TRT_DIRECT))
|
||||
#endif
|
||||
{
|
||||
if (CCSurfacesDebugViewLightingResult(debugColor, lightingResult))
|
||||
|
||||
@@ -20,8 +20,8 @@ struct SurfacesMaterialData
|
||||
#endif
|
||||
|
||||
#if CC_SURFACES_LIGHTING_TRANSMIT_SPECULAR || CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE
|
||||
vec3 inScatteringLightColor;
|
||||
vec4 transmitParams;
|
||||
vec3 outScatteringColor, inScatteringColor;
|
||||
vec4 transmitScatteringParams;
|
||||
#endif
|
||||
#if CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE
|
||||
vec4 transmitDiffuseParams;
|
||||
@@ -29,11 +29,13 @@ struct SurfacesMaterialData
|
||||
#if CC_SURFACES_LIGHTING_TRT
|
||||
vec3 baseColorTRT;
|
||||
float trtIntensity, roughnessTRT;
|
||||
vec3 worldTangentTRT, worldBinormalTRT;
|
||||
vec3 worldNormalTRT, worldTangentTRT, worldBinormalTRT;
|
||||
#endif
|
||||
#if CC_SURFACES_LIGHTING_TT
|
||||
vec3 baseColorTT;
|
||||
float ttIntensity, ttScatterCoef;
|
||||
#endif
|
||||
// float sssCurvature;
|
||||
#if CC_SURFACES_LIGHTING_SSS
|
||||
vec4 sssParams;
|
||||
#endif
|
||||
};
|
||||
|
||||
@@ -70,24 +70,47 @@ vec4 SurfacesFragmentModifyPBRParams()
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifndef CC_SURFACES_FRAGMENT_MODIFY_TRANSMIT_PARAMS
|
||||
void SurfacesFragmentModifyTransmitParams(out vec4 transmitParams, out vec3 inScatteringLightColor)
|
||||
#ifndef CC_SURFACES_FRAGMENT_MODIFY_TRANSMIT_SCATTERING_PARAMS
|
||||
// scattering related parameters and colors
|
||||
vec4 SurfacesFragmentModifyTransmitScatteringParams()
|
||||
{
|
||||
// xy: extinction coef for out/in-scattering (should be same)
|
||||
// z: in-scattering coef (constant phase function)
|
||||
// w: transmit distance(water depth, leaf thickness)
|
||||
transmitParams = vec4(0.0, 0.0, 0.0, 0.0);
|
||||
inScatteringLightColor = vec3(0.0);
|
||||
// x: extinction coef for out/in-scattering, 0 means disable scattering, thin object needs larger value such as 100-1000
|
||||
// y: in-scattering coef (constant phase function)
|
||||
// z: transmit normal type, default is 1 means using back face normal, 0 means using view-dependent normal, for shapeless materials such as hair
|
||||
// w: transmit distance, depending on CC_SURFACES_LIGHTING_USE_SHADOWMAP_TRANSMIT macro value:
|
||||
// macro is 0: affect direct / env transmit lighting, 0 means disable scattering, (water depth, leaf / hair thicknessMap, ear / nose thicknessMap)
|
||||
// macro is 1: only affect env transmit when shadow dir not match back normal (actual mesh thickness for ear / nose, nephrite)
|
||||
return vec4(1.0, 1.0, 1.0, 1.0);
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifndef CC_SURFACES_FRAGMENT_MODIFY_TRANSMIT_IN_SCATTERING_COLOR
|
||||
vec3 SurfacesFragmentModifyTransmitInScatteringColor()
|
||||
{
|
||||
// added light multiplier
|
||||
return vec3(0.0);
|
||||
}
|
||||
#endif
|
||||
#ifndef CC_SURFACES_FRAGMENT_MODIFY_TRANSMIT_OUT_SCATTERING_COLOR
|
||||
vec3 SurfacesFragmentModifyTransmitOutScatteringColor()
|
||||
{
|
||||
// transmit background multiplier
|
||||
return vec3(1.0);
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifndef CC_SURFACES_FRAGMENT_MODIFY_TRANSMIT_DIFFUSE_PARAMS
|
||||
vec4 SurfacesFragmentModifyTransmitDiffuseParams()
|
||||
{
|
||||
// x: transmit irradiance apply shadow
|
||||
// y: additional transmit depth mask, add light transport for area which cannot be covered by shadowmap transmittance, or stand for thin transmittance
|
||||
// zw: min/max DepthWS for shadowmap, 0 means disable shadow transmit
|
||||
return vec4(1.0, 0.0, 0.0, 0.0);
|
||||
// this param valid only when CC_SURFACES_LIGHTING_USE_SHADOWMAP_TRANSMIT is 1
|
||||
// material should use cull none for shadow caster pass, and enable shadow casting and receive shadow
|
||||
|
||||
// x: object (material part) thickness (worldspace unit bounding box max length), apply shadows for backlit only when shadowmap distance > object thickness, 0 means always apply shadows(thin object), SURFACES_MAX_TRANSMIT_DEPTH_VALUE means do not apply shadows.
|
||||
// notice: setting too small a value for thick objects, no transmit light will disappear.
|
||||
// y: transmit area mask, limit area to avoid shadowmap coverage precision artifacts, default 1.0 means enable full transmit, and gradient value makes transmit lighting look smoother
|
||||
// z: environment transmit scale, useless (env transmit is not accuracy, some material should give 0 to disable, or use area mask instead)
|
||||
// w: shadowmap transmit distance scale, useless
|
||||
return vec4(1.0, 1.0, 1.0, 1.0);
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -123,6 +146,17 @@ vec3 SurfacesFragmentModifyTTColor(in vec3 baseColor, in vec3 trtColor)
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifndef CC_SURFACES_FRAGMENT_MODIFY_SSS_PARAMS
|
||||
vec4 SurfacesFragmentModifySSSParams()
|
||||
{
|
||||
// x: sssIntensity, moisture
|
||||
// y: sssCurvature, for preintegrated sss
|
||||
// z: sssColoration, for sss transmitted light color with dark area
|
||||
// w: cavity for specular
|
||||
return vec4(1.0, 0.1, 1.0, 1.0);
|
||||
}
|
||||
#endif
|
||||
|
||||
// some material datas use shared raw data, avoid sample / calculate same raw data multiply times, use this function for better performance
|
||||
// this function invokes at last
|
||||
// should use corresponding shading-model header: #include <surfaces/data-structures/XXX> before function define
|
||||
|
||||
@@ -71,6 +71,9 @@
|
||||
#ifndef CC_SURFACES_LIGHTING_TT
|
||||
#define CC_SURFACES_LIGHTING_TT 0
|
||||
#endif
|
||||
#ifndef CC_SURFACES_LIGHTING_SSS
|
||||
#define CC_SURFACES_LIGHTING_SSS 0
|
||||
#endif
|
||||
|
||||
// render-to-color-map can disable functionality to avoid error data map
|
||||
#ifndef CC_SURFACES_ENABLE_DEBUG_VIEW
|
||||
@@ -78,9 +81,11 @@
|
||||
#endif
|
||||
|
||||
// for skin
|
||||
#ifndef CC_SURFACES_LIGHTING_CALCULATE_DIFFUSE
|
||||
#define CC_SURFACES_LIGHTING_CALCULATE_DIFFUSE 1
|
||||
/*
|
||||
#ifndef CC_SURFACES_LIGHTING_DISABLE_DIFFUSE
|
||||
#define CC_SURFACES_LIGHTING_DISABLE_DIFFUSE 0
|
||||
#endif
|
||||
#ifndef CC_SURFACES_LIGHTING_CALCULATE_SPECULAR
|
||||
#define CC_SURFACES_LIGHTING_CALCULATE_SPECULAR 1
|
||||
#ifndef CC_SURFACES_LIGHTING_DISABLE_SPECULAR
|
||||
#define CC_SURFACES_LIGHTING_DISABLE_SPECULAR 0
|
||||
#endif
|
||||
*/
|
||||
|
||||
@@ -35,7 +35,9 @@ void CCSurfacesFragmentGetMaterialData(inout SurfacesMaterialData surfaceData)
|
||||
surfaceData.specularIntensity = pbr.w;
|
||||
|
||||
#if CC_SURFACES_LIGHTING_TRANSMIT_SPECULAR || CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE
|
||||
SurfacesFragmentModifyTransmitParams(surfaceData.transmitParams, surfaceData.inScatteringLightColor);
|
||||
surfaceData.transmitScatteringParams = SurfacesFragmentModifyTransmitScatteringParams();
|
||||
surfaceData.inScatteringColor = SurfacesFragmentModifyTransmitInScatteringColor();
|
||||
surfaceData.outScatteringColor = SurfacesFragmentModifyTransmitOutScatteringColor();
|
||||
#endif
|
||||
#if CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE
|
||||
surfaceData.transmitDiffuseParams = SurfacesFragmentModifyTransmitDiffuseParams();
|
||||
@@ -47,9 +49,10 @@ void CCSurfacesFragmentGetMaterialData(inout SurfacesMaterialData surfaceData)
|
||||
surfaceData.roughnessTRT = saturate(surfaceData.roughness + trtParams.x);
|
||||
surfaceData.trtIntensity = trtParams.w;
|
||||
surfaceData.baseColorTRT = baseColorTRT = SurfacesFragmentModifyTRTColor();
|
||||
surfaceData.worldNormalTRT = surfaceData.worldNormal;
|
||||
surfaceData.worldTangentTRT = surfaceData.worldTangent;
|
||||
surfaceData.worldBinormalTRT = surfaceData.worldBinormal;
|
||||
RotateTangentAndBinormal(surfaceData.worldTangentTRT, surfaceData.worldBinormalTRT, surfaceData.worldNormal, trtParams.y * PI);
|
||||
RotateNormalAndBinormal(surfaceData.worldBinormalTRT, surfaceData.worldNormalTRT, surfaceData.worldTangentTRT, trtParams.y);
|
||||
#endif
|
||||
|
||||
#if CC_SURFACES_LIGHTING_TT
|
||||
@@ -59,6 +62,10 @@ void CCSurfacesFragmentGetMaterialData(inout SurfacesMaterialData surfaceData)
|
||||
surfaceData.baseColorTT = SurfacesFragmentModifyTTColor(surfaceData.baseColor.rgb, baseColorTRT);
|
||||
#endif
|
||||
|
||||
#if CC_SURFACES_LIGHTING_SSS
|
||||
surfaceData.sssParams = SurfacesFragmentModifySSSParams();
|
||||
#endif
|
||||
|
||||
SurfacesFragmentModifySharedData(surfaceData);
|
||||
|
||||
#if CC_USE_DEBUG_VIEW == CC_SURFACES_DEBUG_VIEW_COMPOSITE_AND_MISC
|
||||
@@ -120,8 +127,9 @@ void CCSurfacesInitializeLightingIntermediateData(inout LightingIntermediateData
|
||||
lightingData.specularParam = surfaceData.roughness;
|
||||
lightingData.ior = surfaceData.ior;
|
||||
#if CC_SURFACES_LIGHTING_TRANSMIT_SPECULAR || CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE
|
||||
lightingData.transmitParams = surfaceData.transmitParams;
|
||||
lightingData.inScatteringLightColor = surfaceData.inScatteringLightColor;
|
||||
lightingData.transmitScatteringParams = surfaceData.transmitScatteringParams;
|
||||
lightingData.inScatteringColor = surfaceData.inScatteringColor;
|
||||
lightingData.outScatteringColor = surfaceData.outScatteringColor;
|
||||
#endif
|
||||
#if CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE
|
||||
lightingData.transmitDiffuseParams = surfaceData.transmitDiffuseParams;
|
||||
@@ -138,12 +146,25 @@ void CCSurfacesLightingCalculateIntermediateData_PerLight(inout LightingIntermed
|
||||
CCSurfacesLightingGetIntermediateData_PerLight(lightingData, lightDirWithDist);
|
||||
}
|
||||
|
||||
// pass original lightingData, get TRT lightingData
|
||||
#if CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE
|
||||
// pass original lightingData, get TD lightingData
|
||||
void CCSurfacesGetLightingIntermediateDataTransmitDiffuse(inout LightingIntermediateData lightingDataTD, in LightingIntermediateData lightingData, in SurfacesMaterialData surfaceData)
|
||||
{
|
||||
lightingDataTD = lightingData;
|
||||
// view-depenedent mode make sure normal always back from view direction
|
||||
// (-N) + (-V) for smoother result
|
||||
lightingDataTD.N = lightingData.transmitScatteringParams.z > 0.0 ? -lightingData.N : -normalize(lightingData.N+lightingData.V);
|
||||
}
|
||||
#endif
|
||||
|
||||
#if CC_SURFACES_LIGHTING_TRT
|
||||
// pass original lightingData, get TRT lightingData
|
||||
void CCSurfacesGetLightingIntermediateDataTRT(inout LightingIntermediateData lightingDataTRT, in LightingIntermediateData lightingData, in SurfacesMaterialData surfaceData)
|
||||
{
|
||||
lightingDataTRT = lightingData;
|
||||
lightingDataTRT.specularParam = surfaceData.roughnessTRT;
|
||||
// new TBN with anisotropic offset
|
||||
lightingDataTRT.N = surfaceData.worldNormalTRT;
|
||||
lightingDataTRT.T = surfaceData.worldTangentTRT;
|
||||
lightingDataTRT.B = surfaceData.worldBinormalTRT;
|
||||
}
|
||||
@@ -228,10 +249,19 @@ vec4 CCSurfacesShading(in SurfacesMaterialData surfaceData, in LightingResult li
|
||||
#if CC_FORWARD_ADD
|
||||
// shadow and fresnel has already been applied with common flow
|
||||
color.xyz += lightingResult.directDiffuse * lightingResult.diffuseColorWithLighting
|
||||
+ lightingResult.directSpecular * lightingResult.specularColorWithLighting;
|
||||
+ lightingResult.directSpecular * lightingResult.specularColorWithLighting
|
||||
#if CC_SURFACES_LIGHTING_TRANSMIT_SPECULAR
|
||||
+ lightingResult.directTransmitSpecular * lightingResult.specularColorWithLighting
|
||||
#endif
|
||||
#if CC_SURFACES_LIGHTING_TRT
|
||||
+ lightingResult.directTRT * lightingResult.specularColorWithLightingTRT * surfaceData.trtIntensity * surfaceData.baseColorTRT
|
||||
#endif
|
||||
#if CC_SURFACES_LIGHTING_TT
|
||||
+ lightingResult.directTT * lightingResult.diffuseColorWithLightingTT
|
||||
#endif
|
||||
#if CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE
|
||||
+ lightingResult.directTransmitDiffuse
|
||||
#endif
|
||||
;
|
||||
|
||||
#else
|
||||
@@ -247,9 +277,6 @@ vec4 CCSurfacesShading(in SurfacesMaterialData surfaceData, in LightingResult li
|
||||
#if CC_SURFACES_LIGHTING_TRANSMIT_SPECULAR
|
||||
+ lightingResult.directTransmitSpecular * lightingResult.specularColorWithLighting * invFresnel
|
||||
#endif
|
||||
#if CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE
|
||||
+ lightingResult.directTransmitDiffuse
|
||||
#endif
|
||||
#if CC_SURFACES_LIGHTING_TRT
|
||||
+ lightingResult.directTRT * lightingResult.specularColorWithLightingTRT * surfaceData.trtIntensity * surfaceData.baseColorTRT
|
||||
#endif
|
||||
@@ -257,7 +284,11 @@ vec4 CCSurfacesShading(in SurfacesMaterialData surfaceData, in LightingResult li
|
||||
+ lightingResult.directTT * lightingResult.diffuseColorWithLightingTT
|
||||
#endif
|
||||
)
|
||||
* lightingResult.shadow;
|
||||
* lightingResult.shadow
|
||||
#if CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE
|
||||
+ lightingResult.directTransmitDiffuse
|
||||
#endif
|
||||
;
|
||||
|
||||
#if CC_SURFACES_USE_LIGHT_MAP == LIGHT_MAP_TYPE_ALL_IN_ONE
|
||||
color.xyz += lightingResult.lightmapColor * lightingResult.diffuseColorWithLighting * lightingResult.shadow; //apply real-time shadows
|
||||
@@ -271,15 +302,16 @@ vec4 CCSurfacesShading(in SurfacesMaterialData surfaceData, in LightingResult li
|
||||
#if CC_SURFACES_LIGHTING_TRANSMIT_SPECULAR
|
||||
+ lightingResult.environmentTransmitSpecular * lightingResult.specularColorWithLighting * invFresnel
|
||||
#endif
|
||||
#if CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE
|
||||
+ lightingResult.environmentTransmitDiffuse
|
||||
#endif
|
||||
#if CC_SURFACES_LIGHTING_TRT
|
||||
+ lightingResult.environmentTRT * lightingResult.specularColorWithLightingTRT * surfaceData.trtIntensity * surfaceData.baseColorTRT
|
||||
#endif
|
||||
)
|
||||
* lightingResult.ao;
|
||||
|
||||
* lightingResult.ao
|
||||
#if CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE
|
||||
+ lightingResult.environmentTransmitDiffuse
|
||||
#endif
|
||||
;
|
||||
|
||||
color.xyz += lightingResult.emissive;
|
||||
#endif
|
||||
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"ver": "1.1.0",
|
||||
"importer": "directory",
|
||||
"imported": true,
|
||||
"uuid": "a2f1d438-9a65-445b-8a7e-3d293e503909",
|
||||
"files": [],
|
||||
"subMetas": {},
|
||||
"userData": {
|
||||
"compressionType": {},
|
||||
"isRemoteBundle": {}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"ver": "1.1.0",
|
||||
"importer": "directory",
|
||||
"imported": true,
|
||||
"uuid": "7825b695-4eed-444c-bf07-d33a772883b1",
|
||||
"files": [],
|
||||
"subMetas": {},
|
||||
"userData": {
|
||||
"compressionType": {},
|
||||
"isRemoteBundle": {}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"ver": "1.1.0",
|
||||
"importer": "directory",
|
||||
"imported": true,
|
||||
"uuid": "e846becb-4080-4ba3-9b67-75d45b7998d5",
|
||||
"files": [],
|
||||
"subMetas": {},
|
||||
"userData": {
|
||||
"compressionType": {},
|
||||
"isRemoteBundle": {}
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 16 KiB |
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"ver": "1.0.25",
|
||||
"importer": "image",
|
||||
"imported": true,
|
||||
"uuid": "b078dcad-656d-4ba3-b76e-70c88e63e045",
|
||||
"files": [
|
||||
".json",
|
||||
".png"
|
||||
],
|
||||
"subMetas": {
|
||||
"6c48a": {
|
||||
"importer": "texture",
|
||||
"uuid": "b078dcad-656d-4ba3-b76e-70c88e63e045@6c48a",
|
||||
"displayName": "preintegrated-skin",
|
||||
"id": "6c48a",
|
||||
"name": "texture",
|
||||
"userData": {
|
||||
"wrapModeS": "clamp-to-edge",
|
||||
"wrapModeT": "clamp-to-edge",
|
||||
"minfilter": "linear",
|
||||
"magfilter": "linear",
|
||||
"mipfilter": "none",
|
||||
"anisotropy": 0,
|
||||
"isUuid": true,
|
||||
"imageUuidOrDatabaseUri": "b078dcad-656d-4ba3-b76e-70c88e63e045",
|
||||
"visible": true
|
||||
},
|
||||
"ver": "1.0.22",
|
||||
"imported": true,
|
||||
"files": [
|
||||
".json"
|
||||
],
|
||||
"subMetas": {}
|
||||
}
|
||||
},
|
||||
"userData": {
|
||||
"fixAlphaTransparencyArtifacts": false,
|
||||
"hasAlpha": false,
|
||||
"type": "texture",
|
||||
"redirect": "b078dcad-656d-4ba3-b76e-70c88e63e045@6c48a"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
// include this file after all fragment surface functions definition
|
||||
// not contain anisotropic params
|
||||
|
||||
#ifndef CC_SURFACES_FRAGMENT_MODIFY_BASECOLOR_AND_TRANSPARENCY
|
||||
#define CC_SURFACES_FRAGMENT_MODIFY_BASECOLOR_AND_TRANSPARENCY
|
||||
vec4 SurfacesFragmentModifyBaseColorAndTransparency()
|
||||
{
|
||||
vec4 baseColor = albedo;
|
||||
|
||||
#if USE_VERTEX_COLOR
|
||||
baseColor.rgb *= SRGBToLinear(FSInput_vertexColor.rgb); // use linear
|
||||
baseColor.a *= FSInput_vertexColor.a;
|
||||
#endif
|
||||
|
||||
#if USE_ALBEDO_MAP
|
||||
vec4 texColor = texture(albedoMap, ALBEDO_UV);
|
||||
texColor.rgb = SRGBToLinear(texColor.rgb);
|
||||
baseColor *= texColor;
|
||||
#endif
|
||||
|
||||
#if USE_ALPHA_TEST
|
||||
if (baseColor.ALPHA_TEST_CHANNEL < albedoScaleAndCutoff.w) discard;
|
||||
#endif
|
||||
|
||||
baseColor.rgb *= albedoScaleAndCutoff.xyz;
|
||||
return baseColor;
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifndef CC_SURFACES_FRAGMENT_ALPHA_CLIP_ONLY
|
||||
#define CC_SURFACES_FRAGMENT_ALPHA_CLIP_ONLY
|
||||
void SurfacesFragmentAlphaClipOnly()
|
||||
{
|
||||
#if USE_ALPHA_TEST
|
||||
float alpha = albedo.ALPHA_TEST_CHANNEL;
|
||||
#if USE_VERTEX_COLOR
|
||||
alpha *= FSInput_vertexColor.a;
|
||||
#endif
|
||||
#if USE_ALBEDO_MAP
|
||||
alpha = texture(albedoMap, ALBEDO_UV).ALPHA_TEST_CHANNEL;
|
||||
#endif
|
||||
|
||||
if (alpha < albedoScaleAndCutoff.w) discard;
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifndef CC_SURFACES_FRAGMENT_MODIFY_WORLD_NORMAL
|
||||
#define CC_SURFACES_FRAGMENT_MODIFY_WORLD_NORMAL
|
||||
vec3 SurfacesFragmentModifyWorldNormal()
|
||||
{
|
||||
vec3 normal = FSInput_worldNormal;
|
||||
#if USE_NORMAL_MAP
|
||||
vec3 nmmp = texture(normalMap, NORMAL_UV).xyz - vec3(0.5);
|
||||
normal = CalculateNormalFromTangentSpace(nmmp, emissiveScaleParam.w, normal.xyz, FSInput_worldTangent, FSInput_mirrorNormal);
|
||||
#endif
|
||||
|
||||
return normalize(normal);
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifndef CC_SURFACES_FRAGMENT_MODIFY_EMISSIVE
|
||||
#define CC_SURFACES_FRAGMENT_MODIFY_EMISSIVE
|
||||
vec3 SurfacesFragmentModifyEmissive()
|
||||
{
|
||||
vec3 emissive = emissive.rgb;
|
||||
#if USE_EMISSIVE_MAP
|
||||
emissive = SRGBToLinear(texture(emissiveMap, EMISSIVE_UV).rgb);
|
||||
#endif
|
||||
return emissive * emissiveScaleParam.xyz;
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifndef CC_SURFACES_FRAGMENT_MODIFY_PBRPARAMS
|
||||
#define CC_SURFACES_FRAGMENT_MODIFY_PBRPARAMS
|
||||
vec4 SurfacesFragmentModifyPBRParams()
|
||||
{
|
||||
vec4 pbr = pbrParams;
|
||||
pbr.x = 1.0;
|
||||
#if USE_PBR_MAP
|
||||
vec4 res = texture(pbrMap, DEFAULT_UV);
|
||||
pbr.x *= res.OCCLUSION_CHANNEL;
|
||||
pbr.y *= res.ROUGHNESS_CHANNEL;
|
||||
pbr.z *= res.METALLIC_CHANNEL;
|
||||
pbr.w *= res.SPECULAR_INTENSITY_CHANNEL;
|
||||
#endif
|
||||
#if USE_OCCLUSION_MAP
|
||||
pbr.x = mix(1.0, texture(occlusionMap, DEFAULT_UV).OCCLUSION_CHANNEL, pbrParams.x);
|
||||
#endif
|
||||
|
||||
return pbr;
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"ver": "1.0.7",
|
||||
"importer": "effect-header",
|
||||
"imported": true,
|
||||
"uuid": "ded549ec-b5b6-4d05-ba54-9b3ea427a58c",
|
||||
"files": [],
|
||||
"subMetas": {},
|
||||
"userData": {}
|
||||
}
|
||||
@@ -17,22 +17,27 @@ CCEffect %{
|
||||
specularIntensity: { value: 0.5, target: pbrParams.w, editor: { slide: true, range: [0.0, 1.0], step: 0.001 } }
|
||||
emissive: { value: [0.0, 0.0, 0.0, 1.0], linear: true, editor: { type: color } }
|
||||
emissiveScale: { value: [1.0, 1.0, 1.0], target: emissiveScaleParam.xyz }
|
||||
normalStrength: { value: 1.0, target: emissiveScaleParam.w, editor: { parent: USE_NORMAL_MAP, slide: true, range: [0, 5.0], step: 0.001 } }
|
||||
normalStrength: { value: 0.4, target: emissiveScaleParam.w, editor: { parent: USE_NORMAL_MAP, slide: true, range: [0, 5.0], step: 0.001 } }
|
||||
anisotropyIntensity: { value: 1.0, target: anisotropyParam.x, editor: { slide : true, range : [0.0, 1.0] , step : 0.0001 } }
|
||||
anisotropyRotation: { value: 0.0, target: anisotropyParam.y, editor: { slide : true, range : [0, 1.0] , step : 0.0001 } }
|
||||
mainTexture: { value: grey, target: albedoMap, editor: { displayName: AlbedoMap } }
|
||||
transparencyMap: { value: white, editor: { parent: USE_TRANSPRENCY_MAP, displayName: AlbedoMap } }
|
||||
normalMap: { value: normal }
|
||||
pbrMap: { value: grey }
|
||||
occlusionMap: { value: white }
|
||||
emissiveMap: { value: grey }
|
||||
anisotropyMap: { value: black }
|
||||
roughnessTRT: { value: 0.2, target: trtParams.x, editor: { displayName: TRT Roughness Offset, slide: true, range: [0, 1.0], step: 0.001, tooltip: 'The extend range of internal reflection lighting around the direct specular' } }
|
||||
rotationTRT: { value: 0.0, target: trtParams.y, editor: { displayName: TRT Lighting Offset, slide: true, range: [0, 1.0], step: 0.001, tooltip: 'The position offset of internal reflection lighting compared to direct specular' } }
|
||||
offsetTRT: { value: 0.0, target: trtParams.y, editor: { displayName: TRT Lighting Offset, slide: true, range: [-0.5, 0.5], step: 0.001, tooltip: 'The position offset of internal reflection lighting compared to direct specular' } }
|
||||
IntensityTRT: { value: 1.0, target: trtParams.w, editor: { displayName: TRT Intensity, slide: true, range: [0, 5.0], step: 0.01 } }
|
||||
baseColorTRT: { value: [0.5, 0.33, 0.18, 1.0], target: trtColor, linear: true, editor: { displayName: TRT Albedo, type: color, tooltip: 'The color of internal reflection lighting' } }
|
||||
ScatterCoefTT: { value: 0.0, target: ttParams.x, editor: { displayName: TT Scatter Coef, slide: true, range: [0, 1.0], step: 0.01, tooltip: 'The saturation of internal transmit lighting color' } }
|
||||
IntensityTT: { value: 1.0, target: ttParams.w, editor: { displayName: TT Intensity, slide: true, range: [0, 1.0], step: 0.01 } }
|
||||
baseColorTT: { value: [0.5, 0.33, 0.18, 1.0], target: ttColor, linear: true, editor: { displayName: TT Albedo, type: color, tooltip: 'The color of internal transmit lighting, allow the light color to vary between backlit and light-facing areas' } }
|
||||
thickness: { value: 1.0, target: ttParams.y, editor: { displayName: Scatter Thickness, slide: true, range: [0, 1.0], step: 0.001, tooltip: 'The extend range of internal reflection lighting around the direct specular' } }
|
||||
extinction: { value: 0.0, target: ttParams.z, editor: { displayName: Scatter Extinction, slide: true, range: [0, 10.0], step: 0.001, tooltip: 'The position offset of internal reflection lighting compared to direct specular' } }
|
||||
depthMap: { value: white }
|
||||
selfShadowMap: { value: white, editor: { parent: USE_SELF_SHADOW_MAP } }
|
||||
rasterizerState:
|
||||
cullMode: None
|
||||
depthStencilState:
|
||||
@@ -139,11 +144,12 @@ CCEffect %{
|
||||
rasterizerState:
|
||||
cullMode: front
|
||||
properties:
|
||||
tilingOffset: { value: [1.0, 1.0, 0.0, 0.0] }
|
||||
mainColor: { value: [1.0, 1.0, 1.0, 1.0], target: albedo, editor: { displayName: Albedo, type: color } }
|
||||
albedoScale: { value: [1.0, 1.0, 1.0], target: albedoScaleAndCutoff.xyz }
|
||||
alphaThreshold: { value: 0.5, target: albedoScaleAndCutoff.w, editor: { parent: USE_ALPHA_TEST } }
|
||||
mainTexture: { value: grey, target: albedoMap, editor: { displayName: AlbedoMap } }
|
||||
tilingOffset: { value: [1.0, 1.0, 0.0, 0.0] }
|
||||
mainColor: { value: [1.0, 1.0, 1.0, 1.0], target: albedo, editor: { displayName: Albedo, type: color } }
|
||||
albedoScale: { value: [1.0, 1.0, 1.0], target: albedoScaleAndCutoff.xyz }
|
||||
alphaThreshold: { value: 0.5, target: albedoScaleAndCutoff.w, editor: { parent: USE_ALPHA_TEST } }
|
||||
mainTexture: { value: grey, target: albedoMap, editor: { displayName: AlbedoMap } }
|
||||
transparencyMap: { value: white, editor: { parent: USE_TRANSPRENCY_MAP, displayName: AlbedoMap } }
|
||||
- &reflect-map
|
||||
vert: standard-vs
|
||||
frag: reflect-map-fs
|
||||
@@ -199,6 +205,7 @@ CCProgram macro-remapping %{
|
||||
|
||||
#define CC_SURFACES_LIGHTING_TRT 1
|
||||
#define CC_SURFACES_LIGHTING_TT 1
|
||||
#define CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE 1
|
||||
#define CC_SURFACES_TRANSFER_CLIP_POS 1
|
||||
|
||||
// depend on UI macros
|
||||
@@ -211,47 +218,9 @@ CCProgram macro-remapping %{
|
||||
}%
|
||||
|
||||
CCProgram surface-vertex %{
|
||||
/*#define CC_SURFACES_VERTEX_MODIFY_WORLD_POS
|
||||
vec3 SurfacesVertexModifyWorldPos(in SurfacesStandardVertexIntermediate In)
|
||||
{
|
||||
vec3 worldPos = In.worldPos;
|
||||
worldPos.x += sin(cc_time.x * worldPos.z);
|
||||
worldPos.y += cos(cc_time.x * worldPos.z);
|
||||
return worldPos;
|
||||
}
|
||||
|
||||
#define CC_SURFACES_VERTEX_MODIFY_WORLD_NORMAL
|
||||
vec3 SurfacesVertexModifyWorldNormal(in SurfacesStandardVertexIntermediate In)
|
||||
{
|
||||
vec3 worldNormal = In.worldNormal.xyz;
|
||||
worldNormal.x += sin(cc_time.x * 3.0);
|
||||
worldNormal.y += cos(cc_time.x * 3.0);
|
||||
#if CC_SURFACES_USE_TWO_SIDED
|
||||
worldNormal.xyz *= In.worldNormal.w;
|
||||
#endif
|
||||
return normalize(worldNormal);
|
||||
}
|
||||
|
||||
// see <surfaces/default-functions/common-vs> for more overrided functions
|
||||
#define CC_SURFACES_VERTEX_MODIFY_SHARED_DATA
|
||||
void SurfacesVertexModifySharedData(inout SurfacesStandardVertexIntermediate In)
|
||||
{
|
||||
}
|
||||
*/
|
||||
|
||||
#define CC_SURFACES_VERTEX_MODIFY_UV
|
||||
void SurfacesVertexModifyUV(inout SurfacesStandardVertexIntermediate In)
|
||||
{
|
||||
In.texCoord = In.texCoord * tilingOffset.xy + tilingOffset.zw;
|
||||
#if CC_SURFACES_USE_SECOND_UV
|
||||
In.texCoord1 = In.texCoord1 * tilingOffset.xy + tilingOffset.zw;
|
||||
#endif
|
||||
}
|
||||
}%
|
||||
|
||||
CCProgram surface-fragment %{
|
||||
#include <common/effect/special-effects>
|
||||
|
||||
#if USE_ALBEDO_MAP
|
||||
uniform sampler2D albedoMap;
|
||||
#pragma define-meta ALBEDO_UV options([v_uv, v_uv1])
|
||||
@@ -271,9 +240,6 @@ CCProgram surface-fragment %{
|
||||
uniform sampler2D emissiveMap;
|
||||
#pragma define-meta EMISSIVE_UV options([v_uv, v_uv1])
|
||||
#endif
|
||||
#if IS_ANISOTROPY && USE_ANISOTROPY_MAP
|
||||
uniform sampler2D anisotropyMap;
|
||||
#endif
|
||||
|
||||
#pragma define OCCLUSION_CHANNEL r
|
||||
#pragma define ROUGHNESS_CHANNEL g
|
||||
@@ -284,6 +250,21 @@ CCProgram surface-fragment %{
|
||||
#pragma define-meta ALPHA_TEST_CHANNEL options([a, r])
|
||||
#endif
|
||||
|
||||
//////////////////User Defines
|
||||
#include <common/effect/special-effects>
|
||||
#if USE_TRANSPRENCY_MAP
|
||||
uniform sampler2D transparencyMap;
|
||||
#endif
|
||||
#if IS_ANISOTROPY && USE_ANISOTROPY_MAP
|
||||
uniform sampler2D anisotropyMap;
|
||||
#endif
|
||||
|
||||
#if USE_DEPTH_MAP
|
||||
uniform sampler2D depthMap;
|
||||
#endif
|
||||
#if USE_SELF_SHADOW_MAP
|
||||
uniform sampler2D selfShadowMap;
|
||||
#endif
|
||||
|
||||
#define CC_SURFACES_FRAGMENT_MODIFY_TRT_PARAMS
|
||||
vec4 SurfacesFragmentModifyTRTParams()
|
||||
@@ -308,6 +289,46 @@ CCProgram surface-fragment %{
|
||||
return mix(baseColor.rgb, ttColor.rgb, ttColor.a); //ttColor can be (0.992, 0.808, 0.516)
|
||||
}
|
||||
|
||||
#define CC_SURFACES_FRAGMENT_MODIFY_TRANSMIT_SCATTERING_PARAMS
|
||||
vec4 SurfacesFragmentModifyTransmitScatteringParams()
|
||||
{
|
||||
float depth = SURFACES_MAX_TRANSMIT_DEPTH_VALUE;
|
||||
depth = ttParams.y;
|
||||
#if USE_DEPTH_MAP
|
||||
// depth = texture(depthMap, FSInput_texcoord).x;
|
||||
// depth = pow(depth, 1.0);
|
||||
// depth = 1.0 - depth;
|
||||
// depth *= ttParams.y;
|
||||
#endif
|
||||
return vec4(ttParams.z, 0.0, 0.0, depth);
|
||||
}
|
||||
|
||||
#define CC_SURFACES_FRAGMENT_MODIFY_TRANSMIT_DIFFUSE_PARAMS
|
||||
vec4 SurfacesFragmentModifyTransmitDiffuseParams()
|
||||
{
|
||||
float mask = 1.0;
|
||||
#if USE_DEPTH_MAP
|
||||
mask = texture(depthMap, FSInput_texcoord).x;
|
||||
mask = pow(mask, 1.0);
|
||||
mask = 1.0 - mask;
|
||||
mask *= 10.0;
|
||||
// depth *= ttParams.y;
|
||||
#endif
|
||||
return vec4(1.0, mask, 0.0, 1.0);
|
||||
}
|
||||
|
||||
#define CC_SURFACES_FRAGMENT_MODIFY_TRANSMIT_IN_SCATTERING_COLOR
|
||||
vec3 SurfacesFragmentModifyTransmitInScatteringColor()
|
||||
{
|
||||
return vec3(0.0);
|
||||
}
|
||||
|
||||
#define CC_SURFACES_FRAGMENT_MODIFY_TRANSMIT_OUT_SCATTERING_COLOR
|
||||
vec3 SurfacesFragmentModifyTransmitOutScatteringColor()
|
||||
{
|
||||
return vec3(0.7, 0.5, 0.3);
|
||||
}
|
||||
|
||||
#define CC_SURFACES_FRAGMENT_MODIFY_BASECOLOR_AND_TRANSPARENCY
|
||||
vec4 SurfacesFragmentModifyBaseColorAndTransparency()
|
||||
{
|
||||
@@ -324,6 +345,10 @@ CCProgram surface-fragment %{
|
||||
baseColor *= texColor;
|
||||
#endif
|
||||
|
||||
#if USE_TRANSPRENCY_MAP
|
||||
baseColor.a = texture(transparencyMap, ALBEDO_UV).x;
|
||||
#endif
|
||||
|
||||
#if USE_DITHERED_ALPHA_TEST
|
||||
#if CC_SURFACES_TRANSFER_CLIP_POS
|
||||
DitheredAlphaClip(FSInput_clipPos, cc_viewPort.zw, baseColor.ALPHA_TEST_CHANNEL + (1.0 - albedoScaleAndCutoff.w));
|
||||
@@ -353,23 +378,14 @@ CCProgram surface-fragment %{
|
||||
#if USE_ALBEDO_MAP
|
||||
alpha = texture(albedoMap, ALBEDO_UV).ALPHA_TEST_CHANNEL;
|
||||
#endif
|
||||
|
||||
#if USE_TRANSPRENCY_MAP
|
||||
alpha = texture(transparencyMap, ALBEDO_UV).x;
|
||||
#endif
|
||||
|
||||
if (alpha < albedoScaleAndCutoff.w) discard;
|
||||
#endif
|
||||
}
|
||||
|
||||
#define CC_SURFACES_FRAGMENT_MODIFY_WORLD_NORMAL
|
||||
vec3 SurfacesFragmentModifyWorldNormal()
|
||||
{
|
||||
vec3 normal = FSInput_worldNormal;
|
||||
#if USE_NORMAL_MAP
|
||||
vec3 nmmp = texture(normalMap, NORMAL_UV).xyz - vec3(0.5);
|
||||
normal = CalculateNormalFromTangentSpace(nmmp, emissiveScaleParam.w, normal.xyz, FSInput_worldTangent, FSInput_mirrorNormal);
|
||||
#endif
|
||||
|
||||
return normalize(normal);
|
||||
}
|
||||
|
||||
#define CC_SURFACES_FRAGMENT_MODIFY_ANISOTROPY_PARAMS
|
||||
vec4 SurfacesFragmentModifyAnisotropyParams(out float isRotation)
|
||||
{
|
||||
@@ -386,52 +402,21 @@ CCProgram surface-fragment %{
|
||||
isRotation = 1.0;
|
||||
return vec4(anisotropyShape, anisotropyRotation, 0.0, 0.0);
|
||||
}
|
||||
|
||||
#include <common-functions>
|
||||
|
||||
#define CC_SURFACES_FRAGMENT_MODIFY_EMISSIVE
|
||||
vec3 SurfacesFragmentModifyEmissive()
|
||||
{
|
||||
vec3 emissive = emissive.rgb;
|
||||
#if USE_EMISSIVE_MAP
|
||||
emissive = SRGBToLinear(texture(emissiveMap, EMISSIVE_UV).rgb);
|
||||
#endif
|
||||
return emissive * emissiveScaleParam.xyz;
|
||||
}
|
||||
|
||||
#define CC_SURFACES_FRAGMENT_MODIFY_PBRPARAMS
|
||||
vec4 SurfacesFragmentModifyPBRParams()
|
||||
{
|
||||
vec4 pbr = pbrParams;
|
||||
pbr.x = 1.0;
|
||||
#if USE_PBR_MAP
|
||||
vec4 res = texture(pbrMap, DEFAULT_UV);
|
||||
pbr.x *= res.OCCLUSION_CHANNEL;
|
||||
pbr.y *= res.ROUGHNESS_CHANNEL;
|
||||
pbr.z *= res.METALLIC_CHANNEL;
|
||||
pbr.w *= res.SPECULAR_INTENSITY_CHANNEL;
|
||||
#endif
|
||||
#if USE_OCCLUSION_MAP
|
||||
pbr.x = mix(1.0, texture(occlusionMap, DEFAULT_UV).OCCLUSION_CHANNEL, pbrParams.x);
|
||||
#endif
|
||||
|
||||
return pbr;
|
||||
}
|
||||
|
||||
/*
|
||||
// definition of SurfacesMaterialData structure with corresponding shading-model
|
||||
#include <surfaces/data-structures/standard>
|
||||
|
||||
//see <surfaces/default-functions/XXXX> for more overrided functions, XXXX is shading-model name
|
||||
#define CC_SURFACES_FRAGMENT_MODIFY_SHARED_DATA
|
||||
void SurfacesFragmentModifySharedData(inout SurfacesMaterialData surfaceData)
|
||||
{
|
||||
}
|
||||
|
||||
// see <lighting-models/default-functions/XXXX> for more overrided functions, XXXX is lighting-model name
|
||||
#include <lighting-models/includes/common>
|
||||
#define CC_SURFACES_LIGHTING_MODIFY_FINAL_RESULT
|
||||
void SurfacesLightingModifyFinalResult(inout LightingResult result, in LightingIntermediateData lightingData, in SurfacesMaterialData surfaceData, in LightingMiscData miscData)
|
||||
{
|
||||
}*/
|
||||
#if USE_SELF_SHADOW_MAP
|
||||
result.shadow *= texture(selfShadowMap, DEFAULT_UV).x;
|
||||
#endif
|
||||
}
|
||||
}%
|
||||
|
||||
CCProgram standard-vs %{
|
||||
|
||||
@@ -0,0 +1,296 @@
|
||||
// Copyright (c) 2017-2022 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
CCEffect %{
|
||||
techniques:
|
||||
- name: opaque
|
||||
passes:
|
||||
- vert: standard-vs
|
||||
frag: standard-fs
|
||||
properties: &props
|
||||
tilingOffset: { value: [1.0, 1.0, 0.0, 0.0] }
|
||||
mainColor: { value: [1.0, 1.0, 1.0, 1.0], target: albedo, linear: true, editor: { displayName: Albedo, type: color } }
|
||||
albedoScale: { value: [1.0, 1.0, 1.0], target: albedoScaleAndCutoff.xyz }
|
||||
alphaThreshold: { value: 0.5, target: albedoScaleAndCutoff.w, editor: { slide: true, range: [0, 1.0], step: 0.001 } }
|
||||
occlusion: { value: 0.0, target: pbrParams.x, editor: { slide: true, range: [0, 1.0], step: 0.001 } }
|
||||
roughness: { value: 0.5, target: pbrParams.y, editor: { slide: true, range: [0, 1.0], step: 0.001 } }
|
||||
metallic: { value: 0.0, target: pbrParams.z, editor: { slide: true, range: [0, 1.0], step: 0.001 } }
|
||||
specularIntensity: { value: 0.5, target: pbrParams.w, editor: { slide: true, range: [0.0, 1.0], step: 0.001 } }
|
||||
emissive: { value: [0.0, 0.0, 0.0, 1.0], linear: true, editor: { type: color } }
|
||||
emissiveScale: { value: [1.0, 1.0, 1.0], target: emissiveScaleParam.xyz }
|
||||
normalStrength: { value: 1.0, target: emissiveScaleParam.w, editor: { parent: USE_NORMAL_MAP, slide: true, range: [0, 5.0], step: 0.001 } }
|
||||
mainTexture: { value: grey, target: albedoMap, editor: { displayName: AlbedoMap } }
|
||||
normalMap: { value: normal }
|
||||
pbrMap: { value: grey }
|
||||
occlusionMap: { value: white }
|
||||
emissiveMap: { value: grey }
|
||||
sssIntensity: { value: 1.0, target: scatterParams.z, editor: { parent: USE_NORMAL_MAP, slide: true, range: [0, 1.0], step: 0.001 } }
|
||||
preIntegratedSkinMap: { value: grey, editor: { parent: USE_PREINTEGRATED_SKIN } }
|
||||
sssCurvatureMap: { value: white, editor: { parent: USE_PREINTEGRATED_SKIN } }
|
||||
sssCurvature: { value: 0.1, target: scatterParams.w, editor: { parent: USE_PREINTEGRATED_SKIN, slide: true, range: [0, 1.0], step: 0.001 } }
|
||||
sssColoration: { value: 1.0, target: scatterColor.w, editor: { parent: USE_PREINTEGRATED_SKIN, slide: true, range: [0, 10.0], step: 0.001 } }
|
||||
cavityMap: { value: white }
|
||||
maskMap: { value: white, editor: { parent: USE_BACK_LIT } }
|
||||
thickness: { value: 0.0, target: scatterParams.x, editor: { parent: USE_BACK_LIT, displayName: Object Thickness, range: [0, 1000.0], tooltip: 'Object thickness (world space unit), setting a too small value will cause the scattered light to disappear' } }
|
||||
extinction: { value: 0.0, target: scatterParams.y, editor: { parent: USE_BACK_LIT, displayName: Transmit Scatter Extinction, slide: true, range: [0, 10.0], step: 0.001 } }
|
||||
scatterColor: { value: [1.0, 0.2, 0.1, 1.0], linear: true, editor: { parent: USE_BACK_LIT, displayName: Transmit Scatter Color, type: color, tooltip: 'The color of scattered lighting' } }
|
||||
rasterizerState:
|
||||
cullMode: None
|
||||
depthStencilState:
|
||||
depthFunc: less_equal
|
||||
depthTest: true
|
||||
depthWrite: true
|
||||
|
||||
- &forward-add
|
||||
vert: standard-vs
|
||||
frag: standard-fs
|
||||
phase: forward-add
|
||||
propertyIndex: 0
|
||||
embeddedMacros: { CC_FORWARD_ADD: true }
|
||||
depthStencilState:
|
||||
depthFunc: equal
|
||||
depthTest: true
|
||||
depthWrite: false
|
||||
blendState:
|
||||
targets:
|
||||
- blend: true
|
||||
blendSrc: one
|
||||
blendDst: one
|
||||
blendSrcAlpha: zero
|
||||
blendDstAlpha: one
|
||||
|
||||
- &shadow-caster
|
||||
vert: shadow-caster-vs
|
||||
frag: shadow-caster-fs
|
||||
phase: shadow-caster
|
||||
propertyIndex: 0
|
||||
rasterizerState:
|
||||
cullMode: none
|
||||
properties:
|
||||
tilingOffset: { value: [1.0, 1.0, 0.0, 0.0] }
|
||||
mainColor: { value: [1.0, 1.0, 1.0, 1.0], target: albedo, editor: { displayName: Albedo, type: color } }
|
||||
albedoScale: { value: [1.0, 1.0, 1.0], target: albedoScaleAndCutoff.xyz }
|
||||
alphaThreshold: { value: 0.5, target: albedoScaleAndCutoff.w, editor: { parent: USE_ALPHA_TEST } }
|
||||
mainTexture: { value: grey, target: albedoMap, editor: { displayName: AlbedoMap } }
|
||||
- name: transparent
|
||||
passes:
|
||||
- vert: standard-vs
|
||||
frag: standard-fs
|
||||
embeddedMacros: { CC_FORCE_FORWARD_SHADING: true }
|
||||
depthStencilState:
|
||||
depthTest: true
|
||||
depthWrite: false
|
||||
blendState:
|
||||
targets:
|
||||
- blend: true
|
||||
blendSrc: src_alpha
|
||||
blendDst: one_minus_src_alpha
|
||||
blendDstAlpha: one_minus_src_alpha
|
||||
properties: *props
|
||||
- *forward-add
|
||||
- *shadow-caster
|
||||
}%
|
||||
|
||||
CCProgram shared-ubos %{
|
||||
uniform Constants {
|
||||
vec4 tilingOffset;
|
||||
vec4 albedo;
|
||||
vec4 albedoScaleAndCutoff;
|
||||
vec4 pbrParams;
|
||||
vec4 emissive;
|
||||
vec4 emissiveScaleParam;
|
||||
vec4 scatterColor;
|
||||
vec4 scatterParams;
|
||||
};
|
||||
}%
|
||||
|
||||
CCProgram macro-remapping %{
|
||||
// ui displayed macros
|
||||
#pragma define-meta HAS_SECOND_UV
|
||||
#pragma define-meta USE_TWOSIDE
|
||||
#pragma define-meta USE_VERTEX_COLOR
|
||||
#pragma define-meta USE_BACK_LIT
|
||||
#pragma define-meta USE_PREINTEGRATED_SKIN
|
||||
|
||||
#define CC_SURFACES_USE_SECOND_UV HAS_SECOND_UV
|
||||
#define CC_SURFACES_USE_TWO_SIDED USE_TWOSIDE
|
||||
#define CC_SURFACES_USE_VERTEX_COLOR USE_VERTEX_COLOR
|
||||
|
||||
#define CC_SURFACES_LIGHTING_TRANSMIT_DIFFUSE USE_BACK_LIT
|
||||
#define CC_SURFACES_LIGHTING_USE_SHADOWMAP_TRANSMIT USE_BACK_LIT
|
||||
#define CC_SURFACES_LIGHTING_SSS 1
|
||||
|
||||
// depend on UI macros
|
||||
#if USE_NORMAL_MAP
|
||||
#define CC_SURFACES_USE_TANGENT_SPACE 1
|
||||
#endif
|
||||
}%
|
||||
|
||||
CCProgram surface-vertex %{
|
||||
}%
|
||||
|
||||
CCProgram surface-fragment %{
|
||||
#if USE_ALBEDO_MAP
|
||||
uniform sampler2D albedoMap;
|
||||
#pragma define-meta ALBEDO_UV options([v_uv, v_uv1])
|
||||
#endif
|
||||
#if USE_NORMAL_MAP
|
||||
uniform sampler2D normalMap;
|
||||
#pragma define-meta NORMAL_UV options([v_uv, v_uv1])
|
||||
#endif
|
||||
#pragma define-meta DEFAULT_UV options([v_uv, v_uv1])
|
||||
#if USE_PBR_MAP
|
||||
uniform sampler2D pbrMap;
|
||||
#endif
|
||||
#if USE_OCCLUSION_MAP
|
||||
uniform sampler2D occlusionMap;
|
||||
#endif
|
||||
#if USE_EMISSIVE_MAP
|
||||
uniform sampler2D emissiveMap;
|
||||
#pragma define-meta EMISSIVE_UV options([v_uv, v_uv1])
|
||||
#endif
|
||||
|
||||
#pragma define OCCLUSION_CHANNEL r
|
||||
#pragma define ROUGHNESS_CHANNEL g
|
||||
#pragma define METALLIC_CHANNEL b
|
||||
#pragma define SPECULAR_INTENSITY_CHANNEL a
|
||||
|
||||
#if USE_ALPHA_TEST
|
||||
#pragma define-meta ALPHA_TEST_CHANNEL options([a, r])
|
||||
#endif
|
||||
|
||||
//////////////////User Defines
|
||||
#if USE_BACK_LIT
|
||||
uniform sampler2D maskMap;
|
||||
#endif
|
||||
#if USE_PREINTEGRATED_SKIN
|
||||
uniform sampler2D sssCurvatureMap;
|
||||
#endif
|
||||
uniform sampler2D cavityMap;
|
||||
|
||||
#define CC_SURFACES_FRAGMENT_MODIFY_TRANSMIT_SCATTERING_PARAMS
|
||||
vec4 SurfacesFragmentModifyTransmitScatteringParams()
|
||||
{
|
||||
return vec4(scatterParams.y * 50.0, 0.0, 1.0, 0.01);
|
||||
}
|
||||
|
||||
#define CC_SURFACES_FRAGMENT_MODIFY_TRANSMIT_DIFFUSE_PARAMS
|
||||
vec4 SurfacesFragmentModifyTransmitDiffuseParams()
|
||||
{
|
||||
float mask = 1.0;
|
||||
#if USE_BACK_LIT
|
||||
mask = texture(maskMap, FSInput_texcoord).x > 0.0 ? 1.0 : 0.0;
|
||||
#endif
|
||||
return vec4(scatterParams.x, mask, 1.0, 1.0);
|
||||
}
|
||||
|
||||
#define CC_SURFACES_FRAGMENT_MODIFY_TRANSMIT_IN_SCATTERING_COLOR
|
||||
vec3 SurfacesFragmentModifyTransmitInScatteringColor()
|
||||
{
|
||||
return vec3(0.0);//1.0, 0.2, 0.05);
|
||||
}
|
||||
|
||||
#define CC_SURFACES_FRAGMENT_MODIFY_TRANSMIT_OUT_SCATTERING_COLOR
|
||||
vec3 SurfacesFragmentModifyTransmitOutScatteringColor()
|
||||
{
|
||||
return scatterColor.rgb;
|
||||
}
|
||||
|
||||
#define CC_SURFACES_FRAGMENT_MODIFY_SSS_PARAMS
|
||||
vec4 SurfacesFragmentModifySSSParams()
|
||||
{
|
||||
float sssCurvature = scatterParams.w;
|
||||
float cavity = texture(cavityMap, FSInput_texcoord).x;
|
||||
#if USE_PREINTEGRATED_SKIN
|
||||
sssCurvature *= texture(sssCurvatureMap, FSInput_texcoord).x;
|
||||
#endif
|
||||
return vec4(scatterParams.z, sssCurvature, scatterColor.w, cavity);
|
||||
}
|
||||
|
||||
#include <common-functions>
|
||||
#include <lighting-models/default-functions/simple-skin>
|
||||
}%
|
||||
|
||||
CCProgram standard-vs %{
|
||||
precision highp float;
|
||||
|
||||
// 1. surface internal macros, for technique usage or remapping some user (material) macros to surface internal macros
|
||||
#include <macro-remapping>
|
||||
#include <surfaces/effect-macros/common-macros>
|
||||
|
||||
// 2. common include with corresponding shader stage, include before surface functions
|
||||
#include <surfaces/includes/common-vs>
|
||||
|
||||
// 3. user surface functions that can use user (effect) parameters (ubo Constants)
|
||||
// see surfaces/default-functions/xxx.chunk
|
||||
#include <shared-ubos>
|
||||
#include <surface-vertex>
|
||||
|
||||
// 4. surface include with corresponding shader stage and shading-model (optional)
|
||||
#include <surfaces/includes/standard-vs>
|
||||
|
||||
// 5. shader entry with corresponding shader stage and technique usage/type
|
||||
#include <shading-entries/main-functions/render-to-scene/vs>
|
||||
}%
|
||||
|
||||
|
||||
CCProgram shadow-caster-vs %{
|
||||
precision highp float;
|
||||
#include <surfaces/effect-macros/render-to-shadowmap>
|
||||
#include <surfaces/includes/common-vs>
|
||||
#include <shared-ubos>
|
||||
#include <surface-vertex>
|
||||
#include <shading-entries/main-functions/render-to-shadowmap/vs>
|
||||
}%
|
||||
|
||||
|
||||
|
||||
CCProgram standard-fs %{
|
||||
// shading-model : standard
|
||||
// lighting-model : standard (isotropy / anisotropy pbr)
|
||||
// shader stage : fs
|
||||
// technique usage/type : render-to-scene
|
||||
|
||||
precision highp float;
|
||||
// 1. surface internal macros, for technique usage or remapping some user (material) macros to surface internal macros
|
||||
#include <macro-remapping>
|
||||
#include <surfaces/effect-macros/common-macros>
|
||||
|
||||
// 2. common include with corresponding shader stage, include before surface functions
|
||||
#include <surfaces/includes/common-fs>
|
||||
|
||||
// 3. user surface functions that can use user (effect) parameters (ubo Constants)
|
||||
// see surfaces/default-functions/xxx.chunk
|
||||
#include <shared-ubos>
|
||||
#include <surface-fragment>
|
||||
|
||||
// 4. lighting-model (optional)
|
||||
#include <lighting-models/includes/standard>
|
||||
|
||||
// 5. surface include with corresponding shader stage and shading-model (optional)
|
||||
#include <surfaces/includes/standard-fs>
|
||||
|
||||
// 6. shader entry with corresponding shader stage and technique usage/type
|
||||
#include <shading-entries/main-functions/render-to-scene/fs>
|
||||
}%
|
||||
|
||||
CCProgram shadow-caster-fs %{
|
||||
precision highp float;
|
||||
#include <surfaces/effect-macros/render-to-shadowmap>
|
||||
#include <surfaces/includes/common-fs>
|
||||
#include <shared-ubos>
|
||||
#include <surface-fragment>
|
||||
#include <shading-entries/main-functions/render-to-shadowmap/fs>
|
||||
}%
|
||||
|
||||
|
||||
CCProgram reflect-map-fs %{
|
||||
precision highp float;
|
||||
#include <macro-remapping>
|
||||
#include <surfaces/effect-macros/common-macros>
|
||||
#include <surfaces/includes/common-fs>
|
||||
#include <shared-ubos>
|
||||
#include <surface-fragment>
|
||||
#include <lighting-models/includes/standard>
|
||||
#include <surfaces/includes/standard-fs>
|
||||
#include <shading-entries/main-functions/render-to-reflectmap/fs>
|
||||
}%
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"ver": "1.6.2",
|
||||
"importer": "effect",
|
||||
"imported": true,
|
||||
"uuid": "472c676f-9f77-4c8d-b550-17825aa0176b",
|
||||
"files": [
|
||||
".json"
|
||||
],
|
||||
"subMetas": {},
|
||||
"userData": {}
|
||||
}
|
||||
@@ -176,18 +176,22 @@ CCProgram surface-fragment %{
|
||||
{
|
||||
return 1.33;
|
||||
}
|
||||
#define CC_SURFACES_FRAGMENT_MODIFY_TRANSMIT_PARAMS
|
||||
void SurfacesFragmentModifyTransmitParams(out vec4 transmitParams, out vec3 inScatteringLightColor)
|
||||
#define CC_SURFACES_FRAGMENT_MODIFY_TRANSMIT_SCATTERING_PARAMS
|
||||
vec4 SurfacesFragmentModifyTransmitScatteringParams()
|
||||
{
|
||||
#if USE_WATER_SCATTERING
|
||||
float depth = max(abs(FSInput_texcoord.x - 0.5), abs(FSInput_texcoord.y - 0.5)) * 2.0;
|
||||
depth = saturate(1.0 - depth);
|
||||
transmitParams = vec4(waterColor.ww, 1.0, depth);
|
||||
return vec4(waterColor.w, 1.0, 1.0, depth);
|
||||
#else
|
||||
transmitParams = vec4(0.0, 0.0, 0.0, 0.0);
|
||||
return vec4(0.0, 0.0, 0.0, 0.0);
|
||||
#endif
|
||||
}
|
||||
|
||||
inScatteringLightColor = waterColor.rgb;
|
||||
#define CC_SURFACES_FRAGMENT_MODIFY_TRANSMIT_IN_SCATTERING_COLOR
|
||||
vec3 SurfacesFragmentModifyTransmitInScatteringColor()
|
||||
{
|
||||
return waterColor.rgb;
|
||||
}
|
||||
|
||||
#include <surfaces/data-structures/standard>
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -188,6 +188,9 @@ if(NOT EXISTS ${EXTERNAL_ROOT}/CMakeLists.txt)
|
||||
message(FATAL_ERROR "Please download external libraries! File ${CMAKE_CURRENT_LIST_DIR}/external/CMakeLists.txt not exist!")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
include_directories(${EXTERNAL_ROOT}/sources)
|
||||
|
||||
################################# list all option values ##############################
|
||||
|
||||
cc_inspect_values(
|
||||
|
||||
@@ -104,7 +104,6 @@ add_definitions(-DCC_PLATFORM_OPENHARMONY=${CC_PLATFORM_OPENHARMONY})
|
||||
add_definitions(-DCC_PLATFORM_EMSCRIPTEN=${CC_PLATFORM_EMSCRIPTEN})
|
||||
add_definitions(-DCC_PLATFORM=${CC_PLATFORM})
|
||||
|
||||
include_directories(${CMAKE_CURRENT_LIST_DIR}/../external/sources)
|
||||
|
||||
# simplify generator condition, please use them everywhere
|
||||
if(CMAKE_GENERATOR STREQUAL Xcode)
|
||||
|
||||
@@ -28,7 +28,7 @@
|
||||
namespace cc {
|
||||
|
||||
namespace {
|
||||
Record<gfx::FormatType, ccstd::string> typeMap{
|
||||
ccstd::unordered_map<gfx::FormatType, ccstd::string> typeMap{
|
||||
{gfx::FormatType::UNORM, "Uint"},
|
||||
{gfx::FormatType::SNORM, "Int"},
|
||||
{gfx::FormatType::UINT, "Uint"},
|
||||
|
||||
@@ -39,8 +39,6 @@ using FlagBits = std::uint32_t;
|
||||
using index_t = int32_t;
|
||||
#define CC_INVALID_INDEX (-1)
|
||||
|
||||
#define Record ccstd::unordered_map // NOLINT(readability-identifier-naming)
|
||||
|
||||
#define CC_ENUM_CONVERSION_OPERATOR(T) \
|
||||
inline std::underlying_type<T>::type toNumber(const T v) { return static_cast<std::underlying_type<T>::type>(v); }
|
||||
|
||||
|
||||
@@ -18820,11 +18820,11 @@ static bool js_cc_scene_Pass_properties_get(se::State& s)
|
||||
{
|
||||
CC_UNUSED bool ok = true;
|
||||
cc::scene::Pass *arg1 = (cc::scene::Pass *) NULL ;
|
||||
Record< ccstd::string,cc::IPropertyInfo > *result = 0 ;
|
||||
ccstd::unordered_map< ccstd::string,cc::IPropertyInfo > *result = 0 ;
|
||||
|
||||
arg1 = SE_THIS_OBJECT<cc::scene::Pass>(s);
|
||||
if (nullptr == arg1) return true;
|
||||
result = (Record< ccstd::string,cc::IPropertyInfo > *) &cc_scene_Pass_properties_get(arg1);
|
||||
result = (ccstd::unordered_map< ccstd::string,cc::IPropertyInfo > *) &cc_scene_Pass_properties_get(arg1);
|
||||
|
||||
ok &= nativevalue_to_se(*result, s.rval(), s.thisObject());
|
||||
SE_PRECONDITION2(ok, false, "Error processing arguments");
|
||||
|
||||
@@ -34,7 +34,7 @@
|
||||
|
||||
namespace cc {
|
||||
|
||||
//class RenderableComponent;
|
||||
// class RenderableComponent;
|
||||
|
||||
namespace scene {
|
||||
class Pass;
|
||||
@@ -239,7 +239,7 @@ public:
|
||||
ccstd::vector<PassOverrides> _states;
|
||||
|
||||
/* @serializable */
|
||||
ccstd::vector<Record<ccstd::string, MaterialPropertyVariant>> _props;
|
||||
ccstd::vector<ccstd::unordered_map<ccstd::string, MaterialPropertyVariant>> _props;
|
||||
//
|
||||
|
||||
protected:
|
||||
|
||||
@@ -62,7 +62,7 @@ private:
|
||||
|
||||
static BuiltinResMgr *instance;
|
||||
|
||||
Record<ccstd::string, IntrusivePtr<Asset>> _resources;
|
||||
ccstd::unordered_map<ccstd::string, IntrusivePtr<Asset>> _resources;
|
||||
bool _isInitialized{false};
|
||||
|
||||
CC_DISALLOW_COPY_MOVE_ASSIGN(BuiltinResMgr);
|
||||
|
||||
@@ -218,6 +218,9 @@ FileUtils::Status FileUtilsAndroid::getContents(const ccstd::string &filename, R
|
||||
}
|
||||
|
||||
ccstd::string FileUtilsAndroid::getWritablePath() const {
|
||||
if (!_writablePath.empty()) {
|
||||
return _writablePath;
|
||||
}
|
||||
// Fix for Nexus 10 (Android 4.2 multi-user environment)
|
||||
// the path is retrieved through Java Context.getCacheDir() method
|
||||
ccstd::string dir;
|
||||
|
||||
@@ -43,9 +43,7 @@ SystemWindow::SystemWindow(uint32_t windowId, void *externalHandle)
|
||||
}
|
||||
}
|
||||
|
||||
SystemWindow::~SystemWindow() {
|
||||
setCursorEnabled(true);
|
||||
}
|
||||
SystemWindow::~SystemWindow() = default;
|
||||
|
||||
bool SystemWindow::createWindow(const char *title,
|
||||
int w, int h, int flags) {
|
||||
|
||||
@@ -77,7 +77,7 @@ public:
|
||||
*/
|
||||
// @serializable
|
||||
// @editable
|
||||
Record<ccstd::string, float> info; //cjh float?
|
||||
ccstd::unordered_map<ccstd::string, float> info; // cjh float?
|
||||
|
||||
explicit Primitive(PrimitiveType type = PrimitiveType::BOX);
|
||||
~Primitive() override;
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2021-2023 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 documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights to
|
||||
@@ -70,7 +70,7 @@ using MacroValue = ccstd::variant<ccstd::monostate, int32_t, bool, ccstd::string
|
||||
* @en Combination of preprocess macros
|
||||
* @zh 预处理宏组合
|
||||
*/
|
||||
using MacroRecord = Record<ccstd::string, MacroValue>;
|
||||
using MacroRecord = ccstd::unordered_map<ccstd::string, MacroValue>;
|
||||
|
||||
using MaterialProperty = ccstd::variant<ccstd::monostate /*0*/, float /*1*/, int32_t /*2*/, Vec2 /*3*/, Vec3 /*4*/, Vec4 /*5*/, Color, /*6*/ Mat3 /*7*/, Mat4 /*8*/, Quaternion /*9*/, IntrusivePtr<TextureBase> /*10*/, IntrusivePtr<gfx::Texture> /*11*/>;
|
||||
|
||||
@@ -85,9 +85,9 @@ using GFXTypeReaderCallback = void (*)(const float *, MaterialProperty &, index_
|
||||
using GFXTypeWriterCallback = void (*)(float *, const MaterialProperty &, index_t);
|
||||
using GFXTypeValidatorCallback = bool (*)(const MaterialProperty &);
|
||||
|
||||
extern const ccstd::unordered_map<gfx::Type, GFXTypeReaderCallback> type2reader; //NOLINT(readability-identifier-naming)
|
||||
extern const ccstd::unordered_map<gfx::Type, GFXTypeWriterCallback> type2writer; //NOLINT(readability-identifier-naming)
|
||||
extern const ccstd::unordered_map<gfx::Type, GFXTypeValidatorCallback> type2validator; //NOLINT(readability-identifier-naming)
|
||||
extern const ccstd::unordered_map<gfx::Type, GFXTypeReaderCallback> type2reader; // NOLINT(readability-identifier-naming)
|
||||
extern const ccstd::unordered_map<gfx::Type, GFXTypeWriterCallback> type2writer; // NOLINT(readability-identifier-naming)
|
||||
extern const ccstd::unordered_map<gfx::Type, GFXTypeValidatorCallback> type2validator; // NOLINT(readability-identifier-naming)
|
||||
|
||||
/**
|
||||
* @en Gets the default values for the given type of uniform
|
||||
|
||||
@@ -60,7 +60,7 @@ struct ITemplateInfo {
|
||||
ccstd::vector<int32_t> blockSizes;
|
||||
RefVector<gfx::DescriptorSetLayout *> setLayouts;
|
||||
IntrusivePtr<gfx::PipelineLayout> pipelineLayout;
|
||||
Record<ccstd::string, uint32_t> handleMap;
|
||||
ccstd::unordered_map<ccstd::string, uint32_t> handleMap;
|
||||
ccstd::vector<gfx::DescriptorSetLayoutBinding> bindings;
|
||||
int32_t samplerStartBinding{-1};
|
||||
};
|
||||
@@ -160,9 +160,9 @@ private:
|
||||
CC_DISALLOW_COPY_MOVE_ASSIGN(ProgramLib);
|
||||
|
||||
static ProgramLib *instance;
|
||||
Record<ccstd::string, IProgramInfo> _templates; // per shader
|
||||
Record<ccstd::string, IntrusivePtr<gfx::Shader>> _cache;
|
||||
Record<uint64_t, ITemplateInfo> _templateInfos;
|
||||
ccstd::unordered_map<ccstd::string, IProgramInfo> _templates; // per shader
|
||||
ccstd::unordered_map<ccstd::string, IntrusivePtr<gfx::Shader>> _cache;
|
||||
ccstd::unordered_map<uint64_t, ITemplateInfo> _templateInfos;
|
||||
};
|
||||
|
||||
} // namespace cc
|
||||
|
||||
@@ -35,7 +35,7 @@ int32_t getBitCount(int32_t cnt) {
|
||||
|
||||
template <class ShaderInfoT>
|
||||
ccstd::unordered_map<ccstd::string, uint32_t> genHandlesImpl(const ShaderInfoT &tmpl) {
|
||||
Record<ccstd::string, uint32_t> handleMap{};
|
||||
ccstd::unordered_map<ccstd::string, uint32_t> handleMap{};
|
||||
// block member handles
|
||||
for (const auto &block : tmpl.blocks) {
|
||||
const auto members = block.members;
|
||||
|
||||
@@ -78,7 +78,7 @@ void CCVKCommandBuffer::doDestroy() {
|
||||
cleanEvent(pair.second);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
_gpuCommandBuffer = nullptr;
|
||||
}
|
||||
|
||||
@@ -650,8 +650,8 @@ void CCVKCommandBuffer::pipelineBarrier(const GeneralBarrier *barrier, const Buf
|
||||
VkPipelineStageFlags splitDstStageMask = VK_PIPELINE_STAGE_NONE_KHR;
|
||||
VkMemoryBarrier const *pMemoryBarrier = nullptr;
|
||||
|
||||
ccstd::vector<VkImageMemoryBarrier> splitImageBarriers;
|
||||
ccstd::vector<VkBufferMemoryBarrier> splitBufferBarriers;
|
||||
ccstd::vector<std::pair<uint32_t, VkImageMemoryBarrier>> splitImageBarriers;
|
||||
ccstd::vector<std::pair<uint32_t, VkBufferMemoryBarrier>> splitBufferBarriers;
|
||||
ccstd::vector<VkImageMemoryBarrier> fullImageBarriers;
|
||||
ccstd::vector<VkBufferMemoryBarrier> fullBufferBarriers;
|
||||
ccstd::vector<VkEvent> scheduledEvents;
|
||||
@@ -688,24 +688,36 @@ void CCVKCommandBuffer::pipelineBarrier(const GeneralBarrier *barrier, const Buf
|
||||
signalEvent(ccTexture, gpuBarrier->srcStageMask);
|
||||
} else {
|
||||
bool fullBarrier = ccBarrier->getInfo().type == BarrierType::FULL;
|
||||
if (!fullBarrier) {
|
||||
CC_ASSERT(_barrierEvents.find(ccTexture) != _barrierEvents.end());
|
||||
bool missed = _barrierEvents.find(ccTexture) == _barrierEvents.end();
|
||||
if (!fullBarrier && !missed) {
|
||||
//CC_ASSERT(_barrierEvents.find(ccTexture) != _barrierEvents.end());
|
||||
VkEvent event = _barrierEvents.at(ccTexture);
|
||||
scheduledEvents.push_back(event);
|
||||
}
|
||||
auto &vkImageBarriers = fullBarrier ? fullImageBarriers : splitImageBarriers;
|
||||
auto &srcStageMask = fullBarrier ? fullSrcStageMask : splitSrcStageMask;
|
||||
auto &dstStageMask = fullBarrier ? fullDstStageMask : splitDstStageMask;
|
||||
gpuTexture->currentAccessTypes.assign(gpuBarrier->barrier.pNextAccesses, gpuBarrier->barrier.pNextAccesses + gpuBarrier->barrier.nextAccessCount);
|
||||
vkImageBarriers.push_back(gpuBarrier->vkBarrier);
|
||||
vkImageBarriers.back().subresourceRange.aspectMask = gpuTexture->aspectMask;
|
||||
if (gpuTexture->swapchain) {
|
||||
vkImageBarriers.back().image = gpuTexture->swapchainVkImages[gpuTexture->swapchain->curImageIndex];
|
||||
|
||||
gpuTexture->currentAccessTypes.assign(gpuBarrier->barrier.pNextAccesses, gpuBarrier->barrier.pNextAccesses + gpuBarrier->barrier.nextAccessCount);
|
||||
auto srcStageMask = gpuBarrier->srcStageMask & VK_PIPELINE_STAGE_HOST_BIT ? 0x0 : gpuBarrier->srcStageMask;
|
||||
auto &barrier = splitImageBarriers.emplace_back(i, gpuBarrier->vkBarrier);
|
||||
barrier.second.subresourceRange.aspectMask = gpuTexture->aspectMask;
|
||||
if (gpuTexture->swapchain) {
|
||||
barrier.second.image = gpuTexture->swapchainVkImages[gpuTexture->swapchain->curImageIndex];
|
||||
} else {
|
||||
barrier.second.image = gpuTexture->vkImage;
|
||||
}
|
||||
splitSrcStageMask |= gpuBarrier->srcStageMask;
|
||||
splitDstStageMask |= gpuBarrier->dstStageMask;
|
||||
} else {
|
||||
vkImageBarriers.back().image = gpuTexture->vkImage;
|
||||
gpuTexture->currentAccessTypes.assign(gpuBarrier->barrier.pNextAccesses, gpuBarrier->barrier.pNextAccesses + gpuBarrier->barrier.nextAccessCount);
|
||||
fullImageBarriers.push_back(gpuBarrier->vkBarrier);
|
||||
fullImageBarriers.back().srcAccessMask = missed ? VK_IMAGE_LAYOUT_UNDEFINED : fullImageBarriers.back().srcAccessMask;
|
||||
fullImageBarriers.back().subresourceRange.aspectMask = gpuTexture->aspectMask;
|
||||
if (gpuTexture->swapchain) {
|
||||
fullImageBarriers.back().image = gpuTexture->swapchainVkImages[gpuTexture->swapchain->curImageIndex];
|
||||
} else {
|
||||
fullImageBarriers.back().image = gpuTexture->vkImage;
|
||||
}
|
||||
fullSrcStageMask |= gpuBarrier->srcStageMask;
|
||||
fullDstStageMask |= gpuBarrier->dstStageMask;
|
||||
}
|
||||
srcStageMask |= gpuBarrier->srcStageMask;
|
||||
dstStageMask |= gpuBarrier->dstStageMask;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -721,20 +733,25 @@ void CCVKCommandBuffer::pipelineBarrier(const GeneralBarrier *barrier, const Buf
|
||||
signalEvent(ccBuffer, gpuBarrier->srcStageMask);
|
||||
} else {
|
||||
bool fullBarrier = ccBarrier->getInfo().type == BarrierType::FULL;
|
||||
if (!fullBarrier) {
|
||||
bool missed = _barrierEvents.find(ccBuffer) != _barrierEvents.end();
|
||||
if (!fullBarrier && !missed) {
|
||||
CC_ASSERT(_barrierEvents.find(ccBuffer) != _barrierEvents.end());
|
||||
VkEvent event = _barrierEvents.at(ccBuffer);
|
||||
scheduledEvents.push_back(event);
|
||||
}
|
||||
auto &vkBufferBarriers = fullBarrier ? fullBufferBarriers : splitBufferBarriers;
|
||||
auto &srcStageMask = fullBarrier ? fullSrcStageMask : splitSrcStageMask;
|
||||
auto &dstStageMask = fullBarrier ? fullDstStageMask : splitDstStageMask;
|
||||
|
||||
gpuBuffer->currentAccessTypes.assign(gpuBarrier->barrier.pNextAccesses, gpuBarrier->barrier.pNextAccesses + gpuBarrier->barrier.nextAccessCount);
|
||||
vkBufferBarriers.push_back(gpuBarrier->vkBarrier);
|
||||
vkBufferBarriers.back().buffer = gpuBuffer->vkBuffer;
|
||||
srcStageMask |= gpuBarrier->srcStageMask;
|
||||
dstStageMask |= gpuBarrier->dstStageMask;
|
||||
gpuBuffer->currentAccessTypes.assign(gpuBarrier->barrier.pNextAccesses, gpuBarrier->barrier.pNextAccesses + gpuBarrier->barrier.nextAccessCount);
|
||||
auto &splitBarrier = splitBufferBarriers.emplace_back(i, gpuBarrier->vkBarrier);
|
||||
splitBarrier.second.buffer = gpuBuffer->vkBuffer;
|
||||
splitSrcStageMask |= gpuBarrier->srcStageMask;
|
||||
splitDstStageMask |= gpuBarrier->dstStageMask;
|
||||
} else {
|
||||
gpuBuffer->currentAccessTypes.assign(gpuBarrier->barrier.pNextAccesses, gpuBarrier->barrier.pNextAccesses + gpuBarrier->barrier.nextAccessCount);
|
||||
fullBufferBarriers.push_back(gpuBarrier->vkBarrier);
|
||||
fullBufferBarriers.back().srcAccessMask = missed ? VK_IMAGE_LAYOUT_UNDEFINED : fullBufferBarriers.back().srcAccessMask;
|
||||
fullBufferBarriers.back().buffer = gpuBuffer->vkBuffer;
|
||||
fullSrcStageMask |= gpuBarrier->srcStageMask;
|
||||
fullDstStageMask |= gpuBarrier->dstStageMask;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -755,24 +772,37 @@ void CCVKCommandBuffer::pipelineBarrier(const GeneralBarrier *barrier, const Buf
|
||||
if (textureBarrierCount || bufferBarrierCount || barrier) {
|
||||
// split end detect
|
||||
if (!splitBufferBarriers.empty() || !splitImageBarriers.empty()) {
|
||||
vkCmdWaitEvents(_gpuCommandBuffer->vkCommandBuffer, scheduledEvents.size(), scheduledEvents.data(), splitSrcStageMask, splitDstStageMask, 0, nullptr, splitBufferBarriers.size(),
|
||||
splitBufferBarriers.data(), splitImageBarriers.size(), splitImageBarriers.data());
|
||||
{
|
||||
ccstd::vector<VkImageMemoryBarrier> vkImageBarriers(splitImageBarriers.size());
|
||||
ccstd::vector<VkBufferMemoryBarrier> vkBufferBarriers(splitBufferBarriers.size());
|
||||
for (size_t idx = 0; idx < splitImageBarriers.size(); ++idx) {
|
||||
vkImageBarriers[idx] = splitImageBarriers[idx].second;
|
||||
}
|
||||
for (size_t idx = 0; idx < splitBufferBarriers.size(); ++idx) {
|
||||
vkBufferBarriers[idx] = splitBufferBarriers[idx].second;
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < textureBarrierCount; ++i) {
|
||||
VkEvent event = _barrierEvents.at(textures[i]);
|
||||
const auto *ccBarrier = static_cast<const CCVKTextureBarrier *const>(textureBarriers[i]);
|
||||
vkCmdWaitEvents(_gpuCommandBuffer->vkCommandBuffer, scheduledEvents.size(), scheduledEvents.data(), splitSrcStageMask, splitDstStageMask, 0, nullptr, vkBufferBarriers.size(),
|
||||
vkBufferBarriers.data(), vkImageBarriers.size(), vkImageBarriers.data());
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < splitImageBarriers.size(); ++i) { // NOLINT (range-based-for)
|
||||
auto index = splitImageBarriers[i].first;
|
||||
VkEvent event = _barrierEvents.at(textures[index]);
|
||||
const auto *ccBarrier = static_cast<const CCVKTextureBarrier *const>(textureBarriers[index]);
|
||||
const auto *gpuBarrier = ccBarrier->gpuBarrier();
|
||||
vkCmdResetEvent(_gpuCommandBuffer->vkCommandBuffer, event, gpuBarrier->dstStageMask);
|
||||
_barrierEvents.erase(textures[i]);
|
||||
_barrierEvents.erase(textures[index]);
|
||||
_availableEvents.push(event);
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < bufferBarrierCount; ++i) {
|
||||
VkEvent event = _barrierEvents.at(buffers[i]);
|
||||
const auto *ccBarrier = static_cast<const CCVKBufferBarrier *const>(bufferBarriers[i]);
|
||||
for (size_t i = 0; i < splitBufferBarriers.size(); ++i) { // NOLINT (range-based-for)
|
||||
auto index = splitBufferBarriers[i].first;
|
||||
VkEvent event = _barrierEvents.at(buffers[index]);
|
||||
const auto *ccBarrier = static_cast<const CCVKBufferBarrier *const>(bufferBarriers[index]);
|
||||
const auto *gpuBarrier = ccBarrier->gpuBarrier();
|
||||
vkCmdResetEvent(_gpuCommandBuffer->vkCommandBuffer, event, gpuBarrier->dstStageMask);
|
||||
_barrierEvents.erase(buffers[i]);
|
||||
_barrierEvents.erase(buffers[index]);
|
||||
_availableEvents.push(event);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -438,12 +438,7 @@ struct BarrierVisitor : public boost::bfs_visitor<> {
|
||||
[](const AccessStatus &lhs, const AccessStatus &rhs) {
|
||||
return lhs.vertID < rhs.vertID;
|
||||
});
|
||||
auto checkMeet = [&](const AccessStatus &status) {
|
||||
const auto &resName = get(ResourceGraph::NameTag{}, resourceGraph, status.vertID);
|
||||
return resourceNames.find(resName) == resourceNames.end();
|
||||
};
|
||||
bool newRes = std::any_of(srcStatus.begin(), srcStatus.end(), checkMeet) || std::any_of(dstStatus.begin(), dstStatus.end(), checkMeet);
|
||||
if (commonResources.empty() && !newRes) {
|
||||
if (commonResources.empty()) {
|
||||
// this edge is a logic edge added during pass reorder,
|
||||
// no real dependency between this two vertices.
|
||||
return;
|
||||
@@ -572,7 +567,7 @@ struct BarrierVisitor : public boost::bfs_visitor<> {
|
||||
}
|
||||
|
||||
//----------------------------------------------check external----------------------------------------------
|
||||
auto barrierExternalResOrFirstMeet = [&](const AccessStatus &resourcecAccess, Vertex vert) {
|
||||
auto barrierExternalRes = [&](const AccessStatus &resourcecAccess, Vertex vert) {
|
||||
uint32_t rescID = resourcecAccess.vertID;
|
||||
const auto &states = get(ResourceGraph::StatesTag{}, resourceGraph, rescID);
|
||||
const auto &traits = get(ResourceGraph::TraitsTag{}, resourceGraph, rescID);
|
||||
@@ -646,43 +641,15 @@ struct BarrierVisitor : public boost::bfs_visitor<> {
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (resourceNames.find(resName) == resourceNames.end()) {
|
||||
auto lastRescAccess = AccessStatus{
|
||||
vert,
|
||||
gfx::ShaderStageFlagBit::NONE,
|
||||
gfx::MemoryAccessBit::NONE,
|
||||
gfx::PassType::RASTER,
|
||||
gfx::AccessFlagBit::NONE,
|
||||
gfx::TextureUsageBit::NONE,
|
||||
TextureRange{},
|
||||
};
|
||||
auto currRescAccess = resourcecAccess;
|
||||
|
||||
// resource id in access -> pass id in barrier
|
||||
currRescAccess.vertID = vert;
|
||||
|
||||
lastRescAccess.accessFlag = gfx::AccessFlagBit::NONE;
|
||||
|
||||
// add undefined layout -> write at first meet
|
||||
barrierMap[vert].blockBarrier.frontBarriers.emplace_back(Barrier{
|
||||
rescID,
|
||||
gfx::BarrierType::FULL,
|
||||
nullptr,
|
||||
lastRescAccess,
|
||||
currRescAccess,
|
||||
});
|
||||
resourceNames.emplace(resName);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
for (const AccessStatus &rescAccess : srcStatus) {
|
||||
barrierExternalResOrFirstMeet(rescAccess, from.vertID);
|
||||
barrierExternalRes(rescAccess, from.vertID);
|
||||
}
|
||||
|
||||
for (const AccessStatus &rescAccess : dstStatus) {
|
||||
barrierExternalResOrFirstMeet(rescAccess, to.vertID);
|
||||
barrierExternalRes(rescAccess, to.vertID);
|
||||
}
|
||||
//---------------------------------------------------------------------------------------------------------
|
||||
}
|
||||
@@ -812,7 +779,7 @@ struct BarrierVisitor : public boost::bfs_visitor<> {
|
||||
BarrierMap &barrierMap;
|
||||
const ResourceGraph &resourceGraph;
|
||||
ExternalResMap &externalMap; // last frame to curr frame status transition
|
||||
ResourceNames &resourceNames; // isExternal ? record those which been written : record those which first meet
|
||||
ResourceNames &resourceNames; // record those which been written
|
||||
ResourceLifeRecordMap &resourceLifeRecord;
|
||||
};
|
||||
|
||||
@@ -835,8 +802,55 @@ void buildBarriers(FrameGraphDispatcher &fgDispatcher) {
|
||||
// found pass id in this map ? barriers you should commit when run into this pass
|
||||
// : or no extra barrier needed.
|
||||
BarrierMap &batchedBarriers = fgDispatcher.barrierMap;
|
||||
|
||||
{
|
||||
// barrier first meet
|
||||
// O(N) actually
|
||||
ccstd::set<ResourceGraph::vertex_descriptor> firstMeet;
|
||||
for (size_t i = 0; i < rag.access.size(); ++i) {
|
||||
const auto *status = &rag.access[i];
|
||||
while (status) {
|
||||
for (const auto &attachment : status->attachmentStatus) {
|
||||
if (get(ResourceGraph::TraitsTag{}, resourceGraph, attachment.vertID).hasSideEffects()) {
|
||||
continue;
|
||||
}
|
||||
if (firstMeet.find(attachment.vertID) == firstMeet.end()) {
|
||||
firstMeet.emplace(attachment.vertID);
|
||||
|
||||
if (batchedBarriers.find(i) == batchedBarriers.end()) {
|
||||
batchedBarriers.emplace(i, BarrierNode{});
|
||||
}
|
||||
|
||||
auto &blockFrontBarrier = batchedBarriers.at(i).blockBarrier.frontBarriers;
|
||||
auto resIter = std::find_if(blockFrontBarrier.begin(), blockFrontBarrier.end(), [&attachment](const Barrier &barrier) { return barrier.resourceID == attachment.vertID; });
|
||||
if (resIter == blockFrontBarrier.end()) {
|
||||
Barrier firstMeetBarrier{
|
||||
attachment.vertID,
|
||||
gfx::BarrierType::FULL,
|
||||
nullptr,
|
||||
{
|
||||
static_cast<uint32_t>(i),
|
||||
gfx::ShaderStageFlagBit::NONE,
|
||||
gfx::MemoryAccessBit::NONE,
|
||||
gfx::PassType::RASTER,
|
||||
gfx::AccessFlagBit::NONE,
|
||||
gfx::TextureUsageBit::NONE,
|
||||
TextureRange{},
|
||||
},
|
||||
attachment,
|
||||
};
|
||||
blockFrontBarrier.emplace_back(firstMeetBarrier);
|
||||
}
|
||||
}
|
||||
}
|
||||
status = status->nextSubpass;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ResourceNames namesSet;
|
||||
{
|
||||
// barrier between passes
|
||||
BarrierVisitor visitor(resourceGraph, batchedBarriers, externalResMap, namesSet, rag.accessRecord, rag.resourceLifeRecord);
|
||||
auto colors = rag.colors(scratch);
|
||||
boost::queue<AccessVertex> q;
|
||||
|
||||
@@ -610,7 +610,7 @@ public:
|
||||
ProgramProxy *getProgramVariant(gfx::Device *device, uint32_t phaseID, const ccstd::string &name, MacroRecord &defines, const ccstd::pmr::string *key) override;
|
||||
gfx::PipelineState *getComputePipelineState(gfx::Device *device, uint32_t phaseID, const ccstd::string &name, MacroRecord &defines, const ccstd::pmr::string *key) override;
|
||||
const ccstd::vector<int32_t> &getBlockSizes(uint32_t phaseID, const ccstd::string &programName) const override;
|
||||
const Record<ccstd::string, uint32_t> &getHandleMap(uint32_t phaseID, const ccstd::string &programName) const override;
|
||||
const ccstd::unordered_map<ccstd::string, uint32_t> &getHandleMap(uint32_t phaseID, const ccstd::string &programName) const override;
|
||||
uint32_t getProgramID(uint32_t phaseID, const ccstd::pmr::string &programName) override;
|
||||
uint32_t getDescriptorNameID(const ccstd::pmr::string &name) override;
|
||||
const ccstd::pmr::string &getDescriptorName(uint32_t nameID) override;
|
||||
|
||||
@@ -1502,7 +1502,7 @@ ProgramProxy *NativeProgramLibrary::getProgramVariant(
|
||||
return res.first->second.get();
|
||||
}
|
||||
|
||||
gfx::PipelineState* NativeProgramLibrary::getComputePipelineState(
|
||||
gfx::PipelineState *NativeProgramLibrary::getComputePipelineState(
|
||||
gfx::Device *device, uint32_t phaseID, const ccstd::string &name,
|
||||
MacroRecord &defines, const ccstd::pmr::string *key) {
|
||||
auto *program = getProgramVariant(device, phaseID, name, defines, key);
|
||||
@@ -1543,7 +1543,7 @@ const ccstd::vector<int32_t> &NativeProgramLibrary::getBlockSizes(
|
||||
throw std::invalid_argument("program not found");
|
||||
}
|
||||
|
||||
const Record<ccstd::string, uint32_t> &NativeProgramLibrary::getHandleMap(
|
||||
const ccstd::unordered_map<ccstd::string, uint32_t> &NativeProgramLibrary::getHandleMap(
|
||||
uint32_t phaseID, const ccstd::string &programName) const {
|
||||
CC_EXPECTS(phaseID != LayoutGraphData::null_vertex());
|
||||
const auto &group = phases.at(phaseID);
|
||||
|
||||
@@ -37,7 +37,7 @@ namespace render {
|
||||
ProgramInfo::ProgramInfo(const allocator_type& alloc) noexcept
|
||||
: attributes(alloc) {}
|
||||
|
||||
ProgramInfo::ProgramInfo(IProgramInfo programInfoIn, gfx::ShaderInfo shaderInfoIn, ccstd::pmr::vector<gfx::Attribute> attributesIn, ccstd::vector<signed> blockSizesIn, Record<ccstd::string, uint32_t> handleMapIn, const allocator_type& alloc) noexcept
|
||||
ProgramInfo::ProgramInfo(IProgramInfo programInfoIn, gfx::ShaderInfo shaderInfoIn, ccstd::pmr::vector<gfx::Attribute> attributesIn, ccstd::vector<signed> blockSizesIn, ccstd::unordered_map<ccstd::string, uint32_t> handleMapIn, const allocator_type& alloc) noexcept
|
||||
: programInfo(std::move(programInfoIn)),
|
||||
shaderInfo(std::move(shaderInfoIn)),
|
||||
attributes(std::move(attributesIn), alloc),
|
||||
|
||||
@@ -49,7 +49,7 @@ struct ProgramInfo {
|
||||
}
|
||||
|
||||
ProgramInfo(const allocator_type& alloc) noexcept; // NOLINT
|
||||
ProgramInfo(IProgramInfo programInfoIn, gfx::ShaderInfo shaderInfoIn, ccstd::pmr::vector<gfx::Attribute> attributesIn, ccstd::vector<signed> blockSizesIn, Record<ccstd::string, uint32_t> handleMapIn, const allocator_type& alloc) noexcept;
|
||||
ProgramInfo(IProgramInfo programInfoIn, gfx::ShaderInfo shaderInfoIn, ccstd::pmr::vector<gfx::Attribute> attributesIn, ccstd::vector<signed> blockSizesIn, ccstd::unordered_map<ccstd::string, uint32_t> handleMapIn, const allocator_type& alloc) noexcept;
|
||||
ProgramInfo(ProgramInfo&& rhs, const allocator_type& alloc);
|
||||
ProgramInfo(ProgramInfo const& rhs, const allocator_type& alloc);
|
||||
|
||||
@@ -62,7 +62,7 @@ struct ProgramInfo {
|
||||
gfx::ShaderInfo shaderInfo;
|
||||
ccstd::pmr::vector<gfx::Attribute> attributes;
|
||||
ccstd::vector<signed> blockSizes;
|
||||
Record<ccstd::string, uint32_t> handleMap;
|
||||
ccstd::unordered_map<ccstd::string, uint32_t> handleMap;
|
||||
};
|
||||
|
||||
struct ProgramGroup {
|
||||
|
||||
@@ -71,7 +71,7 @@ public:
|
||||
virtual ProgramProxy *getProgramVariant(gfx::Device *device, uint32_t phaseID, const ccstd::string &name, MacroRecord &defines, const ccstd::pmr::string *key) = 0;
|
||||
virtual gfx::PipelineState *getComputePipelineState(gfx::Device *device, uint32_t phaseID, const ccstd::string &name, MacroRecord &defines, const ccstd::pmr::string *key) = 0;
|
||||
virtual const ccstd::vector<int32_t> &getBlockSizes(uint32_t phaseID, const ccstd::string &programName) const = 0;
|
||||
virtual const Record<ccstd::string, uint32_t> &getHandleMap(uint32_t phaseID, const ccstd::string &programName) const = 0;
|
||||
virtual const ccstd::unordered_map<ccstd::string, uint32_t> &getHandleMap(uint32_t phaseID, const ccstd::string &programName) const = 0;
|
||||
virtual uint32_t getProgramID(uint32_t phaseID, const ccstd::pmr::string &programName) = 0;
|
||||
virtual uint32_t getDescriptorNameID(const ccstd::pmr::string &name) = 0;
|
||||
virtual const ccstd::pmr::string &getDescriptorName(uint32_t nameID) = 0;
|
||||
|
||||
@@ -687,7 +687,7 @@ void Pass::doInit(const IPassInfoFull &info, bool /*copyDefines*/ /* = false */)
|
||||
// store handles
|
||||
_propertyHandleMap = handleMap;
|
||||
auto &directHandleMap = _propertyHandleMap;
|
||||
Record<ccstd::string, uint32_t> indirectHandleMap;
|
||||
ccstd::unordered_map<ccstd::string, uint32_t> indirectHandleMap;
|
||||
for (const auto &properties : _properties) {
|
||||
if (!properties.second.handleInfo.has_value()) {
|
||||
continue;
|
||||
@@ -727,7 +727,6 @@ void Pass::buildUniformBlock(
|
||||
gfx::BufferViewInfo &bufferViewInfo,
|
||||
ccstd::vector<uint32_t> &startOffsets,
|
||||
size_t &count) {
|
||||
|
||||
const auto alignment = _device->getCapabilities().uboOffsetAlignment;
|
||||
bufferViewInfo.buffer = _rootBuffer;
|
||||
bufferViewInfo.offset = startOffsets[count++];
|
||||
|
||||
@@ -336,7 +336,7 @@ protected:
|
||||
index_t _propertyIndex{0};
|
||||
ccstd::string _programName;
|
||||
IPassDynamics _dynamics;
|
||||
Record<ccstd::string, uint32_t> _propertyHandleMap;
|
||||
ccstd::unordered_map<ccstd::string, uint32_t> _propertyHandleMap;
|
||||
IntrusivePtr<ArrayBuffer> _rootBlock;
|
||||
ccstd::vector<IBlockRef> _blocks; // Point to position in _rootBlock
|
||||
|
||||
@@ -356,8 +356,8 @@ protected:
|
||||
gfx::PrimitiveMode _primitive{gfx::PrimitiveMode::TRIANGLE_LIST};
|
||||
BatchingSchemes _batchingScheme{BatchingSchemes::NONE};
|
||||
gfx::DynamicStateFlagBit _dynamicStates{gfx::DynamicStateFlagBit::NONE};
|
||||
Record<int32_t, IntrusivePtr<pipeline::InstancedBuffer>> _instancedBuffers;
|
||||
Record<int32_t, IntrusivePtr<pipeline::BatchedBuffer>> _batchedBuffers;
|
||||
ccstd::unordered_map<int32_t, IntrusivePtr<pipeline::InstancedBuffer>> _instancedBuffers;
|
||||
ccstd::unordered_map<int32_t, IntrusivePtr<pipeline::BatchedBuffer>> _batchedBuffers;
|
||||
|
||||
ccstd::hash_t _hash{0U};
|
||||
// external references
|
||||
|
||||
@@ -80,9 +80,11 @@ TEST(simpleClosedBarrierTest, test11) {
|
||||
ExpectEq(node3.blockBarrier.rearBarriers.size() == 2, true);
|
||||
ExpectEq(node3.subpassBarriers.empty(), true);
|
||||
|
||||
ExpectEq(node3.blockBarrier.frontBarriers[0].type == cc::gfx::BarrierType::SPLIT_END, true);
|
||||
ExpectEq(node3.blockBarrier.frontBarriers[0].beginStatus.vertID == 1, true);
|
||||
ExpectEq(node3.blockBarrier.frontBarriers[0].endStatus.vertID == 3, true);
|
||||
const auto& res1Index = std::find_if(node3.blockBarrier.frontBarriers.begin(), node3.blockBarrier.frontBarriers.end(), [](const Barrier& barrier) { return barrier.resourceID == 1; });
|
||||
ExpectEq(res1Index != node3.blockBarrier.frontBarriers.end(), true);
|
||||
ExpectEq(res1Index->type == cc::gfx::BarrierType::SPLIT_END, true);
|
||||
ExpectEq(res1Index->beginStatus.vertID == 1, true);
|
||||
ExpectEq(res1Index->endStatus.vertID == 3, true);
|
||||
// res 5
|
||||
ExpectEq(node3.blockBarrier.rearBarriers[0].type == cc::gfx::BarrierType::FULL, true);
|
||||
ExpectEq(node3.blockBarrier.rearBarriers[0].beginStatus.vertID == 3, true);
|
||||
@@ -97,10 +99,11 @@ TEST(simpleClosedBarrierTest, test11) {
|
||||
ExpectEq(node4.blockBarrier.rearBarriers.size() == 1, true);
|
||||
ExpectEq(node4.subpassBarriers.empty(), true);
|
||||
|
||||
ExpectEq(node4.blockBarrier.frontBarriers[0].resourceID == 3, true);
|
||||
ExpectEq(node4.blockBarrier.frontBarriers[0].type == cc::gfx::BarrierType::SPLIT_END, true);
|
||||
ExpectEq(node4.blockBarrier.frontBarriers[0].beginStatus.vertID == 2, true);
|
||||
ExpectEq(node4.blockBarrier.frontBarriers[0].endStatus.vertID == 4, true);
|
||||
const auto& res3Index = std::find_if(node4.blockBarrier.frontBarriers.begin(), node4.blockBarrier.frontBarriers.end(), [](const Barrier& barrier) { return barrier.resourceID == 3; });
|
||||
ExpectEq(res3Index != node4.blockBarrier.frontBarriers.end(), true);
|
||||
ExpectEq(res3Index->type == cc::gfx::BarrierType::SPLIT_END, true);
|
||||
ExpectEq(res3Index->beginStatus.vertID == 2, true);
|
||||
ExpectEq(res3Index->endStatus.vertID == 4, true);
|
||||
|
||||
ExpectEq(node4.blockBarrier.rearBarriers[0].resourceID == 6, true);
|
||||
ExpectEq(node4.blockBarrier.rearBarriers[0].type == cc::gfx::BarrierType::FULL, true);
|
||||
@@ -112,14 +115,16 @@ TEST(simpleClosedBarrierTest, test11) {
|
||||
ExpectEq(node5.blockBarrier.rearBarriers.size() == 1, true);
|
||||
ExpectEq(node5.subpassBarriers.empty(), true);
|
||||
|
||||
ExpectEq(node5.blockBarrier.frontBarriers[0].resourceID == 2, true);
|
||||
ExpectEq(node5.blockBarrier.frontBarriers[0].type == cc::gfx::BarrierType::SPLIT_END, true);
|
||||
ExpectEq(node5.blockBarrier.frontBarriers[0].beginStatus.vertID == 2, true);
|
||||
ExpectEq(node5.blockBarrier.frontBarriers[0].endStatus.vertID == 5, true);
|
||||
ExpectEq(node5.blockBarrier.frontBarriers[2].resourceID == 4, true);
|
||||
ExpectEq(node5.blockBarrier.frontBarriers[2].type == cc::gfx::BarrierType::SPLIT_END, true);
|
||||
ExpectEq(node5.blockBarrier.frontBarriers[2].beginStatus.vertID == 3, true);
|
||||
ExpectEq(node5.blockBarrier.frontBarriers[2].endStatus.vertID == 5, true);
|
||||
const auto& res2Index = std::find_if(node5.blockBarrier.frontBarriers.begin(), node5.blockBarrier.frontBarriers.end(), [](const Barrier& barrier) { return barrier.resourceID == 2; });
|
||||
ExpectEq(res2Index != node5.blockBarrier.frontBarriers.end(), true);
|
||||
ExpectEq(res2Index->type == cc::gfx::BarrierType::SPLIT_END, true);
|
||||
ExpectEq(res2Index->beginStatus.vertID == 2, true);
|
||||
ExpectEq(res2Index->endStatus.vertID == 5, true);
|
||||
const auto& res4Index = std::find_if(node5.blockBarrier.frontBarriers.begin(), node5.blockBarrier.frontBarriers.end(), [](const Barrier& barrier) { return barrier.resourceID == 4; });
|
||||
ExpectEq(res4Index != node5.blockBarrier.frontBarriers.end(), true);
|
||||
ExpectEq(res4Index->type == cc::gfx::BarrierType::SPLIT_END, true);
|
||||
ExpectEq(res4Index->beginStatus.vertID == 3, true);
|
||||
ExpectEq(res4Index->endStatus.vertID == 5, true);
|
||||
|
||||
ExpectEq(node5.blockBarrier.rearBarriers[0].resourceID == 7, true);
|
||||
ExpectEq(node5.blockBarrier.rearBarriers[0].type == cc::gfx::BarrierType::SPLIT_BEGIN, true);
|
||||
|
||||
@@ -262,7 +262,7 @@ using namespace cc;
|
||||
%attribute(cc::scene::Pass, cc::IProgramInfo*, shaderInfo, getShaderInfo);
|
||||
%attribute(cc::scene::Pass, cc::gfx::DescriptorSetLayout*, localSetLayout, getLocalSetLayout);
|
||||
%attribute(cc::scene::Pass, ccstd::string&, program, getProgram);
|
||||
%attribute(cc::scene::Pass, %arg(Record<ccstd::string, cc::IPropertyInfo> &), properties, getProperties);
|
||||
%attribute(cc::scene::Pass, %arg(ccstd::unordered_map<ccstd::string, cc::IPropertyInfo> &), properties, getProperties);
|
||||
%attribute(cc::scene::Pass, cc::MacroRecord&, defines, getDefines);
|
||||
%attribute(cc::scene::Pass, index_t, passIndex, getPassIndex);
|
||||
%attribute(cc::scene::Pass, index_t, propertyIndex, getPropertyIndex);
|
||||
|
||||
Vendored
+5
-2
@@ -23,7 +23,7 @@
|
||||
*/
|
||||
|
||||
/* eslint-disable import/no-dynamic-require */
|
||||
import { BAIDU, TAOBAO, TAOBAO_MINIGAME, WECHAT, XIAOMI } from 'internal:constants';
|
||||
import { BAIDU, TAOBAO, TAOBAO_MINIGAME, WECHAT, WECHAT_MINI_PROGRAM, XIAOMI } from 'internal:constants';
|
||||
|
||||
declare const require: (path: string) => any;
|
||||
declare const __baiduRequire: (path: string) => any;
|
||||
@@ -42,9 +42,12 @@ export function loadJsFile (path: string): any {
|
||||
if (BAIDU) {
|
||||
return __baiduRequire(`./${path}`);
|
||||
}
|
||||
if (WECHAT) {
|
||||
if (WECHAT || WECHAT_MINI_PROGRAM) {
|
||||
return __wxRequire(path);
|
||||
}
|
||||
if (TAOBAO_MINIGAME) {
|
||||
return globalThis.__taobaoRequire(path);
|
||||
}
|
||||
if (TAOBAO) {
|
||||
// NOTE: Taobao doesn't support dynamic require
|
||||
return undefined;
|
||||
|
||||
@@ -74,6 +74,7 @@ Object.defineProperty(minigame, 'orientation', {
|
||||
});
|
||||
// #endregion SystemInfo
|
||||
|
||||
// eslint-disable-next-line func-names
|
||||
function detectLandscapeSupport () {
|
||||
const locSysInfo = minigame.getSystemInfoSync();
|
||||
if (typeof locSysInfo.deviceOrientation === 'string' && locSysInfo.deviceOrientation.startsWith('landscape')) {
|
||||
@@ -91,6 +92,7 @@ const polyfilledCreateInnerAudio = createInnerAudioContextPolyfill(my, {
|
||||
onStop: false,
|
||||
onSeek: false,
|
||||
}, true);
|
||||
// eslint-disable-next-line func-names
|
||||
minigame.createInnerAudioContext = function (): InnerAudioContext {
|
||||
// NOTE: `onCanPlay` is not standard minigame interface,
|
||||
// so here we mark audio as type of any
|
||||
@@ -102,6 +104,7 @@ minigame.createInnerAudioContext = function (): InnerAudioContext {
|
||||
// #region Audio
|
||||
|
||||
// #region Font
|
||||
// eslint-disable-next-line func-names
|
||||
minigame.loadFont = function (url) {
|
||||
// my.loadFont crash when url is not in user data path
|
||||
return 'Arial';
|
||||
@@ -110,6 +113,7 @@ minigame.loadFont = function (url) {
|
||||
|
||||
// #region Accelerometer
|
||||
let _accelerometerCb: AccelerometerChangeCallback | undefined;
|
||||
// eslint-disable-next-line func-names
|
||||
minigame.onAccelerometerChange = function (cb: AccelerometerChangeCallback) {
|
||||
minigame.offAccelerometerChange();
|
||||
// onAccelerometerChange would start accelerometer
|
||||
@@ -131,12 +135,14 @@ minigame.onAccelerometerChange = function (cb: AccelerometerChangeCallback) {
|
||||
cb(resClone);
|
||||
};
|
||||
};
|
||||
// eslint-disable-next-line func-names
|
||||
minigame.offAccelerometerChange = function (cb?: AccelerometerChangeCallback) {
|
||||
if (_accelerometerCb) {
|
||||
my.offAccelerometerChange(_accelerometerCb);
|
||||
_accelerometerCb = undefined;
|
||||
}
|
||||
};
|
||||
// eslint-disable-next-line func-names
|
||||
minigame.startAccelerometer = function (res: any) {
|
||||
if (_accelerometerCb) {
|
||||
my.onAccelerometerChange(_accelerometerCb);
|
||||
@@ -145,6 +151,7 @@ minigame.startAccelerometer = function (res: any) {
|
||||
console.error('minigame.onAccelerometerChange() should be invoked before minigame.startAccelerometer() on taobao platform');
|
||||
}
|
||||
};
|
||||
// eslint-disable-next-line func-names
|
||||
minigame.stopAccelerometer = function (res: any) {
|
||||
// my.stopAccelerometer() is not implemented.
|
||||
minigame.offAccelerometerChange();
|
||||
@@ -154,8 +161,9 @@ minigame.stopAccelerometer = function (res: any) {
|
||||
// #region SafeArea
|
||||
// It should be a value that is not multiplied by dpr
|
||||
minigame.getSafeArea = function () {
|
||||
const systemInfo = minigame.getSystemInfoSync();
|
||||
const systemInfo = my.getWindowInfoSync();
|
||||
if (typeof systemInfo.safeArea !== 'undefined') {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
|
||||
return systemInfo.safeArea;
|
||||
}
|
||||
console.warn('getSafeArea is not supported on this platform');
|
||||
@@ -177,6 +185,7 @@ if (!my.isIDE) {
|
||||
const locCanvas = $global.screencanvas;
|
||||
if (locCanvas) {
|
||||
const originalGetContext = locCanvas.getContext.bind(locCanvas);
|
||||
// eslint-disable-next-line func-names
|
||||
locCanvas.getContext = function (name, param) {
|
||||
if (typeof name === 'string' && typeof param === 'object' && name.startsWith('webgl')) {
|
||||
Object.assign(param, { enable_flip_y_after_read_pixels: false });
|
||||
@@ -204,6 +213,7 @@ function adapterGL (gl) {
|
||||
// Android return value: undefined. iOS return value: {ID: -1}.
|
||||
if (my.getSystemInfoSync().platform.toLocaleLowerCase() === 'ios') {
|
||||
const originalGetUniformLocation = gl.getUniformLocation.bind(gl);
|
||||
// eslint-disable-next-line func-names
|
||||
gl.getUniformLocation = function (program, name) {
|
||||
const glLoc = originalGetUniformLocation(program, name);
|
||||
if (glLoc && glLoc.ID === -1) {
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
/*
|
||||
Copyright (c) 2022-2023 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 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.
|
||||
*/
|
||||
|
||||
import { IMiniGame, SystemInfo } from 'pal/minigame';
|
||||
import { Orientation } from '../screen-adapter/enum-type';
|
||||
import { cloneObject, createInnerAudioContextPolyfill, versionCompare } from '../utils';
|
||||
|
||||
declare let wx: any;
|
||||
|
||||
// @ts-expect-error can't init minigame when it's declared
|
||||
const minigame: IMiniGame = {};
|
||||
cloneObject(minigame, wx);
|
||||
|
||||
// #region platform related
|
||||
minigame.wx = {};
|
||||
minigame.wx.onKeyDown = wx.onKeyDown?.bind(wx);
|
||||
minigame.wx.onKeyUp = wx.onKeyUp?.bind(wx);
|
||||
minigame.wx.onMouseDown = wx.onMouseDown?.bind(wx);
|
||||
minigame.wx.onMouseMove = wx.onMouseMove?.bind(wx);
|
||||
minigame.wx.onMouseUp = wx.onMouseUp?.bind(wx);
|
||||
minigame.wx.onWheel = wx.onWheel?.bind(wx);
|
||||
// #endregion platform related
|
||||
|
||||
// #region SystemInfo
|
||||
let _cachedSystemInfo: SystemInfo = wx.getSystemInfoSync();
|
||||
// @ts-expect-error TODO: move into minigame.d.ts
|
||||
minigame.testAndUpdateSystemInfoCache = function (testAmount: number, testInterval: number) {
|
||||
let successfullyTestTimes = 0;
|
||||
let intervalTimer: number | null = null;
|
||||
function testCachedSystemInfo () {
|
||||
const currentSystemInfo = wx.getSystemInfoSync() as SystemInfo;
|
||||
if (_cachedSystemInfo.screenWidth === currentSystemInfo.screenWidth && _cachedSystemInfo.screenHeight === currentSystemInfo.screenHeight) {
|
||||
if (++successfullyTestTimes >= testAmount && intervalTimer !== null) {
|
||||
clearInterval(intervalTimer);
|
||||
intervalTimer = null;
|
||||
}
|
||||
} else {
|
||||
successfullyTestTimes = 0;
|
||||
}
|
||||
_cachedSystemInfo = currentSystemInfo;
|
||||
}
|
||||
intervalTimer = setInterval(testCachedSystemInfo, testInterval);
|
||||
};
|
||||
// @ts-expect-error TODO: update when view resize
|
||||
minigame.testAndUpdateSystemInfoCache(10, 500);
|
||||
minigame.onWindowResize?.(() => {
|
||||
// update cached system info
|
||||
_cachedSystemInfo = wx.getSystemInfoSync() as SystemInfo;
|
||||
});
|
||||
minigame.getSystemInfoSync = function () {
|
||||
return _cachedSystemInfo;
|
||||
};
|
||||
|
||||
const systemInfo = minigame.getSystemInfoSync();
|
||||
minigame.isDevTool = (systemInfo.platform === 'devtools');
|
||||
// NOTE: size and orientation info is wrong at the init phase, especially on iOS device
|
||||
Object.defineProperty(minigame, 'isLandscape', {
|
||||
get () {
|
||||
const locSystemInfo = wx.getSystemInfoSync() as SystemInfo;
|
||||
if (typeof locSystemInfo.deviceOrientation === 'string') {
|
||||
return locSystemInfo.deviceOrientation.startsWith('landscape');
|
||||
} else {
|
||||
return locSystemInfo.screenWidth > locSystemInfo.screenHeight;
|
||||
}
|
||||
},
|
||||
});
|
||||
// init landscapeOrientation as LANDSCAPE_RIGHT
|
||||
let landscapeOrientation = Orientation.LANDSCAPE_RIGHT;
|
||||
if (systemInfo.platform.toLocaleLowerCase() !== 'android') {
|
||||
// onDeviceOrientationChange doesn't work well on Android.
|
||||
// see this issue: https://developers.weixin.qq.com/community/minigame/doc/000482138dc460e56cfaa5cb15bc00
|
||||
wx.onDeviceOrientationChange((res) => {
|
||||
if (res.value === 'landscape') {
|
||||
landscapeOrientation = Orientation.LANDSCAPE_RIGHT;
|
||||
} else if (res.value === 'landscapeReverse') {
|
||||
landscapeOrientation = Orientation.LANDSCAPE_LEFT;
|
||||
}
|
||||
});
|
||||
}
|
||||
Object.defineProperty(minigame, 'orientation', {
|
||||
get () {
|
||||
return minigame.isLandscape ? landscapeOrientation : Orientation.PORTRAIT;
|
||||
},
|
||||
});
|
||||
// #endregion SystemInfo
|
||||
|
||||
// #region Accelerometer
|
||||
let _accelerometerCb: AccelerometerChangeCallback | undefined;
|
||||
minigame.onAccelerometerChange = function (cb: AccelerometerChangeCallback) {
|
||||
minigame.offAccelerometerChange();
|
||||
// onAccelerometerChange would start accelerometer
|
||||
// so we won't call this method here
|
||||
_accelerometerCb = (res: any) => {
|
||||
let x = res.x;
|
||||
let y = res.y;
|
||||
if (minigame.isLandscape) {
|
||||
const orientationFactor = (landscapeOrientation === Orientation.LANDSCAPE_RIGHT ? 1 : -1);
|
||||
const tmp = x;
|
||||
x = -y * orientationFactor;
|
||||
y = tmp * orientationFactor;
|
||||
}
|
||||
|
||||
const resClone = {
|
||||
x,
|
||||
y,
|
||||
z: res.z,
|
||||
};
|
||||
cb(resClone);
|
||||
};
|
||||
};
|
||||
minigame.offAccelerometerChange = function (cb?: AccelerometerChangeCallback) {
|
||||
if (_accelerometerCb) {
|
||||
wx.offAccelerometerChange(_accelerometerCb);
|
||||
_accelerometerCb = undefined;
|
||||
}
|
||||
};
|
||||
minigame.startAccelerometer = function (res: any) {
|
||||
if (_accelerometerCb) {
|
||||
wx.onAccelerometerChange(_accelerometerCb);
|
||||
}
|
||||
wx.startAccelerometer(res);
|
||||
};
|
||||
// #endregion Accelerometer
|
||||
|
||||
minigame.createInnerAudioContext = createInnerAudioContextPolyfill(wx, {
|
||||
onPlay: true,
|
||||
onPause: true,
|
||||
onStop: true,
|
||||
onSeek: false,
|
||||
}, true);
|
||||
|
||||
// #region SafeArea
|
||||
// FIX_ME: wrong safe area when orientation is landscape left
|
||||
minigame.getSafeArea = function () {
|
||||
const locSystemInfo = wx.getSystemInfoSync() as SystemInfo;
|
||||
return locSystemInfo.safeArea;
|
||||
};
|
||||
// #endregion SafeArea
|
||||
|
||||
// HACK: adapt GL.useProgram: use program not supported to unbind program on pc end
|
||||
if (systemInfo.platform === 'windows' && versionCompare(systemInfo.SDKVersion, '2.16.0') < 0) {
|
||||
// @ts-expect-error canvas defined in global
|
||||
const locCanvas = canvas;
|
||||
if (locCanvas) {
|
||||
const webglRC = locCanvas.getContext('webgl');
|
||||
const originalUseProgram = webglRC.useProgram.bind(webglRC);
|
||||
webglRC.useProgram = function (program) {
|
||||
if (program) {
|
||||
originalUseProgram(program);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export { minigame };
|
||||
@@ -22,7 +22,7 @@
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { ALIPAY, BAIDU, BYTEDANCE, COCOSPLAY, RUNTIME_BASED, VIVO, WECHAT } from 'internal:constants';
|
||||
import { ALIPAY, BAIDU, BYTEDANCE, COCOSPLAY, RUNTIME_BASED, VIVO, WECHAT, WECHAT_MINI_PROGRAM } from 'internal:constants';
|
||||
import { minigame } from 'pal/minigame';
|
||||
import { ConfigOrientation, IScreenOptions, SafeAreaEdge } from 'pal/screen-adapter';
|
||||
import { systemInfo } from 'pal/system-info';
|
||||
@@ -156,7 +156,7 @@ class ScreenAdapter extends EventTarget {
|
||||
constructor () {
|
||||
super();
|
||||
// TODO: onResize or onOrientationChange is not supported well
|
||||
if (WECHAT || COCOSPLAY) {
|
||||
if (WECHAT || WECHAT_MINI_PROGRAM || COCOSPLAY) {
|
||||
minigame.onWindowResize?.(() => {
|
||||
this.emit('window-resize', this.windowSize.width, this.windowSize.height);
|
||||
});
|
||||
|
||||
@@ -38,6 +38,7 @@ export enum Platform {
|
||||
OPENHARMONY = 'OPENHARMONY',
|
||||
// Minigame
|
||||
WECHAT_GAME = 'WECHAT_GAME',
|
||||
WECHAT_MINI_PROGRAM = 'WECHAT_MINI_PROGRAM',
|
||||
BAIDU_MINI_GAME = 'BAIDU_MINI_GAME',
|
||||
XIAOMI_QUICK_GAME = 'XIAOMI_QUICK_GAME',
|
||||
ALIPAY_MINI_GAME = 'ALIPAY_MINI_GAME',
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { ALIPAY, BAIDU, BYTEDANCE, COCOSPLAY, HUAWEI, LINKSURE, OPPO, QTT, VIVO, WECHAT, XIAOMI, DEBUG, TEST, TAOBAO, TAOBAO_MINIGAME } from 'internal:constants';
|
||||
import { ALIPAY, BAIDU, BYTEDANCE, COCOSPLAY, HUAWEI, LINKSURE, OPPO, QTT, VIVO, WECHAT, XIAOMI, DEBUG, TEST, TAOBAO, TAOBAO_MINIGAME, WECHAT_MINI_PROGRAM } from 'internal:constants';
|
||||
import { minigame } from 'pal/minigame';
|
||||
import { IFeatureMap } from 'pal/system-info';
|
||||
import { EventTarget } from '../../../cocos/core/event';
|
||||
@@ -32,6 +32,8 @@ import { BrowserType, NetworkType, OS, Platform, Language, Feature } from '../en
|
||||
let currentPlatform: Platform;
|
||||
if (WECHAT) {
|
||||
currentPlatform = Platform.WECHAT_GAME;
|
||||
} else if (WECHAT_MINI_PROGRAM) {
|
||||
currentPlatform = Platform.WECHAT_MINI_PROGRAM;
|
||||
} else if (BAIDU) {
|
||||
currentPlatform = Platform.BAIDU_MINI_GAME;
|
||||
} else if (XIAOMI) {
|
||||
@@ -130,8 +132,8 @@ class SystemInfo extends EventTarget {
|
||||
[Feature.WEBP]: false, // Initialize in Promise,
|
||||
[Feature.IMAGE_BITMAP]: false,
|
||||
[Feature.WEB_VIEW]: false,
|
||||
[Feature.VIDEO_PLAYER]: WECHAT || OPPO,
|
||||
[Feature.SAFE_AREA]: WECHAT || BYTEDANCE,
|
||||
[Feature.VIDEO_PLAYER]: WECHAT || WECHAT_MINI_PROGRAM || OPPO,
|
||||
[Feature.SAFE_AREA]: WECHAT || WECHAT_MINI_PROGRAM || BYTEDANCE,
|
||||
|
||||
[Feature.INPUT_TOUCH]: !isPCWechat,
|
||||
[Feature.EVENT_KEYBOARD]: isPCWechat,
|
||||
@@ -161,6 +163,10 @@ class SystemInfo extends EventTarget {
|
||||
|
||||
private _supportsWebp (): Promise<boolean> {
|
||||
return new Promise<boolean>((resolve, reject) => {
|
||||
if (WECHAT_MINI_PROGRAM) {
|
||||
resolve(true);
|
||||
return;
|
||||
}
|
||||
// HACK: webp base64 doesn't support on Wechat Android, which reports some internal error log.
|
||||
if (WECHAT && this.os === OS.ANDROID) {
|
||||
resolve(false);
|
||||
|
||||
@@ -18,13 +18,16 @@ const sys = cc.sys;
|
||||
if (sys.platform === sys.Platform.BAIDU_MINI_GAME) {
|
||||
require = __baiduRequire;
|
||||
}
|
||||
if (sys.platform === sys.Platform.TAOBAO_MINI_GAME) {
|
||||
require = globalThis.__taobaoRequire;
|
||||
}
|
||||
|
||||
function downloadScript (url, options, onComplete) {
|
||||
if (REGEX.test(url)) {
|
||||
onComplete && onComplete(new Error('Can not load remote scripts'));
|
||||
} else {
|
||||
if (sys.platform === sys.Platform.TAOBAO_MINI_GAME) {
|
||||
__taobaoRequire(`../../../${url}`);
|
||||
require(`../../../${url}`);
|
||||
} else if (sys.platform !== sys.Platform.TAOBAO_CREATIVE_APP) { //Can't load scripts dynamically on Taobao platform
|
||||
require(`../../../${url}`);
|
||||
}
|
||||
@@ -253,7 +256,7 @@ function downloadBundle (nameOrUrl, options, onComplete) {
|
||||
js = `assets/${bundleName}/index.${suffix}js`;
|
||||
}
|
||||
if (sys.platform === sys.Platform.TAOBAO_MINI_GAME) {
|
||||
__taobaoRequire(js);
|
||||
require(js);
|
||||
} else if (sys.platform !== sys.Platform.TAOBAO_CREATIVE_APP) { // Can't load scripts dynamically on Taobao platform
|
||||
require(`./${js}`);
|
||||
}
|
||||
|
||||
@@ -41,7 +41,9 @@ const CanvasProxy = new Proxy(Canvas, {
|
||||
|
||||
canvas.dispatchEvent = function (event = {}) {
|
||||
console.log('canvas.dispatchEvent', event.type, event);
|
||||
// nothing to do
|
||||
if (my.isIDE) {
|
||||
$global.document.dispatchEvent(event);
|
||||
}
|
||||
};
|
||||
|
||||
Object.defineProperty(canvas, 'clientWidth', {
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import './Canvas'
|
||||
|
||||
var screencanvas = $global.screencanvas;
|
||||
let HTMLImageElement = screencanvas.createImage().constructor;
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// var screencanvas = $global.screencanvas;
|
||||
import './Canvas'
|
||||
|
||||
function Image () {
|
||||
|
||||
return $global.screencanvas.createImage();
|
||||
}
|
||||
|
||||
export default Image;
|
||||
|
||||
@@ -1,64 +1,74 @@
|
||||
// import HTMLCanvasElement from './HTMLCanvasElement'
|
||||
import { innerWidth, innerHeight } from './WindowProperties'
|
||||
import { innerWidth, innerHeight } from './WindowProperties';
|
||||
|
||||
let hasModifiedCanvasPrototype = false
|
||||
let hasInit2DContextConstructor = false
|
||||
let hasInitWebGLContextConstructor = false
|
||||
const hasModifiedCanvasPrototype = false;
|
||||
const hasInit2DContextConstructor = false;
|
||||
const hasInitWebGLContextConstructor = false;
|
||||
|
||||
export default function Canvas() {
|
||||
const canvas = wx.createCanvas()
|
||||
export default function Canvas () {
|
||||
const canvas = wx.createCanvas();
|
||||
|
||||
canvas.type = 'canvas'
|
||||
canvas.type = 'canvas';
|
||||
|
||||
// canvas.__proto__.__proto__.__proto__ = new HTMLCanvasElement()
|
||||
|
||||
const _getContext = canvas.getContext
|
||||
const _getContext = canvas.getContext;
|
||||
|
||||
canvas.getBoundingClientRect = () => {
|
||||
const ret = {
|
||||
top: 0,
|
||||
left: 0,
|
||||
width: window.innerWidth,
|
||||
height: window.innerHeight
|
||||
}
|
||||
return ret
|
||||
}
|
||||
height: window.innerHeight,
|
||||
};
|
||||
return ret;
|
||||
};
|
||||
|
||||
canvas.style = {
|
||||
top: '0px',
|
||||
left: '0px',
|
||||
width: innerWidth + 'px',
|
||||
height: innerHeight + 'px',
|
||||
}
|
||||
width: `${innerWidth}px`,
|
||||
height: `${innerHeight}px`,
|
||||
};
|
||||
|
||||
canvas.addEventListener = function (type, listener, options = {}) {
|
||||
// console.log('canvas.addEventListener', type);
|
||||
document.addEventListener(type, listener, options);
|
||||
}
|
||||
if (typeof getApp === 'function') {
|
||||
// for wechat miniprogram
|
||||
GameGlobal.document.addEventListener(type, listener, options);
|
||||
} else {
|
||||
// for wechat minigame
|
||||
document.addEventListener(type, listener, options);
|
||||
}
|
||||
};
|
||||
|
||||
canvas.removeEventListener = function (type, listener) {
|
||||
// console.log('canvas.removeEventListener', type);
|
||||
document.removeEventListener(type, listener);
|
||||
}
|
||||
if (typeof getApp === 'function') {
|
||||
// for wechat miniprogram
|
||||
GameGlobal.document.removeEventListener(type, listener);
|
||||
} else {
|
||||
// for wechat minigame
|
||||
document.removeEventListener(type, listener);
|
||||
}
|
||||
};
|
||||
|
||||
canvas.dispatchEvent = function (event = {}) {
|
||||
console.log('canvas.dispatchEvent' , event.type, event);
|
||||
console.log('canvas.dispatchEvent', event.type, event);
|
||||
// nothing to do
|
||||
}
|
||||
};
|
||||
|
||||
Object.defineProperty(canvas, 'clientWidth', {
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
return innerWidth
|
||||
}
|
||||
})
|
||||
get: function get () {
|
||||
return innerWidth;
|
||||
},
|
||||
});
|
||||
|
||||
Object.defineProperty(canvas, 'clientHeight', {
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
return innerHeight
|
||||
}
|
||||
})
|
||||
get: function get () {
|
||||
return innerHeight;
|
||||
},
|
||||
});
|
||||
|
||||
return canvas
|
||||
return canvas;
|
||||
}
|
||||
|
||||
@@ -1,64 +1,65 @@
|
||||
import * as _window from './window'
|
||||
import document from './document'
|
||||
import HTMLElement from './HTMLElement'
|
||||
import * as _window from './window';
|
||||
import document from './document';
|
||||
import HTMLElement from './HTMLElement';
|
||||
|
||||
const global = GameGlobal
|
||||
const global = GameGlobal;
|
||||
|
||||
function inject () {
|
||||
_window.document = document;
|
||||
|
||||
_window.addEventListener = (type, listener) => {
|
||||
_window.document.addEventListener(type, listener)
|
||||
}
|
||||
_window.document.addEventListener(type, listener);
|
||||
};
|
||||
_window.removeEventListener = (type, listener) => {
|
||||
_window.document.removeEventListener(type, listener)
|
||||
}
|
||||
_window.document.removeEventListener(type, listener);
|
||||
};
|
||||
_window.dispatchEvent = function (event = {}) {
|
||||
console.log('window.dispatchEvent' , event.type, event);
|
||||
console.log('window.dispatchEvent', event.type, event);
|
||||
// nothing to do
|
||||
}
|
||||
};
|
||||
|
||||
const { platform } = wx.getSystemInfoSync()
|
||||
const { platform } = wx.getSystemInfoSync();
|
||||
|
||||
// 开发者工具无法重定义 window
|
||||
if (typeof __devtoolssubcontext === 'undefined' && platform === 'devtools') {
|
||||
for (const key in _window) {
|
||||
const descriptor = Object.getOwnPropertyDescriptor(global, key)
|
||||
const descriptor = Object.getOwnPropertyDescriptor(global, key);
|
||||
|
||||
if (!descriptor || descriptor.configurable === true) {
|
||||
Object.defineProperty(window, key, {
|
||||
value: _window[key]
|
||||
})
|
||||
value: _window[key],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
for (const key in _window.document) {
|
||||
const descriptor = Object.getOwnPropertyDescriptor(global.document, key)
|
||||
const descriptor = Object.getOwnPropertyDescriptor(global.document, key);
|
||||
|
||||
if (!descriptor || descriptor.configurable === true) {
|
||||
Object.defineProperty(global.document, key, {
|
||||
value: _window.document[key]
|
||||
})
|
||||
value: _window.document[key],
|
||||
});
|
||||
}
|
||||
}
|
||||
window.parent = window
|
||||
window.parent = window;
|
||||
} else {
|
||||
for (const key in _window) {
|
||||
global[key] = _window[key]
|
||||
global[key] = _window[key];
|
||||
}
|
||||
global.window = _window
|
||||
window = global
|
||||
window.top = window.parent = window
|
||||
global.window = _window;
|
||||
window = global;
|
||||
window.top = window.parent = window;
|
||||
}
|
||||
}
|
||||
|
||||
if (!GameGlobal.__isAdapterInjected) {
|
||||
GameGlobal.__isAdapterInjected = true
|
||||
inject()
|
||||
GameGlobal.__isAdapterInjected = true;
|
||||
inject();
|
||||
}
|
||||
|
||||
// overwrite global WebAssembly
|
||||
global.WebAssembly = global.WXWebAssembly
|
||||
global.WebAssembly = global.WXWebAssembly;
|
||||
|
||||
require('../../../../common/xmldom/dom-parser');
|
||||
require('../unify');
|
||||
require('../unify');
|
||||
require('../fs-utils');
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
require('../fs-utils');
|
||||
// require('../fs-utils');
|
||||
require('../../../../common/engine/index');
|
||||
require('./VideoPlayer');
|
||||
require('./sprite-frame');
|
||||
@@ -2,12 +2,12 @@ const utils = require('./utils');
|
||||
|
||||
window.__globalAdapter = window.__globalAdapter || {};
|
||||
if (window.__globalAdapter) {
|
||||
let globalAdapter = window.__globalAdapter;
|
||||
const globalAdapter = window.__globalAdapter;
|
||||
// SystemInfo
|
||||
let systemInfo = wx.getSystemInfoSync();
|
||||
let windowWidth = systemInfo.windowWidth;
|
||||
let windowHeight = systemInfo.windowHeight;
|
||||
let isLandscape = windowWidth > windowHeight;
|
||||
const systemInfo = wx.getSystemInfoSync();
|
||||
const windowWidth = systemInfo.windowWidth;
|
||||
const windowHeight = systemInfo.windowHeight;
|
||||
const isLandscape = windowWidth > windowHeight;
|
||||
globalAdapter.isSubContext = (wx.getOpenDataContext === undefined);
|
||||
globalAdapter.isDevTool = (systemInfo.platform === 'devtools');
|
||||
utils.cloneMethod(globalAdapter, wx, 'getSystemInfoSync');
|
||||
@@ -20,7 +20,7 @@ if (window.__globalAdapter) {
|
||||
|
||||
// Audio
|
||||
utils.cloneMethod(globalAdapter, wx, 'createInnerAudioContext');
|
||||
|
||||
|
||||
// AudioInterruption Evnet
|
||||
utils.cloneMethod(globalAdapter, wx, 'onAudioInterruptionEnd');
|
||||
utils.cloneMethod(globalAdapter, wx, 'onAudioInterruptionBegin');
|
||||
@@ -59,6 +59,12 @@ if (window.__globalAdapter) {
|
||||
utils.cloneMethod(globalAdapter, wx, 'onShow');
|
||||
utils.cloneMethod(globalAdapter, wx, 'onHide');
|
||||
|
||||
// wechat program use onAppShow/onAppHide
|
||||
if (typeof getApp === 'function') {
|
||||
wx.onShow = wx.onAppShow;
|
||||
wx.onHide = wx.onAppHide;
|
||||
}
|
||||
|
||||
// onError
|
||||
utils.cloneMethod(globalAdapter, wx, 'onError');
|
||||
// offError
|
||||
@@ -68,11 +74,10 @@ if (window.__globalAdapter) {
|
||||
let isAccelerometerInit = false;
|
||||
let deviceOrientation = 1;
|
||||
if (wx.onDeviceOrientationChange) {
|
||||
wx.onDeviceOrientationChange(function (res) {
|
||||
wx.onDeviceOrientationChange((res) => {
|
||||
if (res.value === 'landscape') {
|
||||
deviceOrientation = 1;
|
||||
}
|
||||
else if (res.value === 'landscapeReverse') {
|
||||
} else if (res.value === 'landscapeReverse') {
|
||||
deviceOrientation = -1;
|
||||
}
|
||||
});
|
||||
@@ -81,12 +86,12 @@ if (window.__globalAdapter) {
|
||||
startAccelerometer (cb) {
|
||||
if (!isAccelerometerInit) {
|
||||
isAccelerometerInit = true;
|
||||
wx.onAccelerometerChange && wx.onAccelerometerChange(function (res) {
|
||||
let resClone = {};
|
||||
wx.onAccelerometerChange && wx.onAccelerometerChange((res) => {
|
||||
const resClone = {};
|
||||
let x = res.x;
|
||||
let y = res.y;
|
||||
if (isLandscape) {
|
||||
let tmp = x;
|
||||
const tmp = x;
|
||||
x = -y;
|
||||
y = tmp;
|
||||
}
|
||||
@@ -96,8 +101,7 @@ if (window.__globalAdapter) {
|
||||
resClone.z = res.z;
|
||||
cb && cb(resClone);
|
||||
});
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
wx.startAccelerometer && wx.startAccelerometer({
|
||||
fail (err) {
|
||||
console.error('start accelerometer failed', err);
|
||||
@@ -118,4 +122,4 @@ if (window.__globalAdapter) {
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
globalThis.__EDITOR__ = globalThis.process && ('electron' in globalThis.process.versions);
|
||||
|
||||
require('./wasm');
|
||||
const jsbWindow = require('../jsbWindow');
|
||||
|
||||
jsb.device = jsb.Device; // cc namespace will be reset to {} in creator, use jsb namespace instead.
|
||||
@@ -207,10 +208,6 @@ jsb.generateGetSet = function (moduleObj) {
|
||||
for (const key in jsbWindow) {
|
||||
if (globalThis[key] === undefined) {
|
||||
globalThis[key] = jsbWindow[key];
|
||||
console.debug(`[web-adapter] override window.${key}`);
|
||||
} else {
|
||||
// globalThis[key] = jsbWindow[key];
|
||||
console.debug(`[web-adapter] skip window.${key}`);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
/*
|
||||
Copyright (c) 2023 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.
|
||||
*/
|
||||
|
||||
// fix: WebAssembly.instantiate not working well on V8.
|
||||
(function injectWebAssembly() {
|
||||
if (!globalThis.WebAssembly) {
|
||||
console.warn('WebAssembly is not supported!');
|
||||
return;
|
||||
}
|
||||
|
||||
console.info('injectWebAssembly ...');
|
||||
|
||||
const oldWebAssemblyInstantiate = WebAssembly.instantiate;
|
||||
|
||||
WebAssembly.compile = function(bufferSource) {
|
||||
return new Promise((resolve, reject)=>{
|
||||
if (!bufferSource) {
|
||||
reject('WebAssembly.compile: Invalid buffer source!');
|
||||
}
|
||||
else {
|
||||
resolve(new WebAssembly.Module(bufferSource));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
WebAssembly.instantiate = function(bufferSourceOrModule, importObject) {
|
||||
let ret;
|
||||
if (bufferSourceOrModule instanceof WebAssembly.Module) {
|
||||
ret = oldWebAssemblyInstantiate(bufferSourceOrModule, importObject);
|
||||
}
|
||||
else {
|
||||
ret = new Promise((resolve, reject)=>{
|
||||
WebAssembly.compile(bufferSourceOrModule)
|
||||
.then((mod)=>{
|
||||
oldWebAssemblyInstantiate(mod, importObject)
|
||||
.then((instance)=>{
|
||||
resolve({
|
||||
instance: instance,
|
||||
module: mod
|
||||
});
|
||||
})
|
||||
.catch(reject);
|
||||
})
|
||||
.catch(reject);
|
||||
});
|
||||
}
|
||||
|
||||
return ret;
|
||||
};
|
||||
})();
|
||||
@@ -1,3 +1,6 @@
|
||||
globalThis.__taobaoRequire = (urlNoSchema) => {
|
||||
require("./" + urlNoSchema);
|
||||
};
|
||||
loadCC();
|
||||
|
||||
function loadCC() {
|
||||
@@ -46,6 +49,10 @@ function loadCC() {
|
||||
'plugin:': (urlNoSchema) => {
|
||||
requirePlugin(urlNoSchema);
|
||||
},
|
||||
'project:': (urlNoSchema) => {
|
||||
urlNoSchema = urlNoSchema.replace("//", "");
|
||||
require("./" + urlNoSchema);
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
"window": {
|
||||
"allowsBounceVertical": "NO",
|
||||
"transparentTitle": "always",
|
||||
"enableAudioAlign": true
|
||||
"enableAudioAlign": true,
|
||||
"enableMultiAudio": true
|
||||
}
|
||||
}
|
||||
Executable
+29
@@ -0,0 +1,29 @@
|
||||
// app.js
|
||||
App({
|
||||
GameGlobal: {
|
||||
screencanvas: undefined,
|
||||
canvas: undefined,
|
||||
System: undefined,
|
||||
Image: undefined,
|
||||
cc: undefined,
|
||||
CocosEngine: undefined,
|
||||
ccwindow: undefined,
|
||||
fsUtils: undefined,
|
||||
document: undefined,
|
||||
requestAnimationFrame: undefined,
|
||||
cancelAnimationFrame: undefined,
|
||||
Image: undefined,
|
||||
ImageBitmap: undefined,
|
||||
XMLHttpRequest: undefined,
|
||||
WebSocket: undefined,
|
||||
DOMParser: undefined,
|
||||
WebAssembly: undefined,
|
||||
WXWebAssembly: undefined,
|
||||
_touchStart: undefined,
|
||||
_touchMove: undefined,
|
||||
_touchEnd: undefined,
|
||||
_touchCancel: undefined,
|
||||
},
|
||||
onLaunch() {
|
||||
},
|
||||
})
|
||||
Executable
+15
@@ -0,0 +1,15 @@
|
||||
{ "lazyCodeLoading":"requiredComponents",
|
||||
"pages":[
|
||||
"index"
|
||||
],
|
||||
"window":{
|
||||
"backgroundTextStyle":"light",
|
||||
"navigationBarBackgroundColor": "#fff",
|
||||
"navigationBarTitleText": "CocosCreator",
|
||||
"navigationBarTextStyle":"black",
|
||||
"navigationStyle": "custom",
|
||||
"pageOrientation": "auto"
|
||||
},
|
||||
"style": "v2",
|
||||
"sitemapLocation": "sitemap.json"
|
||||
}
|
||||
Executable
+8
@@ -0,0 +1,8 @@
|
||||
/**app.wxss**/
|
||||
.container {
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
position: absolute;
|
||||
top: 0px;
|
||||
bottom: 0px;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"version": "1.0.0",
|
||||
"templates": [
|
||||
"game.ejs",
|
||||
"game.json",
|
||||
"project.config.json"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
<% if(polyfillsBundleFile) { %>
|
||||
// Polyfills bundle.
|
||||
require("<%= polyfillsBundleFile %>");
|
||||
<% } %>
|
||||
// SystemJS support.
|
||||
require("<%= systemJsBundleFile %>");
|
||||
@@ -0,0 +1,280 @@
|
||||
// TODO: insert global variable access by build process in Editor
|
||||
const GameGlobal = getApp().GameGlobal;
|
||||
const window = GameGlobal;
|
||||
const requestAnimationFrame = GameGlobal.canvas.requestAnimationFrame;
|
||||
const cancelAnimationFrame = GameGlobal.canvas.cancelAnimationFrame;
|
||||
|
||||
const VS_LOGO = `
|
||||
attribute vec4 a_Position;
|
||||
attribute vec2 a_TexCoord;
|
||||
varying vec2 v_TexCoord;
|
||||
void main() {
|
||||
gl_Position = a_Position;
|
||||
v_TexCoord = a_TexCoord;
|
||||
}`;
|
||||
|
||||
const FS_LOGO = `
|
||||
precision mediump float;
|
||||
uniform sampler2D u_Sampler;
|
||||
varying vec2 v_TexCoord;
|
||||
void main() {
|
||||
gl_FragColor = texture2D(u_Sampler, v_TexCoord);
|
||||
}`;
|
||||
|
||||
const VS_PROGRESSBAR = `
|
||||
precision mediump float;
|
||||
attribute vec4 a_Position;
|
||||
attribute float a_Progress;
|
||||
varying float v_Progress;
|
||||
void main() {
|
||||
gl_Position = a_Position;
|
||||
v_Progress = a_Progress;
|
||||
}`;
|
||||
|
||||
const FS_PROGRESSBAR = `
|
||||
precision mediump float;
|
||||
uniform float u_CurrentProgress;
|
||||
varying float v_Progress;
|
||||
uniform vec4 u_ProgressBarColor;
|
||||
uniform vec4 u_ProgressBackground;
|
||||
void main() {
|
||||
gl_FragColor = v_Progress <= u_CurrentProgress ? u_ProgressBarColor : u_ProgressBackground;
|
||||
}`;
|
||||
|
||||
const options = {
|
||||
alpha: false,
|
||||
antialias: true,
|
||||
depth: true,
|
||||
stencil: true,
|
||||
premultipliedAlpha: false,
|
||||
preserveDrawingBuffer: false,
|
||||
powerPreference: 'default',
|
||||
failIfMajorPerformanceCaveat: false,
|
||||
};
|
||||
|
||||
//NOTE: canvas
|
||||
let canvas = null;
|
||||
let gl = null;
|
||||
let image = null;
|
||||
let program = null;
|
||||
let programProgress = null;
|
||||
let rafHandle = null;
|
||||
let texture = null;
|
||||
let vertexBuffer = null;
|
||||
let vertexBufferProgress = null;
|
||||
let progress = 0.0;
|
||||
let progressBarColor = [61 / 255, 197 / 255, 222 / 255, 1];
|
||||
let progressBackground = [100 / 255, 111 / 255, 118 / 255, 1];
|
||||
let afterTick = null;
|
||||
|
||||
function initShaders(vshader, fshader) {
|
||||
return createProgram(vshader, fshader);
|
||||
}
|
||||
|
||||
function createProgram(vshader, fshader) {
|
||||
var vertexShader = loadShader(gl.VERTEX_SHADER, vshader);
|
||||
var fragmentShader = loadShader(gl.FRAGMENT_SHADER, fshader);
|
||||
var program = gl.createProgram();
|
||||
gl.attachShader(program, vertexShader);
|
||||
gl.attachShader(program, fragmentShader);
|
||||
gl.linkProgram(program);
|
||||
var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
|
||||
if (!linked) {
|
||||
var error = gl.getProgramInfoLog(program);
|
||||
console.log('Failed to link program: ' + error);
|
||||
gl.deleteProgram(program);
|
||||
program = null;
|
||||
}
|
||||
gl.deleteShader(fragmentShader);
|
||||
gl.deleteShader(vertexShader);
|
||||
return program;
|
||||
}
|
||||
|
||||
function loadShader(type, source) {
|
||||
var shader = gl.createShader(type);
|
||||
gl.shaderSource(shader, source);
|
||||
gl.compileShader(shader);
|
||||
var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
|
||||
if (!compiled) {
|
||||
var error = gl.getShaderInfoLog(shader);
|
||||
console.log('Failed to compile shader: ' + error);
|
||||
gl.deleteShader(shader);
|
||||
return null;
|
||||
}
|
||||
return shader;
|
||||
}
|
||||
|
||||
function initVertexBuffer() {
|
||||
const widthRatio = 2 / canvas.width;
|
||||
const heightRatio = 2 / canvas.height;
|
||||
const vertices = new Float32Array([
|
||||
widthRatio, heightRatio, 1.0, 1.0,
|
||||
widthRatio, heightRatio, 1.0, 0.0,
|
||||
-widthRatio, heightRatio, 0.0, 1.0,
|
||||
-widthRatio, heightRatio, 0.0, 0.0,
|
||||
]);
|
||||
vertexBuffer = gl.createBuffer();
|
||||
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
|
||||
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
|
||||
}
|
||||
|
||||
function initProgressVertexBuffer() {
|
||||
const widthRatio = 0.405;
|
||||
const heightRatio = (window.devicePixelRatio >= 2 ? 6 : 3) / canvas.height;
|
||||
const heightOffset = -0.25;
|
||||
const vertices = new Float32Array([
|
||||
widthRatio, heightOffset - heightRatio, 1,
|
||||
widthRatio, heightOffset + heightRatio, 1,
|
||||
-widthRatio, heightOffset - heightRatio, 0,
|
||||
-widthRatio, heightOffset + heightRatio, 0,
|
||||
]);
|
||||
vertexBufferProgress = gl.createBuffer();
|
||||
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBufferProgress);
|
||||
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
|
||||
}
|
||||
|
||||
function updateVertexBuffer() {
|
||||
const widthRatio = image.width / canvas.width;
|
||||
const heightRatio = image.height / canvas.height;
|
||||
const vertices = new Float32Array([
|
||||
widthRatio, -heightRatio, 1.0, 1.0,
|
||||
widthRatio, heightRatio, 1.0, 0.0,
|
||||
-widthRatio, -heightRatio, 0.0, 1.0,
|
||||
-widthRatio, heightRatio, 0.0, 0.0,
|
||||
]);
|
||||
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
|
||||
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
|
||||
}
|
||||
|
||||
function loadImage(imgPath) {
|
||||
return new Promise((resolve, reject) => {
|
||||
// TODO:replace?
|
||||
// image = new Image();
|
||||
image = GameGlobal.canvas.createImage();
|
||||
image.premultiplyAlpha = false;
|
||||
image.onload = function() {
|
||||
resolve(image);
|
||||
};
|
||||
image.onerror = function(err) {
|
||||
reject(err);
|
||||
};
|
||||
image.src = imgPath.replace('#', '%23');
|
||||
});
|
||||
}
|
||||
|
||||
function initTexture() {
|
||||
texture = gl.createTexture();
|
||||
gl.activeTexture(gl.TEXTURE0);
|
||||
gl.bindTexture(gl.TEXTURE_2D, texture);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
|
||||
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 2, 2, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([0, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0, 255]));
|
||||
}
|
||||
|
||||
function updateTexture() {
|
||||
gl.activeTexture(gl.TEXTURE0);
|
||||
gl.bindTexture(gl.TEXTURE_2D, texture);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
|
||||
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
|
||||
}
|
||||
|
||||
function draw() {
|
||||
gl.clearColor(0.0, 0.0, 0.0, 0.0);
|
||||
gl.clear(gl.COLOR_BUFFER_BIT);
|
||||
gl.useProgram(program);
|
||||
gl.activeTexture(gl.TEXTURE0);
|
||||
gl.bindTexture(gl.TEXTURE_2D, texture);
|
||||
var uSampler = gl.getUniformLocation(program, 'u_Sampler');
|
||||
gl.uniform1i(uSampler, 0);
|
||||
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
|
||||
var vertexFormatLength = 4;
|
||||
var aPosition = gl.getAttribLocation(program, 'a_Position');
|
||||
gl.enableVertexAttribArray(aPosition);
|
||||
gl.vertexAttribPointer(aPosition, 2, gl.FLOAT, false, vertexFormatLength * 4, 0);
|
||||
var aTexCoord = gl.getAttribLocation(program, 'a_TexCoord');
|
||||
gl.enableVertexAttribArray(aTexCoord);
|
||||
gl.vertexAttribPointer(aTexCoord, 2, gl.FLOAT, false, vertexFormatLength * 4, vertexFormatLength * 2);
|
||||
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
|
||||
gl.useProgram(programProgress);
|
||||
var uCurrentProgress = gl.getUniformLocation(programProgress, 'u_CurrentProgress');
|
||||
gl.uniform1f(uCurrentProgress, progress);
|
||||
var uProgressBarColor = gl.getUniformLocation(programProgress, 'u_ProgressBarColor');
|
||||
gl.uniform4fv(uProgressBarColor, progressBarColor);
|
||||
var uProgressBackground = gl.getUniformLocation(programProgress, 'u_ProgressBackground');
|
||||
gl.uniform4fv(uProgressBackground, progressBackground);
|
||||
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBufferProgress);
|
||||
aPosition = gl.getAttribLocation(programProgress, 'a_Position');
|
||||
gl.enableVertexAttribArray(aPosition);
|
||||
gl.vertexAttribPointer(aPosition, 2, gl.FLOAT, false, vertexFormatLength * 3, 0);
|
||||
var aProgress = gl.getAttribLocation(programProgress, 'a_Progress');
|
||||
gl.enableVertexAttribArray(aProgress);
|
||||
gl.vertexAttribPointer(aProgress, 1, gl.FLOAT, false, vertexFormatLength * 3, vertexFormatLength * 2);
|
||||
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
|
||||
}
|
||||
|
||||
function tick() {
|
||||
rafHandle = requestAnimationFrame(() => {
|
||||
draw();
|
||||
tick();
|
||||
if (afterTick) {
|
||||
afterTick();
|
||||
afterTick = null;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function end() {
|
||||
return setProgress(1).then(() => {
|
||||
cancelAnimationFrame(rafHandle);
|
||||
gl.useProgram(null);
|
||||
gl.bindTexture(gl.TEXTURE_2D, null);
|
||||
gl.bindBuffer(gl.ARRAY_BUFFER, null);
|
||||
gl.deleteTexture(texture);
|
||||
gl.deleteBuffer(vertexBuffer);
|
||||
gl.deleteBuffer(vertexBufferProgress);
|
||||
gl.deleteProgram(program);
|
||||
gl.deleteProgram(programProgress);
|
||||
});
|
||||
}
|
||||
|
||||
function setProgress(val) {
|
||||
progress = val;
|
||||
return new Promise((resolve, reject) => {
|
||||
afterTick = () => {
|
||||
resolve();
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function start(alpha, antialias, useWebgl2) {
|
||||
options.alpha = alpha === 'true' ? true : false;
|
||||
options.antialias = antialias === 'false' ? false : true;
|
||||
if (useWebgl2 === 'true') {
|
||||
gl = window.canvas.getContext("webgl2", options);
|
||||
}
|
||||
// TODO: this is a hack method to detect whether WebGL2RenderingContext is supported
|
||||
if (gl) {
|
||||
window.WebGL2RenderingContext = true;
|
||||
} else {
|
||||
window.WebGL2RenderingContext = false;
|
||||
gl = window.canvas.getContext("webgl", options);
|
||||
}
|
||||
canvas = gl.canvas;
|
||||
initVertexBuffer();
|
||||
initProgressVertexBuffer();
|
||||
initTexture();
|
||||
program = initShaders(VS_LOGO, FS_LOGO);
|
||||
programProgress = initShaders(VS_PROGRESSBAR, FS_PROGRESSBAR);
|
||||
tick();
|
||||
return loadImage('splash.png').then(() => {
|
||||
updateVertexBuffer();
|
||||
updateTexture();
|
||||
return setProgress(0);
|
||||
});
|
||||
}
|
||||
module.exports = { start, end, setProgress };
|
||||
@@ -0,0 +1,84 @@
|
||||
globalThis.__wxRequire = require; // FIX: require cannot work in separate engine
|
||||
var GameGlobal = getApp().GameGlobal;
|
||||
Page({
|
||||
onReady() {
|
||||
const query = wx.createSelectorQuery()
|
||||
query.select('#myCanvas').node().exec((res) => {
|
||||
// require('./miniapp-adapter');
|
||||
const canvas = res[0].node;
|
||||
let width = canvas.width;
|
||||
let height = canvas.height;
|
||||
|
||||
const adapter = require('./miniapp-adapter');
|
||||
adapter.adapt(canvas, width, height);
|
||||
require('./web-adapter');
|
||||
|
||||
const firstScreen = require('./first-screen');
|
||||
<%- include(cocosTemplate, {}) %>
|
||||
// Adjust initial canvas size
|
||||
if (canvas && GameGlobal.devicePixelRatio >= 2) {
|
||||
canvas.width *= 2; canvas.height *= 2;
|
||||
}
|
||||
|
||||
const importMap = require("<%= importMapFile%>").default;
|
||||
const System = GameGlobal.System;
|
||||
System.warmup({
|
||||
importMap,
|
||||
importMapUrl: '<%= importMapFile%>',
|
||||
defaultHandler: (urlNoSchema) => {
|
||||
require('.' + urlNoSchema);
|
||||
},
|
||||
handlers: {
|
||||
'plugin:': (urlNoSchema) => {
|
||||
requirePlugin(urlNoSchema);
|
||||
},
|
||||
'project:': (urlNoSchema) => {
|
||||
require(urlNoSchema);
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
firstScreen.start('<%= alpha %>', '<%= antialias %>', '<%= useWebgl2 %>').then(() => {
|
||||
return System.import('<%= applicationJs %>');
|
||||
}).then((module) => {
|
||||
return firstScreen.setProgress(0.2).then(() => Promise.resolve(module));
|
||||
}).then(({ Application }) => {
|
||||
return new Application();
|
||||
}).then((application) => {
|
||||
return firstScreen.setProgress(0.4).then(() => Promise.resolve(application));
|
||||
}).then((application) => {
|
||||
return onApplicationCreated(application);
|
||||
}).catch((err) => {
|
||||
console.error(err);
|
||||
});
|
||||
|
||||
function onApplicationCreated(application) {
|
||||
return System.import('cc').then((module) => {
|
||||
return firstScreen.setProgress(0.6).then(() => Promise.resolve(module));
|
||||
}).then((cc) => {
|
||||
require('./engine-adapter');
|
||||
return application.init(cc);
|
||||
}).then(() => {
|
||||
return firstScreen.end().then(() => application.start());
|
||||
});
|
||||
}
|
||||
|
||||
})
|
||||
},
|
||||
|
||||
touchStart(event) {
|
||||
GameGlobal._touchStart && GameGlobal._touchStart(event);
|
||||
},
|
||||
|
||||
touchEnd(event) {
|
||||
GameGlobal._touchEnd && GameGlobal._touchEnd(event);
|
||||
},
|
||||
|
||||
touchMove(event) {
|
||||
GameGlobal._touchMove && GameGlobal._touchMove(event);
|
||||
},
|
||||
|
||||
touchCancel(event) {
|
||||
GameGlobal._touchCancel && GameGlobal._touchCancel(event);
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"deviceOrientation": "portrait",
|
||||
"openDataContext": "",
|
||||
"networkTimeout": {
|
||||
"request": 5000,
|
||||
"connectSocket": 5000,
|
||||
"uploadFile": 5000,
|
||||
"downloadFile": 500000
|
||||
}
|
||||
}
|
||||
Executable
+3
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"usingComponents": {}
|
||||
}
|
||||
Executable
+11
@@ -0,0 +1,11 @@
|
||||
<!--index.wxml-->
|
||||
<view class="container">
|
||||
<canvas
|
||||
type="webgl"
|
||||
id="myCanvas"
|
||||
bindtouchstart="touchStart"
|
||||
bindtouchmove="touchMove"
|
||||
bindtouchend="touchEnd"
|
||||
bindtouchcancel="touchCancel"
|
||||
></canvas>
|
||||
</view>
|
||||
Executable
+8
@@ -0,0 +1,8 @@
|
||||
/**app.wxss**/
|
||||
#myCanvas {
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
position: absolute;
|
||||
top: 0px;
|
||||
bottom: 0px;
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
var GameGlobal = getApp().GameGlobal;
|
||||
exports.adapt = function (canvas, width, height) {
|
||||
GameGlobal.canvas = canvas;
|
||||
GameGlobal.WXWebAssembly = WXWebAssembly;
|
||||
GameGlobal.requestAnimationFrame = GameGlobal.canvas.requestAnimationFrame || globalThis.setTimeout;
|
||||
GameGlobal.cancelAnimationFrame = GameGlobal.canvas.cancelAnimationFrame || globalThis.setTimeout;
|
||||
GameGlobal.setTimeout = globalThis.setTimeout;
|
||||
GameGlobal.setInterval = globalThis.setInterval;
|
||||
GameGlobal.clearTimeout = globalThis.clearTimeout;
|
||||
GameGlobal.clearInterval = globalThis.clearInterval;
|
||||
|
||||
let isFirstCall = true;
|
||||
|
||||
wx.createCanvas = function () {
|
||||
console.log('wx.createCanvas called');
|
||||
if (isFirstCall) {
|
||||
isFirstCall = false;
|
||||
return canvas;
|
||||
} else {
|
||||
return wx.createOffscreenCanvas(width, height);
|
||||
}
|
||||
}
|
||||
|
||||
wx.createImage = function () {
|
||||
console.log('wx.creatImage in miniapp-adapter')
|
||||
let image = canvas.createImage();
|
||||
return image;
|
||||
}
|
||||
|
||||
wx.onTouchStart = function (cb) {
|
||||
GameGlobal._touchStart = function (event) {
|
||||
handleTouchEvent(event);
|
||||
cb(event);
|
||||
};
|
||||
};
|
||||
wx.onTouchMove = function (cb) {
|
||||
GameGlobal._touchMove = function (event) {
|
||||
handleTouchEvent(event);
|
||||
cb(event);
|
||||
};
|
||||
};
|
||||
wx.onTouchEnd = function (cb) {
|
||||
GameGlobal._touchEnd = function (event) {
|
||||
handleTouchEvent(event);
|
||||
cb(event);
|
||||
};
|
||||
};
|
||||
wx.onTouchCancel = function (cb) {
|
||||
GameGlobal._touchCancel = function (event) {
|
||||
handleTouchEvent(event);
|
||||
cb(event);
|
||||
};
|
||||
};
|
||||
|
||||
function handleTouchEvent (event) {
|
||||
let changedTouches = event.changedTouches;
|
||||
if (changedTouches) {
|
||||
for (let touch of changedTouches) {
|
||||
touch.clientX = touch.x;
|
||||
touch.clientY = touch.y;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//TODO: use wx.onDeviceMotionChange to instead
|
||||
wx.onDeviceOrientationChange = function () {
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"_plugin-version": "3.2.2"
|
||||
}
|
||||
Executable
+53
@@ -0,0 +1,53 @@
|
||||
{
|
||||
"description": "项目配置文件",
|
||||
"packOptions": {
|
||||
"ignore": [],
|
||||
"include": []
|
||||
},
|
||||
"setting": {
|
||||
"ignoreDevUnusedFiles": false,
|
||||
"ignoreUploadUnusedFiles": false,
|
||||
"bundle": false,
|
||||
"userConfirmedBundleSwitch": false,
|
||||
"urlCheck": true,
|
||||
"scopeDataCheck": false,
|
||||
"coverView": true,
|
||||
"es6": true,
|
||||
"postcss": true,
|
||||
"compileHotReLoad": false,
|
||||
"lazyloadPlaceholderEnable": false,
|
||||
"preloadBackgroundData": false,
|
||||
"minified": true,
|
||||
"autoAudits": false,
|
||||
"newFeature": false,
|
||||
"uglifyFileName": false,
|
||||
"uploadWithSourceMap": true,
|
||||
"useIsolateContext": true,
|
||||
"nodeModules": false,
|
||||
"enhance": true,
|
||||
"useMultiFrameRuntime": true,
|
||||
"useApiHook": true,
|
||||
"useApiHostProcess": true,
|
||||
"showShadowRootInWxmlPanel": true,
|
||||
"packNpmManually": false,
|
||||
"enableEngineNative": false,
|
||||
"packNpmRelationList": [],
|
||||
"minifyWXSS": true,
|
||||
"showES6CompileOption": false,
|
||||
"minifyWXML": true,
|
||||
"babelSetting": {
|
||||
"ignore": [],
|
||||
"disablePlugins": [],
|
||||
"outputPath": ""
|
||||
}
|
||||
},
|
||||
"compileType": "miniprogram",
|
||||
"libVersion": "2.19.4",
|
||||
"appid": "wx160703e6ec9ed84e",
|
||||
"projectname": "miniprogram-92",
|
||||
"condition": {},
|
||||
"editorSetting": {
|
||||
"tabIndent": "insertSpaces",
|
||||
"tabSize": 4
|
||||
}
|
||||
}
|
||||
Executable
+7
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"desc": "关于本文件的更多信息,请参考文档 https://developers.weixin.qq.com/miniprogram/dev/framework/sitemap.html",
|
||||
"rules": [{
|
||||
"action": "allow",
|
||||
"page": "*"
|
||||
}]
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 23 KiB |
Reference in New Issue
Block a user