yantar/assets/Scripts/PulsatingHighlighter.ts
Georgy Shive 98e9d62db7 везде где только мог сделал с безопасной подпиской/отпиской через optional chaining
— так компоненты не упадут, даже если кнопка или её node к моменту onDestroy уже не существует
сделал ноды менеджеров списка оборудовани, деталей,
и аварий Persistent Node, чтобы при смене сцены не сбрасывалось
их состояние.
2025-05-11 13:33:08 +07:00

139 lines
4.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// PulsatingHighlighter.ts
import { _decorator, Component, MeshRenderer, Material, Color, math } from "cc";
import { apiSensors } from "./stores/apiSensors";
import { EquipmentManager } from "./stores/EquipmentManager";
const { ccclass, property } = _decorator;
@ccclass("PulsatingHighlighter")
export class PulsatingHighlighter extends Component {
@property(Material) redMaterial: Material = null!;
@property(Material) greenMaterial: Material = null!;
@property(Material) yellowMaterial: Material = null!;
private _originalMaterials: Material[] = [];
private _currentAlpha = 0;
private _direction = 1;
private _animationSpeed = 3;
private static _activeInstance: PulsatingHighlighter | null = null;
@property public sensorName: string = "";
@property public autoHighlight: boolean = false;
onLoad() {
this._storeOriginalMaterials();
if (this.autoHighlight) {
this.waitForEquipmentManager();
}
}
private waitForEquipmentManager() {
if (!EquipmentManager.instance) {
this.scheduleOnce(() => this.waitForEquipmentManager(), 0.1);
return;
}
EquipmentManager.instance.node.on('data-updated', this._onDataUpdated, this);
}
private _storeOriginalMaterials() {
const renderer = this.node.getComponent(MeshRenderer);
if (!renderer) return;
this._originalMaterials = renderer.materials
.filter((m): m is Material => !!m)
.map(m => {
const copy = new Material();
copy.copy(m);
return copy;
});
}
private _onDataUpdated() {
if (!this.autoHighlight) return;
const data = EquipmentManager.instance.dataList.find(s => s.name === this.sensorName);
if (!data) return;
const color = data.value === 2 ? 'red'
: data.value === 1 ? 'green'
: data.value === 0 ? 'yellow'
: '';
if (color) this.switchToColor(color);
}
public switchToColor(color: string) {
const renderer = this.node.getComponent(MeshRenderer);
if (!renderer) return;
// Если есть другой активный хайлайтер — сбросим его, но только если его node ещё жив
if (PulsatingHighlighter._activeInstance && PulsatingHighlighter._activeInstance !== this) {
const prev = PulsatingHighlighter._activeInstance;
if (prev.node) {
prev.resetHighlight();
}
}
PulsatingHighlighter._activeInstance = this;
// Выбираем материал
let sel: Material | null = null;
if (color === 'red') sel = this.redMaterial;
else if (color === 'green') sel = this.greenMaterial;
else if (color === 'yellow') sel = this.yellowMaterial;
if (!sel) return;
// Применяем и запускаем анимацию
const highlightMat = new Material(); highlightMat.copy(sel);
renderer.materials = renderer.materials.map(() => highlightMat);
this._currentAlpha = 0; this._direction = 1;
this.schedule(this._updateAlpha, 0.016);
// Запланируем сброс через 10 секунд
this.scheduleOnce(() => {
if (PulsatingHighlighter._activeInstance === this) {
this.resetHighlight();
PulsatingHighlighter._activeInstance = null;
}
}, 10);
}
private _updateAlpha() {
this._currentAlpha += this._direction * this._animationSpeed;
this._currentAlpha = math.clamp(this._currentAlpha, 0, 255);
if (this._currentAlpha === 0 || this._currentAlpha === 255) this._direction *= -1;
const renderer = this.node?.getComponent(MeshRenderer);
if (renderer) {
renderer.materials.forEach(mat => {
const c = mat?.getProperty('mainColor') as Color;
c.a = this._currentAlpha;
mat?.setProperty('mainColor', c);
});
}
}
public resetHighlight() {
this.unschedule(this._updateAlpha);
this.unscheduleAllCallbacks();
this._restoreOriginalMaterials();
}
private _restoreOriginalMaterials() {
// Guard: node мог быть уничтожен
if (!this.node) return;
const renderer = this.node.getComponent(MeshRenderer);
if (!renderer) return;
renderer.materials = this._originalMaterials.map(orig => {
const copy = new Material();
copy.copy(orig);
return copy;
});
}
onDestroy() {
// Снимаем подписку и сбрасываем статический инстанс, если он — наш
EquipmentManager.instance?.node?.off('data-updated', this._onDataUpdated, this);
this.unscheduleAllCallbacks();
if (PulsatingHighlighter._activeInstance === this) {
PulsatingHighlighter._activeInstance = null;
}
}
}