feat(scene-editor): share environment profiles and separate SOC material surfaces
This commit is contained in:
@@ -9,9 +9,8 @@ export function ChargeGradientInspector({value,onChange}:{value:ChargeGradient;o
|
||||
<RangeControl label="Сила свечения градиента" value={value.intensity} min={0} max={10} step={.05} exactValueBounds={{min:0,max:10}} onChange={intensity=>patch({intensity})}/>
|
||||
<RangeControl label="Скорость переливания" value={value.speed} min={0} max={3} step={.01} exactValueBounds={{min:0,max:3}} onChange={speed=>patch({speed})}/>
|
||||
<RangeControl label="Масштаб рисунка" value={value.scale} min={1} max={50} step={.1} exactValueBounds={{min:1,max:50}} onChange={scale=>patch({scale})}/>
|
||||
<Description>Материал без данных · используется, когда сохранённого заряда нет. Без свечения.</Description>
|
||||
<ControlRow label="Цвет без данных"><ColorField label="Цвет без данных" value={value.fallbackColor} onChange={fallbackColor=>patch({fallbackColor})}/></ControlRow>
|
||||
{([['fallbackMetalness','Металличность без данных'],['fallbackRoughness','Шероховатость без данных'],['fallbackReflectivity','Отражение без данных'],['fallbackOpacity','Непрозрачность без данных']] as const).map(([key,label])=><RangeControl key={key} label={label} value={value[key]} min={0} max={1} step={.01} exactValueBounds={{min:0,max:1}} onChange={v=>patch({[key]:v})}/>)}
|
||||
<RangeControl label="Контраст градиента" value={value.contrast} min={.1} max={4} step={.01} exactValueBounds={{min:.1,max:4}} onChange={contrast=>patch({contrast})}/>
|
||||
<RangeControl label="Насыщенность градиента" value={value.saturation} min={0} max={2} step={.01} exactValueBounds={{min:0,max:2}} onChange={saturation=>patch({saturation})}/>
|
||||
<Description>Ореол свечения настраивается в окружении → Bloom. При временном обрыве связи сохраняются последние цвет и яркость; движение возобновится с новыми показаниями.</Description>
|
||||
</div>;
|
||||
}
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import {EnvironmentProfiles} from './EnvironmentProfiles';
|
||||
import type {ReactNode} from 'react';
|
||||
import {LutField} from './LutField';
|
||||
import {useRef} from 'react';
|
||||
import {Button,ColorField,ControlRow,Inspector,InspectorSelectField,RangeControl,Switch,TextField} from '@nodedc/ui-react';
|
||||
import {environmentFields,fieldValue,fieldDisabled,type SceneDocument,type SceneField} from '../../../core/roverScene/sceneDocument';
|
||||
const labels:Record<string,string>={'Камера':'Камера',Lighting:'Освещение',Rendering:'Рендеринг',Grid:'Сетка',SSAO:'Контактное затенение · SSAO',Bloom:'Свечение · Bloom','Chromatic Aberration':'Хроматическая аберрация',TAA:'Временное сглаживание · TAA',Grading:'Цветокоррекция',LUT:'Цветовая таблица · LUT',Vignette:'Виньетка','Environment Atlas':'Карта окружения','Skybox':'Небо','Directional Light':'Направленный свет','Shadow Catcher':'Тень на поверхности'};
|
||||
export function EnvironmentInspector({document,onChange,onResetCamera,onError}:{document:SceneDocument;onChange:(key:string,value:unknown)=>void;onResetCamera:()=>void;onError:(error:string)=>void}){
|
||||
export function EnvironmentInspector({document,onChange,onResetCamera,onError,update,sceneFiles}:{document:SceneDocument;update:(fn:(doc:SceneDocument)=>SceneDocument)=>void;sceneFiles:ReactNode;onChange:(key:string,value:unknown)=>void;onResetCamera:()=>void;onError:(error:string)=>void}){
|
||||
const groups=[...new Set(environmentFields.map(f=>f.group))];
|
||||
return <Inspector defaultOpen={['Камера','PostProcess/Lighting']} sections={groups.map(group=>({id:group,label:labels[group.split('/').at(-1)!]??group,content:<div className="rover-scene-fields">{environmentFields.filter(f=>f.group===group).map(f=><EnvironmentField key={f.key} field={f} value={fieldValue(document,f.key)} disabled={fieldDisabled(document,f)} onChange={v=>onChange(f.key,v)} onResetCamera={onResetCamera} onError={onError}/>)}</div>}))}/>;
|
||||
return <Inspector defaultOpen={['profiles']} sections={[{id:'profiles',label:'Профили',content:<><EnvironmentProfiles document={document} update={update} onError={onError}/><Inspector sections={[{id:'scene-json',label:'Вся сцена · JSON',content:sceneFiles}]}/></>},...groups.map(group=>({id:group,label:labels[group.split('/').at(-1)!]??group,content:<div className="rover-scene-fields">{environmentFields.filter(f=>f.group===group).map(f=><EnvironmentField key={f.key} field={f} value={fieldValue(document,f.key)} disabled={fieldDisabled(document,f)} onChange={v=>onChange(f.key,v)} onResetCamera={onResetCamera} onError={onError}/>)}</div>}))]}/>;
|
||||
}
|
||||
function EnvironmentField({field:f,value,disabled,onChange,onResetCamera,onError}:{field:SceneField;value:unknown;disabled:boolean;onChange:(v:unknown)=>void;onResetCamera:()=>void;onError:(error:string)=>void}){
|
||||
if(f.type==='texture')return <LutField value={value as string|null} onChange={onChange} onError={onError}/>;
|
||||
@@ -17,7 +19,7 @@ function EnvironmentField({field:f,value,disabled,onChange,onResetCamera,onError
|
||||
if(f.type==='number')return <TextField type="number" label={f.label} min={f.min} max={f.max} step={f.step??.01} value={Number(value)} disabled={disabled} onChange={e=>onChange(Number(e.target.value))}/>;
|
||||
return <RangeControl label={f.label} value={Number(value)} min={f.min??0} max={f.max??100} step={f.step??.01} exactValueBounds={{min:f.min,max:f.max}} disabled={disabled} onChange={onChange}/>;
|
||||
}
|
||||
export function SceneFileActions({onImport,onExport,onReset}:{onImport:(file:File)=>void;onExport:()=>void;onReset:()=>void}){
|
||||
export function SceneFileActions({onImport,onExport}:{onImport:(file:File)=>void;onExport:()=>void}){
|
||||
const input=useRef<HTMLInputElement>(null);
|
||||
return <div className="rover-scene-actions"><Button size="compact" onClick={onExport}>Экспорт JSON</Button><Button size="compact" onClick={()=>input.current?.click()}>Импорт JSON</Button><Button size="compact" onClick={onReset}>Окружение NodeDC</Button><input ref={input} hidden type="file" accept=".json,application/json" onChange={e=>{const f=e.currentTarget.files?.[0];if(f)onImport(f);e.currentTarget.value='';}}/></div>;
|
||||
return <div className="rover-scene-actions"><Button size="compact" onClick={onExport}>Экспорт всей сцены</Button><Button size="compact" onClick={()=>input.current?.click()}>Импорт всей сцены</Button><input ref={input} hidden type="file" accept=".json,application/json" onChange={e=>{const f=e.currentTarget.files?.[0];if(f)onImport(f);e.currentTarget.value='';}}/></div>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import {useEffect,useRef,useState} from 'react';
|
||||
import {Button,Description,InspectorSelectField,TextField,Window,WindowFooterActions} from '@nodedc/ui-react';
|
||||
import {applyEnvironment,builtinEnvironment,environmentMatches,parseEnvironmentProfile,sceneEnvironment,type EnvironmentProfile,type StoredEnvironmentProfile} from '../../../core/roverScene/environmentProfiles';
|
||||
import {readEnvironmentProfiles,saveEnvironmentProfile,watchEnvironmentProfiles} from '../../../core/roverScene/environmentProfileStorage';
|
||||
import type {SceneDocument} from '../../../core/roverScene/sceneDocument';
|
||||
export function EnvironmentProfiles({document:doc,update,onError}:{document:SceneDocument;update:(fn:(doc:SceneDocument)=>SceneDocument)=>void;onError:(message:string)=>void}){
|
||||
const [profiles,setProfiles]=useState<StoredEnvironmentProfile[]>([]),[ready,setReady]=useState(false),[pending,setPending]=useState(false),[draft,setDraft]=useState<EnvironmentProfile|null>(null),[name,setName]=useState('');
|
||||
const input=useRef<HTMLInputElement>(null),mounted=useRef(true);
|
||||
useEffect(()=>{mounted.current=true;let generation=0;const refresh=()=>{const current=++generation;readEnvironmentProfiles().then(value=>{if(mounted.current&¤t===generation){setProfiles(value);setReady(true);}}).catch(e=>{if(mounted.current&¤t===generation)onError(e instanceof Error?e.message:'Не удалось прочитать профили.');});};refresh();const stop=watchEnvironmentProfiles(refresh);return()=>{mounted.current=false;stop();};},[onError]);
|
||||
const builtin=builtinEnvironment(),all=[builtin,...profiles],id=doc.environmentProfileId??(environmentMatches(doc,builtin.environment)?builtin.id:'current'),selected=all.find(p=>p.id===id);
|
||||
const dirty=!selected||!environmentMatches(doc,selected.environment);
|
||||
const current=():EnvironmentProfile=>({schema:'missioncore.environment-profile/v1',name:selected?.name??'Мой профиль',environment:sceneEnvironment(doc)});
|
||||
const begin=(value=current())=>{setDraft(value);setName(value.name==='NodeDC'?'Мой профиль':value.name);};
|
||||
const save=async(copy:boolean)=>{
|
||||
const source=copy?draft:current();if(!source||(!copy&&!selected))return;setPending(true);
|
||||
try{const saved=await saveEnvironmentProfile({...source,name:copy?name:source.name,id:copy?`env/${crypto.randomUUID()}`:selected!.id,revision:0},copy?null:selected!.revision);
|
||||
if(mounted.current){setProfiles(previous=>[...previous.filter(p=>p.id!==saved.id),saved]);if(copy){update(d=>applyEnvironment(d,saved));setDraft(null);}else update(d=>d.environmentProfileId===saved.id?d:{...d,environmentProfileId:saved.id});}
|
||||
}catch(e){onError(e instanceof Error?e.message:'Не удалось сохранить профиль.');}finally{if(mounted.current)setPending(false);}
|
||||
};
|
||||
const exportJson=()=>{const value=current(),url=URL.createObjectURL(new Blob([JSON.stringify(value,null,2)],{type:'application/json'}));const a=globalThis.document.createElement('a');a.href=url;a.download='environment-profile.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);};
|
||||
return <div className="rover-scene-fields">
|
||||
<InspectorSelectField label="Профиль окружения" value={id} disabled={!ready||pending} options={[...(!selected?[{value:id,label:'Текущие настройки · без сохранённого профиля'}]:[]),...all.map(p=>({value:p.id,label:p.name}))]} onChange={value=>{const profile=all.find(p=>p.id===value);if(profile)update(d=>applyEnvironment(d,profile));}}/>
|
||||
<Description>{dirty?'Есть изменения относительно профиля. Настройки сцены сохраняются автоматически.':'Настройки совпадают с профилем.'}</Description>
|
||||
<div className="rover-scene-actions"><Button size="compact" disabled={!ready||!selected||selected.id===builtin.id||pending||!dirty} loading={pending&&!draft} onClick={()=>void save(false)}>Пересохранить профиль</Button><Button size="compact" disabled={!ready||pending} onClick={()=>begin()}>Сохранить как…</Button></div>
|
||||
<div className="rover-scene-actions"><Button size="compact" onClick={exportJson}>Экспорт JSON</Button><Button size="compact" disabled={!ready||pending} onClick={()=>input.current?.click()}>Импорт JSON</Button></div>
|
||||
<Description>Библиотека общая для сцен на этом компьютере. Профиль переносит окружение и поведение камеры; ракурс, материалы и компоновка сцены сохраняются.</Description>
|
||||
<input ref={input} type="file" hidden accept=".json,application/json" onChange={async e=>{const f=e.currentTarget.files?.[0];e.currentTarget.value='';if(!f)return;try{if(f.size>2_000_000)throw new Error('Профиль больше 2 МБ.');const value=parseEnvironmentProfile(JSON.parse(await f.text()));if(mounted.current)begin(value);}catch(error){onError(error instanceof Error?error.message:'Не удалось импортировать профиль.');}}}/>
|
||||
<Window open={!!draft} onClose={()=>{if(!pending)setDraft(null);}} title="Сохранить профиль окружения" size="sm" footer={<WindowFooterActions><Button disabled={pending} onClick={()=>setDraft(null)}>Отмена</Button><Button variant="primary" loading={pending} disabled={!name.trim()} onClick={()=>void save(true)}>Сохранить</Button></WindowFooterActions>}>
|
||||
<TextField label="Название профиля" value={name} maxLength={80} disabled={pending} onChange={e=>setName(e.target.value)}/>
|
||||
<Description>Профиль будет доступен для батареи, ровера и других сцен.</Description>
|
||||
</Window>
|
||||
</div>;
|
||||
}
|
||||
@@ -1,19 +1,17 @@
|
||||
import {Description,Inspector,InspectorSelectField,TextField,Button} from '@nodedc/ui-react';
|
||||
import type {MaterialSpec} from '../../../core/roverScene/sceneDocument';
|
||||
import {ChargeGradientInspector} from './ChargeGradientInspector';
|
||||
import {useRef,useState} from 'react';
|
||||
import {Button,ColorField,ControlRow,Icon,IconButton,Inspector,RangeControl,Switch,TextField} from '@nodedc/ui-react';
|
||||
import {textureSlots,type TextureSlot,type MaterialSpec} from '../../../core/roverScene/sceneDocument';
|
||||
import {textureFromFile} from '../../../core/roverScene/sceneStorage';
|
||||
const slotLabels:Record<TextureSlot,string>={diffuse:'Базовый цвет',normal:'Нормали',roughness:'Шероховатость',metalness:'Металличность',opacity:'Прозрачность',emissive:'Свечение',ao:'Окклюзия · AO'};
|
||||
export function MaterialInspector({material,onChange,onReset,onError}:{material:MaterialSpec;onChange:(patch:Partial<MaterialSpec>)=>void;onReset:()=>void;onError:(message:string)=>void}){
|
||||
const range=(key:keyof MaterialSpec,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 <><TextField label="Название материала" value={material.name} maxLength={120} onChange={e=>onChange({name:e.target.value})}/><p className="rover-scene-note">Изменения применяются ко всем деталям с этим материалом.</p><Inspector defaultOpen={material.chargeGradient?['charge']:['surface']} sections={[
|
||||
...(material.chargeGradient?[{id:'charge',label:'Градиент заряда',content:<ChargeGradientInspector value={material.chargeGradient} onChange={chargeGradient=>onChange({chargeGradient})}/>}]:[]),
|
||||
{id:'surface',label:'Поверхность',content:<div className="rover-scene-fields">{!material.chargeGradient?.enabled&&<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>},
|
||||
]}/><Button onClick={onReset}>Исходный материал</Button></>;
|
||||
}
|
||||
function TextureField({slot,value,onChange,onError}:{slot:TextureSlot;value:MaterialSpec['textures'][TextureSlot];onChange:(value:MaterialSpec['textures'][TextureSlot])=>void;onError:(message:string)=>void}){
|
||||
const input=useRef<HTMLInputElement>(null),[pending,setPending]=useState(false);
|
||||
return <div className="rover-scene-texture"><ControlRow label={slotLabels[slot]} layout="stack"><div className="rover-scene-texture__row">{value&&<img src={value.data} alt=""/>}<Button size="compact" loading={pending} onClick={()=>input.current?.click()}>{value?.name??'Загрузить текстуру'}</Button>{value&&<IconButton label={`Удалить текстуру: ${slotLabels[slot]}`} onClick={()=>onChange(undefined)}><Icon name="trash"/></IconButton>}</div></ControlRow><input hidden ref={input} type="file" accept="image/png,image/jpeg,image/webp" onChange={async e=>{const file=e.currentTarget.files?.[0];e.currentTarget.value='';if(!file)return;setPending(true);try{onChange(await textureFromFile(file));}catch(error){onError(error instanceof Error?error.message:'Не удалось загрузить текстуру.');}finally{setPending(false);}}}/></div>;
|
||||
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={[
|
||||
{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></>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import {useRef,useState} 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}){
|
||||
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={[
|
||||
{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>},
|
||||
|
||||
]}/>;
|
||||
}
|
||||
function TextureField({slot,value,onChange,onError}:{slot:TextureSlot;value:MaterialSurface['textures'][TextureSlot];onChange:(value:MaterialSurface['textures'][TextureSlot])=>void;onError:(message:string)=>void}){
|
||||
const input=useRef<HTMLInputElement>(null),[pending,setPending]=useState(false);
|
||||
return <div className="rover-scene-texture"><ControlRow label={slotLabels[slot]} layout="stack"><div className="rover-scene-texture__row">{value&&<img src={value.data} alt=""/>}<Button size="compact" loading={pending} onClick={()=>input.current?.click()}>{value?.name??'Загрузить текстуру'}</Button>{value&&<IconButton label={`Удалить текстуру: ${slotLabels[slot]}`} onClick={()=>onChange(undefined)}><Icon name="trash"/></IconButton>}</div></ControlRow><input hidden ref={input} type="file" accept="image/png,image/jpeg,image/webp" onChange={async e=>{const file=e.currentTarget.files?.[0];e.currentTarget.value='';if(!file)return;setPending(true);try{onChange(await textureFromFile(file));}catch(error){onError(error instanceof Error?error.message:'Не удалось загрузить текстуру.');}finally{setPending(false);}}}/></div>;
|
||||
}
|
||||
@@ -8,7 +8,7 @@ import {useSceneDocument} from '../../../core/roverScene/useSceneDocument';
|
||||
import PlayCanvasViewer,{type PlayCanvasViewerProps} from '../playcanvas/PlayCanvasViewer';
|
||||
import type {ScenePicker,ScenePick} from '../playcanvas/useSceneMaterials';
|
||||
import {EnvironmentInspector,SceneFileActions} from './EnvironmentInspector';
|
||||
import {MaterialInspector} from './MaterialInspector';
|
||||
import {MaterialInspector,type MaterialPreview} from './MaterialInspector';
|
||||
import {MaterialPalette,MaterialPaletteActions,MaterialTile} from './MaterialPalette';
|
||||
import {SceneObjectTree} from './SceneObjectTree';
|
||||
import {useSceneUndo} from './useSceneUndo';
|
||||
@@ -22,6 +22,7 @@ export function SceneEditor({scene,editing,onModelState,modelUrl=roverModelURL,d
|
||||
useSceneUndo(scene,editing);
|
||||
const layout=scene.document.editorLayout;
|
||||
const docking=editorDockLayout(layout),tileSize=layout?.materialTileSize??materialTileSizes.default;
|
||||
const [materialPreview,setMaterialPreview]=useState<MaterialPreview>('auto');
|
||||
const [palette,setPalette]=useState(true),[environment,setEnvironment]=useState(false),[selected,setSelected]=useState<string|null>(null),[materialOpen,setMaterialOpen]=useState(false),[cameraReset,setCameraReset]=useState(0),[textureState,setTextureState]=useState<'loading'|'ready'|'error'>('ready');
|
||||
const [objectsOpen,setObjectsOpen]=useState(true),[root,setRoot]=useState<SceneObject|null>(null),[selectedObject,setSelectedObject]=useState<string|null>(null);
|
||||
const [selectionVersion,setSelectionVersion]=useState(0);
|
||||
@@ -33,7 +34,7 @@ export function SceneEditor({scene,editing,onModelState,modelUrl=roverModelURL,d
|
||||
const sceneReady=useCallback((api:Parameters<NonNullable<PlayCanvasViewerProps['onSceneReady']>>[0])=>{setSceneApi(api);onSceneReady?.(api);},[onSceneReady]);
|
||||
const modelState=useCallback((value:'loading'|'ready'|'error')=>{setModelPhase(value);onModelState(value);},[onModelState]);
|
||||
|
||||
const pick=useCallback((id:string)=>{setSelected(id);setMaterialOpen(true);setObjectsOpen(true);},[]);
|
||||
const pick=useCallback((id:string)=>{setMaterialPreview('auto');setSelected(id);setMaterialOpen(true);setObjectsOpen(true);},[]);
|
||||
const objectPick=useCallback((hit:ScenePick|null)=>{setSelectionVersion(v=>v+1);if(!hit){setSelectedObject(null);setSelected(null);setMaterialOpen(false);return;}setSelectedObject(hit.objectId);setPalette(true);pick(hit.materialId);},[pick]);
|
||||
const selectObject=(id:string)=>{setSelectionVersion(v=>v+1);setSelectedObject(id);const item=findSceneObject(root,id),source=item?.materialIds?.[0];const material=scene.document.objectAssignments?.[id]??(source?(scene.document.assignments[source]??source):null);if(material){setPalette(true);pick(material);}};
|
||||
const addMaterial=()=>{if(Object.keys(scene.document.materials).length>=maxSceneMaterials){scene.setError(`В сцене может быть не больше ${maxSceneMaterials} материалов.`);return;}const id=`custom/${crypto.randomUUID()}`;scene.update(doc=>createMaterial(doc,id));pick(id);};
|
||||
@@ -47,10 +48,10 @@ export function SceneEditor({scene,editing,onModelState,modelUrl=roverModelURL,d
|
||||
{id:'objects',title:'Объекты сцены',label:'Объекты сцены',open:objectsOpen,onClose:()=>setObjectsOpen(false),className:'scene-object-window',initialRect:{left:16,top:16,width:380,height:600},content:<SceneObjectTree revealVersion={selectionVersion} root={root} selected={selectedObject} visibility={scene.document.objectVisibility} legacyVisibility={scene.document.objects} onSelect={selectObject} onVisibility={(id,value)=>scene.update(doc=>({...doc,objectVisibility:{...doc.objectVisibility,[id]:value}}))}/>},
|
||||
{id:'palette',title:'Материалы сцены',label:'Материалы сцены',open:palette,onClose:()=>setPalette(false),className:'rover-material-palette',initialRect:{left:400,top:420,width:640,height:340},minimumSize:{width:280,height:180},
|
||||
actions:<MaterialPaletteActions tileSize={tileSize} onTileSize={size=>scene.update(doc=>({...doc,editorLayout:{windows:{},...doc.editorLayout,materialTileSize:size}}))}/>,content:<MaterialPalette tileSize={tileSize} revealVersion={selectionVersion} materials={scene.document.materials} selected={selected} pick={pick} add={addMaterial}/>},
|
||||
{id:'environment',title:'Окружение сцены',label:'Окружение сцены',open:environment,onClose:()=>setEnvironment(false),footer:<SceneFileActions onImport={scene.importDocument} onExport={scene.exportDocument} onReset={()=>scene.update(doc=>({...doc,postFx:defaults().postFx}))}/>,content:<EnvironmentInspector onError={scene.setError} document={scene.document} onChange={(key,value)=>scene.update(doc=>changeField(doc,key,value))} onResetCamera={()=>setCameraReset(v=>v+1)}/>},
|
||||
{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} 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?<><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}
|
||||
];
|
||||
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;
|
||||
@@ -61,7 +62,7 @@ export function SceneEditor({scene,editing,onModelState,modelUrl=roverModelURL,d
|
||||
}}>
|
||||
<EditorDockLayout value={docking} enabled={editing} tools={tools} onChange={next=>scene.update(doc=>({...doc,editorLayout:{windows:{},materialTileSize:materialTileSizes.default,...doc.editorLayout,docking:next}}))} primary={<>
|
||||
<DropZone id="scene-model" className="rover-scene-drop"><LoadingRegion className="rover-view__scene" loading={!scene.ready} label="Загрузка настроек сцены">
|
||||
{scene.ready&&<PlayCanvasViewer modelUrl={modelUrl} onSceneReady={sceneReady} onSceneGraph={sceneGraph} minFitDistance={minFitDistance} postFx={scene.document.postFx} cameraAutoRotate={scene.document.cameraAutoRotate} cameraZoomStrength={scene.document.cameraZoomStrength} cameraResetToken={cameraReset} cameraState={scene.document.camera} onCameraChange={scene.recordCamera} materials={scene.document.materials} assignments={scene.document.assignments} objectAssignments={scene.document.objectAssignments} objectVisibility={scene.document.objectVisibility} legacyObjectVisibility={scene.document.objects} editing={editing} chargeState={chargeState} onObjectPick={objectPick} onPickerReady={pickerReady} onModelState={modelState} onTextureState={setTextureState}/>}
|
||||
{scene.ready&&<PlayCanvasViewer modelUrl={modelUrl} onSceneReady={sceneReady} onSceneGraph={sceneGraph} minFitDistance={minFitDistance} postFx={scene.document.postFx} cameraAutoRotate={scene.document.cameraAutoRotate} cameraZoomStrength={scene.document.cameraZoomStrength} cameraResetToken={cameraReset} cameraState={scene.document.camera} onCameraChange={scene.recordCamera} materials={scene.document.materials} assignments={scene.document.assignments} objectAssignments={scene.document.objectAssignments} objectVisibility={scene.document.objectVisibility} legacyObjectVisibility={scene.document.objects} editing={editing} chargeState={chargeState} materialPreview={editing&&materialOpen&&selected&&materialPreview!=='auto'?{id:selected,mode:materialPreview}:undefined} onObjectPick={objectPick} onPickerReady={pickerReady} onModelState={modelState} onTextureState={setTextureState}/>}
|
||||
</LoadingRegion></DropZone>
|
||||
{editing&&<>
|
||||
<div className="rover-scene-tools"><GlassSurface className="rover-scene-tools__surface nodedc-viewport-controls"><IconButton label="Отменить изменение · Ctrl/Cmd+Z" disabled={!scene.canUndo} onClick={scene.undo}><Icon name="undo"/></IconButton><IconButton label="Повторить изменение · Ctrl/Cmd+Shift+Z" disabled={!scene.canRedo} onClick={scene.redo}><Icon name="redo"/></IconButton><IconButton label="Материалы сцены" aria-pressed={palette} onClick={()=>{setPalette(v=>!v);setObjectsOpen(true);}}><Icon name="layers"/></IconButton><IconButton label="Окружение сцены" aria-pressed={environment} onClick={()=>setEnvironment(v=>!v)}><Icon name="globe"/></IconButton><IconButton label="Объекты сцены" aria-pressed={objectsOpen} onClick={()=>setObjectsOpen(v=>!v)}><Icon name="list"/></IconButton></GlassSurface></div>
|
||||
|
||||
@@ -882,7 +882,7 @@ function applyPostFx(
|
||||
export default function PlayCanvasViewer({
|
||||
minFitDistance = 1.8,
|
||||
modelUrl,
|
||||
materials, assignments, objectAssignments, objectVisibility, legacyObjectVisibility, editing, onObjectPick, onPickerReady, onTextureState, chargeState,
|
||||
materials, assignments, objectAssignments, objectVisibility, legacyObjectVisibility, editing, onObjectPick, onPickerReady, onTextureState, chargeState, materialPreview,
|
||||
postFx,
|
||||
viewportSize,
|
||||
onSceneReady,
|
||||
@@ -930,7 +930,7 @@ export default function PlayCanvasViewer({
|
||||
const [skyboxVersion, setSkyboxVersion] = useState(0)
|
||||
const [modelVersion, setModelVersion] = useState(0)
|
||||
|
||||
useSceneMaterials(appRef,cameraEntityRef,canvasRef,modelVersion,{materials,assignments,objectAssignments,objectVisibility,legacyObjectVisibility,editing,onObjectPick,onPickerReady,onTextureState,chargeState})
|
||||
useSceneMaterials(appRef,cameraEntityRef,canvasRef,modelVersion,{materials,assignments,objectAssignments,objectVisibility,legacyObjectVisibility,editing,onObjectPick,onPickerReady,onTextureState,chargeState,materialPreview})
|
||||
|
||||
const fx = useMemo(() => mergePostFxDefaults(postFx), [postFx])
|
||||
const lutError = useCallback(()=>onTextureState?.('error'),[onTextureState])
|
||||
|
||||
@@ -1,8 +1,15 @@
|
||||
import * as pc from 'playcanvas';
|
||||
import {chargePair,type ChargeGradient} from '../../../core/roverScene/chargeGradient';
|
||||
import type {MaterialSpec} from '../../../core/roverScene/sceneDocument';
|
||||
const surfaces=new WeakMap<pc.StandardMaterial,{known:boolean;spec:MaterialSpec;gradient:ChargeGradient}>();
|
||||
import type {MaterialSurface} from '../../../core/roverScene/materialSurface';
|
||||
import {applyMaterialSurface} from './materialSurface';
|
||||
const surfaces=new WeakMap<pc.StandardMaterial,{surface:MaterialSurface;gradient:ChargeGradient}>();
|
||||
export type ChargeState={soc:number|null;fresh:boolean};
|
||||
export type ChargePreview={id:string;mode:'active'|'inactive'};
|
||||
export function previewChargeState(state:ChargeState|undefined,preview?:ChargePreview):ChargeState|undefined{
|
||||
return preview?.mode==='inactive'?{soc:null,fresh:false}:preview?.mode==='active'?{soc:Number.isFinite(state?.soc)?state!.soc:50,fresh:true}:state;
|
||||
}
|
||||
export function chargeSurface(spec:MaterialSpec,state:ChargeState|undefined):MaterialSurface{return spec.chargeGradient&&!Number.isFinite(state?.soc)?spec.chargeGradient.inactive:spec;}
|
||||
const emission=`
|
||||
uniform vec3 chargeColorA;
|
||||
uniform vec3 chargeColorB;
|
||||
@@ -10,38 +17,42 @@ uniform float chargeTime;
|
||||
uniform float chargeScale;
|
||||
uniform float chargeIntensity;
|
||||
uniform float chargeSaturation;
|
||||
uniform float chargeContrast;
|
||||
uniform vec3 material_emissive;
|
||||
uniform float material_emissiveIntensity;
|
||||
void getEmission() {
|
||||
vec3 p=vPositionW*chargeScale;
|
||||
float wave=sin(p.x*0.77+sin(p.y*0.91+chargeTime)*1.2+chargeTime*0.43);
|
||||
wave+=sin(p.z*0.71-p.y*0.48+sin(p.x*0.57-chargeTime*0.61));
|
||||
float blend=smoothstep(-1.6,1.6,wave);
|
||||
float blend=clamp((smoothstep(-1.6,1.6,wave)-0.5)*chargeContrast+0.5,0.0,1.0);
|
||||
vec3 color=mix(chargeColorA,chargeColorB,blend);
|
||||
color=mix(vec3(dot(color,vec3(0.2126,0.7152,0.0722))),color,chargeSaturation);
|
||||
dEmission=color*chargeIntensity;
|
||||
vec3 baseEmission=material_emissive*material_emissiveIntensity;
|
||||
#ifdef STD_EMISSIVE_TEXTURE
|
||||
baseEmission *= {STD_EMISSIVE_TEXTURE_DECODE}(texture2DBias({STD_EMISSIVE_TEXTURE_NAME}, {STD_EMISSIVE_TEXTURE_UV}, textureBias)).{STD_EMISSIVE_TEXTURE_CHANNEL};
|
||||
#endif
|
||||
#ifdef STD_EMISSIVE_VERTEX
|
||||
baseEmission *= saturate(vVertexColor.{STD_EMISSIVE_VERTEX_CHANNEL});
|
||||
#endif
|
||||
dEmission=baseEmission+max(color,vec3(0.0))*chargeIntensity;
|
||||
}`;
|
||||
export function configureChargeMaterial(material:pc.StandardMaterial,gradient?:ChargeGradient){
|
||||
const chunks=material.getShaderChunks(pc.SHADERLANGUAGE_GLSL);
|
||||
if(gradient?.enabled){chunks.set('emissivePS',emission);material.emissive.set(1,1,1);material.emissiveIntensity=1;material.diffuse.set(.02,.02,.02);}
|
||||
else chunks.delete('emissivePS');
|
||||
if(gradient)chunks.set('emissivePS',emission);else chunks.delete('emissivePS');
|
||||
surfaces.delete(material);
|
||||
}
|
||||
export function updateChargeMaterial(material:pc.StandardMaterial,gradient:ChargeGradient,state:ChargeState|undefined,time:number,spec:MaterialSpec){
|
||||
const known=typeof state?.soc==='number'&&Number.isFinite(state.soc);
|
||||
export function updateChargeMaterial(material:pc.StandardMaterial,gradient:ChargeGradient,state:ChargeState|undefined,time:number,spec:MaterialSpec,bindTextures?:(surface:MaterialSurface)=>void){
|
||||
const known=typeof state?.soc==='number'&&Number.isFinite(state.soc),surface=known?spec:gradient.inactive;
|
||||
const applied=surfaces.get(material);
|
||||
if(!applied||applied.known!==known||applied.spec!==spec||applied.gradient!==gradient){
|
||||
if(known)material.diffuse.set(.02,.02,.02);else material.diffuse.fromString(gradient.fallbackColor);
|
||||
material.metalness=known?spec.metalness:gradient.fallbackMetalness;
|
||||
material.gloss=known?spec.roughness:gradient.fallbackRoughness;
|
||||
material.specularityFactor=known?spec.reflectivity:gradient.fallbackReflectivity;
|
||||
material.opacity=known?spec.opacity:gradient.fallbackOpacity;
|
||||
material.blendType=material.opacity<1||spec.textures.opacity?pc.BLEND_NORMAL:pc.BLEND_NONE;
|
||||
material.depthWrite=material.blendType===pc.BLEND_NONE;
|
||||
material.update();surfaces.set(material,{known,spec,gradient});
|
||||
if(!applied||applied.surface!==surface||applied.gradient!==gradient){
|
||||
applyMaterialSurface(material,surface);bindTextures?.(surface);material.update();surfaces.set(material,{surface,gradient});
|
||||
}
|
||||
const colors=known?chargePair(gradient,state!.soc):[[0,0,0],[0,0,0]];
|
||||
material.setParameter('chargeColorA',colors[0].map(value=>value**2.2));
|
||||
material.setParameter('chargeColorB',colors[1].map(value=>value**2.2));
|
||||
material.setParameter('chargeTime',time*gradient.speed);
|
||||
material.setParameter('chargeScale',gradient.scale);
|
||||
material.setParameter('chargeIntensity',known?gradient.intensity:0);
|
||||
material.setParameter('chargeSaturation',known?1:0);
|
||||
material.setParameter('chargeIntensity',known&&gradient.enabled?gradient.intensity:0);
|
||||
material.setParameter('chargeSaturation',gradient.saturation);
|
||||
material.setParameter('chargeContrast',gradient.contrast);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import * as pc from 'playcanvas';
|
||||
import type {MaterialSurface,TextureSlot} from '../../../core/roverScene/materialSurface';
|
||||
export const surfaceMaps:Record<TextureSlot,string>={diffuse:'diffuseMap',normal:'normalMap',metalness:'metalnessMap',roughness:'glossMap',opacity:'opacityMap',emissive:'emissiveMap',ao:'aoMap'};
|
||||
export function applyMaterialSurface(m:pc.StandardMaterial,spec:MaterialSurface){
|
||||
m.diffuse.fromString(spec.color);m.useMetalness=true;m.metalness=spec.metalness;
|
||||
m.glossInvert=true;m.gloss=spec.roughness;m.opacity=spec.opacity;
|
||||
m.specularityFactor=spec.reflectivity;m.clearCoat=spec.clearCoat;
|
||||
m.clearCoatGlossInvert=true;m.clearCoatGloss=spec.clearCoatRoughness;
|
||||
m.emissive.fromString(spec.emissive);m.emissiveIntensity=spec.emissiveIntensity;
|
||||
m.bumpiness=spec.normalStrength;m.cull=spec.doubleSided?pc.CULLFACE_NONE:pc.CULLFACE_BACK;
|
||||
m.blendType=spec.opacity<1||spec.textures.opacity?pc.BLEND_NORMAL:pc.BLEND_NONE;
|
||||
m.depthWrite=m.blendType===pc.BLEND_NONE;
|
||||
}
|
||||
@@ -1,14 +1,16 @@
|
||||
import {useEffect,useRef,type RefObject} from 'react';
|
||||
import * as pc from 'playcanvas';
|
||||
import {configureChargeMaterial,updateChargeMaterial,type ChargeState} from './chargeMaterial';
|
||||
import {configureChargeMaterial,updateChargeMaterial,chargeSurface,previewChargeState,type ChargePreview,type ChargeState} from './chargeMaterial';
|
||||
import {sceneObjectId} from './sceneTree';
|
||||
export type ScenePick={objectId:string;materialId:string};
|
||||
export type ScenePicker={pick:(x:number,y:number)=>ScenePick|null};
|
||||
import type {MaterialSpec,TextureSlot} from '../../../core/roverScene/sceneDocument';
|
||||
export type SceneMaterialsProps={materials?:Record<string,MaterialSpec>;assignments?:Record<string,string>;objectAssignments?:Record<string,string>;objectVisibility?:Record<string,boolean>;legacyObjectVisibility?:Record<string,boolean>;editing?:boolean;onObjectPick?:(hit:ScenePick|null)=>void;chargeState?:ChargeState;onPickerReady?:(picker:ScenePicker|null)=>void;onTextureState?:(state:'loading'|'ready'|'error')=>void};
|
||||
const maps:Record<TextureSlot,string>={diffuse:'diffuseMap',normal:'normalMap',metalness:'metalnessMap',roughness:'glossMap',opacity:'opacityMap',emissive:'emissiveMap',ao:'aoMap'};
|
||||
export function useSceneMaterials(appRef:RefObject<pc.Application|null>,cameraRef:RefObject<pc.Entity|null>,canvasRef:RefObject<HTMLCanvasElement|null>,modelVersion:number,{materials,assignments,objectAssignments,objectVisibility,legacyObjectVisibility,editing,onObjectPick,onPickerReady,onTextureState,chargeState}:SceneMaterialsProps){
|
||||
const latest=useRef({materials,onObjectPick,onTextureState,chargeState});latest.current={materials,onObjectPick,onTextureState,chargeState};
|
||||
import type {MaterialSpec} from '../../../core/roverScene/sceneDocument';
|
||||
import type {MaterialSurface,TextureSlot} from '../../../core/roverScene/materialSurface';
|
||||
import {applyMaterialSurface,surfaceMaps as maps} from './materialSurface';
|
||||
export type SceneMaterialsProps={materials?:Record<string,MaterialSpec>;assignments?:Record<string,string>;objectAssignments?:Record<string,string>;objectVisibility?:Record<string,boolean>;legacyObjectVisibility?:Record<string,boolean>;editing?:boolean;onObjectPick?:(hit:ScenePick|null)=>void;chargeState?:ChargeState;materialPreview?:ChargePreview;onPickerReady?:(picker:ScenePicker|null)=>void;onTextureState?:(state:'loading'|'ready'|'error')=>void};
|
||||
export function useSceneMaterials(appRef:RefObject<pc.Application|null>,cameraRef:RefObject<pc.Entity|null>,canvasRef:RefObject<HTMLCanvasElement|null>,modelVersion:number,{materials,assignments,objectAssignments,objectVisibility,legacyObjectVisibility,editing,onObjectPick,onPickerReady,onTextureState,chargeState,materialPreview}:SceneMaterialsProps){
|
||||
const latest=useRef({materials,onObjectPick,onTextureState,chargeState,materialPreview});latest.current={materials,onObjectPick,onTextureState,chargeState,materialPreview};
|
||||
const bindings=useRef(new Map<string,(surface:MaterialSurface)=>void>());
|
||||
const animated=useRef(new Map<string,pc.StandardMaterial>());
|
||||
const textures=useRef(new Map<string,{texture?:pc.Texture;promise:Promise<pc.Texture>}>());
|
||||
const generation=useRef(0);
|
||||
@@ -32,40 +34,36 @@ export function useSceneMaterials(appRef:RefObject<pc.Application|null>,cameraRe
|
||||
const source=originalGroups.current.get(mi);if(source)mi.material=map.get(objectAssignments?.[sceneObjectId(mi.node)]??assignments?.[source.id]??source.id)??source.material;
|
||||
}
|
||||
for(const [id,m] of customMaterials.current)if(!Object.hasOwn(materials,id)){m.destroy();customMaterials.current.delete(id);}
|
||||
const applyTexture=(m:pc.StandardMaterial,slot:TextureSlot,texture:pc.Texture|null,spec:MaterialSpec)=>{
|
||||
const applyTexture=(m:pc.StandardMaterial,slot:TextureSlot,texture:pc.Texture|null,spec:MaterialSurface)=>{
|
||||
(m as any)[maps[slot]]=texture;
|
||||
const prefix=maps[slot];(m as any)[prefix+'Tiling']=new pc.Vec2(spec.tiling,spec.tiling);
|
||||
if(['metalness','roughness','opacity','ao'].includes(slot))(m as any)[prefix+'Channel']='r';
|
||||
m.update();
|
||||
};
|
||||
const used=new Set<string>();animated.current.clear();
|
||||
const used=new Set<string>();animated.current.clear();bindings.current.clear();
|
||||
for(const [id,spec] of Object.entries(materials)){
|
||||
const m=map.get(id);if(!m)continue;
|
||||
m.diffuse.fromString(spec.color);m.useMetalness=true;m.metalness=spec.metalness;
|
||||
m.glossInvert=true;m.gloss=spec.roughness;m.opacity=spec.opacity;
|
||||
// Specular factor is independent from the donor's global IBL multiplier.
|
||||
m.specularityFactor=spec.reflectivity;m.clearCoat=spec.clearCoat;
|
||||
m.clearCoatGlossInvert=true;m.clearCoatGloss=spec.clearCoatRoughness;
|
||||
m.emissive.fromString(spec.emissive);m.emissiveIntensity=spec.emissiveIntensity;
|
||||
m.bumpiness=spec.normalStrength;m.cull=spec.doubleSided?pc.CULLFACE_NONE:pc.CULLFACE_BACK;
|
||||
m.blendType=spec.opacity<1||spec.textures.opacity?pc.BLEND_NORMAL:pc.BLEND_NONE;
|
||||
m.depthWrite=m.blendType===pc.BLEND_NONE;
|
||||
const state=()=>previewChargeState(latest.current.chargeState,latest.current.materialPreview?.id===id?latest.current.materialPreview:undefined);
|
||||
const selectedSurface=()=>chargeSurface(spec,state());
|
||||
const bind=(surface:MaterialSurface)=>{for(const slot of Object.keys(maps) as TextureSlot[]){const data=surface.textures[slot]?.data;applyTexture(m,slot,data?textures.current.get(`${slot==='diffuse'||slot==='emissive'}:${data}`)?.texture??null:null,surface);}};
|
||||
bindings.current.set(id,bind);
|
||||
for(const surface of [spec,...(spec.chargeGradient?[spec.chargeGradient.inactive]:[])]){
|
||||
for(const slot of Object.keys(maps) as TextureSlot[]){
|
||||
const data=spec.textures[slot]?.data;if(!data){applyTexture(m,slot,null,spec);continue;}
|
||||
const data=surface.textures[slot]?.data;if(!data)continue;
|
||||
const srgb=slot==='diffuse'||slot==='emissive';const key=`${srgb}:${data}`;used.add(key);
|
||||
let item=textures.current.get(key);
|
||||
if(!item){
|
||||
const promise=new Promise<pc.Texture>((resolve,reject)=>{const img=new Image();img.onload=()=>{if(generation.current<0){reject(new Error('Scene disposed'));return;}const tex=new pc.Texture(app.graphicsDevice,{name:spec.textures[slot]?.name,format:srgb?pc.PIXELFORMAT_SRGBA8:pc.PIXELFORMAT_RGBA8,mipmaps:true,addressU:pc.ADDRESS_REPEAT,addressV:pc.ADDRESS_REPEAT});tex.setSource(img);resolve(tex);};img.onerror=()=>reject(new Error('Texture decode failed'));img.src=data;});
|
||||
const promise=new Promise<pc.Texture>((resolve,reject)=>{const img=new Image();img.onload=()=>{if(generation.current<0){reject(new Error('Scene disposed'));return;}const tex=new pc.Texture(app.graphicsDevice,{name:surface.textures[slot]?.name,format:srgb?pc.PIXELFORMAT_SRGBA8:pc.PIXELFORMAT_RGBA8,mipmaps:true,addressU:pc.ADDRESS_REPEAT,addressV:pc.ADDRESS_REPEAT});tex.setSource(img);resolve(tex);};img.onerror=()=>reject(new Error('Texture decode failed'));img.src=data;});
|
||||
item={promise};textures.current.set(key,item);const cached=item;
|
||||
promise.then(tex=>{cached.texture=tex;if(textures.current.get(key)!==cached){tex.destroy();}}).catch(()=>{if(textures.current.get(key)===cached)textures.current.delete(key);});
|
||||
}
|
||||
if(item.texture)applyTexture(m,slot,item.texture,spec);
|
||||
else{
|
||||
pending++;item.promise.then(tex=>{if(generation.current===current)applyTexture(m,slot,tex,spec);}).catch(()=>{failed=true;}).finally(()=>{pending--;if(generation.current===current&&!pending)latest.current.onTextureState?.(failed?'error':'ready');});
|
||||
if(!item.texture){
|
||||
pending++;item.promise.then(tex=>{if(generation.current===current&&selectedSurface()===surface)applyTexture(m,slot,tex,surface);}).catch(()=>{failed=true;}).finally(()=>{pending--;if(generation.current===current&&!pending)latest.current.onTextureState?.(failed?'error':'ready');});
|
||||
}
|
||||
}
|
||||
}
|
||||
configureChargeMaterial(m,spec.chargeGradient);
|
||||
if(spec.chargeGradient?.enabled){animated.current.set(id,m);updateChargeMaterial(m,spec.chargeGradient,latest.current.chargeState,0,spec);}
|
||||
if(spec.chargeGradient){animated.current.set(id,m);updateChargeMaterial(m,spec.chargeGradient,state(),0,spec,bind);}else{applyMaterialSurface(m,spec);bind(spec);}
|
||||
m.update();
|
||||
}
|
||||
for(const [key,item] of textures.current)if(!used.has(key)){item.texture?.destroy();textures.current.delete(key);}
|
||||
@@ -75,7 +73,7 @@ export function useSceneMaterials(appRef:RefObject<pc.Application|null>,cameraRe
|
||||
useEffect(()=>{
|
||||
const app=appRef.current;if(!app||!modelVersion)return;
|
||||
let time=0;const motion=window.matchMedia('(prefers-reduced-motion: reduce)');
|
||||
const update=(dt:number)=>{const live=latest.current;if(live.chargeState?.fresh&&!motion.matches)time+=Math.min(dt,.1);for(const [id,material] of animated.current){const gradient=live.materials?.[id]?.chargeGradient;if(gradient?.enabled)updateChargeMaterial(material,gradient,live.chargeState,time,live.materials![id]);}};
|
||||
const update=(dt:number)=>{const live=latest.current;if(live.chargeState?.fresh&&!motion.matches)time+=Math.min(dt,.1);for(const [id,material] of animated.current){const gradient=live.materials?.[id]?.chargeGradient;if(gradient)updateChargeMaterial(material,gradient,previewChargeState(live.chargeState,live.materialPreview?.id===id?live.materialPreview:undefined),time,live.materials![id],bindings.current.get(id));}};
|
||||
app.on('update',update);return()=>{app.off('update',update);};
|
||||
},[appRef,modelVersion]);
|
||||
useEffect(()=>()=>{generation.current=-1;for(const item of textures.current.values())item.texture?.destroy();textures.current.clear();for(const m of customMaterials.current.values())m.destroy();customMaterials.current.clear();},[]);
|
||||
|
||||
@@ -6,7 +6,7 @@ import type {SceneDocumentProfile} from '../roverScene/useSceneDocument';
|
||||
|
||||
export function defaultBatteryScene():SceneDocument {
|
||||
return {...defaultScene(),schema:'missioncore.battery-scene/v1',model:'catl-r04/v1',
|
||||
materials:{...structuredClone(r04.materials),'bms/cells':{...structuredClone(r04.materials['bms/cells']),chargeGradient:defaultChargeGradient()}},assignments:{},objects:{...r04.objects}};
|
||||
materials:{...structuredClone(r04.materials),'bms/cells':{...structuredClone(r04.materials['bms/cells']),color:'#050505',emissiveIntensity:0,chargeGradient:defaultChargeGradient()}},assignments:{},objects:{...r04.objects}};
|
||||
}
|
||||
function database():Promise<IDBDatabase>{return new Promise((resolve,reject)=>{
|
||||
const request=indexedDB.open('missioncore-battery-scenes',1);
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
export type ChargeGradient={enabled:boolean;lowA:string;lowB:string;highA:string;highB:string;speed:number;scale:number;intensity:number;fallbackColor:string;fallbackMetalness:number;fallbackRoughness:number;fallbackOpacity:number;fallbackReflectivity:number};
|
||||
export const defaultChargeGradient=():ChargeGradient=>({enabled:true,lowA:'#ef2815',lowB:'#ff9b23',highA:'#20db62',highB:'#6cffe0',speed:.45,scale:12,intensity:2.5,fallbackColor:'#737b80',fallbackMetalness:.1,fallbackRoughness:.65,fallbackOpacity:1,fallbackReflectivity:.5});
|
||||
import {parseMaterialSurface,defaultMaterialSurface,type MaterialSurface} from './materialSurface';
|
||||
export type ChargeGradient={surfaceVersion:1;enabled:boolean;lowA:string;lowB:string;highA:string;highB:string;speed:number;scale:number;intensity:number;contrast:number;saturation:number;inactive:MaterialSurface};
|
||||
export const defaultChargeGradient=():ChargeGradient=>({surfaceVersion:1,enabled:true,lowA:'#ef2815',lowB:'#ff9b23',highA:'#20db62',highB:'#6cffe0',speed:.45,scale:12,intensity:2.5,contrast:1,saturation:1,inactive:defaultMaterialSurface()});
|
||||
export function parseChargeGradient(raw:unknown):ChargeGradient{
|
||||
const result=defaultChargeGradient(),value=raw as Partial<ChargeGradient>|undefined;
|
||||
if(!value)return result;
|
||||
const result=defaultChargeGradient(),value=raw as Partial<ChargeGradient>&Record<string,unknown>;
|
||||
if(!value||typeof value!=='object')return result;
|
||||
if(typeof value.enabled==='boolean')result.enabled=value.enabled;
|
||||
for(const key of ['lowA','lowB','highA','highB','fallbackColor'] as const)if(typeof value[key]==='string'&&/^#[0-9a-f]{6}$/i.test(value[key]))result[key]=value[key];
|
||||
for(const [key,min,max] of [['speed',0,3],['scale',1,50],['intensity',0,10],['fallbackMetalness',0,1],['fallbackRoughness',0,1],['fallbackOpacity',0,1],['fallbackReflectivity',0,1]] as const)if(typeof value[key]==='number'&&Number.isFinite(value[key]))result[key]=Math.max(min,Math.min(max,value[key]));
|
||||
for(const key of ['lowA','lowB','highA','highB'] as const)if(typeof value[key]==='string'&&/^#[0-9a-f]{6}$/i.test(value[key]))result[key]=value[key];
|
||||
for(const [key,min,max] of [['speed',0,3],['scale',1,50],['intensity',0,10],['contrast',.1,4],['saturation',0,2]] as const)if(typeof value[key]==='number'&&Number.isFinite(value[key]))result[key]=Math.max(min,Math.min(max,value[key]));
|
||||
// Preserve pre-split fallback edits; inactive textures and coat start independently.
|
||||
result.inactive=parseMaterialSurface(value.inactive??{color:value.fallbackColor,metalness:value.fallbackMetalness,roughness:value.fallbackRoughness,opacity:value.fallbackOpacity,reflectivity:value.fallbackReflectivity});
|
||||
return result;
|
||||
}
|
||||
/** Interpolate each end of the gradient; no individual-cell SOC is inferred. */
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import {parseEnvironmentProfile,prepareEnvironmentSave,validEnvironmentId,type StoredEnvironmentProfile} from './environmentProfiles';
|
||||
const eventName='missioncore:environment-profiles';
|
||||
function database():Promise<IDBDatabase>{return new Promise((resolve,reject)=>{const r=indexedDB.open('missioncore-environment-profiles',1);r.onupgradeneeded=()=>r.result.createObjectStore('profiles',{keyPath:'id'});r.onsuccess=()=>resolve(r.result);r.onerror=()=>reject(r.error);r.onblocked=()=>reject(new Error('Хранилище профилей занято другим окном.'));});}
|
||||
function records(raw:unknown[]):StoredEnvironmentProfile[]{return raw.map((r:any)=>{if(!validEnvironmentId(r?.id)||r.id==='nodedc'||!Number.isInteger(r.revision)||r.revision<1)throw new Error('Не удалось прочитать библиотеку профилей.');return {...parseEnvironmentProfile(r),id:r.id,revision:r.revision};});}
|
||||
export async function readEnvironmentProfiles():Promise<StoredEnvironmentProfile[]>{
|
||||
const db=await database();try{return await new Promise((resolve,reject)=>{const r=db.transaction('profiles').objectStore('profiles').getAll();r.onsuccess=()=>{try{resolve(records(r.result));}catch(e){reject(e);}};r.onerror=()=>reject(r.error);});}finally{db.close();}
|
||||
}
|
||||
export async function saveEnvironmentProfile(profile:StoredEnvironmentProfile,expectedRevision:number|null):Promise<StoredEnvironmentProfile>{
|
||||
const db=await database();let saved:StoredEnvironmentProfile;
|
||||
try{saved=await new Promise((resolve,reject)=>{
|
||||
const tx=db.transaction('profiles','readwrite'),store=tx.objectStore('profiles'),r=store.getAll();let next:StoredEnvironmentProfile,error:unknown;
|
||||
r.onsuccess=()=>{try{next=prepareEnvironmentSave(records(r.result),profile,expectedRevision);store.put(next);}catch(e){error=e;tx.abort();}};
|
||||
tx.oncomplete=()=>resolve(next);tx.onabort=()=>reject(error??tx.error);tx.onerror=()=>reject(error??tx.error);
|
||||
});}finally{db.close();}
|
||||
window.dispatchEvent(new Event(eventName));
|
||||
if(typeof BroadcastChannel!=='undefined'){const channel=new BroadcastChannel(eventName);channel.postMessage('changed');channel.close();}
|
||||
return saved;
|
||||
}
|
||||
export function watchEnvironmentProfiles(refresh:()=>void):()=>void{
|
||||
window.addEventListener(eventName,refresh);window.addEventListener('focus',refresh);
|
||||
const channel=typeof BroadcastChannel!=='undefined'?new BroadcastChannel(eventName):null;if(channel)channel.onmessage=refresh;
|
||||
return()=>{window.removeEventListener(eventName,refresh);window.removeEventListener('focus',refresh);channel?.close();};
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import {changeField,defaultScene,environmentFields,fieldValue,type SceneDocument} from './sceneDocument';
|
||||
export type EnvironmentSettings=Pick<SceneDocument,'postFx'|'cameraZoomStrength'|'cameraAutoRotate'>;
|
||||
export type EnvironmentProfile={schema:'missioncore.environment-profile/v1';name:string;environment:EnvironmentSettings};
|
||||
export type StoredEnvironmentProfile=EnvironmentProfile&{id:string;revision:number};
|
||||
export const builtinEnvironmentId='nodedc';
|
||||
export const validEnvironmentId=(id:unknown):id is string=>typeof id==='string'&&(id===builtinEnvironmentId||/^env\/[a-zA-Z0-9-]{1,80}$/.test(id));
|
||||
export function sceneEnvironment(doc:EnvironmentSettings):EnvironmentSettings{return structuredClone({postFx:doc.postFx,cameraZoomStrength:doc.cameraZoomStrength,cameraAutoRotate:doc.cameraAutoRotate});}
|
||||
export const builtinEnvironment=():StoredEnvironmentProfile=>({schema:'missioncore.environment-profile/v1',id:builtinEnvironmentId,revision:0,name:'NodeDC',environment:sceneEnvironment(defaultScene())});
|
||||
export function parseEnvironmentProfile(raw:unknown):EnvironmentProfile{
|
||||
const r=raw as any;
|
||||
if(!r||!['missioncore.environment-profile/v1','missioncore.rover-scene/v1','missioncore.battery-scene/v1'].includes(r.schema))throw new Error('Выберите профиль окружения или JSON сцены Mission Core.');
|
||||
const value=r.schema==='missioncore.environment-profile/v1'?r.environment:r;
|
||||
if(!value?.postFx||typeof value.postFx!=='object'||Array.isArray(value.postFx))throw new Error('В файле нет настроек окружения.');
|
||||
let doc=defaultScene();for(const f of environmentFields){const v=fieldValue(value,f.key);if(v!==undefined)doc=changeField(doc,f.key,v);}
|
||||
return {schema:'missioncore.environment-profile/v1',name:typeof r.name==='string'?r.name.trim().slice(0,80)||'Импортированный профиль':'Импортированный профиль',environment:sceneEnvironment(doc)};
|
||||
}
|
||||
export function applyEnvironment(doc:SceneDocument,profile:StoredEnvironmentProfile):SceneDocument{
|
||||
return {...doc,...sceneEnvironment(profile.environment),environmentProfileId:profile.id};
|
||||
}
|
||||
export const environmentMatches=(a:EnvironmentSettings,b:EnvironmentSettings)=>JSON.stringify(sceneEnvironment(a))===JSON.stringify(sceneEnvironment(b));
|
||||
export function prepareEnvironmentSave(records:StoredEnvironmentProfile[],profile:StoredEnvironmentProfile,expectedRevision:number|null):StoredEnvironmentProfile{
|
||||
if(!validEnvironmentId(profile.id)||profile.id===builtinEnvironmentId)throw new Error('Сохраните встроенный профиль под новым именем.');
|
||||
const existing=records.find(p=>p.id===profile.id);
|
||||
if((existing?.revision??null)!==expectedRevision)throw new Error('Профиль изменился в другом окне. Выберите его заново или сохраните копию.');
|
||||
const name=profile.name.trim().slice(0,80);if(!name)throw new Error('Введите название профиля.');
|
||||
if(records.some(p=>p.id!==profile.id&&p.name.toLocaleLowerCase()===name.toLocaleLowerCase())||name.toLocaleLowerCase()==='nodedc')throw new Error('Это имя уже занято. Выберите другое название.');
|
||||
const next={...parseEnvironmentProfile(profile),id:profile.id,name,revision:(expectedRevision??0)+1};
|
||||
const all=[...records.filter(p=>p.id!==profile.id),next];
|
||||
if(all.length>64||JSON.stringify(all).length>16_000_000)throw new Error('Библиотека профилей заполнена. Пересохраните существующий профиль или экспортируйте JSON.');
|
||||
return next;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
export const textureSlots=['diffuse','normal','metalness','roughness','opacity','emissive','ao'] as const;
|
||||
export type TextureSlot=typeof textureSlots[number];
|
||||
export type MaterialSurface={color:string;metalness:number;roughness:number;opacity:number;reflectivity:number;clearCoat:number;clearCoatRoughness:number;emissive:string;emissiveIntensity:number;normalStrength:number;doubleSided:boolean;tiling:number;textures:Partial<Record<TextureSlot,{name:string;data:string}>>};
|
||||
export const materialRanges:Record<string,[number,number]>={metalness:[0,1],roughness:[0,1],opacity:[0,1],reflectivity:[0,1],clearCoat:[0,1],clearCoatRoughness:[0,1],emissiveIntensity:[0,10],normalStrength:[0,2],tiling:[.01,20]};
|
||||
export const defaultMaterialSurface=():MaterialSurface=>({color:'#737b80',metalness:.1,roughness:.65,opacity:1,reflectivity:.5,clearCoat:0,clearCoatRoughness:.3,emissive:'#000000',emissiveIntensity:0,normalStrength:1,doubleSided:false,tiling:1,textures:{}});
|
||||
export function parseMaterialSurface(raw:unknown,defaults:MaterialSurface=defaultMaterialSurface()):MaterialSurface{
|
||||
const result=structuredClone(defaults),m=raw as Partial<MaterialSurface>|undefined;if(!m||typeof m!=='object')return result;
|
||||
for(const key of ['color','emissive'] as const)if(typeof m[key]==='string'&&/^#[0-9a-f]{6}$/i.test(m[key]))result[key]=m[key];
|
||||
for(const [key,[lo,hi]] of Object.entries(materialRanges)){const v=m[key as keyof MaterialSurface];if(typeof v==='number'&&Number.isFinite(v))(result as any)[key]=Math.max(lo,Math.min(hi,v));}
|
||||
if(typeof m.doubleSided==='boolean')result.doubleSided=m.doubleSided;
|
||||
for(const slot of textureSlots){const t=m.textures?.[slot];if(!t)continue;if(typeof t.name!=='string'||typeof t.data!=='string'||t.data.length>12_000_000||!/^data:image\/(png|jpeg|webp);base64,[A-Za-z0-9+/=]+$/.test(t.data))throw new Error('Некорректная текстура в файле сцены.');result.textures[slot]={name:t.name.slice(0,200),data:t.data};}
|
||||
return result;
|
||||
}
|
||||
export const surfaceTextureBytes=(s:MaterialSurface)=>Object.values(s.textures).reduce((sum,t)=>sum+(t?.data.length??0),0);
|
||||
@@ -1,3 +1,5 @@
|
||||
import {parseMaterialSurface,surfaceTextureBytes,type MaterialSurface} from './materialSurface';
|
||||
export {textureSlots,materialRanges,type TextureSlot} from './materialSurface';
|
||||
import {parseEditorLayout,type SceneEditorLayout} from './editorLayout';
|
||||
import {parseCameraState,type CameraState} from './cameraState';
|
||||
import {parseChargeGradient,type ChargeGradient} from './chargeGradient';
|
||||
@@ -13,10 +15,8 @@ export const environmentFields:SceneField[]=[...donorFields,
|
||||
{key:'postFx.grid.step',type:'sliderNumber',label:'Шаг основной сетки, м',group:'PostProcess/Grid',min:.01,max:10,step:.01},
|
||||
{key:'postFx.grid.diameter',type:'sliderNumber',label:'Диаметр сетки, м',group:'PostProcess/Grid',min:1,max:1000,step:1},
|
||||
];
|
||||
export const textureSlots=['diffuse','normal','metalness','roughness','opacity','emissive','ao'] as const;
|
||||
export type TextureSlot=typeof textureSlots[number];
|
||||
export type MaterialSpec={chargeGradient?:ChargeGradient;name:string;color:string;metalness:number;roughness:number;opacity:number;reflectivity:number;clearCoat:number;clearCoatRoughness:number;emissive:string;emissiveIntensity:number;normalStrength:number;doubleSided:boolean;tiling:number;textures:Partial<Record<TextureSlot,{name:string;data:string}>>};
|
||||
export type SceneDocument={schema:'missioncore.rover-scene/v1'|'missioncore.battery-scene/v1';model:string;environmentVersion:2;camera?:CameraState;editorLayout?:SceneEditorLayout;postFx:PostFxSettings;cameraZoomStrength:number;cameraAutoRotate:boolean;materials:Record<string,MaterialSpec>;assignments:Record<string,string>;objectAssignments?:Record<string,string>;objectVisibility?:Record<string,boolean>;objects?:Record<string,boolean>};
|
||||
export type MaterialSpec=MaterialSurface&{chargeGradient?:ChargeGradient;name:string};
|
||||
export type SceneDocument={schema:'missioncore.rover-scene/v1'|'missioncore.battery-scene/v1';model:string;environmentVersion:2;environmentProfileId?:string;camera?:CameraState;editorLayout?:SceneEditorLayout;postFx:PostFxSettings;cameraZoomStrength:number;cameraAutoRotate:boolean;materials:Record<string,MaterialSpec>;assignments:Record<string,string>;objectAssignments?:Record<string,string>;objectVisibility?:Record<string,boolean>;objects?:Record<string,boolean>};
|
||||
// Reserve the added equipment slots without consuming the legacy custom-material budget.
|
||||
export const maxSceneMaterials=128+Object.keys(equipmentMaterials).length;
|
||||
const material=(name:string,color:string,metalness:number,roughness:number):MaterialSpec=>({name,color,metalness,roughness,opacity:1,reflectivity:1,clearCoat:0,clearCoatRoughness:.3,emissive:'#000000',emissiveIntensity:0,normalStrength:1,doubleSided:false,tiling:1,textures:{}});
|
||||
@@ -73,11 +73,11 @@ export function changeField(doc:SceneDocument,key:string,value:unknown):SceneDoc
|
||||
if(key==='postFx.skybox.enabled'&&value)result.postFx.envAtlas.enabled=false;
|
||||
return result;
|
||||
}
|
||||
export const materialRanges:Record<string,[number,number]>={metalness:[0,1],roughness:[0,1],opacity:[0,1],reflectivity:[0,1],clearCoat:[0,1],clearCoatRoughness:[0,1],emissiveIntensity:[0,10],normalStrength:[0,2],tiling:[.01,20]};
|
||||
export function textureBytes(doc:SceneDocument):number{return Object.values(doc.materials).reduce((sum,m)=>sum+Object.values(m.textures).reduce((n,t)=>n+(t?.data.length??0),0),0);}
|
||||
export function textureBytes(doc:SceneDocument):number{return Object.values(doc.materials).reduce((sum,m)=>sum+surfaceTextureBytes(m)+(m.chargeGradient?surfaceTextureBytes(m.chargeGradient.inactive):0),0);}
|
||||
export function parseScene(raw:unknown,defaults:()=>SceneDocument=defaultScene):SceneDocument{
|
||||
const base=defaults(),r=raw as SceneDocument;const models=base.schema==='missioncore.rover-scene/v1'?[roverModelRevision,legacyRoverModelRevision,previousRoverModelRevision]:[base.model];if(!r||r.schema!==base.schema||!models.includes(r.model))throw new Error('Файл сцены не подходит к этой модели.');
|
||||
let doc=base;
|
||||
if(typeof r.environmentProfileId==='string'&&/^(nodedc|env\/[a-zA-Z0-9-]{1,80})$/.test(r.environmentProfileId))doc.environmentProfileId=r.environmentProfileId;
|
||||
const layout=parseEditorLayout(r.editorLayout);if(layout)doc.editorLayout=layout;
|
||||
const camera=parseCameraState(r.camera);if(camera)doc.camera=camera;
|
||||
if(doc.objects)for(const id of Object.keys(doc.objects)){const legacy=Object.keys(r.objects??{}).filter(key=>id===key||id.startsWith(key+'/')).sort((a,b)=>b.length-a.length)[0];if(legacy&&typeof r.objects?.[legacy]==='boolean')doc.objects[id]=r.objects[legacy];}
|
||||
@@ -87,11 +87,8 @@ export function parseScene(raw:unknown,defaults:()=>SceneDocument=defaultScene):
|
||||
for(const [id,base] of Object.entries(doc.materials)){
|
||||
const m=r.materials?.[id];if(!m)continue;
|
||||
if(typeof m.name==='string')base.name=m.name.trim().slice(0,120)||base.name;
|
||||
for(const key of ['color','emissive'] as const)if(/^#[0-9a-f]{6}$/i.test(m[key]))base[key]=m[key];
|
||||
for(const [key,[lo,hi]] of Object.entries(materialRanges)){const v=m[key as keyof MaterialSpec];if(typeof v==='number'&&Number.isFinite(v))(base as any)[key]=Math.max(lo,Math.min(hi,v));}
|
||||
if(typeof m.doubleSided==='boolean')base.doubleSided=m.doubleSided;
|
||||
if(m.chargeGradient)base.chargeGradient=parseChargeGradient(m.chargeGradient);
|
||||
for(const slot of textureSlots){const t=m.textures?.[slot];if(!t)continue;if(typeof t.name!=='string'||typeof t.data!=='string'||t.data.length>12_000_000||!/^data:image\/(png|jpeg|webp);base64,[A-Za-z0-9+/=]+$/.test(t.data))throw new Error('Некорректная текстура в файле сцены.');base.textures[slot]={name:t.name.slice(0,200),data:t.data};}
|
||||
Object.assign(base,parseMaterialSurface(m,base));
|
||||
if(m.chargeGradient){base.chargeGradient=parseChargeGradient(m.chargeGradient);if(m.chargeGradient.enabled){if(!m.chargeGradient.inactive)base.color='#050505';if(m.chargeGradient.surfaceVersion!==1)base.emissiveIntensity=0;}}
|
||||
}
|
||||
for(const [group,id] of Object.entries(r.assignments??{}))if(typeof id==='string')doc=assignMaterial(doc,group,id);
|
||||
for(const key of ['objectAssignments','objectVisibility'] as const){
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {StandardMaterial} from 'playcanvas';
|
||||
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 {defaultBatteryScene}=await load('../src/core/batteryScene/profile.ts');
|
||||
@@ -39,11 +40,11 @@ test('view height round trips independently per battery and rejects corrupt geom
|
||||
const {updateChargeMaterial}=await load('../src/components/rover/playcanvas/chargeMaterial.ts');
|
||||
test('temporary disconnect holds the exact last colour and emission; expired telemetry is unknown',()=>{
|
||||
const spec=defaultBatteryScene().materials['bms/cells'],gradient=spec.chargeGradient;
|
||||
const values=state=>{const result={};updateChargeMaterial({diffuse:{set(){},fromString(value){result.diffuse=value;}},update(){},setParameter:(key,value)=>result[key]=value},gradient,state,3.5,spec);return result;};
|
||||
const values=state=>{const result={},m=new StandardMaterial();m.setParameter=(key,value)=>result[key]=value;updateChargeMaterial(m,gradient,state,3.5,spec);result.diffuse=m.diffuse.toString();return result;};
|
||||
const live=values({soc:82,fresh:true});
|
||||
assert.deepEqual(values({soc:82,fresh:false}),live);
|
||||
const expired=values({soc:null,fresh:false});
|
||||
assert.equal(expired.chargeIntensity,0);assert.equal(expired.diffuse,gradient.fallbackColor);assert.equal(expired.chargeSaturation,0);assert.notDeepEqual(expired.chargeColorA,live.chargeColorA);
|
||||
assert.equal(expired.chargeIntensity,0);assert.equal(expired.diffuse,gradient.inactive.color);assert.equal(expired.chargeSaturation,gradient.saturation);assert.notDeepEqual(expired.chargeColorA,live.chargeColorA);
|
||||
assert.notDeepEqual(values({soc:52,fresh:true}).chargeColorA,live.chargeColorA);
|
||||
});
|
||||
|
||||
@@ -109,21 +110,39 @@ test('missing samples retain the last valid charge across view reopens, never bo
|
||||
assert.equal(batteryState({...absent,id:'another'},true,now+20000).sample,null);
|
||||
assert.equal(batteryState(absent,true,Date.parse('2026-11-05T00:00:00Z')).sample,null);
|
||||
});
|
||||
test('fallback material edits round trip and never emit light',()=>{
|
||||
test('independent active and inactive materials round trip and restore every surface parameter',()=>{
|
||||
const scene=defaultBatteryScene(),spec=scene.materials['bms/cells'];
|
||||
Object.assign(spec.chargeGradient,{fallbackColor:'#123456',fallbackMetalness:.7,fallbackRoughness:.4,fallbackReflectivity:.8,fallbackOpacity:.6});
|
||||
assert.deepEqual(parseScene(JSON.parse(JSON.stringify(scene)),defaultBatteryScene).materials['bms/cells'].chargeGradient,spec.chargeGradient);
|
||||
const params={},m={diffuse:{set(){},fromString(v){this.color=v;}},update(){},setParameter:(k,v)=>params[k]=v};
|
||||
updateChargeMaterial(m,spec.chargeGradient,{soc:null,fresh:false},0,spec);
|
||||
assert.equal(m.diffuse.color,'#123456');assert.equal(m.metalness,.7);assert.equal(m.opacity,.6);assert.equal(params.chargeIntensity,0);
|
||||
updateChargeMaterial(m,spec.chargeGradient,{soc:0,fresh:true},0,spec);
|
||||
assert.equal(m.metalness,spec.metalness);assert.equal(m.opacity,spec.opacity);assert.equal(params.chargeIntensity,spec.chargeGradient.intensity);
|
||||
Object.assign(spec,{color:'#102030',metalness:.2,roughness:.1,clearCoat:.8,clearCoatRoughness:.15,opacity:.8,reflectivity:.4,emissive:'#ff1100',emissiveIntensity:2,normalStrength:.4,doubleSided:false,tiling:2});
|
||||
Object.assign(spec.chargeGradient.inactive,{color:'#123456',metalness:.7,roughness:.4,reflectivity:.8,opacity:.6,clearCoat:.3,clearCoatRoughness:.5,emissive:'#2255aa',emissiveIntensity:1.5,normalStrength:1.7,doubleSided:true,tiling:4});
|
||||
const parsed=parseScene(JSON.parse(JSON.stringify(scene)),defaultBatteryScene).materials['bms/cells'];assert.deepEqual(parsed,spec);
|
||||
const params={},m=new StandardMaterial(),bound=[];m.setParameter=(k,v)=>params[k]=v;
|
||||
for(const soc of [null,0,null,82]){
|
||||
const expected=soc===null?spec.chargeGradient.inactive:spec;
|
||||
updateChargeMaterial(m,spec.chargeGradient,{soc,fresh:soc!==null},0,spec,surface=>bound.push(surface));
|
||||
for(const key of ['metalness','opacity','clearCoat','emissiveIntensity'])assert.equal(m[key],expected[key]);
|
||||
assert.equal(m.diffuse.toString(),expected.color);assert.equal(m.emissive.toString(),expected.emissive);
|
||||
assert.equal(m.gloss,expected.roughness);assert.equal(m.clearCoatGloss,expected.clearCoatRoughness);assert.equal(m.bumpiness,expected.normalStrength);
|
||||
assert.equal(params.chargeIntensity,soc===null?0:spec.chargeGradient.intensity);assert.equal(bound.at(-1),expected);
|
||||
}
|
||||
assert.equal(bound.length,4);
|
||||
const old={...scene,materials:{...scene.materials,'bms/cells':{...spec,chargeGradient:{enabled:true,fallbackColor:'#aabbcc',fallbackMetalness:.9,fallbackOpacity:.3}}}};
|
||||
const migrated=parseScene(old,defaultBatteryScene).materials['bms/cells'];
|
||||
assert.equal(migrated.chargeGradient.inactive.color,'#aabbcc');assert.equal(migrated.chargeGradient.inactive.metalness,.9);assert.equal(migrated.chargeGradient.inactive.opacity,.3);assert.equal(migrated.chargeGradient.inactive.emissiveIntensity,0);
|
||||
assert.equal(migrated.color,'#050505');assert.equal(migrated.clearCoat,.8);
|
||||
});
|
||||
test('inactive textures obey the same import validation and total scene quota',()=>{
|
||||
const doc=defaultBatteryScene(),m=doc.materials['bms/cells'];
|
||||
m.chargeGradient.inactive.textures.diffuse={name:'bad',data:'https://untrusted/image.png'};
|
||||
assert.throws(()=>parseScene(doc,defaultBatteryScene),/текстура/);
|
||||
const data='data:image/png;base64,'+'A'.repeat(10_000_000);
|
||||
m.textures.diffuse={name:'active',data};m.chargeGradient.inactive.textures={diffuse:{name:'inactive',data},emissive:{name:'emission',data}};
|
||||
assert.throws(()=>parseScene(doc,defaultBatteryScene),/объём текстур/);
|
||||
});
|
||||
|
||||
test('indicator design migrates old profiles and retains bounded independent colour ranges',()=>{
|
||||
const old=defaultBatteryAppearance();delete old.indicator;
|
||||
assert.deepEqual(parseBatteryAppearance(old).indicator,defaultBatteryAppearance().indicator);
|
||||
const p=defaultBatteryAppearance();p.indicator={mode:'ranges',color:'#ffffff',lowColor:'#110000',middleColor:'#222200',highColor:'#003300',lowUntil:20,middleUntil:70};
|
||||
const p=defaultBatteryAppearance();p.indicator={...p.indicator,mode:'ranges',color:'#ffffff',lowColor:'#110000',middleColor:'#222200',highColor:'#003300',lowUntil:20,middleUntil:70};
|
||||
assert.deepEqual(parseBatteryAppearance(JSON.parse(JSON.stringify(p))),p);
|
||||
assert.equal(batteryIndicatorColor(p.indicator,19),'#110000');
|
||||
assert.equal(batteryIndicatorColor(p.indicator,20),'#222200');
|
||||
@@ -133,3 +152,11 @@ test('indicator design migrates old profiles and retains bounded independent col
|
||||
const bounded=parseBatteryAppearance({...p,indicator:{lowUntil:900,middleUntil:-1,color:'url(bad)'}}).indicator;
|
||||
assert.equal(bounded.lowUntil,99);assert.equal(bounded.middleUntil,100);assert.equal(bounded.color,'#f1f1ef');
|
||||
});
|
||||
|
||||
test('legacy ignored white emission never bleaches the gradient after migration; new emission stays editable',()=>{
|
||||
const old=defaultBatteryScene(),m=old.materials['bms/cells'];delete m.chargeGradient.surfaceVersion;m.emissiveIntensity=.65;
|
||||
const migrated=parseScene(old,defaultBatteryScene);assert.equal(migrated.materials['bms/cells'].emissiveIntensity,0);
|
||||
migrated.materials['bms/cells'].emissiveIntensity=1.7;
|
||||
assert.equal(parseScene(migrated,defaultBatteryScene).materials['bms/cells'].emissiveIntensity,1.7);
|
||||
assert.equal(migrated.materials['bms/cells'].chargeGradient.surfaceVersion,1);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {build} from 'esbuild';
|
||||
const bundle=await build({stdin:{contents:"export * from './src/core/roverScene/environmentProfiles'; export * from './src/core/roverScene/sceneDocument'; export * from './src/core/batteryScene/profile';",resolveDir:process.cwd()},bundle:true,write:false,platform:'node',format:'esm'});
|
||||
const {defaultScene,defaultBatteryScene,parseScene,changeField,builtinEnvironment,sceneEnvironment,parseEnvironmentProfile,applyEnvironment,environmentMatches,prepareEnvironmentSave}=await import('data:text/javascript;base64,'+Buffer.from(bundle.outputFiles[0].contents).toString('base64'));
|
||||
const record=(doc=defaultScene())=>({...builtinEnvironment(),id:'env/synthetic',name:'Мой свет',environment:sceneEnvironment(doc),revision:0});
|
||||
test('shared environment profiles copy between models without moving the camera or touching materials/layout',()=>{
|
||||
const source=changeField(defaultScene(),'postFx.lighting.exposure',1.7),profile=prepareEnvironmentSave([],record(source),null);
|
||||
const battery=defaultBatteryScene();battery.camera={pivot:{x:1,y:2,z:3},distance:2,azimuthDeg:20,elevationDeg:30,referenceHeight:800};battery.editorLayout={windows:{},materialTileSize:80};
|
||||
const before=structuredClone(battery),applied=applyEnvironment(battery,profile);
|
||||
assert.equal(applied.postFx.lighting.exposure,1.7);assert.deepEqual(applied.camera,before.camera);assert.deepEqual(applied.materials,before.materials);assert.deepEqual(applied.editorLayout,before.editorLayout);
|
||||
assert.equal(applied.environmentProfileId,profile.id);assert.equal(parseScene(applied,defaultBatteryScene).environmentProfileId,profile.id);
|
||||
const other=applyEnvironment(defaultScene(),profile);applied.postFx.lighting.exposure=.5;
|
||||
assert.equal(other.postFx.lighting.exposure,1.7);assert.equal(profile.environment.postFx.lighting.exposure,1.7);assert.equal(source.postFx.lighting.exposure,1.7);
|
||||
assert.equal(environmentMatches(applied,profile.environment),false);assert.deepEqual(battery,before);
|
||||
});
|
||||
test('save/overwrite preserves IDs and rejects stale revisions and duplicate names',()=>{
|
||||
const saved=prepareEnvironmentSave([],record(),null);assert.equal(saved.revision,1);
|
||||
const edited={...saved,environment:sceneEnvironment(changeField(defaultScene(),'postFx.lighting.exposure',1.8))};
|
||||
const next=prepareEnvironmentSave([saved],edited,1);assert.equal(next.id,saved.id);assert.equal(next.revision,2);
|
||||
assert.throws(()=>prepareEnvironmentSave([next],edited,1),/другом окне/);
|
||||
assert.throws(()=>prepareEnvironmentSave([saved],{...saved,id:'env/other'},null),/имя/);
|
||||
assert.throws(()=>prepareEnvironmentSave([],builtinEnvironment(),null),/новым именем/);
|
||||
assert.equal(saved.environment.postFx.lighting.exposure,defaultScene().postFx.lighting.exposure);
|
||||
});
|
||||
test('export/import is model independent, bounded and also extracts only environment from legacy scene JSON',()=>{
|
||||
const d=changeField(defaultBatteryScene(),'postFx.lighting.exposure',1.9),profile=record(d);
|
||||
const parsed=parseEnvironmentProfile(JSON.parse(JSON.stringify(profile)));assert.deepEqual(parsed.environment,sceneEnvironment(d));
|
||||
assert.deepEqual(parseEnvironmentProfile(d).environment,sceneEnvironment(d));assert.ok(!('materials' in parsed.environment));assert.ok(!('camera' in parsed.environment));
|
||||
assert.throws(()=>parseEnvironmentProfile({schema:'foreign'}));assert.throws(()=>parseEnvironmentProfile({schema:profile.schema}));
|
||||
const invalid=structuredClone(profile);invalid.environment.postFx.lighting.exposure=Infinity;invalid.environment.postFx.rendering.backgroundColor='url(bad)';
|
||||
assert.equal(parseEnvironmentProfile(invalid).environment.postFx.lighting.exposure,defaultScene().postFx.lighting.exposure);
|
||||
assert.equal(parseEnvironmentProfile(invalid).environment.postFx.rendering.backgroundColor,defaultScene().postFx.rendering.backgroundColor);
|
||||
});
|
||||
test('old scenes retain their custom environment and no selected profile is invented',()=>{
|
||||
const doc=changeField(defaultBatteryScene(),'postFx.lighting.exposure',.9),parsed=parseScene(doc,defaultBatteryScene);
|
||||
assert.equal(parsed.environmentProfileId,undefined);assert.deepEqual(parsed.postFx,doc.postFx);
|
||||
});
|
||||
@@ -64,3 +64,45 @@ An atomic IndexedDB transaction retains the old document under
|
||||
and explicit JSON imports are preserved; the version prevents future resets.
|
||||
Regression tests cover the legacy scene, material preservation, idempotence,
|
||||
custom environments, deliberate gray scenes, imports and already restored scenes.
|
||||
|
||||
|
||||
Owner refinement, 2026-11-04: reusable environment profiles and SOC surfaces
|
||||
------------------------------------------------------------------------
|
||||
|
||||
The first Environment Inspector section is now Profiles. A shared local
|
||||
IndexedDB library (`missioncore-environment-profiles`) holds named environment
|
||||
snapshots, independently of a model. The immutable NodeDC preset is the initial
|
||||
option. Save as creates a new identity; overwrite retains that identity and
|
||||
uses a transactional revision check. Duplicate names and stale overwrites are
|
||||
rejected. Library updates notify other mounted scene editors and browser tabs.
|
||||
Limits are 64 user profiles and 16 MB of encoded configuration including LUTs.
|
||||
|
||||
Applying a profile copies post-processing/environment and camera behaviour
|
||||
(zoom strength, autorotation) into the current scene. Camera pose, materials,
|
||||
object assignments, visibility and editor layout remain scene-owned. Later
|
||||
scene edits and library overwrites never propagate into other scenes. The
|
||||
selected profile ID is persisted in scene JSON; settings remain usable if the
|
||||
library record is absent. Existing custom environments are preserved on load.
|
||||
Environment JSON uses `missioncore.environment-profile/v1`; import also accepts
|
||||
an older full scene JSON and extracts only the environment. Full scene JSON
|
||||
import/export remains in a separate subsection of Profiles.
|
||||
|
||||
SOC materials have two independent complete MaterialSurface configurations:
|
||||
active surface at the existing MaterialSpec root, and inactive surface under
|
||||
`chargeGradient.inactive`. Both expose colour, metalness, roughness, opacity,
|
||||
reflection, clear coat, emission, double-sided rendering and all seven texture
|
||||
slots with their normal/tiling controls. Active gradient additionally exposes
|
||||
its colour pairs, intensity, speed, scale, contrast and saturation. Its emission
|
||||
is additive to the active surface's own emission. Legacy fallback fields migrate
|
||||
without losing their values; the formerly fixed active base colour migrates to
|
||||
an editable dark colour. Surface version 1 also starts the previously ignored
|
||||
base emission at zero so the donor white emission cannot bleach the gradient
|
||||
on upgrade. Newly edited base emission then persists independently. Texture
|
||||
quotas include both surfaces.
|
||||
|
||||
The material inspector can preview either mode without changing telemetry or
|
||||
saved scene mode. Preview falls back to 50% only for the active appearance when
|
||||
SOC is absent, and ends on leaving editing. Automatic mode retains valid stale
|
||||
SOC and uses the independent inactive surface only when no retained value exists.
|
||||
The renderer switches the complete surface and its texture bindings together;
|
||||
async texture completion cannot apply a hidden mode's texture over the live mode.
|
||||
|
||||
Reference in New Issue
Block a user