Compare commits

..
2 Commits
13 changed files with 106 additions and 31 deletions
@@ -22,9 +22,10 @@ export function BatteryDesignSettings({value,update}:{value:BatteryAppearance;up
{range('Прозрачность стекла, %',100-p.glass.tintOpacity,0,100,transparency=>glass({tintOpacity:100-transparency}))}
{range('Размытие стекла, px',p.glass.blur,0,60,blur=>glass({blur}))}
</SettingsCard>:<SettingsCard title="Индикатор в обсерватории" description="Размеры, цвет заливки и диапазоны уровня заряда для этой батареи.">
{range('Ширина индикатора, px',i.width,64,320,width=>indicator({width}))}
{range('Высота индикатора, px',i.height,24,96,height=>indicator({height}))}
{range('Ширина индикатора, px',i.width,32,320,width=>indicator({width}))}
{range('Высота индикатора, px',i.height,12,96,height=>indicator({height}))}
{range('Радиус углов индикатора, px',i.radius,0,48,radius=>indicator({radius}))}
{range('Отступ от кнопок шапки влево, px',i.offset,0,320,offset=>indicator({offset}))}
<Select label="Режим цвета индикатора" value={i.mode} onChange={mode=>indicator({mode})} options={[{value:'ranges',label:'По уровню заряда'},{value:'mono',label:'Один цвет'}]}/>
{i.mode==='mono'?color('Цвет индикатора',i.color,color=>indicator({color})):<>
{range('Низкий заряд ниже, %',i.lowUntil,0,99,lowUntil=>indicator({lowUntil,middleUntil:Math.max(i.middleUntil,lowUntil+1)}))}
@@ -2,5 +2,5 @@ import {LevelButton,type LevelButtonProps} from '@nodedc/ui-react';
import {batteryIndicatorColor,type BatteryIndicatorAppearance} from '../../core/batteryScene/appearance';
type Props=Omit<LevelButtonProps,'value'|'fillColor'>&{appearance:BatteryIndicatorAppearance;soc:number|null};
export function BatteryIndicator({appearance,soc,style,...props}:Props){
return <LevelButton {...props} value={soc===null?null:soc/100} fillColor={batteryIndicatorColor(appearance,soc)} style={{...style,width:appearance.width,minWidth:appearance.width,height:appearance.height,minHeight:appearance.height,borderRadius:appearance.radius,paddingInline:'var(--nodedc-space-2)',flexShrink:0}}/>;
return <LevelButton {...props} value={soc===null?null:soc/100} fillColor={batteryIndicatorColor(appearance,soc)} geometry={{width:appearance.width,height:appearance.height,radius:appearance.radius}} style={style}/>;
}
@@ -5,7 +5,7 @@ import {useMemo,useState} from 'react';
import {Description} from '@nodedc/ui-react';
import {SceneEditor} from '../rover/editor/RoverScene';
import {useSceneDocument} from '../../core/roverScene/useSceneDocument';
import {batterySceneProfile,defaultBatteryScene} from '../../core/batteryScene/profile';
import {batterySceneProfile} from '../../core/batteryScene/profile';
export function BatteryScene({editing,soc,fresh,deviceId,seedKey,cellVoltages=[],markingAppearance}:{editing:boolean;soc:number|null;fresh:boolean;deviceId:string;seedKey?:string;cellVoltages?:readonly number[];markingAppearance:CellMarkingAppearance}){
const profile=useMemo(()=>batterySceneProfile(seedKey),[seedKey]);
@@ -13,7 +13,7 @@ export function BatteryScene({editing,soc,fresh,deviceId,seedKey,cellVoltages=[]
const [api,setApi]=useState<Parameters<NonNullable<PlayCanvasViewerProps['onSceneReady']>>[0]|null>(null);
const [phase,setPhase]=useState<'loading'|'ready'|'error'>('loading');
return <div className="bms-scene" data-editing={editing} aria-label="3D-модель батареи R05">
<SceneEditor scene={scene} defaults={defaultBatteryScene} editing={editing} modelUrl="/battery-scene/catl-r04.glb?objects-v6-r05" minFitDistance={.6} chargeState={{soc,fresh}} onModelState={setPhase} onSceneReady={setApi}/>
<SceneEditor scene={scene} editing={editing} modelUrl="/battery-scene/catl-r04.glb?objects-v6-r05" minFitDistance={.6} chargeState={{soc,fresh}} onModelState={setPhase} onSceneReady={setApi}/>
<BatteryCellLabels api={api} ready={phase==='ready'} values={cellVoltages} appearance={markingAppearance}/>
{phase!=='ready'&&<div className="bms-scene-status"><Description role="status">{phase==='error'?'Модель не загрузилась. Показания BMS доступны ниже.':'Загружается модель аккумулятора…'}</Description></div>}
</div>;
@@ -0,0 +1,10 @@
import {useState} from 'react';
import {Button,Description,TextField,Window,WindowFooterActions} from '@nodedc/ui-react';
export function DuplicateMaterialDialog({initialName,onDuplicate,onClose}:{initialName:string;onDuplicate:(name:string)=>void;onClose:()=>void}){
const [name,setName]=useState(initialName),[error,setError]=useState('');
const save=()=>{try{onDuplicate(name);onClose();}catch(e){setError(e instanceof Error?e.message:'Не удалось создать копию материала.');}};
return <Window open title="Дублировать материал" size="sm" onClose={onClose} footer={<WindowFooterActions><Button onClick={onClose}>Отмена</Button><Button variant="primary" tone="neutral" disabled={!name.trim()} onClick={save}>Создать дубликат</Button></WindowFooterActions>}>
<TextField label="Название дубликата" autoFocus maxLength={120} value={name} onChange={e=>{setName(e.target.value);setError('');}} onKeyDown={e=>{if(e.key==='Enter'&&!e.nativeEvent.isComposing&&name.trim()){e.preventDefault();save();}}}/>
{error&&<Description role="alert">{error}</Description>}
</Window>;
}
@@ -1,17 +1,20 @@
import {useState} from 'react';
import {DuplicateMaterialDialog} from './DuplicateMaterialDialog';
import {Description,Inspector,InspectorSelectField,TextField,Button} from '@nodedc/ui-react';
import type {MaterialSpec} from '../../../core/roverScene/sceneDocument';
import {ChargeGradientInspector} from './ChargeGradientInspector';
import {MaterialSurfaceInspector} from './MaterialSurfaceInspector';
export type MaterialPreview='auto'|'active'|'inactive';
export function MaterialInspector({material,onChange,onReset,onError,preview='auto',onPreview}:{material:MaterialSpec;onChange:(patch:Partial<MaterialSpec>)=>void;onReset:()=>void;onError:(message:string)=>void;preview?:MaterialPreview;onPreview?:(value:MaterialPreview)=>void}){
const gradient=material.chargeGradient;
return <><TextField label="Название материала" value={material.name} maxLength={120} onChange={e=>onChange({name:e.target.value})}/><Description>Изменения применяются ко всем деталям с этим материалом.</Description>
{gradient?<>
<InspectorSelectField label="Предпросмотр материала" value={preview} options={[{value:'auto',label:'По данным BMS'},{value:'active',label:'Активный · градиент'},{value:'inactive',label:'Неактивный · без данных'}]} onChange={v=>onPreview?.(v as MaterialPreview)}/>
{preview==='active'&&<Description>Предпросмотр градиента: текущий заряд, а при отсутствии показаний — 50%.</Description>}
<Inspector defaultOpen={['active']} sections={[
export function MaterialInspector({material,onChange,onDuplicate,copyName,selectionDescription,onError,preview='auto',onPreview}:{material:MaterialSpec;onChange:(patch:Partial<MaterialSpec>)=>void;onDuplicate:(name:string)=>void;copyName:string;selectionDescription:string;onError:(message:string)=>void;preview?:MaterialPreview;onPreview?:(value:MaterialPreview)=>void}){
const gradient=material.chargeGradient,[duplicate,setDuplicate]=useState(false);
const header=<><Description>{selectionDescription}</Description><TextField label="Название материала" value={material.name} maxLength={120} onChange={e=>onChange({name:e.target.value})}/><Description>Изменения применяются ко всем деталям с этим материалом.</Description>
{gradient&&<InspectorSelectField label="Предпросмотр материала" value={preview} options={[{value:'auto',label:'По данным BMS'},{value:'active',label:'Активный · градиент'},{value:'inactive',label:'Неактивный · без данных'}]} onChange={v=>onPreview?.(v as MaterialPreview)}/>}
{gradient&&preview==='active'&&<Description>Предпросмотр градиента: текущий заряд, а при отсутствии показаний — 50%.</Description>}</>;
const footer=<Button variant="primary" tone="neutral" onClick={()=>setDuplicate(true)}>Дублировать материал</Button>;
return <>{gradient?
<Inspector header={header} footer={footer} defaultOpen={['active']} sections={[
{id:'active',label:'Активный материал · градиент',content:<><ChargeGradientInspector value={gradient} onChange={chargeGradient=>onChange({chargeGradient})}/><MaterialSurfaceInspector material={material} onChange={onChange} onError={onError}/></>},
{id:'inactive',label:'Неактивный материал · без данных',content:<><Description>Самостоятельный материал, когда сохранённого заряда нет. Свои поверхность, текстуры и свечение.</Description><MaterialSurfaceInspector material={gradient.inactive} onChange={patch=>onChange({chargeGradient:{...gradient,inactive:{...gradient.inactive,...patch}}})} onError={onError}/></>}
]}/></>:<MaterialSurfaceInspector material={material} onChange={onChange} onError={onError}/>}
<Button onClick={onReset}>Исходный материал</Button></>;
]}/>:<MaterialSurfaceInspector header={header} footer={footer} material={material} onChange={onChange} onError={onError}/>}
{duplicate&&<DuplicateMaterialDialog initialName={copyName} onDuplicate={onDuplicate} onClose={()=>setDuplicate(false)}/>}</>;
}
@@ -1,11 +1,11 @@
import {useRef,useState} from 'react';
import {useRef,useState,type ReactNode} from 'react';
import {Button,ColorField,ControlRow,Icon,IconButton,Inspector,RangeControl,Switch} from '@nodedc/ui-react';
import {textureSlots,type TextureSlot,type MaterialSurface} from '../../../core/roverScene/materialSurface';
import {textureFromFile} from '../../../core/roverScene/sceneStorage';
const slotLabels:Record<TextureSlot,string>={diffuse:'Базовый цвет',normal:'Нормали',roughness:'Шероховатость',metalness:'Металличность',opacity:'Прозрачность',emissive:'Свечение',ao:'Окклюзия · AO'};
export function MaterialSurfaceInspector({material,onChange,onError}:{material:MaterialSurface;onChange:(patch:Partial<MaterialSurface>)=>void;onError:(message:string)=>void}){
export function MaterialSurfaceInspector({material,onChange,onError,header,footer}:{header?:ReactNode;footer?:ReactNode;material:MaterialSurface;onChange:(patch:Partial<MaterialSurface>)=>void;onError:(message:string)=>void}){
const range=(key:keyof MaterialSurface,label:string,max=1)=><RangeControl label={label} value={Number(material[key])} min={0} max={max} step={.01} exactValueBounds={{min:0,max}} onChange={v=>onChange({[key]:v})}/>;
return <Inspector defaultOpen={['surface']} sections={[
return <Inspector header={header} footer={footer} defaultOpen={['surface']} sections={[
{id:'surface',label:'Поверхность',content:<div className="rover-scene-fields"><ControlRow label="Базовый цвет"><ColorField label="Базовый цвет" value={material.color} onChange={color=>onChange({color})}/></ControlRow>{range('metalness','Металличность')}{range('roughness','Шероховатость')}{range('reflectivity','Отражение')}{range('opacity','Непрозрачность')}<Switch label="Двусторонняя поверхность" checked={material.doubleSided} onChange={doubleSided=>onChange({doubleSided})}/></div>},
{id:'coat',label:'Лак и свечение',content:<div className="rover-scene-fields">{range('clearCoat','Слой лака')}{range('clearCoatRoughness','Шероховатость лака')}<ControlRow label="Цвет свечения"><ColorField label="Цвет свечения" value={material.emissive} onChange={emissive=>onChange({emissive})}/></ControlRow>{range('emissiveIntensity','Сила свечения',10)}</div>},
{id:'textures',label:'Текстуры',description:'PNG / JPEG / WebP · до 4096 px',content:<div className="rover-scene-fields">{textureSlots.map(slot=><TextureField key={slot} slot={slot} value={material.textures[slot]} onChange={texture=>onChange({textures:{...material.textures,[slot]:texture}})} onError={onError}/>)}{range('normalStrength','Сила нормалей',2)}<RangeControl label="Повторение текстуры" min={.01} max={20} step={.01} exactValueBounds={{min:.01,max:20}} value={material.tiling} onChange={tiling=>onChange({tiling})}/></div>},
@@ -1,8 +1,9 @@
import {duplicateMaterial,materialCopyName} from '../../../core/roverScene/materialActions';
import {editorDockLayout,materialTileSizes} from '../../../core/roverScene/editorLayout';
import {roverModelURL} from '../../../core/roverScene/model';
import {useCallback,useEffect,useRef,useState} from 'react';
import {Description,DragDropRoot,DropZone,EditorDockLayout,GlassSurface,Icon,IconButton,LoadingRegion,StatusBadge,ToastStack,type EditorDockTool} from '@nodedc/ui-react';
import {createMaterial,changeField,defaultScene,maxSceneMaterials,textureBytes,type MaterialSpec} from '../../../core/roverScene/sceneDocument';
import {DragDropRoot,DropZone,EditorDockLayout,GlassSurface,Icon,IconButton,LoadingRegion,StatusBadge,ToastStack,type EditorDockTool} from '@nodedc/ui-react';
import {createMaterial,changeField,maxSceneMaterials,textureBytes,type MaterialSpec} from '../../../core/roverScene/sceneDocument';
import {assignObjectMaterial,findSceneObject,objectTargets,type SceneObject} from '../../../core/roverScene/sceneObjects';
import {useSceneDocument} from '../../../core/roverScene/useSceneDocument';
import PlayCanvasViewer,{type PlayCanvasViewerProps} from '../playcanvas/PlayCanvasViewer';
@@ -18,7 +19,7 @@ import './sceneEditor.css';
export default function RoverScene({vehicleID,...props}:{vehicleID:string;editing:boolean;onModelState:(state:'loading'|'ready'|'error')=>void}){
const scene=useSceneDocument(vehicleID);return <SceneEditor {...props} scene={scene}/>;
}
export function SceneEditor({scene,editing,onModelState,modelUrl=roverModelURL,defaults=defaultScene,onSceneReady,minFitDistance,chargeState}:{scene:ReturnType<typeof useSceneDocument>;editing:boolean;onModelState:NonNullable<PlayCanvasViewerProps['onModelState']>;modelUrl?:string;defaults?:typeof defaultScene;onSceneReady?:PlayCanvasViewerProps['onSceneReady'];minFitDistance?:number;chargeState?:ChargeState}){
export function SceneEditor({scene,editing,onModelState,modelUrl=roverModelURL,onSceneReady,minFitDistance,chargeState}:{scene:ReturnType<typeof useSceneDocument>;editing:boolean;onModelState:NonNullable<PlayCanvasViewerProps['onModelState']>;modelUrl?:string;onSceneReady?:PlayCanvasViewerProps['onSceneReady'];minFitDistance?:number;chargeState?:ChargeState}){
useSceneUndo(scene,editing);
const layout=scene.document.editorLayout;
const docking=editorDockLayout(layout),tileSize=layout?.materialTileSize??materialTileSizes.default;
@@ -51,7 +52,7 @@ export function SceneEditor({scene,editing,onModelState,modelUrl=roverModelURL,d
{id:'environment',title:'Окружение сцены',label:'Окружение сцены',open:environment,onClose:()=>setEnvironment(false),content:<EnvironmentInspector update={scene.update} sceneFiles={<SceneFileActions onImport={scene.importDocument} onExport={scene.exportDocument}/>} onError={scene.setError} document={scene.document} onChange={(key,value)=>scene.update(doc=>changeField(doc,key,value))} onResetCamera={()=>setCameraReset(v=>v+1)}/>},
{id:'material',title:material?.name||'Материал',label:'Материал',activationKey:`${selectionVersion}:${selected}`,subtitle:node?`Назначить: ${node.name}`:'Выберите объект в дереве',open:materialOpen&&!!material,onClose:()=>setMaterialOpen(false),
actions:<IconButton label="Назначить материал выбранному объекту" disabled={!selected||!targets.length} onClick={()=>selected&&scene.update(doc=>assignObjectMaterial(doc,targets,selected))}><Icon name="chevron-right"/></IconButton>,
content:material&&selected?<><Description>{node?`Выбран объект: ${node.name}${targets.length>1?` · деталей: ${targets.length}`:''}`:'Выберите деталь в дереве объектов. Назначение доступно стрелкой рядом с крестиком.'}</Description><MaterialInspector key={selected} preview={materialPreview} onPreview={setMaterialPreview} material={material} onChange={patch=>patchMaterial(selected,patch)} onReset={()=>{const base=defaults().materials[selected]??createMaterial(defaults(),selected).materials[selected];if(base)patchMaterial(selected,{...base,name:material.name});}} onError={scene.setError}/></>:null}
content:material&&selected?<MaterialInspector key={selected} selectionDescription={node?`Выбран объект: ${node.name}${targets.length>1?` · деталей: ${targets.length}`:''}`:'Выберите деталь в дереве объектов. Назначение доступно стрелкой рядом с крестиком.'} copyName={materialCopyName(scene.document,selected)} onDuplicate={name=>{const id=`custom/${crypto.randomUUID()}`,next=duplicateMaterial(scene.document,selected,id,name);scene.update(()=>next);setPalette(true);setSelectionVersion(v=>v+1);pick(id);}} preview={materialPreview} onPreview={setMaterialPreview} material={material} onChange={patch=>patchMaterial(selected,patch)} onError={scene.setError}/>:null}
];
return <DragDropRoot renderOverlay={({data})=>{const m=scene.document.materials[String(data?.materialId)];return m?<GlassSurface padding="sm"><MaterialTile material={m}/></GlassSurface>:null;}} onDragEnd={({activeData,pointer})=>{
const id=String(activeData?.materialId??'');if(!editing||!pointer||!Object.hasOwn(scene.document.materials,id))return;
@@ -1,10 +1,10 @@
import {defaultGlassMaterial,type GlassMaterialSettings} from '@nodedc/ui-core';
export type CellMarkingAppearance={color:string;size:number};
export type BatteryPanelAppearance={height:number;radius:number;labelSize:number;valueSize:number;textColor:string;glass:GlassMaterialSettings};
export type BatteryIndicatorAppearance={width:number;height:number;radius:number;mode:'ranges'|'mono';color:string;lowColor:string;middleColor:string;highColor:string;lowUntil:number;middleUntil:number};
export type BatteryIndicatorAppearance={offset:number;width:number;height:number;radius:number;mode:'ranges'|'mono';color:string;lowColor:string;middleColor:string;highColor:string;lowUntil:number;middleUntil:number};
export type BatteryAppearance={schema:'missioncore.battery-ui/v1';markings:CellMarkingAppearance;panels:BatteryPanelAppearance;indicator:BatteryIndicatorAppearance};
export const batteryAppearanceKey=(id:string)=>`missioncore.battery-ui/v1:${id}`;
export function defaultBatteryAppearance():BatteryAppearance{return {schema:'missioncore.battery-ui/v1',markings:{color:'#ffffff',size:100},indicator:{width:115,height:46,radius:23,mode:'ranges',color:'#f1f1ef',lowColor:'#ff7474',middleColor:'#ffd166',highColor:'#b5ff5a',lowUntil:15,middleUntil:30},panels:{height:76,radius:24,labelSize:12,valueSize:18,textColor:'#f1f1ef',glass:{...defaultGlassMaterial,tintOpacity:52,blur:18}}};}
export function defaultBatteryAppearance():BatteryAppearance{return {schema:'missioncore.battery-ui/v1',markings:{color:'#ffffff',size:100},indicator:{offset:0,width:115,height:46,radius:23,mode:'ranges',color:'#f1f1ef',lowColor:'#ff7474',middleColor:'#ffd166',highColor:'#b5ff5a',lowUntil:15,middleUntil:30},panels:{height:76,radius:24,labelSize:12,valueSize:18,textColor:'#f1f1ef',glass:{...defaultGlassMaterial,tintOpacity:52,blur:18}}};}
const object=(v:unknown):Record<string,unknown>=>v!==null&&typeof v==='object'?v as Record<string,unknown>:{};
const number=(v:unknown,fallback:number,min:number,max:number)=>typeof v==='number'&&Number.isFinite(v)?Math.min(max,Math.max(min,v)):fallback;
const color=(v:unknown,fallback:string)=>typeof v==='string'&&/^#[0-9a-f]{6}$/i.test(v)?v.toLowerCase():fallback;
@@ -12,7 +12,7 @@ export function parseBatteryAppearance(raw:unknown):BatteryAppearance{
const source=object(raw);if(source.schema!=='missioncore.battery-ui/v1')throw new Error('Это не профиль интерфейса батареи.');
const d=defaultBatteryAppearance(),m=object(source.markings),p=object(source.panels),g=object(p.glass),i=object(source.indicator);
const lowUntil=number(i.lowUntil,15,0,99),middleUntil=number(i.middleUntil,30,lowUntil+1,100);
return {schema:d.schema,indicator:{width:number(i.width,115,64,320),height:number(i.height,46,24,96),radius:number(i.radius,23,0,48),mode:i.mode==='mono'?'mono':'ranges',color:color(i.color,d.indicator.color),lowColor:color(i.lowColor,d.indicator.lowColor),middleColor:color(i.middleColor,d.indicator.middleColor),highColor:color(i.highColor,d.indicator.highColor),lowUntil,middleUntil},markings:{color:color(m.color,d.markings.color),size:number(m.size,100,50,160)},panels:{height:number(p.height,76,56,160),radius:number(p.radius,24,0,48),labelSize:number(p.labelSize,12,10,20),valueSize:number(p.valueSize,18,12,30),textColor:color(p.textColor,d.panels.textColor),glass:{...d.panels.glass,tintHex:color(g.tintHex,d.panels.glass.tintHex),tintOpacity:number(g.tintOpacity,52,0,100),blur:number(g.blur,18,0,60)}}};
return {schema:d.schema,indicator:{offset:number(i.offset,0,0,320),width:number(i.width,115,32,320),height:number(i.height,46,12,96),radius:number(i.radius,23,0,48),mode:i.mode==='mono'?'mono':'ranges',color:color(i.color,d.indicator.color),lowColor:color(i.lowColor,d.indicator.lowColor),middleColor:color(i.middleColor,d.indicator.middleColor),highColor:color(i.highColor,d.indicator.highColor),lowUntil,middleUntil},markings:{color:color(m.color,d.markings.color),size:number(m.size,100,50,160)},panels:{height:number(p.height,76,56,160),radius:number(p.radius,24,0,48),labelSize:number(p.labelSize,12,10,20),valueSize:number(p.valueSize,18,12,30),textColor:color(p.textColor,d.panels.textColor),glass:{...d.panels.glass,tintHex:color(g.tintHex,d.panels.glass.tintHex),tintOpacity:number(g.tintOpacity,52,0,100),blur:number(g.blur,18,0,60)}}};
}
export function batteryIndicatorColor(value:BatteryIndicatorAppearance,soc:number|null):string|undefined{
@@ -0,0 +1,14 @@
import {maxSceneMaterials,textureBytes,type SceneDocument} from './sceneDocument';
export function materialCopyName(doc:SceneDocument,id:string):string{
const base=doc.materials[id]?.name??'Материал',used=new Set(Object.values(doc.materials).map(m=>m.name));
for(let n=1;;n++){const suffix=` · копия${n===1?'':` ${n}`}`,name=base.slice(0,120-suffix.length)+suffix;if(!used.has(name))return name;}
}
export function duplicateMaterial(doc:SceneDocument,sourceId:string,id:string,name:string):SceneDocument{
const source=doc.materials[sourceId];if(!source)throw new Error('Исходный материал больше не существует.');
if(!/^custom\/[a-zA-Z0-9-]{1,80}$/.test(id)||Object.hasOwn(doc.materials,id))throw new Error('Не удалось создать идентификатор копии.');
if(!name.trim()||name.trim().length>120)throw new Error('Введите название длиной до 120 символов.');
if(Object.keys(doc.materials).length>=maxSceneMaterials)throw new Error(`В сцене может быть не больше ${maxSceneMaterials} материалов.`);
const next={...doc,materials:{...doc.materials,[id]:{...structuredClone(source),name:name.trim()}}};
if(textureBytes(next)>28_000_000)throw new Error('Копия превышает общий объём текстур сцены — 20 МБ.');
return next;
}
@@ -19,7 +19,7 @@ export function ObservationBattery({devices,transport,contributions,enabled,vehi
const Detail=device?sensorContribution(contributions,device)?.Detail:null;
const close=()=>{setOpen(false);setFullscreen(false);setError('');};
const choose=()=>{if(batteries.length===1)setSelected(batteries[0].id);setOpen(true);};
return <><BatteryIndicator appearance={appearance.indicator} soc={soc} label={device?`Аккумулятор · ${device.name}`:'Аккумуляторы аппарата'} title={device?`${device.name} · ${state?.fresh?'Данные поступают':soc!==null?'Последние показания':'Нет свежих данных'}`:'Выбрать аккумулятор'} valueText={device?`${number(soc,0)} %`:`АКБ · ${batteries.length}`} freshness={state?.fresh?'live':soc!==null?'stale':'unknown'} levelTone={soc!==null&&soc<15?'danger':soc!==null&&soc<30?'warning':'success'} disabled={!batteries.length} onClick={choose}/>
return <><BatteryIndicator style={{marginInlineEnd:appearance.indicator.offset}} appearance={appearance.indicator} soc={soc} label={device?`Аккумулятор · ${device.name}`:'Аккумуляторы аппарата'} title={device?`${device.name} · ${state?.fresh?'Данные поступают':soc!==null?'Последние показания':'Нет свежих данных'}`:'Выбрать аккумулятор'} valueText={device?`${number(soc,0)} %`:`АКБ · ${batteries.length}`} freshness={state?.fresh?'live':soc!==null?'stale':'unknown'} levelTone={soc!==null&&soc<15?'danger':soc!==null&&soc<30?'warning':'success'} disabled={!batteries.length} onClick={choose}/>
<Window open={open} title={`${name} / ${device?.name??'Аккумуляторы'}`} subtitle="Аккумулятор" onClose={close} size="lg" allowFloating={false} closeOnBackdrop={false}
className="observation-battery-window" style={{width:fullscreen?'calc(100vw - 2 * var(--nodedc-space-4))':'min(1440px, calc(100vw - 2 * var(--nodedc-space-6)))',maxWidth:'none',height:fullscreen?'calc(100dvh - 2 * var(--nodedc-space-4))':'calc(100dvh - 2 * var(--nodedc-space-6))',maxHeight:'none'}}
headerActions={<><IconButton label="Вернуться в обсерваторию" onClick={close}><Icon name="chevron-left"/></IconButton><span ref={setActions} className="observation-actions"/></>}>
@@ -154,12 +154,12 @@ test('indicator design migrates old profiles and retains bounded independent col
});
test('indicator dimensions migrate without changing the old visual size and remain battery-local',()=>{
const old=defaultBatteryAppearance();delete old.indicator.width;delete old.indicator.height;delete old.indicator.radius;
const migrated=parseBatteryAppearance(old);assert.equal(migrated.indicator.width,115);assert.equal(migrated.indicator.height,46);assert.equal(migrated.indicator.radius,23);
Object.assign(migrated.indicator,{width:184,height:64,radius:8});assert.deepEqual(parseBatteryAppearance(JSON.parse(JSON.stringify(migrated))),migrated);
const old=defaultBatteryAppearance();delete old.indicator.width;delete old.indicator.height;delete old.indicator.radius;delete old.indicator.offset;
const migrated=parseBatteryAppearance(old);assert.equal(migrated.indicator.width,115);assert.equal(migrated.indicator.height,46);assert.equal(migrated.indicator.radius,23);assert.equal(migrated.indicator.offset,0);
Object.assign(migrated.indicator,{width:32,height:12,radius:8,offset:40});assert.deepEqual(parseBatteryAppearance(JSON.parse(JSON.stringify(migrated))),migrated);
assert.equal(defaultBatteryAppearance().indicator.width,115);
const bounded=parseBatteryAppearance({...migrated,indicator:{...migrated.indicator,width:-1,height:9999,radius:NaN}}).indicator;
assert.equal(bounded.width,64);assert.equal(bounded.height,96);assert.equal(bounded.radius,23);
const bounded=parseBatteryAppearance({...migrated,indicator:{...migrated.indicator,width:-1,height:9999,radius:NaN,offset:9999}}).indicator;
assert.equal(bounded.width,32);assert.equal(bounded.offset,320);assert.equal(bounded.height,96);assert.equal(bounded.radius,23);
});
test('legacy ignored white emission never bleaches the gradient after migration; new emission stays editable',()=>{
@@ -0,0 +1,35 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {build} from 'esbuild';
const load=async path=>{const result=await build({entryPoints:[new URL(path,import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm'});return import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64'));};
const {duplicateMaterial,materialCopyName}=await load('../src/core/roverScene/materialActions.ts');
const {defaultBatteryScene}=await load('../src/core/batteryScene/profile.ts');
const {parseScene,maxSceneMaterials}=await load('../src/core/roverScene/sceneDocument.ts');
const {SceneHistory}=await load('../src/core/roverScene/sceneHistory.ts');
test('material duplication preserves both full surfaces and textures independently, without assigning it',()=>{
const doc=defaultBatteryScene(),source=doc.materials['bms/cells'];
source.textures.diffuse={name:'Base',data:'data:image/png;base64,aGVsbG8='};
source.chargeGradient.inactive.textures.emissive={name:'Emission',data:'data:image/png;base64,aGVsbG8='};
source.chargeGradient.inactive.roughness=.123;
const copy=duplicateMaterial(doc,'bms/cells','custom/copy',' Копия ');
assert.equal(copy.materials['custom/copy'].name,'Копия');
assert.deepEqual(copy.materials['custom/copy'],{...source,name:'Копия'});
assert.deepEqual(copy.assignments,doc.assignments);assert.deepEqual(copy.objectAssignments,doc.objectAssignments);
assert.deepEqual(parseScene(JSON.parse(JSON.stringify(copy)),defaultBatteryScene),copy);
copy.materials['custom/copy'].chargeGradient.inactive.roughness=.9;
copy.materials['custom/copy'].textures.diffuse.data='';
assert.equal(source.chargeGradient.inactive.roughness,.123);assert.ok(source.textures.diffuse.data);
const history=new SceneHistory(doc);history.update(copy);history.undo();assert.equal(history.present,doc);history.redo();assert.equal(history.present,copy);
});
test('duplicate names avoid existing suggestions and invalid copies cannot change the document',()=>{
const doc=defaultBatteryScene(),name=materialCopyName(doc,'bms/cells');
const next=duplicateMaterial(doc,'bms/cells','custom/copy',name);
assert.notEqual(materialCopyName(next,'bms/cells'),name);
const before=JSON.stringify(next);
for(const [source,id,label] of [['missing','custom/x','Name'],['bms/cells','custom/copy','Name'],['bms/cells','bad','Name'],['bms/cells','custom/x',' '],['bms/cells','custom/x','x'.repeat(121)]])assert.throws(()=>duplicateMaterial(next,source,id,label));
assert.equal(JSON.stringify(next),before);
const full=structuredClone(doc);for(let n=Object.keys(full.materials).length;n<maxSceneMaterials;n++)full.materials['custom/fill-'+n]=structuredClone(full.materials['bms/cells']);
assert.throws(()=>duplicateMaterial(full,'bms/cells','custom/overflow','Copy'),/материалов/);
const heavy=structuredClone(doc);heavy.materials['bms/cells'].chargeGradient.inactive.textures.diffuse={name:'A',data:'data:image/png;base64,'+'x'.repeat(7_000_001)};heavy.materials['bms/cells'].textures.emissive={name:'B',data:'data:image/png;base64,'+'x'.repeat(7_000_001)};
assert.throws(()=>duplicateMaterial(heavy,'bms/cells','custom/overflow','Copy'),/объём текстур/);
});
+12 -1
View File
@@ -110,7 +110,18 @@ async texture completion cannot apply a hidden mode's texture over the live mode
The battery Design form separates its target selector from the settings card
with the canonical 16 px gap. Observatory indicator geometry is per battery:
width 64–320 px, height 24–96 px, radius 0–48 px. Existing documents migrate to
width 32–320 px, height 12–96 px, radius 0–48 px; a separate 0–320 px offset
moves the indicator left of the header action group. Existing documents migrate to
115 × 46 px and radius 23 px, matching the previous pill. Live and preview use
the same BatteryIndicator adapter over the canonical LevelButton; changes are
immediate, persist in battery UI JSON and participate in its existing undo.
Material inspectors use the canonical Inspector header/footer and 12 px section
rhythm, including nested active/inactive materials. The reset-to-source action
is removed. “Дублировать материал” asks for a name in a standard Window and
creates an independent custom material with all textures and SOC surfaces.
It selects the copy in the palette without assigning it to an object; creation
is undoable and obeys the existing material-count and total texture limits.
LevelButton owns compact geometry: text and padding scale together below
64 × 24 px down to 32 × 12 px, including both contrasting fill text layers.