repo_name string | dataset string | owner string | lang string | func_name string | code string | docstring string | url string | sha string |
|---|---|---|---|---|---|---|---|---|
effects-runtime | github_2023 | galacean | typescript | CheckerHelper.assertTreeOptions | static assertTreeOptions (v: ModelTreeOptions) {
if (!this.checkNumberUndef(v.animation)) { console.error(`Invalid tree animation ${v.animation}, ${this.stringify(v)}.`); }
if (v.animations !== undefined) {
if (!Array.isArray(v.animations)) { console.error(`Invalid tree animations ${v.animations}, ${this.stringify(v)}.`); }
v.animations.forEach(anim => { this.assertModelAnimOptions(anim); });
if (v.animation !== undefined) {
if (v.animation < -1 || v.animation >= v.animations.length) { console.error(`Invalid tree animations ${v.animations}, ${this.stringify(v)}.`); }
}
}
} | /**
* 检查场景树参数
* @param v - 场景树参数
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/model/src/utility/plugin-helper.ts#L2440-L2449 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | CheckerHelper.stringify | static stringify (object: any) {
const simpleObject: { [k: string]: any } = {};
for (const prop in object) {
// if (typeof(object[prop]) == 'object'){
// continue;
// }
if (prop === 'internal') {
// 与WebGL相关的数据,可以忽略
continue;
}
if (typeof (object[prop]) == 'function') {
continue;
}
if (object[prop] instanceof Texture) {
simpleObject[prop] = object[prop].name;
continue;
}
if (object[prop] instanceof Geometry) {
simpleObject[prop] = object[prop].name;
continue;
}
if (object[prop] instanceof Renderer) {
continue;
}
simpleObject[prop] = object[prop];
}
return JSON.stringify(simpleObject);
} | /**
* 将对象转成 JSON 字符串,需要忽略函数和渲染相关的对象
* @param object - 目标对象
* @returns
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/model/src/utility/plugin-helper.ts#L2456-L2485 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | CheckerHelper.pow2 | static pow2 (index: number): number {
let res = 1;
while (index-- > 0) { res *= 2; }
return res;
} | /**
* 获取 2 的 index 指数结果
* @param index - 指数
* @returns
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/model/src/utility/plugin-helper.ts#L2492-L2498 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | Float16ArrayWrapper.set | set (number: ArrayLike<number>, startIndex: number) {
for (let i = 0; i < number.length; i++) {
this.data[i + startIndex] = toHalf(number[i]);
}
} | /**
* 将类数值数组转成半进度浮点,并从起始索引开始添加
* @param number - 类数值数组
* @param startIndex - 起始索引
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/model/src/utility/plugin-helper.ts#L2524-L2528 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | Float16ArrayWrapper.bytes | get bytes () {
return this.size * 2;
} | /**
* 获取数组字节数
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/model/src/utility/plugin-helper.ts#L2533-L2535 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | FBOOptions.constructor | constructor (options: Record<string, any>) {
this.resolution = options.resolution ?? new Vector2(512, 512);
this.colorAttachments = options.colorAttachments ?? [];
this.depthAttachment = options.depthAttachment;
} | /**
* 构造函数
* @param options - FBO 参数
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/model/src/utility/ri-helper.ts#L27-L31 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | FBOOptions.addDepthAttachment | addDepthAttachment (options: Record<string, any>) {
this.depthAttachment = {
storageType: options.storageType ?? RenderPassAttachmentStorageType.depth_16_texture,
};
} | /**
* 添加深度附件
* @param options - 深度附件参数
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/model/src/utility/ri-helper.ts#L37-L41 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | FBOOptions.addDefaultDepthAttachment | addDefaultDepthAttachment () {
this.depthAttachment = { storageType: RenderPassAttachmentStorageType.depth_16_texture };
} | /**
* 添加默认深度附件,数据格式是 depth_16_texture
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/model/src/utility/ri-helper.ts#L46-L48 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | FBOOptions.deleteDepthAttachment | deleteDepthAttachment () {
this.depthAttachment = undefined;
} | /**
* 删除深度附件
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/model/src/utility/ri-helper.ts#L53-L55 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | FBOOptions.addColorAttachment | addColorAttachment (options: Record<string, any>) {
this.colorAttachments.push({
texture: {
format: options.format ?? glContext.RGBA,
type: options.type ?? glContext.HALF_FLOAT,
minFilter: options.filter ?? glContext.LINEAR,
magFilter: options.filter ?? glContext.LINEAR,
},
});
} | /**
* 添加颜色附件
* @param options - 颜色附件参数
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/model/src/utility/ri-helper.ts#L61-L70 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | FBOOptions.deleteColorAttachment | deleteColorAttachment (target: number) {
if (target >= 0 && target < this.colorAttachments.length) {
this.colorAttachments.splice(target, 1);
}
} | /**
* 删除颜色附件,按照索引值
* @param target - 颜色附件索引值
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/model/src/utility/ri-helper.ts#L76-L80 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | FBOOptions.viewport | get viewport (): [number, number, number, number] {
return [0, 0, this.resolution.x, this.resolution.y];
} | /**
* 获取视口大小
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/model/src/utility/ri-helper.ts#L85-L87 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | BoxMesh.constructor | constructor (engine: Engine, priority: number) {
const material = Material.create(
engine,
{
shader: {
vertex: this.vertexShader,
fragment: this.fragmentShader,
shared: true,
},
}
);
material.depthTest = true;
material.depthMask = true;
this.mesh = Mesh.create(
engine,
{
name: 'boxMesh',
material,
geometry: Geometry.create(engine, this.geometry),
priority,
}
);
} | /**
* 构造函数,创建基础 Mesh 对象
* @param engine - 引擎
* @param priority - 优先级
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/model/src/utility/ri-helper.ts#L104-L127 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | BoxMesh.update | update (modelMatrix: Matrix4, viewProjMatrix: Matrix4, positions: Float32Array, lineColor: Vector3) {
const material = this.mesh.material;
material.setMatrix('effects_ObjectToWorld', modelMatrix);
material.setMatrix('effects_MatrixVP', viewProjMatrix);
for (let i = 0; i < positions.length; i += 3) {
material.setVector3(`_PositionList[${i / 3}]`, Vector3.fromArray(positions, i));
}
material.setVector3('_LineColor', lineColor);
} | /**
* 更新包围盒着色器 Uniform 数据
* @param modelMatrix - 模型矩阵
* @param viewProjMatrix - 相机投影矩阵
* @param positions - 位置数组
* @param lineColor - 线颜色
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/model/src/utility/ri-helper.ts#L136-L145 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | BoxMesh.dispose | dispose () {
this.mesh.dispose();
// @ts-expect-error
this.mesh = undefined;
} | /**
* 销毁,需要销毁 Mesh 对象
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/model/src/utility/ri-helper.ts#L150-L154 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | BoxMesh.vertexShader | get vertexShader (): string {
return `
precision highp float;
uniform mat4 effects_ObjectToWorld;
uniform mat4 effects_MatrixVP;
uniform vec3 _PositionList[8];
attribute vec3 aPos;
void main(){
int index = int(aPos.x + 0.5);
vec4 pos = effects_ObjectToWorld * vec4(_PositionList[index], 1);
gl_Position = effects_MatrixVP * pos;
}
`;
} | /**
* 获取顶点着色器代码
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/model/src/utility/ri-helper.ts#L159-L173 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | BoxMesh.fragmentShader | get fragmentShader (): string {
return `
precision highp float;
uniform vec3 _LineColor;
void main(){
gl_FragColor = vec4(_LineColor, 1);
}
`;
} | /**
* 获取片段着色器代码
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/model/src/utility/ri-helper.ts#L178-L187 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | BoxMesh.geometry | get geometry (): GeometryProps {
const data = new Float32Array([0, 1, 2, 3, 4, 5, 6, 7]);
const index = new Uint32Array([
0, 1, 1, 2, 2, 3, 3, 0,
4, 5, 5, 6, 6, 7, 7, 4,
0, 4, 1, 5, 2, 6, 3, 7,
]);
return {
attributes: {
aPos: {
type: glContext.FLOAT,
size: 1,
data,
stride: Float32Array.BYTES_PER_ELEMENT,
offset: 0,
},
},
mode: glContext.LINES,
indices: { data: index },
drawStart: 0,
drawCount: 24,
};
} | /**
* 获取基础几何体
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/model/src/utility/ri-helper.ts#L192-L215 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | TwoStatesSet.clear | clear () {
this.now.clear();
this.last.clear();
} | /**
* 清空 last 和 now
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/model/src/utility/ts-helper.ts#L22-L25 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | TwoStatesSet.forward | forward () {
const temp = this.last;
this.last = this.now;
this.now = temp;
this.now.clear();
} | /**
* 状态前进,当前变成 last,now 被清空
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/model/src/utility/ts-helper.ts#L30-L36 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | TwoStatesSet.forAddedItem | forAddedItem (callbackfn: (value: T) => void) {
this.now.forEach(item => {
if (!this.last.has(item)) {
callbackfn(item);
}
});
} | /**
* 遍历当前帧新加的元素
*
* @param callbackfn - 增加新元素的回调
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/model/src/utility/ts-helper.ts#L43-L49 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | TwoStatesSet.forRemovedItem | forRemovedItem (callbackfn: (value: T) => void) {
this.last.forEach(item => {
if (!this.now.has(item)) {
callbackfn(item);
}
});
} | /**
* 遍历当前帧删除的元素
*
* @param callbackfn - 删除旧元素的回调
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/model/src/utility/ts-helper.ts#L56-L62 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | TwoStatesSet.forNowItem | forNowItem (callbackfn: (value: T) => void) {
this.now.forEach(item => {
callbackfn(item);
});
} | /**
* 遍历当前帧所有的元素
*
* @param callbackfn - 当前帧元素的回调
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/model/src/utility/ts-helper.ts#L69-L73 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | AudioComponent.setAudioSource | setAudioSource (audio: HTMLAudioElement | AudioBuffer): void {
this.audioPlayer.setAudioSource(audio);
} | /**
* 设置音频资源
* @param audio - 音频资源
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/multimedia/src/audio/audio-component.ts#L51-L53 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | AudioComponent.setVolume | setVolume (volume: number): void {
this.audioPlayer.setVolume(volume);
} | /**
* 设置音量
* @param volume - 音量
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/multimedia/src/audio/audio-component.ts#L59-L61 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | AudioComponent.getCurrentTime | getCurrentTime (): number {
return this.audioPlayer.getCurrentTime();
} | /**
* 获取当前音频的播放时刻
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/multimedia/src/audio/audio-component.ts#L66-L68 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | AudioComponent.setMuted | setMuted (muted: boolean): void {
this.audioPlayer.setMuted(muted);
} | /**
* 设置是否静音
* @param muted - 是否静音
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/multimedia/src/audio/audio-component.ts#L74-L76 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | AudioComponent.setLoop | setLoop (loop: boolean): void {
this.audioPlayer.setLoop(loop);
} | /**
* 设置是否循环播放
* @param loop - 是否循环播放
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/multimedia/src/audio/audio-component.ts#L82-L84 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | AudioComponent.setPlaybackRate | setPlaybackRate (rate: number): void {
this.audioPlayer.setPlaybackRate(rate);
} | /**
* 设置播放速率
* @param rate - 播放速率
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/multimedia/src/audio/audio-component.ts#L90-L92 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | AudioPlayer.setAudioSource | setAudioSource (audio: AudioBuffer | HTMLAudioElement) {
if (this.audio || this.audioSourceInfo.source) {
this.dispose();
}
if (audio instanceof AudioBuffer) {
const audioContext = new AudioContext();
const gainNode = audioContext.createGain();
gainNode.connect(audioContext.destination);
const source = audioContext.createBufferSource();
source.buffer = audio;
source.connect(gainNode);
this.audioSourceInfo = {
source,
audioContext,
gainNode,
};
} else {
this.audio = audio;
}
if (this.started) {
this.play();
}
} | /**
* 设置音频资源
* @param audio - 音频资源
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/multimedia/src/audio/audio-player.ts#L40-L66 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | VideoComponent.getDuration | getDuration (): number {
return this.video ? this.video.duration : 0;
} | /**
* 获取当前视频时长
* @returns 视频时长
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/multimedia/src/video/video-component.ts#L151-L153 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | VideoComponent.getCurrentTime | getCurrentTime (): number {
return this.video ? this.video.currentTime : 0;
} | /**
* 获取当前视频播放时刻
* @returns 当前视频播放时刻
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/multimedia/src/video/video-component.ts#L159-L161 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | VideoComponent.setThreshold | setThreshold (threshold: number) {
this.threshold = threshold;
} | /**
* 设置阈值(由于视频是单独的 update,有时并不能完全对其 GE 的 update)
* @param threshold 阈值
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/multimedia/src/video/video-component.ts#L167-L169 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | VideoComponent.setCurrentTime | setCurrentTime (time: number) {
if (this.video) {
this.video.currentTime = time;
}
} | /**
* 设置当前视频播放时刻
* @param time 视频播放时刻
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/multimedia/src/video/video-component.ts#L175-L179 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | VideoComponent.setLoop | setLoop (loop: boolean) {
if (this.video) {
this.video.loop = loop;
}
} | /**
* 设置视频是否循环播放
* @param loop 是否循环播放
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/multimedia/src/video/video-component.ts#L185-L189 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | VideoComponent.setMuted | setMuted (muted: boolean) {
if (this.video && this.video.muted !== muted) {
this.video.muted = muted;
}
} | /**
* 设置视频是否静音
* @param muted 是否静音
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/multimedia/src/video/video-component.ts#L195-L199 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | VideoComponent.setVolume | setVolume (volume: number) {
if (this.video && this.video.volume !== volume) {
this.video.volume = volume;
}
} | /**
* 设置视频音量
* @param volume 视频音量
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/multimedia/src/video/video-component.ts#L205-L209 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | VideoComponent.setPlaybackRate | setPlaybackRate (rate: number) {
if (!this.video || this.video.playbackRate === rate) {
return;
}
this.video.playbackRate = rate;
} | /**
* 设置视频播放速率
* @param rate 视频播放速率
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/multimedia/src/video/video-component.ts#L215-L220 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | handleWatch | const handleWatch = (e: Pick<DeviceOrientationEvent, 'alpha' | 'beta' | 'gamma'>) => {
if (this.stoped) {
return;
}
alpha = e.alpha || 0; // 垂直于屏幕的轴 0 ~ 360
beta = e.beta || 0; // 横向 X 轴 -180 ~ 180
gamma = e.gamma || 0; // 纵向 Y 轴 -90 ~ 90
isInValidDegRange = angleLimit.call(this, {
alpha,
beta,
gamma,
}, this.options.validRange);
// 对 alpha beta gamma 初始化位置
if (isNaN(referAlpha)) {
referAlpha = alpha || 0;
}
if (isNaN(referGamma)) {
referGamma = gamma;
this.filterX.lastValue = gamma;
}
if (isNaN(referBeta)) {
referBeta = beta;
this.filterY.lastValue = beta;
}
if (isInValidDegRange) {
// 最终结果值
if (this.options.X) {
x = this.options.relativeGamma ? gamma - referGamma : gamma;
x = this.filterX.stableFix(x);
x = this.filterX.changeLimit(x);
x = this.filterX.linearRegressionMedian(+x);
} else {
x = 0;
}
if (this.options.Y) {
y = this.options.relativeBeta ? beta - referBeta : beta;
y = this.filterY.stableFix(y);
y = this.filterY.changeLimit(y);
y = this.filterY.linearRegressionMedian(+y);
} else {
y = 0;
}
if (this.isValid(x, y)) {
if (this.options.useRequestAnimationFrame) {
window.requestAnimationFrame(() => {
callback(x, y, { alpha, beta: y - referBeta, gamma: x - referGamma });
});
} else {
callback(x, y, { alpha, beta: y - referBeta, gamma: x - referGamma });
}
this.lastX = x;
this.lastY = y;
}
}
}; | // 最终输出的 y | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/orientation-transformer/src/device-orientation.ts#L126-L183 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | switchIOSEvent | function switchIOSEvent (open: boolean, interval?: number) {
window.AlipayJSBridge.call(
'watchShake',
{
monitorGyroscope: false,
monitorAccelerometer: !!open,
interval: !open ? 10 : parseFloat(interval!.toFixed(3)),
},
() => { }
);
} | // 开启/关闭 iOS 的陀螺仪监听 | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/orientation-transformer/src/device-orientation.ts#L282-L292 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | OrientationAdapterAcceler.dispatchMotion | dispatchMotion (motion: AccelerMotionData) {
this.transformers.forEach(t => t.update(motion));
} | /**
*
* @param motion
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/orientation-transformer/src/orientation-adapter-acceler.ts#L58-L60 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | Filtering.stableFix | stableFix (value: number) {
const stableRange = this.options.stableRange || STABLE_RANGE;
if (Math.abs(value) < stableRange) {
return 0;
}
return value > stableRange ? value - stableRange : value + stableRange;
} | /**
* 0deg 左右保持一定的稳定区间 STABLE_RANGE
* - 小于 STABLE_RANGE 的算 0
* - 大于 STABLE_RANGE 的减去 STABLE_RANGE
* @param value - 输入值
* @returns
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/orientation-transformer/src/utils/filtering.ts#L50-L58 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | Filtering.changeLimit | changeLimit (value: number) {
const lastValue = this.lastValue;
let result = value;
if (Math.abs(value - lastValue) > MAX_CHANGE) {
result = lastValue < value ? lastValue + MAX_CHANGE : lastValue - MAX_CHANGE;
}
if (Math.abs(value - lastValue) < MIN_CHANGE) {
result = lastValue;
}
this.lastValue = result;
return result;
} | /**
* 变幅限制
* - 最大变化 MAX_CHANGE
* - 最小变化 MIN_CHANGE
* @param value
* @returns
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/orientation-transformer/src/utils/filtering.ts#L67-L80 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | linearRegression | function linearRegression (x: number[], y: number[]) {
const result: Record<string, number> = {};
const n = y.length;
let sumX = 0;
let sumY = 0;
let sumXY = 0;
let sumXX = 0;
let sumYY = 0;
for (let i = 0; i < y.length; i++) {
sumX += x[i];
sumY += y[i];
sumXY += (x[i] * y[i]);
sumXX += (x[i] * x[i]);
sumYY += (y[i] * y[i]);
}
const avgX = sumX / n;
const avgY = sumY / n;
result['a'] = (sumXY - n * avgX * avgY) / (sumXX - n * avgX * avgX);
result['b'] = avgY - result.a * avgX;
result['miss'] = Math.pow((n * sumXY - sumX * sumY) / Math.sqrt((n * sumXX - sumX * sumX) * (n * sumYY - sumY * sumY)), 2);
return result;
} | // 计算出线性回归参数 | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/orientation-transformer/src/utils/filtering.ts#L99-L124 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | createLinearRegressionFx | function createLinearRegressionFx (values: number[]) {
const x: number[] = [];
const y: number[] = [];
values.forEach((item, index) => {
x.push(index); // 数据是连续的,所以直接取数组下标为 x
y.push(item);
});
const key = linearRegression(x, y);
return (x: number) => {
return key.a * x + key.b;
};
} | // 生成线性回归函数 F(x) = ax + b | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/orientation-transformer/src/utils/filtering.ts#L127-L140 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | getLinearRegressionFixedVal | function getLinearRegressionFixedVal (valuePool: number[]) {
const fx = createLinearRegressionFx(valuePool);
// 这个迭代修正很重要
valuePool = valuePool.map((item, index) => {
return fx(index);
});
return fx(valuePool.length / 2);
} | // 获取线性回归后的中位数 | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/orientation-transformer/src/utils/filtering.ts#L143-L152 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | RichTextComponent.setOverflow | setOverflow (overflow: spec.TextOverflow) {
this.textLayout.overflow = overflow;
this.isDirty = true;
} | /**
* 设置文本溢出模式
*
* - clip: 当文本内容超出边界框时,多余的会被截断。
* - display: 该模式下会显示所有文本,会自动调整文本字号以保证显示完整。
* > 当存在多行时,部分行内文本可能存在文本字号变小的情况,其他行为正常情况
*
* @param overflow - 文本溢出模式
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/rich-text/src/rich-text-component.ts#L272-L275 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | SlotGroup.constructor | constructor (drawOrder: Slot[], props: SlotGroupProps) {
this.slotList = drawOrder;
this.meshName = props.meshName;
this.transform = props.transform;
this.listIndex = props.listIndex;
this.pma = props.pma;
this.renderOptions = props.renderOptions;
this.engine = props.engine;
} | /**
*
* @param drawOrder
* @param props
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/spine/src/slot-group.ts#L95-L103 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | SlotGroup.update | update () {
const clipper = this.clipper;
const pma = this.pma;
let vertices = this.vertices;
let uvs: NumberArrayLike;
let triangles: number[] = [];
let finalVertices: number[] = [];
let finalVerticesLength = 0;
let finalIndices: number[] = [];
let finalIndicesLength = 0;
let currentIndex = 0;
this.currentMesh = this.meshGroups[currentIndex];
this.meshGroups.map(sp => sp.startUpdate());
for (const slot of this.slotList) {
const vertexSize = clipper.isClipping() ? 2 : SlotGroup.VERTEX_SIZE;
const attachment = slot.getAttachment();
let attachmentColor: Color | null;
let texture: Texture | null;
let numFloats = 0;
finalVertices = [];
finalIndices = [];
finalVerticesLength = 0;
finalIndicesLength = 0;
if (!slot.bone.active) {
clipper.clipEndWithSlot(slot);
continue;
}
/**
* RegionAttachment:包含一个纹理(texture)区域和一个偏移 SRT,这个偏移量用于对齐相对于附件的骨骼区域
*/
if (attachment instanceof RegionAttachment) {
const region = attachment;
attachmentColor = region.color;
vertices = this.vertices;
numFloats = vertexSize << 2;
region.computeWorldVertices(slot, vertices, 0, vertexSize);
triangles = SlotGroup.QUAD_TRIANGLES;
uvs = region.uvs;
// @ts-expect-error
texture = region.region.page.texture;
} else if (attachment instanceof MeshAttachment) {
const mesh = attachment;
attachmentColor = mesh.color;
vertices = this.vertices;
numFloats = (mesh.worldVerticesLength >> 1) * vertexSize;
mesh.computeWorldVertices(slot, 0, mesh.worldVerticesLength, vertices, 0, vertexSize);
triangles = mesh.triangles;
uvs = mesh.uvs;
// @ts-expect-error
texture = mesh.region.page.texture;
} else if (attachment instanceof ClippingAttachment) {
// 剪裁应用于绘制顺序中从裁剪附件开始到裁剪附件的结束插槽之间的所有插槽(包括这两个位置)。
clipper.clipStart(slot, attachment);
continue;
} else {
clipper.clipEndWithSlot(slot);
continue;
}
if (texture) {
const skeleton = slot.bone.skeleton;
const skeletonColor = skeleton.color;
const slotColor = slot.color;
const color = this.tempColor;
const darkColor = this.tempDark;
// const attachmentName = `${slot.data.name}-${attachment.name}`;
// 设置颜色,全部进行 alpha 预乘,设置对应的 blendMode
color.set(skeletonColor.r * slotColor.r * attachmentColor.r,
skeletonColor.g * slotColor.g * attachmentColor.g,
skeletonColor.b * slotColor.b * attachmentColor.b,
skeletonColor.a * slotColor.a * attachmentColor.a);
if (pma) {
color.r *= color.a;
color.g *= color.a;
color.b *= color.a;
}
if (!slot.darkColor) {
darkColor.set(0, 0, 0, 1);
} else {
if (pma) {
darkColor.r = slot.darkColor.r * color.a;
darkColor.g = slot.darkColor.g * color.a;
darkColor.b = slot.darkColor.b * color.a;
darkColor.a = 1.0;
} else {
darkColor.setFromColor(slot.darkColor);
darkColor.a = 0.0;
}
}
// 顶点裁剪
if (clipper.isClipping()) {
clipper.clipTriangles(vertices, numFloats, triangles, triangles.length, uvs, color, darkColor, true);
finalVertices = clipper.clippedVertices;
finalVerticesLength = finalVertices.length;
finalIndices = clipper.clippedTriangles;
finalIndicesLength = finalIndices.length;
} else {
for (let v = 2, u = 0, n = numFloats; v < n; v += vertexSize, u += 2) {
vertices[v] = color.r;
vertices[v + 1] = color.g;
vertices[v + 2] = color.b;
vertices[v + 3] = color.a;
vertices[v + 4] = uvs[u];
vertices[v + 5] = uvs[u + 1];
vertices[v + 6] = darkColor.r;
vertices[v + 7] = darkColor.g;
vertices[v + 8] = darkColor.b;
vertices[v + 9] = darkColor.a;
}
finalVertices = vertices.slice(0, numFloats);
finalVerticesLength = numFloats;
finalIndices = triangles;
finalIndicesLength = triangles.length;
}
if (finalVerticesLength == 0 || finalIndicesLength == 0) {
clipper.clipEndWithSlot(slot);
continue;
}
const index = this.findMeshIndex(currentIndex, slot.data.blendMode, texture, finalIndicesLength);
if (index === -1) {
const newMesh = this.currentMesh = new SpineMesh({
blendMode: slot.data.blendMode,
texture,
name: this.meshName,
priority: this.listIndex += 0.01,
pma,
renderOptions: this.renderOptions,
engine: this.engine,
});
currentIndex = this.meshGroups.length;
this.meshGroups.push(newMesh);
this.meshToAdd.push(newMesh.mesh);
} else {
currentIndex = index;
this.currentMesh = this.meshGroups[index];
}
this.currentMesh.updateMesh(finalVertices, finalIndices, finalVerticesLength);
}
clipper.clipEndWithSlot(slot);
}
clipper.clipEnd();
this.wm = this.transform.getWorldMatrix();
this.meshGroups.map((sp, index) => {
sp.endUpdate(this.wm);
});
} | /**
* 按照 drawOrder 遍历 slot,根据 region、mesh、clip 附件更新 mesh 的 geometry 和 material 信息
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/spine/src/slot-group.ts#L112-L274 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | SlotGroup.render | render (renderer: Renderer) {
const worldMatrix = this.transform.getWorldMatrix();
this.meshGroups.forEach(spineMesh => {
const mesh = spineMesh.mesh;
mesh.worldMatrix = worldMatrix;
mesh.render(renderer);
});
} | /**
* @since 2.0.0
* @internal
* @param renderer
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/spine/src/slot-group.ts#L281-L291 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | SlotGroup.findMeshIndex | private findMeshIndex (startIndex: number, blendMode: BlendMode, texture: Texture, vertexNum: number): number {
let res = -1;
for (let i = startIndex; i < this.meshGroups.length; i++) {
const mesh = this.meshGroups[i];
if (
mesh
&& mesh.blending === blendMode
&& mesh.texture === texture
&& vertexNum + mesh.indicesNum < SlotGroup.MAX_VERTICES
) {
res = i;
break;
}
}
return res;
} | /**
* * 从 startIndex 开始,找到材质和顶点数符合限制的 SpineMesh
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/spine/src/slot-group.ts#L296-L315 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | SpineComponent.getBoundingBox | getBoundingBox (): BoundingBoxTriangle {
const bounds = this.getBounds();
const res: BoundingBoxTriangle = {
type: HitTestType.triangle,
area: [],
};
if (!bounds) {
return res;
}
const { x, y, width, height } = bounds;
const wm = this.transform.getWorldMatrix();
const centerX = x + width / 2;
const centerY = y + height / 2;
const p0 = new Vector3(centerX - width / 2, centerY - height / 2, 0);
const p1 = new Vector3(centerX + width / 2, centerY - height / 2, 0);
const p2 = new Vector3(centerX + width / 2, centerY + height / 2, 0);
const p3 = new Vector3(centerX - width / 2, centerY + height / 2, 0);
wm.projectPoint(p0);
wm.projectPoint(p1);
wm.projectPoint(p2);
wm.projectPoint(p3);
res.area = [
{ p0, p1, p2 },
{ p0: p0, p1: p2, p2: p3 },
];
return res;
} | /**
* 返回当前 AABB 包围盒对应的三角形顶点数组
* @returns
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/spine/src/spine-component.ts#L240-L270 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | SpineComponent.setAnimation | setAnimation (animation: string, speed?: number) {
if (!this.skeleton || !this.state) {
throw new Error('Set animation before skeleton create.');
}
if (!this.animationList.length) {
throw new Error('animationList is empty, check your spine file.');
}
const loop = this.item.endBehavior === spec.EndBehavior.restart;
const listener = this.state.tracks[0]?.listener;
if (listener) {
listener.end = () => { };
}
this.state.setEmptyAnimation(0);
if (!this.animationList.includes(animation)) {
console.warn(`Animation ${JSON.stringify(animation)} not exists in animationList: ${this.animationList}, set to ${this.animationList[0]}.`);
this.state.setAnimation(0, this.animationList[0], loop);
this.activeAnimation = [this.animationList[0]];
} else {
this.state.setAnimation(0, animation, loop);
this.activeAnimation = [animation];
}
if (speed !== undefined && !Number.isNaN(speed)) {
this.setSpeed(speed);
}
} | /**
* 设置单个动画
* @param animation - 动画名
* @param speed - 播放速度
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/spine/src/spine-component.ts#L296-L323 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | SpineComponent.setAnimationList | setAnimationList (animationList: string[], speed?: number) {
if (!this.skeleton || !this.state) {
throw new Error('Set animation before skeleton create.');
}
if (!this.animationList.length) {
throw new Error('animationList is empty, please check your setting.');
}
if (animationList.length === 1) {
this.setAnimation(animationList[0], speed);
return;
}
const listener = this.state.tracks[0]?.listener;
if (listener) {
listener.end = () => { };
}
this.state.setEmptyAnimation(0);
for (const animation of animationList) {
const trackEntry = this.state.addAnimation(0, animation, false);
if (this.item.endBehavior === spec.EndBehavior.restart) {
const listener: AnimationStateListener = {
end: () => {
const trackEntry = this.state.addAnimation(0, animation, false);
trackEntry.listener = listener;
},
};
trackEntry.listener = listener;
}
}
this.activeAnimation = animationList;
if (speed !== undefined && !isNaN(speed)) {
this.setSpeed(speed);
}
} | /**
* 设置播放一组动画
* @param animationList - 动画名列表
* @param speed - 播放速度
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/spine/src/spine-component.ts#L330-L367 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | SpineComponent.setAnimationListLoopEnd | setAnimationListLoopEnd (animationList: string[], speed?: number) {
if (!this.skeleton || !this.state) {
throw new Error('Set animation before skeleton create.');
}
if (!this.animationList.length) {
throw new Error('animationList is empty, please check your setting.');
}
if (animationList.length === 1) {
this.setAnimation(animationList[0], speed);
return;
}
const listener = this.state.tracks[0]?.listener;
if (listener) {
listener.end = () => { };
}
this.state.setEmptyAnimation(0);
for (let i = 0; i < animationList.length - 1; i++) {
const animation = animationList[i];
const trackEntry = this.state.setAnimation(0, animation, false);
if (i === animationList.length - 2) {
trackEntry.listener = {
complete: () => {
this.state.setAnimation(0, animationList[animationList.length - 1], true);
},
};
}
}
if (!isNaN(speed as number)) {
this.setSpeed(speed as number);
}
} | /**
* 设置播放一组动画,循环播放最后一个
* @param animationList - 动画名列表
* @param speed - 播放速度
* @since 1.6.0
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/spine/src/spine-component.ts#L375-L409 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | SpineComponent.setSpeed | setSpeed (speed: number) {
if (!this.state) {
return;
}
this.state.timeScale = speed;
} | /**
* 设置 Spine 播放的速度
* @param speed - 速度
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/spine/src/spine-component.ts#L415-L421 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | SpineComponent.getSpeed | getSpeed () {
return this.state.timeScale || 1;
} | /**
* 获取 Spine 播放的速度
* @returns
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/spine/src/spine-component.ts#L427-L429 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | SpineComponent.getActiveAnimation | getActiveAnimation (): string[] {
return this.activeAnimation;
} | /**
* 获取正在播放的动作列表
* @returns
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/spine/src/spine-component.ts#L435-L437 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | SpineComponent.getAnimationState | getAnimationState (): AnimationState {
return this.state;
} | /**
* 获取当前 Spine 中的 AnimationState
* @returns
* @since 1.6.0
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/spine/src/spine-component.ts#L444-L446 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | SpineComponent.setMixDuration | setMixDuration (fromName: string, toName: string, duration: number) {
if (!this.animationStateData) {
return;
}
this.animationStateData.setMix(fromName, toName, duration);
} | /**
* 设置指定动画之间的融合时间,请在 `player.play` 之前进行设置
* @param fromName - 淡出动作
* @param toName - 淡入动作
* @param duration - 融合时间
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/spine/src/spine-component.ts#L454-L459 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | SpineComponent.setDefaultMixDuration | setDefaultMixDuration (mixDuration: number) {
if (!this.state) {
return;
}
this.animationStateData.defaultMix = mixDuration;
if (this.state.tracks[0]) {
this.state.tracks[0].mixDuration = mixDuration;
}
} | /**
* 修改所有动作之间的融合时间,请在 `player.play` 之前进行设置
* @param mixDuration - 融合时间
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/spine/src/spine-component.ts#L465-L473 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | SpineComponent.deleteMixForLoop | deleteMixForLoop () {
const last = this.activeAnimation[this.activeAnimation.length - 1];
const first = this.activeAnimation[0];
this.animationStateData.setMix(last, first, 0);
} | /**
* 动画循环时,移除最后一个动作切换到第一个动作的融合效果,请在 `player.play` 之前进行设置
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/spine/src/spine-component.ts#L478-L483 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | SpineComponent.setSkin | setSkin (skin: string) {
if (!this.skeleton) {
throw new Error('Set skin before skeleton create.');
}
if (!skin || (skin !== 'default' && !this.skinList.includes(skin))) {
throw new Error(`skin ${skin} not exists in skinList: ${this.skinList}.`);
}
this.skeleton.setSkinByName(skin);
this.skeleton.setToSetupPose();
} | /**
* 设置皮肤
* @param skin - 要设置的皮肤
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/spine/src/spine-component.ts#L489-L498 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | SpineComponent.resize | resize () {
const res = this.getBounds();
if (!res || !this.item.composition) {
return;
}
const { width } = res;
const scale = this.transform.scale;
let scaleFactor;
if (this.resizeRule) {
const camera = this.item.composition.camera;
const { z } = this.transform.getWorldPosition();
const { x: rx, y: ry } = camera.getInverseVPRatio(z);
if (camera.clipMode === spec.CameraClipMode.portrait) {
scaleFactor = rx / 1500;
} else {
scaleFactor = ry / 3248;
}
} else {
scaleFactor = 1 / width;
}
this.scaleFactor = scaleFactor;
this.transform.setScale(this.startSize * scaleFactor, this.startSize * scaleFactor, scale.z);
} | // 将缩放比例设置到当前scale | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/spine/src/spine-component.ts#L502-L527 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | SpineComponent.convertSizeToOldRule | convertSizeToOldRule (): number {
const res = this.getBounds();
if (!res || !this.item.composition || !this.resizeRule) {
return 1;
}
const { width } = res;
const scaleFactor = this.scaleFactor;
return this.startSize * scaleFactor * width;
} | // 转换当前大小为旧缩放规则下的大小 | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/spine/src/spine-component.ts#L530-L540 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | Core.reset | reset (): void {
this.drawCallHook?.reset();
this.programHook?.reset();
} | /**
* reset draw call hook
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/stats/src/core.ts#L45-L48 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | Core.release | release (): void {
this.drawCallHook?.release();
this.textureHook?.release();
this.shaderHook?.release();
this.programHook?.release();
} | /**
* release hook
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/stats/src/core.ts#L53-L58 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | Core.update | update (dt: number): PerformanceData | undefined {
const now = performance.now();
this.updateCounter++;
if (now - this.updateTime < 1000) {
return undefined;
}
if (this.samplingIndex !== this.samplingFrames) {
this.reset();
this.samplingIndex++;
return undefined;
}
this.samplingIndex = 0;
const data: PerformanceData = {
fps: Math.round((this.updateCounter * 1000) / (now - this.updateTime)),
// eslint-disable-next-line compat/compat -- performance.memory is not standard
memory: performance.memory && (performance.memory.usedJSHeapSize / 1048576) >> 0,
drawCall: (this.drawCallHook.drawCall === 0) ? 0 : this.drawCallHook.drawCall,
triangles: (this.drawCallHook.triangles === 0) ? 0 : this.drawCallHook.triangles,
lines: this.drawCallHook.lines,
points: this.drawCallHook.points,
textures: this.textureHook.textures,
shaders: (this.shaderHook.shaders === 0) ? 0 : this.shaderHook.shaders,
programs: this.programHook.programs,
webglContext: this.gl instanceof WebGL2RenderingContext ? '2.0' : '1.0',
};
this.reset();
this.updateCounter = 0;
this.updateTime = now;
return data;
} | /**
* update performance data
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/stats/src/core.ts#L63-L101 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | Monitor.update | update (dt: number): void {
const data = this.core.update(dt);
if (!data || data.triangles === 0) {
return;
}
for (let i = 0, l = this.items.length; i < l; i++) {
const dom = this.doms[i];
const item = this.items[i];
const value = data[item as keyof PerformanceData] || 0;
// see: http://wilsonpage.co.uk/preventing-layout-thrashing/
requestAnimationFrame(() => {
dom.innerText = String(value);
});
}
} | /**
* Update per frame
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/stats/src/monitor.ts#L116-L133 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | Monitor.reset | reset (): void {
this.core.reset();
for (let i = 0, l = this.items.length; i < l; i++) {
const dom = this.doms[i];
const item = this.items[i];
const value = this.data[item as keyof PerformanceData] || 0;
// see: http://wilsonpage.co.uk/preventing-layout-thrashing/
requestAnimationFrame(() => {
dom.innerText = String(value);
});
}
} | /**
* reset all hooks
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/stats/src/monitor.ts#L146-L159 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | Monitor.release | release (): void {
this.core.release();
} | /**
* release all hooks
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/stats/src/monitor.ts#L164-L166 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | Monitor.dispose | dispose (): void {
this.release();
this.container.remove();
} | /**
* dispose the instance
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/stats/src/monitor.ts#L171-L174 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | Stats.constructor | constructor (
public readonly player: Player,
private readonly options?: StatsOptions,
) {
void this.init();
} | /**
*
* @param player
* @param options
*/ | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/plugin-packages/stats/src/stats.ts#L114-L119 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | setDatGUI | function setDatGUI (composition: Composition) {
if (gui) {
gui.destroy();
}
// @ts-expect-error
gui = new window.GUI();
const ParticleFolder = gui.addFolder('Particle');
const BloomFolder = gui.addFolder('Bloom');
const ToneMappingFlolder = gui.addFolder('ToneMapping');
const VignetteFolder = gui.addFolder('Vignette');
const ColorAdjustmentsFolder = gui.addFolder('ColorAdjustments');
const globalVolume = composition.renderFrame.globalVolume;
if (!globalVolume) {
return;
}
ParticleFolder.addColor(postProcessSettings, 'color');
ParticleFolder.add(postProcessSettings, 'intensity', -10, 10).step(0.1);
ParticleFolder.open();
BloomFolder.add(globalVolume.bloom, 'active', 0, 1).step(1);
BloomFolder.add(globalVolume.bloom, 'threshold', 0, 40).step(0.1);
BloomFolder.add(globalVolume.bloom, 'intensity', 0, 10);
BloomFolder.open();
VignetteFolder.add(globalVolume.vignette, 'intensity', 0, 2);
VignetteFolder.add(globalVolume.vignette, 'smoothness', 0, 2);
VignetteFolder.add(globalVolume.vignette, 'roundness', 0, 1.5);
ColorAdjustmentsFolder.add(globalVolume.colorAdjustments, 'brightness').step(0.1);
ColorAdjustmentsFolder.add(globalVolume.colorAdjustments, 'saturation', -100, 100);
ColorAdjustmentsFolder.add(globalVolume.colorAdjustments, 'contrast', -100, 100);
ColorAdjustmentsFolder.open();
ToneMappingFlolder.add(globalVolume.tonemapping, 'active', 0, 1).step(1);
ToneMappingFlolder.open();
} | // dat gui 参数及修改 | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/web-packages/demo/src/post-processing.ts#L65-L103 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | getDataTextureMesh | function getDataTextureMesh () {
const w = 512;
const h = 512;
const size = w * h;
const data = new Uint8Array(4 * size);
const r = Math.floor(Math.random() * 255);
const g = Math.floor(Math.random() * 255);
const b = Math.floor(Math.random() * 255);
for (let i = 0; i < size; i++) {
const stride = i * 4;
data[stride] = r;
data[stride + 1] = g;
data[stride + 2] = b;
data[stride + 3] = Math.random() * 255;
}
const t = new THREE.DataTexture(data, w, h);
t.needsUpdate = true;
const sprite = new THREE.Sprite(new THREE.SpriteMaterial({ map: t }));
sprite.position.set(0, 0, 0);
sprite.scale.set(1, 1, 0);
return sprite;
} | // 使用dataTexture创建material | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/web-packages/demo/src/three-sprite.ts#L58-L88 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | getNormalTextureMesh | async function getNormalTextureMesh (texture) {
// 加载纹理
const material = new THREE.SpriteMaterial({ map: texture.texture, color: 0xffffff });
const mesh = new THREE.Sprite(material);
mesh.position.set(0, 0, 0);
mesh.scale.set(1, 1, 1);
return mesh;
} | // 使用 @galacean/effects-core assetmanager加载的图片创建texture | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/web-packages/demo/src/three-sprite.ts#L91-L100 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | getRawShaderMesh | function getRawShaderMesh (texture) {
const vertexShader = `
precision mediump float;
attribute vec2 uv;
attribute vec3 position;
uniform mat4 effects_ObjectToWorld;
uniform mat4 effects_MatrixInvV;
uniform mat4 uProjection;
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = uProjection * effects_MatrixInvV * effects_ObjectToWorld * vec4(position,1.0);
}`;
const fragmentShader = `
precision mediump float;
varying vec2 vUv;
uniform sampler2D uTexture;
void main()
{
gl_FragColor = texture2D(uTexture, vUv);
}
`;
const shaderMaterial = new THREE.RawShaderMaterial({
uniforms:
{
'uTexture': { value: null },
'effects_ObjectToWorld': { value: null },
'effects_MatrixInvV': { value: null },
'uProjection': { value: null },
},
vertexShader,
fragmentShader,
});
shaderMaterial.uniforms.uTexture.value = texture.texture;
const gg = new THREE.BufferGeometry();
const POINTS = 4;
const vertices = new Float32Array([
-0.2, -0.2, 1.0, 0.0, 0.0, // x,y,z,u,v
0.2, -0.2, 1.0, 1.0, 0.0,
0.2, 0.2, 1.0, 1.0, 1.0,
-0.2, 0.2, 1.0, 0.0, 1.0,
]);
const ver = new Float32Array(5 * POINTS);
const indices = new Uint8Array([0, 1, 2, 0, 2, 3]);
const vertexBuffer = new THREE.InterleavedBuffer(ver, 5);
gg.setAttribute('position', new THREE.InterleavedBufferAttribute(vertexBuffer, 3, 0, false));
gg.setAttribute('uv', new THREE.InterleavedBufferAttribute(vertexBuffer, 2, 3, false));
gg.setIndex(new THREE.BufferAttribute(indices, 1));
for (let i = 0; i < vertices.length; i++) {
ver[i] = vertices[i];
}
gg.drawRange.start = 0;
gg.drawRange.count = indices.length;
const ss = new THREE.Mesh(gg, shaderMaterial);
ss.position.set(0, 0.5, 0);
ss.scale.set(1, 1, 1);
ss.onBeforeRender = function (renderer, scene, camera, geometry, material) {
const uniformsMap = {
'effects_ObjectToWorld': ss.matrixWorld,
'effects_MatrixInvV': camera.matrixWorldInverse,
'uProjection': camera.projectionMatrix,
};
for (const [key, value] of Object.entries(uniformsMap)) {
material.uniforms[key].value = value;
}
material.uniformsNeedUpdate = true;
};
return ss;
} | // 自定义shader(不带ubo) | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/web-packages/demo/src/three-sprite.ts#L103-L176 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | getRawShaderLine | function getRawShaderLine () {
const vertexShader = `
precision mediump float;
attribute vec2 position;
uniform mat4 effects_ObjectToWorld;
uniform mat4 effects_MatrixInvV;
uniform mat4 uProjection;
uniform vec4 uColor;
varying vec4 vColor;
void main() {
gl_Position = uProjection * effects_MatrixInvV * effects_ObjectToWorld * vec4(position,0.0,1.0);
vColor = uColor;
}`;
const fragmentShader = `
precision mediump float;
varying vec4 vColor;
void main()
{
gl_FragColor = vColor;
}
`;
const shaderMaterial = new THREE.RawShaderMaterial({
uniforms:
{
'uColor': { value: [0.6, 1, 1, 1] },
'effects_ObjectToWorld': { value: null },
'effects_MatrixInvV': { value: null },
'uProjection': { value: null },
},
vertexShader,
fragmentShader,
});
const gg = new THREE.BufferGeometry();
const vertices = new Float32Array([
-0.5, -0.5,
0.5, -0.5,
0.5, 0.5,
-0.5, 0.5,
]);
// gl.LINES使用
const indices = new Uint8Array([0, 1, 1, 2, 2, 3, 3, 0]);
const vertexBuffer = new THREE.InterleavedBuffer(vertices, 2);
gg.setAttribute('position', new THREE.InterleavedBufferAttribute(vertexBuffer, 2, 0, false));
gg.setIndex(new THREE.BufferAttribute(indices, 1));
// gl.LINES使用
const ss = new THREE.LineSegments(gg, shaderMaterial);
ss.position.set(1, 0, 0);
ss.onBeforeRender = function (renderer, scene, camera, geometry, material) {
const uniformsMap = {
'effects_ObjectToWorld': ss.matrixWorld,
'effects_MatrixInvV': camera.matrixWorldInverse,
'uProjection': camera.projectionMatrix,
};
for (const [key, value] of Object.entries(uniformsMap)) {
material.uniforms[key].value = value;
}
material.uniformsNeedUpdate = true;
};
return ss;
} | // 自定义material gl.LINES | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/web-packages/demo/src/three-sprite.ts#L260-L325 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | _main | async function _main (): Promise<void> {
await _init();
for (let i = 0; i < 3; ++i) { _loop(1 / 60); }
await _done();
} | // eslint-disable-next-line no-inner-declarations | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/web-packages/imgui-demo/src/main.ts#L47-L51 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | _loop | function _loop (time: number): void {
// Poll and handle events (inputs, window resize, etc.)
// You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
// Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
// Start the Dear ImGui frame
ImGui_Impl.NewFrame(time);
ImGui.NewFrame();
ImGui.DockSpaceOverMainViewport();
// 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!).
if (!done && show_demo_window) {
done = /*ImGui.*/ShowDemoWindow((value = show_demo_window) => show_demo_window = value);
}
// 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window.
{
// static float f = 0.0;
// static int counter = 0;
ImGui.Begin('Hello, world!'); // Create a window called "Hello, world!" and append into it.
ImGui.Text('This is some useful text.'); // Display some text (you can use a format strings too)
ImGui.Checkbox('Demo Window', (value = show_demo_window) => show_demo_window = value); // Edit bools storing our windows open/close state
ImGui.Checkbox('Another Window', (value = show_another_window) => show_another_window = value);
ImGui.SliderFloat('float', (value = f) => f = value, 0.0, 1.0); // Edit 1 float using a slider from 0.0f to 1.0f
ImGui.ColorEdit3('clear color', clear_color); // Edit 3 floats representing a color
if (ImGui.Button('Button')) { // Buttons return true when clicked (NB: most widgets return true when edited/activated)
counter++;
}
ImGui.SameLine();
ImGui.Text(`counter = ${counter}`);
ImGui.Text(`Application average ${(1000.0 / ImGui.GetIO().Framerate).toFixed(3)} ms/frame (${ImGui.GetIO().Framerate.toFixed(1)} FPS)`);
ImGui.Checkbox('Memory Editor', (value = memory_editor.Open) => memory_editor.Open = value);
if (memory_editor.Open) { memory_editor.DrawWindow('Memory Editor', ImGui.bind.HEAP8.buffer); }
const mi: ImGui.Bind.mallinfo = ImGui.bind.mallinfo();
// ImGui.Text(`Total non-mmapped bytes (arena): ${mi.arena}`);
// ImGui.Text(`# of free chunks (ordblks): ${mi.ordblks}`);
// ImGui.Text(`# of free fastbin blocks (smblks): ${mi.smblks}`);
// ImGui.Text(`# of mapped regions (hblks): ${mi.hblks}`);
// ImGui.Text(`Bytes in mapped regions (hblkhd): ${mi.hblkhd}`);
ImGui.Text(`Max. total allocated space (usmblks): ${mi.usmblks}`);
// ImGui.Text(`Free bytes held in fastbins (fsmblks): ${mi.fsmblks}`);
ImGui.Text(`Total allocated space (uordblks): ${mi.uordblks}`);
ImGui.Text(`Total free space (fordblks): ${mi.fordblks}`);
// ImGui.Text(`Topmost releasable block (keepcost): ${mi.keepcost}`);
if (ImGui.ImageButton(image_gl_texture, new ImGui.Vec2(48, 48))) {
// show_demo_window = !show_demo_window;
image_url = image_urls[(image_urls.indexOf(image_url) + 1) % image_urls.length];
if (image_element) {
image_element.src = image_url;
}
}
if (ImGui.IsItemHovered()) {
ImGui.BeginTooltip();
ImGui.Text(image_url);
ImGui.EndTooltip();
}
if (ImGui.Button('Sandbox Window')) { show_sandbox_window = true; }
if (show_sandbox_window) { ShowSandboxWindow('Sandbox Window', (value = show_sandbox_window) => show_sandbox_window = value); }
ImGui.SameLine();
if (ImGui.Button('Gamepad Window')) { show_gamepad_window = true; }
if (show_gamepad_window) { ShowGamepadWindow('Gamepad Window', (value = show_gamepad_window) => show_gamepad_window = value); }
ImGui.SameLine();
if (ImGui.Button('Movie Window')) { show_movie_window = true; }
if (show_movie_window) { ShowMovieWindow('Movie Window', (value = show_movie_window) => show_movie_window = value); }
if (font) {
ImGui.PushFont(font);
ImGui.Text(`${font.GetDebugName()}`);
if (font.FindGlyphNoFallback(0x5929)) {
ImGui.Text('U+5929: \u5929');
}
ImGui.PopFont();
}
ImGui.End();
}
// 3. Show another simple window.
if (show_another_window) {
ImGui.Begin('Another Window', (value = show_another_window) => show_another_window = value, ImGui.WindowFlags.AlwaysAutoResize);
ImGui.Text('Hello from another window!');
if (ImGui.Button('Close Me')) { show_another_window = false; }
ImGui.End();
}
uiManager.draw();
ImGui.EndFrame();
// Rendering
ImGui.Render();
const gl: WebGLRenderingContext | null = ImGui_Impl.gl;
if (gl) {
gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
gl.clearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w);
gl.clear(gl.COLOR_BUFFER_BIT);
//gl.useProgram(0); // You may want this if using this code in an OpenGL 3+ context where shaders may be bound
}
const ctx: CanvasRenderingContext2D | null = ImGui_Impl.ctx;
if (ctx) {
// ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.fillStyle = `rgba(${clear_color.x * 0xff}, ${clear_color.y * 0xff}, ${clear_color.z * 0xff}, ${clear_color.w})`;
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
}
UpdateVideo();
ImGui_Impl.RenderDrawData(ImGui.GetDrawData());
if (typeof (window) !== 'undefined') {
window.requestAnimationFrame(done ? _done : _loop);
}
} | // Main loop | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/web-packages/imgui-demo/src/main.ts#L156-L281 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | AssetDatabase.loadGUID | override async loadGUID (guid: string): Promise<EffectsObject | undefined> {
const packageGuid = AssetDatabase.objectToPackageGuidMap[guid];
if (!packageGuid) {
return;
}
// let effectsPackage = this.effectsPackages[packageGuid]; // 合成播放完会把对象设置为销毁,无法复用
let effectsPackage: EffectsPackage | undefined;
if (!effectsPackage) {
const path = this.GUIDToAssetPath(packageGuid);
const loadedPackage = await this.loadPackage(path);
if (!loadedPackage) {
return;
}
effectsPackage = loadedPackage;
}
for (const effectsObject of effectsPackage.exportObjects) {
if (effectsObject.getInstanceId() === guid) {
return effectsObject;
}
}
} | // } | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/web-packages/imgui-demo/src/core/asset-data-base.ts#L27-L50 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | AssetDatabase.importAsset | static async importAsset (path: string) {
const fileHandle = await this.getFileHandle(path);
if (!fileHandle) {
return;
}
const file = await fileHandle.getFile();
const fileReader = new FileReader();
let res: string;
try {
res = await readFileAsText(file);
} catch (error) {
console.error('读取文件出错:', error);
return;
}
const packageData = JSON.parse(res) as spec.EffectsPackageData;
if (!packageData.exportObjects) {
return;
}
// packageData = {
// fileSummary:{
// guid:generateUuid(),
// },
// ...packageData,
// };
// packageData.id = undefined;
const guid = packageData.fileSummary.guid;
AssetDatabase.packageGuidToPathMap[guid] = path;
AssetDatabase.pathToPackageGuidMap[path] = guid;
for (const objectData of packageData.exportObjects) {
AssetDatabase.objectToPackageGuidMap[objectData.id] = guid;
}
// this.dirtyPackageSet.add(guid);
// TODO 加入到场景资产 SceneData 中
// eslint-disable-next-line no-console
console.log('import ' + guid + ' : ' + path);
fileReader.readAsText(file);
} | // TODO 只加载 filesummary 到 map | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/web-packages/imgui-demo/src/core/asset-data-base.ts#L148-L196 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | fmodf | function fmodf (a: float, b: float): float { return a - (Math.floor(a / b) * b); } | // const LLONG_MIN: float = 0; // 0x8000000000000000 | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/web-packages/imgui-demo/src/imgui/imgui_demo.ts#L107-L107 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | UNIQUE | function UNIQUE (key: string): string { return key; } | // #include <stdio.h> // vsnprintf, sscanf, printf | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/web-packages/imgui-demo/src/imgui/imgui_demo.ts#L116-L116 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | IM_MIN | function IM_MIN (A: float, B: float): float { return A < B ? A : B; } | // Helpers | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/web-packages/imgui-demo/src/imgui/imgui_demo.ts#L198-L198 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | HelpMarker | function HelpMarker (desc: string): void {
ImGui.TextDisabled('(?)');
if (ImGui.IsItemHovered()) {
ImGui.BeginTooltip();
ImGui.PushTextWrapPos(ImGui.GetFontSize() * 35.0);
ImGui.TextUnformatted(desc);
ImGui.PopTextWrapPos();
ImGui.EndTooltip();
}
} | // Enforce cdecl calling convention for functions called by the standard library, in case compilation settings changed the default to e.g. __vectorcall | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/web-packages/imgui-demo/src/imgui/imgui_demo.ts#L234-L243 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | ShowUserGuide | function /*ImGui.*/ShowUserGuide (): void {
const io: ImGui.IO = ImGui.GetIO();
ImGui.BulletText('Double-click on title bar to collapse window.');
ImGui.BulletText(
'Click and drag on lower corner to resize window\n' +
'(double-click to auto fit window to its contents).');
ImGui.BulletText('CTRL+Click on a slider or drag box to input value as text.');
ImGui.BulletText('TAB/SHIFT+TAB to cycle through keyboard editable fields.');
if (io.FontAllowUserScaling) {ImGui.BulletText('CTRL+Mouse Wheel to zoom window contents.');}
ImGui.BulletText('While inputing text:\n');
ImGui.Indent();
ImGui.BulletText('CTRL+Left/Right to word jump.');
ImGui.BulletText('CTRL+A or double-click to select all.');
ImGui.BulletText('CTRL+X/C/V to use clipboard cut/copy/paste.');
ImGui.BulletText('CTRL+Z,CTRL+Y to undo/redo.');
ImGui.BulletText('ESCAPE to revert.');
ImGui.BulletText('You can apply arithmetic operators +,*,/ on numerical values.\nUse +- to subtract.');
ImGui.Unindent();
ImGui.BulletText('With keyboard navigation enabled:');
ImGui.Indent();
ImGui.BulletText('Arrow keys to navigate.');
ImGui.BulletText('Space to activate a widget.');
ImGui.BulletText('Return to input text into a widget.');
ImGui.BulletText('Escape to deactivate a widget, close popup, exit child window.');
ImGui.BulletText('Alt to jump to the menu layer of a window.');
ImGui.BulletText('CTRL+Tab to select a window.');
ImGui.Unindent();
} | // Helper to display basic user controls. | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/web-packages/imgui-demo/src/imgui/imgui_demo.ts#L246-L274 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | TextFilters.FilterImGuiLetters | static FilterImGuiLetters (data: ImGui.InputTextCallbackData<null>): int {
if (data.EventChar < 256 && /[imgui]/.test(String.fromCharCode(data.EventChar))) {return 0;}
return 1;
} | // Return 0 (pass) if the character is 'i' or 'm' or 'g' or 'u' or 'i' | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/web-packages/imgui-demo/src/imgui/imgui_demo.ts#L1283-L1287 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | Funcs.MyInputTextMultiline | static MyInputTextMultiline (label: string, my_str: ImGui.StringBuffer, size: ImGui.Vec2 = new ImGui.Vec2(0, 0), flags: ImGui.InputTextFlags = 0): boolean {
ImGui.ASSERT((flags & ImGui.InputTextFlags.CallbackResize) === 0);
// return ImGui.InputTextMultiline(label, my_str.begin(), /*(size_t)*/my_str.size(), size, flags | ImGui.InputTextFlags.CallbackResize, Funcs.MyResizeCallback, /*(void*)*/my_str);
return ImGui.InputTextMultiline(label, my_str, /*(size_t)*/my_str.size, size, flags | ImGui.InputTextFlags.CallbackResize, Funcs.MyResizeCallback, /*(void*)*/my_str);
} | // For example, you code may declare a function 'ImGui.InputText(string label, MyString* my_str)' | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/web-packages/imgui-demo/src/imgui/imgui_demo.ts#L1398-L1403 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | MyItem.CompareWithSortSpecs | static CompareWithSortSpecs (lhs: MyItem, rhs: MyItem): int {
const a: MyItem = /*(const MyItem*)*/lhs;
const b: MyItem = /*(const MyItem*)*/rhs;
ImGui.ASSERT(MyItem.s_current_sort_specs !== null);
for (let n = 0; n < MyItem.s_current_sort_specs.SpecsCount; n++) {
// Here we identify columns using the ColumnUserID value that we ourselves passed to TableSetupColumn()
// We could also choose to identify columns based on their index (sort_spec.ColumnIndex), which is simpler!
const sort_spec: ImGui.TableColumnSortSpecs = MyItem.s_current_sort_specs.Specs[n];
let delta: int = 0;
switch (sort_spec.ColumnUserID) {
case MyItemColumnID.ID: delta = (a.ID - b.ID);
break;
case MyItemColumnID.Name: delta = (a.Name.localeCompare(b.Name));
break;
case MyItemColumnID.Quantity: delta = (a.Quantity - b.Quantity);
break;
case MyItemColumnID.Description: delta = (a.Name.localeCompare(b.Name));
break;
default: ImGui.ASSERT(0);
break;
}
if (delta > 0) {return (sort_spec.SortDirection === ImGui.SortDirection.Ascending) ? +1 : -1;}
if (delta < 0) {return (sort_spec.SortDirection === ImGui.SortDirection.Ascending) ? -1 : +1;}
}
// qsort() is instable so always return a way to differenciate items.
// Your own compare function may want to avoid fallback on implicit sort specs e.g. a Name compare if it wasn't already part of the sort specs.
return (a.ID - b.ID);
} | // Compare function to be used by qsort() | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/web-packages/imgui-demo/src/imgui/imgui_demo.ts#L3280-L3315 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | PushStyleCompact | function PushStyleCompact (): void {
const style: ImGui.Style = ImGui.GetStyle();
ImGui.PushStyleVar(ImGui.StyleVar.FramePadding, new ImGui.Vec2(style.FramePadding.x, Math.floor/*(float)(int)*/(style.FramePadding.y * 0.60)));
ImGui.PushStyleVar(ImGui.StyleVar.ItemSpacing, new ImGui.Vec2(style.ItemSpacing.x, Math.floor/*(float)(int)*/(style.ItemSpacing.y * 0.60)));
} | // const ImGui.TableSortSpecs* MyItem::s_current_sort_specs = null; | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/web-packages/imgui-demo/src/imgui/imgui_demo.ts#L3321-L3326 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | EditTableSizingFlags | function EditTableSizingFlags (p_flags: ImGui.Access<ImGui.TableFlags>): void {
class EnumDesc { constructor (public Value: ImGui.TableFlags, public Name: string, public Tooltip: string) {} }
const policies = STATIC_ARRAY<EnumDesc>(5, UNIQUE('policies#4d5a69af'), [
new EnumDesc(ImGui.TableFlags.None, 'Default', 'Use default sizing policy:\n- ImGui.TableFlags.SizingFixedFit if ScrollX is on or if host window has ImGui.WindowFlags.AlwaysAutoResize.\n- ImGui.TableFlags.SizingStretchSame otherwise.'),
new EnumDesc(ImGui.TableFlags.SizingFixedFit, 'ImGui.TableFlags.SizingFixedFit', 'Columns default to _WidthFixed (if resizable) or _WidthAuto (if not resizable), matching contents width.'),
new EnumDesc(ImGui.TableFlags.SizingFixedSame, 'ImGui.TableFlags.SizingFixedSame', 'Columns are all the same width, matching the maximum contents width.\nImplicitly disable ImGui.TableFlags.Resizable and enable ImGui.TableFlags.NoKeepColumnsVisible.'),
new EnumDesc(ImGui.TableFlags.SizingStretchProp, 'ImGui.TableFlags.SizingStretchProp', 'Columns default to _WidthStretch with weights proportional to their widths.'),
new EnumDesc(ImGui.TableFlags.SizingStretchSame, 'ImGui.TableFlags.SizingStretchSame', 'Columns default to _WidthStretch with same weights.'),
]);
let idx: int;
for (idx = 0; idx < ImGui.ARRAYSIZE(policies.value); idx++) {
if (policies.value[idx].Value === (p_flags() & ImGui.TableFlags.SizingMask_)) {break;}
}
const preview_text: string = (idx < ImGui.ARRAYSIZE(policies.value)) ? policies.value[idx].Name + (idx > 0 ? 'ImGui.TableFlags'.length : 0) : '';
if (ImGui.BeginCombo('Sizing Policy', preview_text)) {
for (let n = 0; n < ImGui.ARRAYSIZE(policies.value); n++) {
if (ImGui.Selectable(policies.value[n].Name, idx === n)) {p_flags((p_flags() & ~ImGui.TableFlags.SizingMask_) | policies.value[n].Value);}
}
ImGui.EndCombo();
}
ImGui.SameLine();
ImGui.TextDisabled('(?)');
if (ImGui.IsItemHovered()) {
ImGui.BeginTooltip();
ImGui.PushTextWrapPos(ImGui.GetFontSize() * 50.0);
for (let m = 0; m < ImGui.ARRAYSIZE(policies.value); m++) {
ImGui.Separator();
ImGui.Text(`${policies.value[m].Name}:`);
ImGui.Separator();
ImGui.SetCursorPosX(ImGui.GetCursorPosX() + ImGui.GetStyle().IndentSpacing * 0.5);
ImGui.TextUnformatted(policies.value[m].Tooltip);
}
ImGui.PopTextWrapPos();
ImGui.EndTooltip();
}
} | // Show a combo box with a choice of sizing policies | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/web-packages/imgui-demo/src/imgui/imgui_demo.ts#L3333-L3370 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | ShowDemoWindowColumns | function ShowDemoWindowColumns (): void {
const open: boolean = ImGui.TreeNode('Legacy Columns API');
ImGui.SameLine();
HelpMarker('Columns() is an old API! Prefer using the more flexible and powerful BeginTable() API!');
if (!open) {return;}
// Basic columns
if (ImGui.TreeNode('Basic')) {
ImGui.Text('Without border:');
ImGui.Columns(3, 'mycolumns3', false); // 3-ways, no border
ImGui.Separator();
for (let n = 0; n < 14; n++) {
const label: string = `Item ${n}`;
if (ImGui.Selectable(label)) {}
//if (ImGui.Button(label, new ImGui.Vec2(-FLT_MIN,0.0))) {}
ImGui.NextColumn();
}
ImGui.Columns(1);
ImGui.Separator();
ImGui.Text('With border:');
ImGui.Columns(4, 'mycolumns'); // 4-ways, with border
ImGui.Separator();
ImGui.Text('ID'); ImGui.NextColumn();
ImGui.Text('Name'); ImGui.NextColumn();
ImGui.Text('Path'); ImGui.NextColumn();
ImGui.Text('Hovered'); ImGui.NextColumn();
ImGui.Separator();
const names: string[/*3*/] = ['One', 'Two', 'Three'];
const paths: string[/*3*/] = ['/path/one', '/path/two', '/path/three'];
const selected = STATIC<int>(UNIQUE('selected#7f97a06b'), -1);
for (let i = 0; i < 3; i++) {
const label: string = `${i.toString().padStart(4, '0')}`;
if (ImGui.Selectable(label, selected.value === i, ImGui.SelectableFlags.SpanAllColumns)) {selected.value = i;}
const hovered: boolean = ImGui.IsItemHovered();
ImGui.NextColumn();
ImGui.Text(names[i]); ImGui.NextColumn();
ImGui.Text(paths[i]); ImGui.NextColumn();
ImGui.Text(`${hovered}`); ImGui.NextColumn();
}
ImGui.Columns(1);
ImGui.Separator();
ImGui.TreePop();
}
if (ImGui.TreeNode('Borders')) {
// NB: Future columns API should allow automatic horizontal borders.
const h_borders = STATIC<boolean>(UNIQUE('h_borders#d7f23137'), true);
const v_borders = STATIC<boolean>(UNIQUE('v_borders#17e24566'), true);
const columns_count = STATIC<int>(UNIQUE('columns_count#3b93013c'), 4);
const lines_count: int = 3;
ImGui.SetNextItemWidth(ImGui.GetFontSize() * 8);
ImGui.DragInt('##columns_count', columns_count.access, 0.1, 2, 10, '%d columns');
if (columns_count.value < 2) {columns_count.value = 2;}
ImGui.SameLine();
ImGui.Checkbox('horizontal', h_borders.access);
ImGui.SameLine();
ImGui.Checkbox('vertical', v_borders.access);
ImGui.Columns(columns_count.value, null, v_borders.value);
for (let i = 0; i < columns_count.value * lines_count; i++) {
if (h_borders.value && ImGui.GetColumnIndex() === 0) {ImGui.Separator();}
const c: string = String.fromCharCode('a'.charCodeAt(0) + i);
ImGui.Text(`${c}${c}${c}`);
ImGui.Text(`Width ${ImGui.GetColumnWidth().toFixed(2)}`);
ImGui.Text(`Avail ${ImGui.GetContentRegionAvail().x.toFixed(2)}`);
ImGui.Text(`Offset ${ImGui.GetColumnOffset().toFixed(2)}`);
ImGui.Text('Long text that is likely to clip');
ImGui.Button('Button', new ImGui.Vec2(-FLT_MIN, 0.0));
ImGui.NextColumn();
}
ImGui.Columns(1);
if (h_borders.value) {ImGui.Separator();}
ImGui.TreePop();
}
// Create multiple items in a same cell before switching to next column
if (ImGui.TreeNode('Mixed items')) {
ImGui.Columns(3, 'mixed');
ImGui.Separator();
ImGui.Text('Hello');
ImGui.Button('Banana');
ImGui.NextColumn();
ImGui.Text('ImGui');
ImGui.Button('Apple');
const foo = STATIC<float>(UNIQUE('foo#845ff349'), 1.0);
ImGui.InputFloat('red', foo.access, 0.05, 0, '%.3f');
ImGui.Text('An extra line here.');
ImGui.NextColumn();
ImGui.Text('Sailor');
ImGui.Button('Corniflower');
const bar = STATIC<float>(UNIQUE('bar#32ef50e7'), 1.0);
ImGui.InputFloat('blue', bar.access, 0.05, 0, '%.3f');
ImGui.NextColumn();
if (ImGui.CollapsingHeader('Category A')) { ImGui.Text('Blah blah blah'); } ImGui.NextColumn();
if (ImGui.CollapsingHeader('Category B')) { ImGui.Text('Blah blah blah'); } ImGui.NextColumn();
if (ImGui.CollapsingHeader('Category C')) { ImGui.Text('Blah blah blah'); } ImGui.NextColumn();
ImGui.Columns(1);
ImGui.Separator();
ImGui.TreePop();
}
// Word wrapping
if (ImGui.TreeNode('Word-wrapping')) {
ImGui.Columns(2, 'word-wrapping');
ImGui.Separator();
ImGui.TextWrapped('The quick brown fox jumps over the lazy dog.');
ImGui.TextWrapped('Hello Left');
ImGui.NextColumn();
ImGui.TextWrapped('The quick brown fox jumps over the lazy dog.');
ImGui.TextWrapped('Hello Right');
ImGui.Columns(1);
ImGui.Separator();
ImGui.TreePop();
}
if (ImGui.TreeNode('Horizontal Scrolling')) {
ImGui.SetNextWindowContentSize(new ImGui.Vec2(1500.0, 0.0));
const child_size: ImGui.Vec2 = new ImGui.Vec2(0, ImGui.GetFontSize() * 20.0);
ImGui.BeginChild('##ScrollingRegion', child_size, false, ImGui.WindowFlags.HorizontalScrollbar);
ImGui.Columns(10);
// Also demonstrate using clipper for large vertical lists
const ITEMS_COUNT: int = 2000;
const clipper = new ImGui.ListClipper();
clipper.Begin(ITEMS_COUNT);
while (clipper.Step()) {
for (let i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) {
for (let j = 0; j < 10; j++) {
ImGui.Text(`Line ${i} Column ${j}...`);
ImGui.NextColumn();
}
}
}
ImGui.Columns(1);
ImGui.EndChild();
ImGui.TreePop();
}
if (ImGui.TreeNode('Tree')) {
ImGui.Columns(2, 'tree', true);
for (let x = 0; x < 3; x++) {
const open1: boolean = ImGui.TreeNode(/*(void*)(intptr_t)*/x, `Node${x}`);
ImGui.NextColumn();
ImGui.Text('Node contents');
ImGui.NextColumn();
if (open1) {
for (let y = 0; y < 3; y++) {
const open2: boolean = ImGui.TreeNode(/*(void*)(intptr_t)*/y, `Node${x}.${y}`);
ImGui.NextColumn();
ImGui.Text('Node contents');
if (open2) {
ImGui.Text('Even more contents');
if (ImGui.TreeNode('Tree in column')) {
ImGui.Text('The quick brown fox jumps over the lazy dog');
ImGui.TreePop();
}
}
ImGui.NextColumn();
if (open2) {ImGui.TreePop();}
}
ImGui.TreePop();
}
}
ImGui.Columns(1);
ImGui.TreePop();
}
ImGui.TreePop();
} | // Demonstrate old/legacy Columns API! | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/web-packages/imgui-demo/src/imgui/imgui_demo.ts#L4921-L5106 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | ShowAboutWindow | function /*ImGui.*/ShowAboutWindow (p_open: ImGui.Access<boolean>): void {
if (!ImGui.Begin('About Dear ImGui', p_open, ImGui.WindowFlags.AlwaysAutoResize)) {
ImGui.End();
return;
}
ImGui.Text(`Dear ImGui ${ImGui.GetVersion()}`);
ImGui.Separator();
ImGui.Text('By Omar Cornut and all Dear ImGui contributors.');
ImGui.Text('Dear ImGui is licensed under the MIT License, see LICENSE for more information.');
const show_config_info = STATIC<boolean>(UNIQUE('show_config_info#714b2250'), false);
ImGui.Checkbox('Config/Build Information', show_config_info.access);
if (show_config_info.value) {
const io: ImGui.IO = ImGui.GetIO();
const style: ImGui.Style = ImGui.GetStyle();
const copy_to_clipboard: boolean = ImGui.Button('Copy to clipboard');
const child_size: ImGui.Vec2 = new ImGui.Vec2(0, ImGui.GetTextLineHeightWithSpacing() * 18);
ImGui.BeginChildFrame(ImGui.GetID('cfg_infos'), child_size, ImGui.WindowFlags.NoMove);
if (copy_to_clipboard) {
ImGui.LogToClipboard();
ImGui.LogText('```\n'); // Back quotes will make text appears without formatting when pasting on GitHub
}
ImGui.Text(`Dear ImGui ${ImGui.VERSION} (${ImGui.VERSION_NUM})`);
ImGui.Separator();
// ImGui.Text("sizeof(size_t): %d, sizeof(ImDrawIdx): %d, sizeof(ImDrawVert): %d", (int)sizeof(size_t), (int)sizeof(ImDrawIdx), (int)sizeof(ImDrawVert));
ImGui.Text(`ImGui.DrawIdxSize: ${ImGui.DrawIdxSize}, ImGui.DrawVertSize: ${ImGui.DrawVertSize}`);
// ImGui.Text("define: __cplusplus=%d", (int)__cplusplus);
// #ifdef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
// ImGui.Text("define: IMGUI_DISABLE_OBSOLETE_FUNCTIONS");
// #endif
// #ifdef IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS
// ImGui.Text("define: IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS");
// #endif
// #ifdef IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
// ImGui.Text("define: IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS");
// #endif
// #ifdef IMGUI_DISABLE_WIN32_FUNCTIONS
// ImGui.Text("define: IMGUI_DISABLE_WIN32_FUNCTIONS");
// #endif
// #ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
// ImGui.Text("define: IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS");
// #endif
// #ifdef IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS
// ImGui.Text("define: IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS");
// #endif
// #ifdef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
// ImGui.Text("define: IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS");
// #endif
// #ifdef IMGUI_DISABLE_FILE_FUNCTIONS
// ImGui.Text("define: IMGUI_DISABLE_FILE_FUNCTIONS");
// #endif
// #ifdef IMGUI_DISABLE_DEFAULT_ALLOCATORS
// ImGui.Text("define: IMGUI_DISABLE_DEFAULT_ALLOCATORS");
// #endif
// #ifdef IMGUI_USE_BGRA_PACKED_COLOR
// ImGui.Text("define: IMGUI_USE_BGRA_PACKED_COLOR");
// #endif
// #ifdef _WIN32
// ImGui.Text("define: _WIN32");
// #endif
// #ifdef _WIN64
// ImGui.Text("define: _WIN64");
// #endif
// #ifdef __linux__
// ImGui.Text("define: __linux__");
// #endif
// #ifdef __APPLE__
// ImGui.Text("define: __APPLE__");
// #endif
// #ifdef _MSC_VER
// ImGui.Text("define: _MSC_VER=%d", _MSC_VER);
// #endif
// #ifdef _MSVC_LANG
// ImGui.Text("define: _MSVC_LANG=%d", (int)_MSVC_LANG);
// #endif
// #ifdef __MINGW32__
// ImGui.Text("define: __MINGW32__");
// #endif
// #ifdef __MINGW64__
// ImGui.Text("define: __MINGW64__");
// #endif
// #ifdef __GNUC__
// ImGui.Text("define: __GNUC__=%d", (int)__GNUC__);
// #endif
// #ifdef __clang_version__
// ImGui.Text("define: __clang_version__=%s", __clang_version__);
// #endif
ImGui.Separator();
ImGui.Text(`io.BackendPlatformName: ${io.BackendPlatformName ? io.BackendPlatformName : 'null'}`);
ImGui.Text(`io.BackendRendererName: ${io.BackendRendererName ? io.BackendRendererName : 'null'}`);
ImGui.Text(`io.ConfigFlags: 0x${io.ConfigFlags.toString(16).toUpperCase().padStart(8, '0')}`);
if (io.ConfigFlags & ImGui.ConfigFlags.NavEnableKeyboard) {ImGui.Text(' NavEnableKeyboard');}
if (io.ConfigFlags & ImGui.ConfigFlags.NavEnableGamepad) {ImGui.Text(' NavEnableGamepad');}
if (io.ConfigFlags & ImGui.ConfigFlags.NavEnableSetMousePos) {ImGui.Text(' NavEnableSetMousePos');}
if (io.ConfigFlags & ImGui.ConfigFlags.NavNoCaptureKeyboard) {ImGui.Text(' NavNoCaptureKeyboard');}
if (io.ConfigFlags & ImGui.ConfigFlags.NoMouse) {ImGui.Text(' NoMouse');}
if (io.ConfigFlags & ImGui.ConfigFlags.NoMouseCursorChange) {ImGui.Text(' NoMouseCursorChange');}
if (io.MouseDrawCursor) {ImGui.Text('io.MouseDrawCursor');}
if (io.ConfigMacOSXBehaviors) {ImGui.Text('io.ConfigMacOSXBehaviors');}
if (io.ConfigInputTextCursorBlink) {ImGui.Text('io.ConfigInputTextCursorBlink');}
if (io.ConfigWindowsResizeFromEdges) {ImGui.Text('io.ConfigWindowsResizeFromEdges');}
if (io.ConfigWindowsMoveFromTitleBarOnly) {ImGui.Text('io.ConfigWindowsMoveFromTitleBarOnly');}
if (io.ConfigMemoryCompactTimer >= 0.0) {ImGui.Text(`io.ConfigMemoryCompactTimer = ${io.ConfigMemoryCompactTimer.toFixed(1)}`);}
ImGui.Text(`io.BackendFlags: 0x${io.BackendFlags.toString(16).toUpperCase().padStart(8, '0')}`);
if (io.BackendFlags & ImGui.BackendFlags.HasGamepad) {ImGui.Text(' HasGamepad');}
if (io.BackendFlags & ImGui.BackendFlags.HasMouseCursors) {ImGui.Text(' HasMouseCursors');}
if (io.BackendFlags & ImGui.BackendFlags.HasSetMousePos) {ImGui.Text(' HasSetMousePos');}
if (io.BackendFlags & ImGui.BackendFlags.RendererHasVtxOffset) {ImGui.Text(' RendererHasVtxOffset');}
ImGui.Separator();
ImGui.Text(`io.Fonts: ${io.Fonts.Fonts.Size} fonts, Flags: 0x${io.Fonts.Flags.toString(16).toUpperCase().padStart(8, '0')}, TexSize: ${io.Fonts.TexWidth},${io.Fonts.TexHeight}`);
ImGui.Text(`io.DisplaySize: ${io.DisplaySize.x.toFixed(2)},${io.DisplaySize.y.toFixed(2)}`);
ImGui.Text(`io.DisplayFramebufferScale: ${io.DisplayFramebufferScale.x.toFixed(2)},${io.DisplayFramebufferScale.y.toFixed(2)}`);
ImGui.Separator();
ImGui.Text(`style.WindowPadding: ${style.WindowPadding.x.toFixed(2)},${style.WindowPadding.y.toFixed(2)}`);
ImGui.Text(`style.WindowBorderSize: ${style.WindowBorderSize.toFixed(2)}`);
ImGui.Text(`style.FramePadding: ${style.FramePadding.x.toFixed(2)},${style.FramePadding.y.toFixed(2)}`);
ImGui.Text(`style.FrameRounding: ${style.FrameRounding.toFixed(2)}`);
ImGui.Text(`style.FrameBorderSize: ${style.FrameBorderSize.toFixed(2)}`);
ImGui.Text(`style.ItemSpacing: ${style.ItemSpacing.x.toFixed(2)},${style.ItemSpacing.y.toFixed(2)}`);
ImGui.Text(`style.ItemInnerSpacing: ${style.ItemInnerSpacing.x.toFixed(2)},${style.ItemInnerSpacing.y.toFixed(2)}`);
if (copy_to_clipboard) {
ImGui.LogText('\n```\n');
ImGui.LogFinish();
}
ImGui.EndChildFrame();
}
ImGui.End();
} | //----------------------------------------------------------------------------- | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/web-packages/imgui-demo/src/imgui/imgui_demo.ts#L5278-L5411 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | ShowStyleSelector | function /*ImGui.*/ShowStyleSelector (label: string): boolean {
const style_idx = STATIC<int>(UNIQUE('style_idx#8531ae65'), -1);
if (ImGui.Combo(label, style_idx.access, 'Dark\0Light\0Classic\0')) {
switch (style_idx.value) {
case 0: ImGui.StyleColorsDark();
break;
case 1: ImGui.StyleColorsLight();
break;
case 2: ImGui.StyleColorsClassic();
break;
}
return true;
}
return false;
} | //----------------------------------------------------------------------------- | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/web-packages/imgui-demo/src/imgui/imgui_demo.ts#L5424-L5444 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | ShowFontSelector | function /*ImGui.*/ShowFontSelector (label: string): void {
const io: ImGui.IO = ImGui.GetIO();
const font_current: ImGui.Font = ImGui.GetFont();
if (ImGui.BeginCombo(label, font_current.GetDebugName())) {
for (let n = 0; n < io.Fonts.Fonts.Size; n++) {
const font: ImGui.Font = io.Fonts.Fonts[n];
ImGui.PushID(/*(void*)*/font.native.$$.ptr);
if (ImGui.Selectable(font.GetDebugName(), font === font_current)) {io.FontDefault = font;}
ImGui.PopID();
}
ImGui.EndCombo();
}
ImGui.SameLine();
HelpMarker(
'- Load additional fonts with io.Fonts.AddFontFromFileTTF().\n' +
'- The font atlas is built when calling io.Fonts.GetTexDataAsXXXX() or io.Fonts.Build().\n' +
'- Read FAQ and docs/FONTS.md for more details.\n' +
'- If you need to add/remove fonts at runtime (e.g. for DPI change), do it before calling NewFrame().');
} | // Demo helper function to select among loaded fonts. | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/web-packages/imgui-demo/src/imgui/imgui_demo.ts#L5448-L5468 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | NodeFont | function NodeFont (font: ImGui.Font): void {
const io: ImGui.IO = ImGui.GetIO();
const style: ImGui.Style = ImGui.GetStyle();
const font_details_opened: boolean = ImGui.TreeNode(font.native.$$.ptr, `Font: \"${font.ConfigData ? font.ConfigData[0].Name : ''}\"\n${font.FontSize.toFixed(2)} px, ${font.Glyphs.Size} glyphs, ${font.ConfigDataCount} file(s)`);
ImGui.SameLine(); if (ImGui.SmallButton('Set as default')) { io.FontDefault = font; }
if (!font_details_opened) {return;}
ImGui.PushFont(font);
ImGui.Text('The quick brown fox jumps over the lazy dog');
ImGui.PopFont();
ImGui.DragFloat('Font scale', (_ = font.Scale) => font.Scale = _, 0.005, 0.3, 2.0, '%.1f'); // Scale only this font
ImGui.SameLine(); HelpMarker(
'Note than the default embedded font is NOT meant to be scaled.\n\n' +
'Font are currently rendered into bitmaps at a given size at the time of building the atlas. ' +
'You may oversample them to get some flexibility with scaling. ' +
'You can also render at multiple sizes and select which one to use at runtime.\n\n' +
'(Glimmer of hope: the atlas system will be rewritten in the future to make scaling more flexible.)');
ImGui.Text(`Ascent: ${font.Ascent}, Descent: ${font.Descent}, Height: ${font.Ascent - font.Descent}`);
ImGui.Text(`Fallback character: '${String.fromCharCode(font.FallbackChar)}' (U+${font.FallbackChar.toString().padStart(4, '0')})`);
ImGui.Text(`Ellipsis character: '${String.fromCharCode(font.EllipsisChar)}' (U+${font.EllipsisChar.toString().padStart(4, '0')})`);
const surface_sqrt: int = Math.floor(/*(int)*/Math.sqrt(font.MetricsTotalSurface));
ImGui.Text(`Texture Area: about ${font.MetricsTotalSurface} px ~${surface_sqrt}x${surface_sqrt} px`);
for (let config_i = 0, cfg: ImGui.FontConfig; config_i < font.ConfigDataCount; config_i++) {
if (font.ConfigData) {
if (cfg = font.ConfigData[config_i]) {ImGui.BulletText(`Input ${config_i}: '${cfg.Name}', Oversample: (${cfg.OversampleH},${cfg.OversampleV}), PixelSnapH: ${cfg.PixelSnapH}, Offset: (${cfg.GlyphOffset.x.toFixed(1)},${cfg.GlyphOffset.x.toFixed(1)})`);}
}
}
if (ImGui.TreeNode('Glyphs', `Glyphs (${font.Glyphs.Size})`)) {
// Display all glyphs of the fonts in separate pages of 256 characters
const glyph_col: ImGui.U32 = ImGui.GetColorU32(ImGui.Col.Text);
for (let base = 0; base <= ImGui.UNICODE_CODEPOINT_MAX; base += 256) {
// Skip ahead if a large bunch of glyphs are not present in the font (test in chunks of 4k)
// This is only a small optimization to reduce the number of iterations when IM_UNICODE_MAX_CODEPOINT
// is large // (if ImWchar==ImWchar32 we will do at least about 272 queries here)
if (!(base & 4095) && font.IsGlyphRangeUnused(base, base + 4095)) {
base += 4096 - 256;
continue;
}
let count: int = 0;
for (let n = 0; n < 256; n++) {
if (font.FindGlyphNoFallback((base + n))) {count++;}
}
if (count <= 0) {continue;}
if (!ImGui.TreeNode(/*(void*)(intptr_t)*/base, `U+${base.toString(16).toUpperCase().padStart(4, '0')}..U+${(base + 255).toString(16).toUpperCase().padStart(4, '0')} (${count} ${count > 1 ? 'glyphs' : 'glyph'})`)) {continue;}
const cell_size: float = font.FontSize * 1;
const cell_spacing: float = style.ItemSpacing.y;
const base_pos: ImGui.Vec2 = ImGui.GetCursorScreenPos();
const draw_list: ImGui.DrawList = ImGui.GetWindowDrawList();
for (let n = 0; n < 256; n++) {
// We use ImFont.RenderChar as a shortcut because we don't have UTF-8 conversion functions
// available here and thus cannot easily generate a zero-terminated UTF-8 encoded string.
const cell_p1: ImGui.Vec2 = new ImGui.Vec2(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + (0 | (n / 16)) * (cell_size + cell_spacing));
const cell_p2: ImGui.Vec2 = new ImGui.Vec2(cell_p1.x + cell_size, cell_p1.y + cell_size);
const glyph: ImGui.FontGlyph | null = font.FindGlyphNoFallback((base + n));
draw_list.AddRect(cell_p1, cell_p2, glyph ? ImGui.COL32(255, 255, 255, 100) : ImGui.COL32(255, 255, 255, 50));
if (glyph) {font.RenderChar(draw_list, cell_size, cell_p1, glyph_col, (base + n));}
if (glyph && ImGui.IsMouseHoveringRect(cell_p1, cell_p2)) {
ImGui.BeginTooltip();
ImGui.Text(`Codepoint: U+${(base + n).toString(16).toUpperCase().padStart(4, '0')}`);
ImGui.Separator();
ImGui.Text(`Visible: ${glyph.Visible}`);
ImGui.Text(`AdvanceX: ${glyph.AdvanceX.toFixed(1)}`);
ImGui.Text(`Pos: (${glyph.X0.toFixed(2)},${glyph.Y0.toFixed(2)}).(${glyph.X1.toFixed(2)},${glyph.Y1.toFixed(2)})`);
ImGui.Text(`UV: (${glyph.U0.toFixed(3)},${glyph.V0.toFixed(3)}).(${glyph.U1.toFixed(3)},${glyph.V1.toFixed(3)})`);
ImGui.EndTooltip();
}
}
ImGui.Dummy(new ImGui.Vec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16));
ImGui.TreePop();
}
ImGui.TreePop();
}
ImGui.TreePop();
} | // [Internal] Display details for a single font, called by ShowStyleEditor(). | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/web-packages/imgui-demo/src/imgui/imgui_demo.ts#L5471-L5551 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | ShowExampleAppMainMenuBar | function ShowExampleAppMainMenuBar (): void {
if (ImGui.BeginMainMenuBar()) {
if (ImGui.BeginMenu('File')) {
ShowExampleMenuFile();
ImGui.EndMenu();
}
if (ImGui.BeginMenu('Edit')) {
if (ImGui.MenuItem('Undo', 'CTRL+Z')) {}
if (ImGui.MenuItem('Redo', 'CTRL+Y', false, false)) {} // Disabled item
ImGui.Separator();
if (ImGui.MenuItem('Cut', 'CTRL+X')) {}
if (ImGui.MenuItem('Copy', 'CTRL+C')) {}
if (ImGui.MenuItem('Paste', 'CTRL+V')) {}
ImGui.EndMenu();
}
ImGui.EndMainMenuBar();
}
} | //----------------------------------------------------------------------------- | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/web-packages/imgui-demo/src/imgui/imgui_demo.ts#L5796-L5813 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | ShowExampleMenuFile | function ShowExampleMenuFile (): void {
ImGui.MenuItem('(demo menu)', null, false, false);
if (ImGui.MenuItem('New')) {}
if (ImGui.MenuItem('Open', 'Ctrl+O')) {}
if (ImGui.BeginMenu('Open Recent')) {
ImGui.MenuItem('fish_hat.c');
ImGui.MenuItem('fish_hat.inl');
ImGui.MenuItem('fish_hat.h');
if (ImGui.BeginMenu('More..')) {
ImGui.MenuItem('Hello');
ImGui.MenuItem('Sailor');
if (ImGui.BeginMenu('Recurse..')) {
ShowExampleMenuFile();
ImGui.EndMenu();
}
ImGui.EndMenu();
}
ImGui.EndMenu();
}
if (ImGui.MenuItem('Save', 'Ctrl+S')) {}
if (ImGui.MenuItem('Save As..')) {}
ImGui.Separator();
if (ImGui.BeginMenu('Options')) {
const enabled = STATIC<boolean>(UNIQUE('enabled#5f4b3785'), true);
ImGui.MenuItem('Enabled', '', enabled.access);
ImGui.BeginChild('child', new ImGui.Vec2(0, 60), true);
for (let i = 0; i < 10; i++) {ImGui.Text(`Scrolling Text ${i}`);}
ImGui.EndChild();
const f = STATIC<float>(UNIQUE('f#cddcae77'), 0.5);
const n = STATIC<int>(UNIQUE('n#e3c8fe24'), 0);
ImGui.SliderFloat('Value', f.access, 0.0, 1.0);
ImGui.InputFloat('Input', f.access, 0.1);
ImGui.Combo('Combo', n.access, 'Yes\0No\0Maybe\0\0');
ImGui.EndMenu();
}
if (ImGui.BeginMenu('Colors')) {
const sz: float = ImGui.GetTextLineHeight();
for (let i = 0; i < ImGui.Col.COUNT; i++) {
const name: string = ImGui.GetStyleColorName(<ImGui.Col>i);
const p: ImGui.Vec2 = ImGui.GetCursorScreenPos();
ImGui.GetWindowDrawList().AddRectFilled(p, new ImGui.Vec2(p.x + sz, p.y + sz), ImGui.GetColorU32(<ImGui.Col>i));
ImGui.Dummy(new ImGui.Vec2(sz, sz));
ImGui.SameLine();
ImGui.MenuItem(name);
}
ImGui.EndMenu();
}
// Here we demonstrate appending again to the "Options" menu (which we already created above)
// Of course in this demo it is a little bit silly that this function calls BeginMenu("Options") twice.
// In a real code-base using it would make senses to use this feature from very different code locations.
if (ImGui.BeginMenu('Options')) // <-- Append!
{
const b = STATIC<boolean>(UNIQUE('b#d9276246'), true);
ImGui.Checkbox('SomeOption', b.access);
ImGui.EndMenu();
}
if (ImGui.BeginMenu('Disabled', false)) // Disabled
{
ImGui.ASSERT(0);
}
if (ImGui.MenuItem('Checked', null, true)) {}
if (ImGui.MenuItem('Quit', 'Alt+F4')) { done = true; }
} | // Note that shortcuts are currently provided for display only | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/web-packages/imgui-demo/src/imgui/imgui_demo.ts#L5817-L5888 | 20512f4406e62c400b2b4255576cfa628db74a22 |
effects-runtime | github_2023 | galacean | typescript | ExampleAppConsole.ClearLog | ClearLog (): void {
// for (let i = 0; i < this.Items.Size; i++)
// free(this.Items[i]);
this.Items.clear();
} | // const Strtrim(char* s) { char* str_end = s + strlen(s); while (str_end > s && str_end[-1] === ' ') str_end--; *str_end = STATIC<void>(UNIQUE(" Strtrim(char* s) { char* str_end = s + strlen(s); while (str_end > s && str_end[-1] === ' ') str_end--; *str_end"), 0); } | https://github.com/galacean/effects-runtime/blob/20512f4406e62c400b2b4255576cfa628db74a22/web-packages/imgui-demo/src/imgui/imgui_demo.ts#L5932-L5936 | 20512f4406e62c400b2b4255576cfa628db74a22 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.