171 lines
5.9 KiB
TypeScript
171 lines
5.9 KiB
TypeScript
// 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();
|
||
// Если авто-подсветка включена, подписываемся на обновления EquipmentManager
|
||
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 newMat = new Material();
|
||
newMat.copy(m);
|
||
return newMat;
|
||
});
|
||
}
|
||
|
||
private _onDataUpdated() {
|
||
// Если авто-подсветка выключена, не реагируем на обновления данных
|
||
if (!this.autoHighlight) return;
|
||
|
||
const sensors: apiSensors[] = EquipmentManager.instance.dataList;
|
||
const sensorData = sensors.find((s) => s.name === this.sensorName);
|
||
if (sensorData) {
|
||
let color = "";
|
||
if (sensorData.value === 2) {
|
||
color = "red";
|
||
} else if (sensorData.value === 1) {
|
||
color = "green";
|
||
} else if (sensorData.value === 0) {
|
||
color = "yellow";
|
||
} else {
|
||
console.warn(`Неожиданное значение sensorData.value: ${sensorData.value}`);
|
||
return;
|
||
}
|
||
this.switchToColor(color);
|
||
}
|
||
}
|
||
|
||
public switchToColor(color: string) {
|
||
const renderer = this.node.getComponent(MeshRenderer);
|
||
if (!renderer) return;
|
||
|
||
// Если уже есть активный объект и он не этот, сбрасываем его подсветку
|
||
if (PulsatingHighlighter._activeInstance && PulsatingHighlighter._activeInstance !== this) {
|
||
PulsatingHighlighter._activeInstance.resetHighlight();
|
||
}
|
||
PulsatingHighlighter._activeInstance = this;
|
||
|
||
let selectedMaterial: Material | null = null;
|
||
if (color === "red" && this.redMaterial) {
|
||
selectedMaterial = this.redMaterial;
|
||
} else if (color === "green" && this.greenMaterial) {
|
||
selectedMaterial = this.greenMaterial;
|
||
} else if (color === "yellow" && this.yellowMaterial) {
|
||
selectedMaterial = this.yellowMaterial;
|
||
} else {
|
||
console.warn(`Неизвестный цвет "${color}", используем оригинальный.`);
|
||
return;
|
||
}
|
||
|
||
// Создаем копию выбранного материала для эффекта подсветки
|
||
const highlightMat = new Material();
|
||
highlightMat.copy(selectedMaterial);
|
||
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 === 255 || this._currentAlpha === 0) {
|
||
this._direction *= -1;
|
||
}
|
||
|
||
const renderer = this.node.getComponent(MeshRenderer);
|
||
if (renderer) {
|
||
renderer.materials.forEach((mat) => {
|
||
const mainColor = mat?.getProperty("mainColor") as Color;
|
||
mainColor.a = this._currentAlpha;
|
||
mat?.setProperty("mainColor", mainColor);
|
||
});
|
||
}
|
||
}
|
||
|
||
// Сброс подсветки: остановка анимации и восстановление оригинальных материалов
|
||
public resetHighlight() {
|
||
this.unschedule(this._updateAlpha);
|
||
this.unscheduleAllCallbacks();
|
||
this._restoreOriginalMaterials();
|
||
}
|
||
|
||
private _restoreOriginalMaterials() {
|
||
const renderer = this.node.getComponent(MeshRenderer);
|
||
if (!renderer) return;
|
||
|
||
renderer.materials = this._originalMaterials.map((m) => {
|
||
const mat = new Material();
|
||
mat.copy(m);
|
||
return mat;
|
||
});
|
||
}
|
||
|
||
onDestroy() {
|
||
this.unscheduleAllCallbacks();
|
||
if (EquipmentManager.instance) {
|
||
EquipmentManager.instance.node.off('data-updated', this._onDataUpdated, this);
|
||
}
|
||
}
|
||
}
|