Implement global axis system and advanced motion logic

This commit is contained in:
2025-12-21 23:25:23 +09:00
parent 182c364e37
commit a459b81884
7 changed files with 802 additions and 365 deletions

181
App.tsx
View File

@@ -6,12 +6,13 @@ import { OrbitControls, Grid, GizmoHelper, GizmoViewcube } from '@react-three/dr
import { Sidebar } from './components/Sidebar';
import { IOPanel } from './components/IOPanel';
import { LadderEditor } from './components/LadderEditor';
import { SystemSetupDialog } from './components/SystemSetupDialog';
import {
SimObject, ObjectType, AxisObject, CylinderObject, SwitchObject, LedObject,
IOLogicRule, LogicCondition, LogicAction, ProjectData
IOLogicRule, LogicCondition, LogicAction, ProjectData, AxisData, LogicTriggerType, LogicActionType
} from './types';
import { EditableObject } from './components/SceneObjects';
import { Layout as LayoutIcon, Cpu, Play, Pause, Square, Download, Upload, Magnet } from 'lucide-react';
import { Layout as LayoutIcon, Cpu, Play, Pause, Square, Download, Upload, Magnet, Settings } from 'lucide-react';
// --- Simulation Manager (PLC Scan Cycle) ---
const SimulationLoop = ({
@@ -22,7 +23,9 @@ const SimulationLoop = ({
manualInputs,
manualOutputs,
setInputs,
setOutputs
setOutputs,
axes,
setAxes
}: {
isPlaying: boolean,
objects: SimObject[],
@@ -31,25 +34,30 @@ const SimulationLoop = ({
manualInputs: boolean[],
manualOutputs: boolean[],
setInputs: (inputs: boolean[]) => void,
setOutputs: (outputs: boolean[]) => void
setOutputs: (outputs: boolean[]) => void,
axes: AxisData[],
setAxes: React.Dispatch<React.SetStateAction<AxisData[]>>
}) => {
useFrame((state, delta) => {
if (!isPlaying) return;
// --- 1. PLC Input Scan (Physical + Manual Force) ---
const sensorInputs = new Array(16).fill(false);
const sensorInputs = new Array(32).fill(false);
objects.forEach(obj => {
if (obj.type === ObjectType.SWITCH && (obj as SwitchObject).isOn) {
const port = (obj as SwitchObject).inputPort;
if (port >= 0 && port < 16) sensorInputs[port] = true;
if (port >= 0 && port < 32) sensorInputs[port] = true;
}
if ((obj.type === ObjectType.AXIS_LINEAR || obj.type === ObjectType.AXIS_ROTARY) && (obj as AxisObject).triggers) {
const axis = obj as AxisObject;
axis.triggers.forEach(trig => {
const met = trig.condition === '>' ? axis.currentValue > trig.position : axis.currentValue < trig.position;
if (met && trig.targetInputPort >= 0 && trig.targetInputPort < 16) sensorInputs[trig.targetInputPort] = true;
});
const axisObj = obj as AxisObject;
const globalAxis = axes[axisObj.axisIndex];
if (globalAxis) {
axisObj.triggers.forEach(trig => {
const met = trig.condition === '>' ? globalAxis.value > trig.position : globalAxis.value < trig.position;
if (met && trig.targetInputPort >= 0 && trig.targetInputPort < 32) sensorInputs[trig.targetInputPort] = true;
});
}
}
});
@@ -57,20 +65,57 @@ const SimulationLoop = ({
setInputs(effectiveInputs);
// --- 2. PLC Logic Execution ---
const logicOutputs = new Array(16).fill(false);
const logicOutputs = new Array(32).fill(false);
// Axis updates from Logic (collected to avoid multiple setState calls)
const axisUpdates = new Map<number, number>();
logicRules.forEach(rule => {
if (!rule.enabled) return;
const inputState = effectiveInputs[rule.inputPort];
const conditionMet = rule.condition === LogicCondition.IS_ON ? inputState : !inputState;
if (conditionMet && rule.action === LogicAction.SET_ON) {
logicOutputs[rule.outputPort] = true;
// 1. Evaluate Trigger
let conditionMet = false;
if (rule.triggerType === LogicTriggerType.INPUT_BIT) {
const inputState = effectiveInputs[rule.inputPort];
conditionMet = inputState; // Default IS_ON behavior for now
} else if (rule.triggerType === LogicTriggerType.AXIS_COMPARE) {
const axis = axes[rule.triggerAxisIndex];
if (axis) {
switch (rule.triggerCompareOp) {
case LogicCondition.GREATER: conditionMet = axis.value > rule.triggerValue; break;
case LogicCondition.LESS: conditionMet = axis.value < rule.triggerValue; break;
case LogicCondition.EQUAL: conditionMet = Math.abs(axis.value - rule.triggerValue) < 0.1; break;
}
}
}
// 2. Execute Action if Trigger Met
if (conditionMet) {
if (rule.actionType === LogicActionType.OUTPUT_COIL) {
if (rule.action === LogicAction.SET_ON) {
logicOutputs[rule.outputPort] = true;
}
} else if (rule.actionType === LogicActionType.AXIS_MOVE) {
axisUpdates.set(rule.targetAxisIndex, rule.targetAxisValue);
}
}
});
// Effective Outputs = Logic OR Manual Force
// Apply Logical Outputs
const effectiveOutputs = logicOutputs.map((bit, i) => bit || manualOutputs[i]);
setOutputs(effectiveOutputs);
// Apply Axis Logic Updates (Only if changed to prevent thrashing)
if (axisUpdates.size > 0) {
setAxes(prev => prev.map(a => {
if (axisUpdates.has(a.id)) {
const target = axisUpdates.get(a.id)!;
if (a.target !== target) return { ...a, target };
}
return a;
}));
}
// --- 3. Physical Update Scan ---
setObjects(prevObjects => {
let hasChanges = false;
@@ -101,17 +146,8 @@ const SimulationLoop = ({
}
}
else if (obj.type === ObjectType.AXIS_LINEAR || obj.type === ObjectType.AXIS_ROTARY) {
const axis = obj as AxisObject;
if (axis.currentValue !== axis.targetValue) {
const diff = axis.targetValue - axis.currentValue;
const step = axis.speed * delta * 10;
if (Math.abs(diff) < step) {
newObj = { ...axis, currentValue: axis.targetValue };
} else {
newObj = { ...axis, currentValue: axis.currentValue + Math.sign(diff) * step };
}
changed = true;
}
// Axis objects are now just visualizers, no internal state update needed here
// Their position is derived from global 'axes' state in render
}
if (changed) hasChanges = true;
@@ -119,6 +155,23 @@ const SimulationLoop = ({
});
return hasChanges ? newObjects : prevObjects;
});
// --- 4. Axis Update Scan ---
setAxes(prevAxes => {
return prevAxes.map(axis => {
if (axis.value !== axis.target) {
const diff = axis.target - axis.value;
const step = axis.speed * delta * 10;
if (Math.abs(diff) < step) {
return { ...axis, value: axis.target };
} else {
return { ...axis, value: axis.value + Math.sign(diff) * step };
}
}
return axis;
});
});
});
return null;
@@ -129,18 +182,31 @@ export default function App() {
const [objects, setObjects] = useState<SimObject[]>([]);
const [logicRules, setLogicRules] = useState<IOLogicRule[]>([]);
const [inputs, setInputs] = useState<boolean[]>(new Array(16).fill(false));
const [outputs, setOutputs] = useState<boolean[]>(new Array(16).fill(false));
const [manualInputs, setManualInputs] = useState<boolean[]>(new Array(16).fill(false));
const [manualOutputs, setManualOutputs] = useState<boolean[]>(new Array(16).fill(false));
const [inputs, setInputs] = useState<boolean[]>(new Array(32).fill(false));
const [outputs, setOutputs] = useState<boolean[]>(new Array(32).fill(false));
const [manualInputs, setManualInputs] = useState<boolean[]>(new Array(32).fill(false));
const [manualOutputs, setManualOutputs] = useState<boolean[]>(new Array(32).fill(false));
const [inputNames, setInputNames] = useState<string[]>(new Array(16).fill(''));
const [outputNames, setOutputNames] = useState<string[]>(new Array(16).fill(''));
const [inputNames, setInputNames] = useState<string[]>(new Array(32).fill(''));
const [outputNames, setOutputNames] = useState<string[]>(new Array(32).fill(''));
const [selectedId, setSelectedId] = useState<string | null>(null);
const [isPlaying, setIsPlaying] = useState(false);
const [isSnapEnabled, setIsSnapEnabled] = useState(false);
const [isSetupOpen, setIsSetupOpen] = useState(false);
const controlsRef = useRef<any>(null);
// Initialize 8 Global Axes
const [axes, setAxes] = useState<AxisData[]>(() =>
Array.from({ length: 8 }, (_, i) => ({
id: i,
name: `Axis ${i + 1}`,
value: 0,
target: 0,
speed: 5,
type: 'linear'
}))
);
const handleSetView = (view: 'TOP' | 'BOTTOM' | 'FRONT' | 'BACK' | 'LEFT' | 'RIGHT') => {
const ctrl = controlsRef.current;
if (!ctrl) return;
@@ -194,19 +260,20 @@ export default function App() {
const handleReset = () => {
setIsPlaying(false);
setManualInputs(new Array(16).fill(false));
setManualOutputs(new Array(16).fill(false));
setManualInputs(new Array(32).fill(false));
setManualOutputs(new Array(32).fill(false));
setObjects(prev => prev.map(o => {
if (o.type === ObjectType.AXIS_LINEAR || o.type === ObjectType.AXIS_ROTARY) return { ...o, currentValue: (o as AxisObject).min, targetValue: (o as AxisObject).min };
// Reset logic handles axes reset separately, but visualizers don't hold state anymore
if (o.type === ObjectType.CYLINDER) return { ...o, currentPosition: 0, extended: false };
if (o.type === ObjectType.LED) return { ...o, isOn: false };
if (o.type === ObjectType.SWITCH) return { ...o, isOn: false };
return o;
}));
setAxes(prev => prev.map(a => ({ ...a, value: 0, target: 0 })));
};
const handleExport = () => {
const project: ProjectData = { version: "1.0", objects, logicRules, inputNames, outputNames };
const project: ProjectData = { version: "1.1", objects, logicRules, inputNames, outputNames, axes };
const blob = new Blob([JSON.stringify(project, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
@@ -225,6 +292,7 @@ export default function App() {
if (data.logicRules) setLogicRules(data.logicRules);
if (data.inputNames) setInputNames(data.inputNames);
if (data.outputNames) setOutputNames(data.outputNames);
if (data.axes) setAxes(data.axes);
} catch (err) { alert("Invalid JSON"); }
};
reader.readAsText(file);
@@ -237,10 +305,10 @@ export default function App() {
let newObj: SimObject;
switch (type) {
case ObjectType.AXIS_LINEAR:
newObj = { id, type, name: 'Linear Axis', position, rotation: { x: 0, y: 0, z: 0 }, min: 0, max: 100, currentValue: 0, targetValue: 0, speed: 1, isOscillating: false, triggers: [] } as AxisObject;
newObj = { id, type, name: 'Linear Axis', position, rotation: { x: 0, y: 0, z: 0 }, min: 0, max: 100, axisIndex: 0, triggers: [] } as AxisObject;
break;
case ObjectType.AXIS_ROTARY:
newObj = { id, type, name: 'Rotary Axis', position, rotation: { x: 0, y: 0, z: 0 }, min: 0, max: 360, currentValue: 0, targetValue: 0, speed: 1, isOscillating: false, triggers: [] } as AxisObject;
newObj = { id, type, name: 'Rotary Axis', position, rotation: { x: 0, y: 0, z: 0 }, min: 0, max: 360, axisIndex: 0, triggers: [] } as AxisObject;
break;
case ObjectType.CYLINDER:
newObj = { id, type, name: 'Cylinder', position, rotation: { x: 0, y: 0, z: 0 }, stroke: 2, extended: false, currentPosition: 0, speed: 2, outputPort: 0 } as CylinderObject;
@@ -274,18 +342,27 @@ export default function App() {
onClick={() => setActiveView('layout')}
className={`flex items-center gap-2 px-6 py-2 rounded-lg text-sm font-bold transition-all ${activeView === 'layout' ? 'bg-blue-600 text-white shadow-md' : 'text-gray-500 hover:text-gray-300'}`}
>
<LayoutIcon size={16} /> Layout
<LayoutIcon size={32} /> Layout
</button>
<button
onClick={() => setActiveView('logic')}
className={`flex items-center gap-2 px-6 py-2 rounded-lg text-sm font-bold transition-all ${activeView === 'logic' ? 'bg-blue-600 text-white shadow-md' : 'text-gray-500 hover:text-gray-300'}`}
>
<Cpu size={16} /> Logic
<Cpu size={32} /> Logic
</button>
</div>
<div className="h-8 w-[1px] bg-gray-800 mx-2" />
{/* 4. Top Navigation에 Setup 버튼 추가 */}
<button
onClick={() => setIsSetupOpen(true)}
className="p-2 rounded-lg bg-gray-950 text-gray-400 hover:text-white border border-gray-800 hover:bg-gray-800 transition-all"
title="System Setup"
>
<Settings size={18} />
</button>
<button
onClick={() => setIsSnapEnabled(!isSnapEnabled)}
className={`p-2 rounded-lg transition-all ${isSnapEnabled ? 'bg-blue-600 text-white shadow shadow-blue-500/50' : 'bg-gray-950 text-gray-500 hover:text-gray-300 border border-gray-800'}`}
@@ -332,7 +409,7 @@ export default function App() {
title="Reset System"
className="p-1.5 rounded-lg text-gray-400 hover:text-white hover:bg-gray-800 transition-all"
>
<Square size={16} fill="currentColor" />
<Square size={32} fill="currentColor" />
</button>
</div>
</div>
@@ -349,6 +426,8 @@ export default function App() {
outputNames={outputNames}
onToggleInput={handleToggleManualInput}
onToggleOutput={handleToggleManualOutput}
axes={axes}
setAxes={setAxes}
/>
{/* Center/Right: Dynamic Content based on tab */}
@@ -399,6 +478,7 @@ export default function App() {
onSelect={setSelectedId}
onUpdate={(id, updates) => setObjects(prev => prev.map(o => o.id === id ? { ...o, ...updates } as SimObject : o))}
onInteract={(id) => setObjects(prev => prev.map(o => (o.id === id && o.type === ObjectType.SWITCH) ? { ...o, isOn: !o.isOn } as SwitchObject : o))}
axes={axes}
/>
))}
@@ -411,6 +491,8 @@ export default function App() {
manualOutputs={manualOutputs}
setInputs={setInputs}
setOutputs={setOutputs}
axes={axes}
setAxes={setAxes}
/>
</Canvas>
</div>
@@ -421,9 +503,11 @@ export default function App() {
isPlaying={isPlaying}
inputNames={inputNames}
outputNames={outputNames}
axes={axes}
onAddObject={handleAddObject}
onDeleteObject={(id) => { setObjects(prev => prev.filter(o => o.id !== id)); setSelectedId(null); }}
onUpdateObject={(id, updates) => setObjects(prev => prev.map(o => o.id === id ? { ...o, ...updates } as SimObject : o))}
onUpdateAxis={(index, updates) => setAxes(prev => prev.map((a, i) => i === index ? { ...a, ...updates } : a))}
onSelect={setSelectedId}
onUpdatePortName={handleUpdatePortName}
/>
@@ -438,9 +522,20 @@ export default function App() {
onAddRule={(r) => setLogicRules(prev => [...prev, r])}
onDeleteRule={(id) => setLogicRules(prev => prev.filter(r => r.id !== id))}
onUpdateRule={(id, updates) => setLogicRules(prev => prev.map(r => r.id === id ? { ...r, ...updates } : r))}
axes={axes}
/>
)}
</div>
<SystemSetupDialog
isOpen={isSetupOpen}
onClose={() => setIsSetupOpen(false)}
inputNames={inputNames}
outputNames={outputNames}
axes={axes}
onUpdatePortName={handleUpdatePortName}
onUpdateAxis={(index, updates) => setAxes(prev => prev.map((a, i) => i === index ? { ...a, ...updates } : a))}
/>
</div>
);
}