logicgate: improvements to the circuit screen
- Commit
88e16b35198602c4169eae26192f6d0c5cc82668- Author
- Vayun Mathur <[email protected]>
- When
- 2026-07-22 22:18 UTC (4 months ago)
- Parents
63c6458
Diff
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/MainActivity.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/MainActivity.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/MainActivity.ktindex 7c48d03a54..eb8a2fbe3b 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/MainActivity.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/MainActivity.kt@@ -4,29 +4,23 @@ import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge+import androidx.compose.foundation.Canvas import androidx.compose.foundation.background-import androidx.compose.foundation.layout.Box-import androidx.compose.foundation.layout.BoxWithConstraints-import androidx.compose.foundation.layout.Column-import androidx.compose.foundation.layout.Row-import androidx.compose.foundation.layout.Spacer-import androidx.compose.foundation.layout.fillMaxHeight-import androidx.compose.foundation.layout.fillMaxSize-import androidx.compose.foundation.layout.fillMaxWidth-import androidx.compose.foundation.layout.height-import androidx.compose.foundation.layout.padding-import androidx.compose.foundation.layout.width-import androidx.compose.foundation.rememberScrollState-import androidx.compose.foundation.verticalScroll-import androidx.compose.runtime.Composable-import androidx.compose.runtime.LaunchedEffect-import androidx.compose.runtime.collectAsState-import androidx.compose.runtime.getValue+import androidx.compose.foundation.layout.*+import androidx.compose.runtime.* import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.CornerRadius+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Rect+import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.drawscope.Stroke+import androidx.compose.ui.layout.onGloballyPositioned+import androidx.compose.ui.layout.positionInRoot import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.lifecycle.viewmodel.compose.viewModel+import com.vayunmathur.games.logicgate.data.ChipLibrary import com.vayunmathur.games.logicgate.data.Levels import com.vayunmathur.games.logicgate.ui.CircuitCanvas import com.vayunmathur.games.logicgate.ui.InventoryBar@@ -66,43 +60,24 @@ class MainActivity : ComponentActivity() { @Serializable sealed interface Route : NavKey {- @Serializable- data object Progression : Route-- @Serializable- data class Game(val levelId: String) : Route-- @Serializable- data object GameCenter : Route+ @Serializable data object Progression : Route+ @Serializable data class Game(val levelId: String) : Route+ @Serializable data object GameCenter : Route } @Composable fun Navigation(viewModel: LogicViewModel) { val backStack = rememberNavBackStack<Route>(Route.Progression) val newAchievement by viewModel.achievementsManager.newAchievement.collectAsState()-- Box(Modifier.fillMaxSize()) {+ Box(modifier = Modifier.fillMaxSize()) { MainNavigation(backStack) {- entry<Route.Progression> {- ProgressionScreen(backStack, viewModel)- }- entry<Route.Game> {- GameScreen(backStack, viewModel, it.levelId)- }+ entry<Route.Progression> { ProgressionScreen(backStack, viewModel) }+ entry<Route.Game> { GameScreen(backStack, viewModel, it.levelId) } entry<Route.GameCenter> {- GameCenterScreen(- backupAgent = AppBackupAgent(),- manager = viewModel.achievementsManager,- onBack = { backStack.pop() }- )- }- }-- newAchievement?.let {- AchievementNotification(it) {- viewModel.dismissAchievement()+ GameCenterScreen(backupAgent = AppBackupAgent(), manager = viewModel.achievementsManager, onBack = { backStack.pop() }) } }+ newAchievement?.let { AchievementNotification(it) { viewModel.dismissAchievement() } } } } @@ -114,20 +89,21 @@ fun GameScreen(backStack: NavBackStack<Route>, viewModel: LogicViewModel, levelI val unlocked by viewModel.unlockedChips.collectAsState() val completed by viewModel.completedIds.collectAsState() - LaunchedEffect(levelId) {- viewModel.selectLevel(levelId)- }-+ LaunchedEffect(levelId) { viewModel.selectLevel(levelId) } val isCurrent = uiState.currentLevelId == levelId + var canvasRect by remember { mutableStateOf(Rect.Zero) }+ var draggingChipId by remember { mutableStateOf<String?>(null) }+ var draggingChipGlobal by remember { mutableStateOf(Offset.Zero) }+ Scaffold( topBar = { TopAppBar(- title = { Text("${level.displayName} ${if (levelId in completed) "✓" else ""}", fontSize = 16.sp) },+ title = { Text(text = "${level.displayName} ${if (levelId in completed) "✓" else ""}", fontSize = 16.sp) }, navigationIcon = { IconNavigation(backStack) }, actions = {- Button(onClick = { viewModel.toggleTruthTable() }, modifier = Modifier.padding(end = 4.dp)) {- Text(if (uiState.showTruthTable) "Hide TT" else "Show TT", fontSize = 11.sp)+ Row(modifier = Modifier.padding(end = 6.dp), horizontalArrangement = Arrangement.spacedBy(6.dp)) {+ Button(onClick = { viewModel.toggleTruthTable() }) { Text(text = if (uiState.showTruthTable) "Hide TT" else "Show TT", fontSize = 10.sp) } } } )@@ -137,114 +113,152 @@ fun GameScreen(backStack: NavBackStack<Route>, viewModel: LogicViewModel, levelI InventoryBar( allowed = level.allowedChipIds, unlockedChips = unlocked,- onAddGate = { viewModel.addGate(it) },+ onChipDragStart = { chipId, global ->+ draggingChipId = chipId+ draggingChipGlobal = global+ },+ onChipDrag = { chipId, global ->+ draggingChipId = chipId+ draggingChipGlobal = global+ },+ onChipDrop = { chipId, global ->+ val local = Offset(global.x - canvasRect.left, global.y - canvasRect.top)+ if (canvasRect.contains(global)) {+ // Free placement – wherever finger lifted, no grid snap+ viewModel.addGateAt(chipId, local.x, local.y)+ }+ draggingChipId = null+ draggingChipGlobal = Offset.Zero+ }, modifier = Modifier.fillMaxWidth() ) } } ) { padding -> if (!isCurrent) {- Box(- Modifier.fillMaxSize().padding(padding),- contentAlignment = androidx.compose.ui.Alignment.Center- ) {- Text("Loading...")- }+ Box(modifier = Modifier.fillMaxSize().padding(padding), contentAlignment = androidx.compose.ui.Alignment.Center) { Text(text = "Loading...") } return@Scaffold } - Column(- Modifier.fillMaxSize().padding(padding).background(Color(0xFF0B1218))- ) {- val status = uiState.evalStatus- val statusText = when (status) {- is EvalStatus.Ok -> if (status.isFullyCorrect) "✓ CORRECT"- else "${status.passingRows}/${status.totalRows} passing — ${status.failingRows.size} failing"-- is EvalStatus.Error -> "Error: ${status.msg}"- is EvalStatus.Cycle -> "Cycle: ${status.ids.take(3).joinToString()}"- else -> "Wire inputs → gates → outputs • Drag to move • Long-press to delete"+ Column(modifier = Modifier.fillMaxSize().padding(padding).background(Color(0xFF0B1218))) {+ val statusText = when (val s = uiState.evalStatus) {+ is EvalStatus.Ok -> if (s.isFullyCorrect) "✓ CORRECT — ${level.unlocksChipId?.let { "Unlocked $it!" } ?: "Done!"}"+ else "${s.passingRows}/${s.totalRows} passing — ${s.failingRows.size} failing"+ is EvalStatus.Error -> "Error: ${s.msg}"+ is EvalStatus.Cycle -> "Cycle: ${s.ids.take(3).joinToString()}"+ else -> "Drag chip onto board to place • Drag gates & I/O to move • Drag output dot → input dot to wire • Tap wire to delete • Long-press gate to delete" } val statusColor = when {- status is EvalStatus.Ok && status.isFullyCorrect -> Color(0xFF22C55E)- status is EvalStatus.Ok && status.passingRows > 0 -> Color(0xFFFBBF24)+ uiState.evalStatus is EvalStatus.Ok && (uiState.evalStatus as EvalStatus.Ok).isFullyCorrect -> Color(0xFF22C55E)+ uiState.evalStatus is EvalStatus.Ok && (uiState.evalStatus as EvalStatus.Ok).passingRows > 0 -> Color(0xFFFBBF24) else -> Color(0xFF94A3B8) } - Box(- Modifier.fillMaxWidth().background(Color(0xFF16202B))- .padding(horizontal = 12.dp, vertical = 6.dp)- ) {- Row(Modifier.fillMaxWidth(), horizontalArrangement = androidx.compose.foundation.layout.Arrangement.SpaceBetween) {- Column(Modifier.weight(1f)) {- Text(statusText, fontSize = 12.sp, color = statusColor)- Text(level.description, fontSize = 10.sp, color = Color(0xFF94A3B8))- if (level.hint.isNotEmpty()) {- Text("Hint: ${level.hint}", fontSize = 10.sp, color = Color(0xFF64748B))- }+ Box(modifier = Modifier.fillMaxWidth().background(Color(0xFF16202B)).padding(horizontal = 12.dp, vertical = 7.dp)) {+ Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {+ Column(modifier = Modifier.weight(1f)) {+ Text(text = statusText, fontSize = 11.sp, color = statusColor)+ Text(text = level.description, fontSize = 10.sp, color = Color(0xFF94A3B8))+ if (level.hint.isNotEmpty()) Text(text = "Hint: ${level.hint}", fontSize = 10.sp, color = Color(0xFF64748B)) }- Row(horizontalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(6.dp)) {- Button(onClick = { viewModel.clearCircuit() }) { Text("Clear", fontSize = 10.sp) }- if (uiState.wiringFrom != null) {- Button(onClick = { viewModel.cancelWiring() }) { Text("Cancel Wire", fontSize = 10.sp) }- }- val gateCount = uiState.circuit.gates.size- Card(modifier = Modifier.padding(start = 4.dp)) {- Text(" $gateCount gates ", fontSize = 11.sp, modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp))- }+ Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {+ Button(onClick = { viewModel.clearCircuit() }) { Text(text = "Clear", fontSize = 10.sp) }+ if (uiState.wiringFrom != null) Button(onClick = { viewModel.cancelWiring() }) { Text(text = "Cancel Wire", fontSize = 10.sp) }+ Card(modifier = Modifier.padding(start = 4.dp)) { Text(text = " ${uiState.circuit.gates.size} gates ", fontSize = 11.sp, modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp)) } } } } - BoxWithConstraints(Modifier.weight(1f).fillMaxWidth()) {+ // Canvas container – NO scroll wrapper that would steal drags. Full freeform.+ BoxWithConstraints(modifier = Modifier.weight(1f).fillMaxWidth()) { val wide = maxWidth > maxHeight- if (wide) {- Row(Modifier.fillMaxSize()) {- Box(Modifier.weight(1f).fillMaxHeight().verticalScroll(rememberScrollState())) {- CircuitCanvas(- level = level,- gates = uiState.circuit.gates,- wires = uiState.circuit.wires,- outputMaps = uiState.circuit.outputMappings,- wiringFrom = uiState.wiringFrom,- onStartWiringOutput = { viewModel.startWiring(it) },- onCompleteWiringInput = { viewModel.completeWiring(it) },- onGateDrag = { id, x, y -> viewModel.onGateMoved(id, x, y) },- onGateLongPress = { id -> viewModel.removeGate(id) },- modifier = Modifier.fillMaxWidth().height(900.dp)- )+ Box(+ modifier = Modifier.fillMaxSize().onGloballyPositioned { coords ->+ val pos = coords.positionInRoot()+ canvasRect = Rect(pos, Size(coords.size.width.toFloat(), coords.size.height.toFloat()))+ }+ ) {+ if (wide) {+ Row(modifier = Modifier.fillMaxSize()) {+ Box(modifier = Modifier.weight(1f).fillMaxHeight()) {+ CircuitCanvas(+ level = level,+ gates = uiState.circuit.gates,+ wires = uiState.circuit.wires,+ outputMaps = uiState.circuit.outputMappings,+ inputPositions = uiState.circuit.inputPositions,+ outputPositions = uiState.circuit.outputPositions,+ wiringFrom = uiState.wiringFrom,+ onCreateWire = { f, t -> viewModel.createWire(f, t) },+ onStartWiring = { viewModel.startWiring(it) },+ onCancelWiring = { viewModel.cancelWiring() },+ onGateMove = { id, x, y -> viewModel.onGateMoved(id, x, y) },+ onInputTermMove = { idx, x, y -> viewModel.onInputMoved(idx, x, y) },+ onOutputTermMove = { idx, x, y -> viewModel.onOutputMoved(idx, x, y) },+ onGateDelete = { viewModel.removeGate(it) },+ onWireDelete = { viewModel.removeWire(it) },+ onOutputMapDelete = { viewModel.removeOutputMapping(it) },+ dragGhostLineEnd = uiState.dragGhostLineEnd,+ onGhostLine = { viewModel.updateGhostLine(it) },+ modifier = Modifier.fillMaxSize()+ )+ }+ if (uiState.showTruthTable) {+ val failing = (uiState.evalStatus as? EvalStatus.Ok)?.failingRows ?: emptyList()+ TruthTableView(level, failing, modifier = Modifier.width(210.dp).fillMaxHeight().background(Color(0xFF0E141B)))+ } }- if (uiState.showTruthTable) {- val failing = (uiState.evalStatus as? EvalStatus.Ok)?.failingRows ?: emptyList()- TruthTableView(- level = level,- failingRows = failing,- modifier = Modifier.width(210.dp).fillMaxHeight().background(Color(0xFF0E141B))- )+ } else {+ Column(modifier = Modifier.fillMaxSize()) {+ if (uiState.showTruthTable) {+ val failing = (uiState.evalStatus as? EvalStatus.Ok)?.failingRows ?: emptyList()+ TruthTableView(level, failing, modifier = Modifier.fillMaxWidth().height(180.dp).background(Color(0xFF0E141B)))+ }+ Box(modifier = Modifier.weight(1f).fillMaxWidth()) {+ CircuitCanvas(+ level = level,+ gates = uiState.circuit.gates,+ wires = uiState.circuit.wires,+ outputMaps = uiState.circuit.outputMappings,+ inputPositions = uiState.circuit.inputPositions,+ outputPositions = uiState.circuit.outputPositions,+ wiringFrom = uiState.wiringFrom,+ onCreateWire = { f, t -> viewModel.createWire(f, t) },+ onStartWiring = { viewModel.startWiring(it) },+ onCancelWiring = { viewModel.cancelWiring() },+ onGateMove = { id, x, y -> viewModel.onGateMoved(id, x, y) },+ onInputTermMove = { idx, x, y -> viewModel.onInputMoved(idx, x, y) },+ onOutputTermMove = { idx, x, y -> viewModel.onOutputMoved(idx, x, y) },+ onGateDelete = { viewModel.removeGate(it) },+ onWireDelete = { viewModel.removeWire(it) },+ onOutputMapDelete = { viewModel.removeOutputMapping(it) },+ dragGhostLineEnd = uiState.dragGhostLineEnd,+ onGhostLine = { viewModel.updateGhostLine(it) },+ modifier = Modifier.fillMaxSize()+ )+ } } }- } else {- Column(Modifier.fillMaxSize()) {- if (uiState.showTruthTable) {- val failing = (uiState.evalStatus as? EvalStatus.Ok)?.failingRows ?: emptyList()- TruthTableView(- level = level,- failingRows = failing,- modifier = Modifier.fillMaxWidth().height(180.dp).background(Color(0xFF0E141B))++ if (draggingChipId != null) {+ val isOver = canvasRect.contains(draggingChipGlobal)+ val localGhost = Offset(draggingChipGlobal.x - canvasRect.left, draggingChipGlobal.y - canvasRect.top)+ Canvas(modifier = Modifier.fillMaxSize()) {+ val ghW = 116f+ val ghH = 54f+ val lt = Offset(localGhost.x - ghW / 2f, localGhost.y - ghH / 2f)+ drawRoundRect(+ color = if (isOver) Color(0xFFD1FAE5).copy(alpha = 0.92f) else Color(0xFF4B5563).copy(alpha = 0.62f),+ topLeft = lt,+ size = Size(ghW, ghH),+ cornerRadius = CornerRadius(10f, 10f) )- }- Box(Modifier.weight(1f).fillMaxWidth().verticalScroll(rememberScrollState())) {- CircuitCanvas(- level = level,- gates = uiState.circuit.gates,- wires = uiState.circuit.wires,- outputMaps = uiState.circuit.outputMappings,- wiringFrom = uiState.wiringFrom,- onStartWiringOutput = { viewModel.startWiring(it) },- onCompleteWiringInput = { viewModel.completeWiring(it) },- onGateDrag = { id, x, y -> viewModel.onGateMoved(id, x, y) },- onGateLongPress = { id -> viewModel.removeGate(id) },- modifier = Modifier.fillMaxWidth().height(900.dp)+ drawRoundRect(+ color = if (isOver) Color(0xFF22C55E) else Color.White.copy(alpha = 0.28f),+ topLeft = lt,+ size = Size(ghW, ghH),+ cornerRadius = CornerRadius(10f, 10f),+ style = Stroke(width = if (isOver) 2.5f else 1.2f) ) } }
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/CircuitModel.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/CircuitModel.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/CircuitModel.ktindex 4a5214f542..b14ebcc180 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/CircuitModel.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/CircuitModel.kt@@ -6,6 +6,7 @@ package com.vayunmathur.games.logicgate.data * - Gates: placed chips with generated unique ids * - Wires: connections from (sourceId, outputIdx) to (destId, inputIdx) * - OutputMappings: final outputs resolved+ * - Input/output terminal positions are now draggable and persisted. */ data class PlacedChip(@@ -28,10 +29,17 @@ data class OutputMapping( val from: WireEnd ) +data class IoPos(+ val x: Float,+ val y: Float+)+ data class Circuit( val gates: List<PlacedChip> = emptyList(), val wires: List<Wire> = emptyList(),- val outputMappings: List<OutputMapping> = emptyList()+ val outputMappings: List<OutputMapping> = emptyList(),+ val inputPositions: Map<Int, IoPos> = emptyMap(),+ val outputPositions: Map<Int, IoPos> = emptyMap() ) { fun totalNandCost(): Int = gates.sumOf { ChipLibrary.get(it.chipId).nandCost } }@@ -53,7 +61,6 @@ object CircuitEvaluator { /** Evaluate circuit for all input combos, but sample if inputCount > 10 to avoid explosion. */ fun evaluate(level: LevelDef, circuit: Circuit): EvalResult { val inputCount = level.inputs.size- // If circuit has structural issues we still try one combo first to surface errors fast val quickCheck = evalCombo(level, circuit, List(inputCount) { false }) if (quickCheck is ComboEval.Err) return EvalResult.Error(quickCheck.msg) if (quickCheck is ComboEval.Cycle) return EvalResult.Cycle(quickCheck.ids)@@ -61,16 +68,13 @@ object CircuitEvaluator { val combos = if (inputCount <= 10) { (0 until (1 shl inputCount)).toList() } else {- // Sample: exhaustive for low bits + random val sampleSize = 256 val rnd = java.util.Random(1234) val set = LinkedHashSet<Int>()- // include edges set.add(0); set.add((1 shl minOf(inputCount, 20)) - 1) while (set.size < sampleSize) { var v = 0 for (b in 0 until inputCount) if (rnd.nextBoolean()) v = v or (1 shl b)- // clamp if inputCount > 30 we limited loops but still sample via bits if (inputCount > 30) v = rnd.nextInt(1 shl 18) set.add(v) }@@ -91,7 +95,6 @@ object CircuitEvaluator { return EvalResult.Success(results) } - /** For full truth table comparison, generate expected rows matching the same sampled combos */ fun evaluateFullCorrectness(level: LevelDef, circuit: Circuit): Pair<Boolean, List<Int>> { val targetDef = ChipLibrary.get(level.targetChipId) val inputCount = level.inputs.size@@ -107,16 +110,11 @@ object CircuitEvaluator { while (set.size < sampleSize) { var v = 0 for (b in 0 until minOf(inputCount, 18)) if (rnd.nextBoolean()) v = v or (1 shl b)- if (inputCount > 18) {- for (b in 18 until inputCount) if (rnd.nextBoolean()) v = v or (1 shl (b % 18)) // overflow guard- // Actually re-generate full bits sampled- } set.add(v) } set.toList() } - // For large input counts we can't use combo as int for >30 bits; generate bit lists directly in sampled mode val testVectors: List<List<Boolean>> = if (inputCount <= 10) { combos.map { c -> List(inputCount) { i -> ((c shr i) and 1) == 1 } } } else {@@ -137,7 +135,7 @@ object CircuitEvaluator { for ((idx, vec) in testVectors.withIndex()) { when (val r = evalCombo(level, circuit, vec)) { is ComboEval.Ok -> actualRows.add(r.outputs)- else -> return false to listOf(idx) // structure error = incorrect+ else -> return false to listOf(idx) } } @@ -235,7 +233,6 @@ object CircuitEvaluator { target.eval(inp).take(outputCount) } } else {- // Sampled truth table for large gates val rnd = java.util.Random(42) val vectors = mutableListOf<List<Boolean>>() vectors.add(List(inputCount) { false })
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/CircuitCanvas.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/CircuitCanvas.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/CircuitCanvas.ktindex baffde16fe..94c32e5a8e 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/CircuitCanvas.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/CircuitCanvas.kt@@ -2,20 +2,17 @@ package com.vayunmathur.games.logicgate.ui import androidx.compose.foundation.Canvas import androidx.compose.foundation.background-import androidx.compose.foundation.gestures.detectDragGestures-import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.layout.fillMaxSize-import androidx.compose.runtime.Composable-import androidx.compose.runtime.getValue-import androidx.compose.runtime.mutableStateOf-import androidx.compose.runtime.remember-import androidx.compose.runtime.setValue+import androidx.compose.runtime.* import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.CornerRadius import androidx.compose.ui.geometry.Offset-import androidx.compose.ui.geometry.Size as GeomSize+import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.Path import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.graphics.drawscope.Stroke+import androidx.compose.ui.input.pointer.changedToUpIgnoreConsumed import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.drawText@@ -23,231 +20,471 @@ import androidx.compose.ui.text.rememberTextMeasurer import androidx.compose.ui.unit.sp import com.vayunmathur.games.logicgate.data.* import kotlin.math.max+import kotlin.math.min data class GateRect(val chip: PlacedChip, val left: Float, val top: Float, val width: Float, val height: Float) { fun inputPos(i: Int, count: Int): Offset {- if (count == 0) return Offset(left, top + height / 2f)+ if (count <= 1) return Offset(left, top + height / 2f) val gap = height / (count + 1) return Offset(left, top + gap * (i + 1)) } fun outputPos(i: Int, count: Int): Offset {- if (count == 0) return Offset(left + width, top + height / 2f)+ if (count <= 1) return Offset(left + width, top + height / 2f) val gap = height / (count + 1) return Offset(left + width, top + gap * (i + 1)) }- fun contains(p: Offset): Boolean = p.x in left..left + width && p.y in top..top + height+ fun bodyContains(p: Offset): Boolean = p.x in left..left + width && p.y in top..top + height } +data class IoTerminalLayout(val index: Int, val center: Offset, val name: String, val isInput: Boolean)+private enum class DragMode { None, Gate, InputTerm, OutputTerm, Wire }+private data class HitOutput(val end: WireEnd, val pos: Offset)+private data class HitInput(val end: WireEnd, val pos: Offset)+ @Composable fun CircuitCanvas( level: LevelDef, gates: List<PlacedChip>, wires: List<Wire>, outputMaps: List<OutputMapping>,+ inputPositions: Map<Int, IoPos>,+ outputPositions: Map<Int, IoPos>, wiringFrom: WireEnd?,- onStartWiringOutput: (WireEnd) -> Unit,- onCompleteWiringInput: (WireEnd) -> Unit,- onGateDrag: (String, Float, Float) -> Unit,- onGateLongPress: (String) -> Unit,+ onCreateWire: (from: WireEnd, to: WireEnd) -> Unit,+ onStartWiring: (WireEnd) -> Unit,+ onCancelWiring: () -> Unit,+ onGateMove: (id: String, x: Float, y: Float) -> Unit,+ onInputTermMove: (idx: Int, x: Float, y: Float) -> Unit,+ onOutputTermMove: (idx: Int, x: Float, y: Float) -> Unit,+ onGateDelete: (String) -> Unit,+ onWireDelete: (String) -> Unit,+ onOutputMapDelete: (Int) -> Unit,+ dragGhostLineEnd: Offset?,+ onGhostLine: (Offset?) -> Unit, modifier: Modifier = Modifier ) { val textMeasurer = rememberTextMeasurer()- val chipDefs = gates.associate { it.instanceId to ChipLibrary.get(it.chipId) }-- fun computeRects(): List<GateRect> {- return gates.map { g ->- val def = ChipLibrary.get(g.chipId)- val w = 120f- val h = max(56f, 20f * max(def.inputCount, def.outputCount) + 24f)- GateRect(g, g.x, g.y, w, h)+ fun computeRects(): List<GateRect> = gates.map { g ->+ val def = ChipLibrary.get(g.chipId)+ val w = when {+ def.inputCount > 8 || def.outputCount > 8 -> 154f+ def.inputCount > 4 || def.outputCount > 4 -> 134f+ else -> 118f }+ val h = max(54f, 19f * max(def.inputCount, def.outputCount) + 28f)+ GateRect(g, g.x, g.y, w, h) } var rects by remember(gates) { mutableStateOf(computeRects()) }- // keep in sync rects = computeRects() val rectById = rects.associateBy { it.chip.instanceId }+ val chipDefs = gates.associate { it.instanceId to ChipLibrary.get(it.chipId) } - fun inputSourcePos(idx: Int): Offset {- val spacing = 52f- return Offset(22f, 70f + idx * spacing)+ fun defaultInputPos(idx: Int) = Offset(32f, 78f + idx * 56f)+ fun defaultOutputPos(idx: Int) = Offset(920f, 78f + idx * 56f)++ val inputLayouts = level.inputs.mapIndexed { i, name ->+ val p = inputPositions[i]+ IoTerminalLayout(i, if (p != null) Offset(p.x, p.y) else defaultInputPos(i), name, true) }- fun outputSinkPos(idx: Int): Offset {- val spacing = 52f- return Offset(760f, 70f + idx * spacing)+ val outputLayouts = level.outputs.mapIndexed { i, name ->+ val p = outputPositions[i]+ IoTerminalLayout(i, if (p != null) Offset(p.x, p.y) else defaultOutputPos(i), name, false) } - fun hitOutputPin(pos: Offset): WireEnd? {- // check external inputs- for ((i, _) in level.inputs.withIndex()) {- if ((pos - inputSourcePos(i)).getDistance() < 18f) return WireEnd("__IN_$i", 0)- }- for (gr in rects) {- val def = ChipLibrary.get(gr.chip.chipId)+ val latestRects by rememberUpdatedState(rects)+ val latestInputLayouts by rememberUpdatedState(inputLayouts)+ val latestOutputLayouts by rememberUpdatedState(outputLayouts)+ val latestWires by rememberUpdatedState(wires)+ val latestOutputMaps by rememberUpdatedState(outputMaps)+ val latestWiringFrom by rememberUpdatedState(wiringFrom)+ val latestChipDefs by rememberUpdatedState(chipDefs)+ val latestRectById by rememberUpdatedState(rectById)++ val currentOnCreateWire by rememberUpdatedState(onCreateWire)+ val currentOnStartWiring by rememberUpdatedState(onStartWiring)+ val currentOnCancelWiring by rememberUpdatedState(onCancelWiring)+ val currentOnGateMove by rememberUpdatedState(onGateMove)+ val currentOnInputMove by rememberUpdatedState(onInputTermMove)+ val currentOnOutputMove by rememberUpdatedState(onOutputTermMove)+ val currentOnGateDelete by rememberUpdatedState(onGateDelete)+ val currentOnWireDelete by rememberUpdatedState(onWireDelete)+ val currentOnOutputMapDelete by rememberUpdatedState(onOutputMapDelete)+ val currentOnGhostLine by rememberUpdatedState(onGhostLine)++ var dragMode by remember { mutableStateOf(DragMode.None) }+ var draggedGateId by remember { mutableStateOf<String?>(null) }+ var wiringStart by remember { mutableStateOf<HitOutput?>(null) }++ val pinHitR = 26f+ val termMoveHitR = 44f+ val termWireDotR = 18f++ fun pillW(name: String) = 70f + name.length * 3.6f+ fun dotForInput(t: IoTerminalLayout) = Offset(t.center.x + pillW(t.name) / 2f - 10f, t.center.y)+ fun dotForOutput(t: IoTerminalLayout) = Offset(t.center.x - pillW(t.name) / 2f + 10f, t.center.y)++ fun hitOutputDot(pos: Offset): HitOutput? {+ for (t in latestInputLayouts) if ((pos - dotForInput(t)).getDistance() < termWireDotR) return HitOutput(WireEnd("__IN_${t.index}", 0), dotForInput(t))+ for (gr in latestRects) {+ val def = latestChipDefs[gr.chip.instanceId] ?: continue for (j in 0 until def.outputCount) {- if ((pos - gr.outputPos(j, def.outputCount)).getDistance() < 16f) {- return WireEnd(gr.chip.instanceId, j)- }+ val pp = gr.outputPos(j, def.outputCount)+ if ((pos - pp).getDistance() < pinHitR) return HitOutput(WireEnd(gr.chip.instanceId, j), pp) } } return null }-- fun hitInputPin(pos: Offset): WireEnd? {- for (gr in rects) {- val def = ChipLibrary.get(gr.chip.chipId)+ fun hitInputDot(pos: Offset): HitInput? {+ for (gr in latestRects) {+ val def = latestChipDefs[gr.chip.instanceId] ?: continue for (j in 0 until def.inputCount) {- if ((pos - gr.inputPos(j, def.inputCount)).getDistance() < 16f) {- return WireEnd(gr.chip.instanceId, j)- }+ val pp = gr.inputPos(j, def.inputCount)+ if ((pos - pp).getDistance() < pinHitR) return HitInput(WireEnd(gr.chip.instanceId, j), pp) } }- for ((i, _) in level.outputs.withIndex()) {- if ((pos - outputSinkPos(i)).getDistance() < 18f) return WireEnd("__OUT_$i", 0)- }+ for (t in latestOutputLayouts) if ((pos - dotForOutput(t)).getDistance() < termWireDotR) return HitInput(WireEnd("__OUT_${t.index}", 0), dotForOutput(t)) return null }+ fun hitGateBody(pos: Offset): PlacedChip? = latestRects.reversed().firstOrNull { it.bodyContains(pos) }?.chip+ fun hitInputTermMove(pos: Offset): IoTerminalLayout? = latestInputLayouts.firstOrNull { (pos - it.center).getDistance() < termMoveHitR }+ fun hitOutputTermMove(pos: Offset): IoTerminalLayout? = latestOutputLayouts.firstOrNull { (pos - it.center).getDistance() < termMoveHitR } - fun hitGate(pos: Offset): PlacedChip? {- for (gr in rects.reversed()) if (gr.contains(pos)) return gr.chip- return null+ fun resolveSource(end: WireEnd): Offset? {+ if (end.instanceId.startsWith("__IN_")) {+ val idx = end.instanceId.removePrefix("__IN_").toIntOrNull() ?: return null+ return latestInputLayouts.find { it.index == idx }?.let { dotForInput(it) }+ }+ val gr = latestRectById[end.instanceId] ?: return null+ val def = latestChipDefs[end.instanceId] ?: return null+ return gr.outputPos(end.pinIndex.coerceIn(0, max(0, def.outputCount - 1)), def.outputCount)+ }+ fun resolveSink(end: WireEnd): Offset? {+ if (end.instanceId.startsWith("__OUT_")) {+ val idx = end.instanceId.removePrefix("__OUT_").toIntOrNull() ?: return null+ return latestOutputLayouts.find { it.index == idx }?.let { dotForOutput(it) }+ }+ val gr = latestRectById[end.instanceId] ?: return null+ val def = latestChipDefs[end.instanceId] ?: return null+ return gr.inputPos(end.pinIndex.coerceIn(0, max(0, def.inputCount - 1)), def.inputCount)+ }+ fun findClosestWire(pos: Offset): Wire? {+ var best: Wire? = null+ var bestD = 28f+ for (w in latestWires) {+ val a = resolveSource(w.from) ?: continue+ val b = resolveSink(w.to) ?: continue+ val d = distPointToBezier(pos, a, b)+ if (d < bestD) { bestD = d; best = w }+ }+ return best+ }+ fun findClosestOutputMap(pos: Offset): OutputMapping? {+ var best: OutputMapping? = null+ var bestD = 28f+ for (om in latestOutputMaps) {+ val a = resolveSource(om.from) ?: continue+ val b = latestOutputLayouts.find { it.index == om.outputIndex }?.let { dotForOutput(it) } ?: continue+ val d = distPointToBezier(pos, a, b)+ if (d < bestD) { bestD = d; best = om }+ }+ return best } Canvas( modifier = modifier .fillMaxSize()- .background(Color(0xFF101820))- .pointerInput(rects, wiringFrom) {- detectTapGestures(- onTap = { tapPos ->- if (wiringFrom != null) {- val dest = hitInputPin(tapPos)- if (dest != null) {- onCompleteWiringInput(dest)+ .background(Color(0xFF0C141D))+ .pointerInput(Unit) {+ awaitPointerEventScope {+ while (true) {+ val down = awaitFirstDown(requireUnconsumed = false)+ val downPos = down.position+ var currentPos = downPos+ var totalDrag = Offset.Zero+ var isDragStarted = false+ var mode = DragMode.None+ var gateId: String? = null+ var gateStartLeft = 0f+ var gateStartTop = 0f+ var inputIdx: Int? = null+ var outputIdx: Int? = null+ var inputStart = Offset.Zero+ var outputStart = Offset.Zero+ var wireStart: HitOutput? = null++ // At down, check what's underneath – dot hits take priority for wiring+ val outDotAtDown = hitOutputDot(downPos)+ val inDotAtDown = hitInputDot(downPos)+ val gateAtDown = if (outDotAtDown == null && inDotAtDown == null) hitGateBody(downPos) else null+ val inTermMoveAtDown = if (outDotAtDown == null && gateAtDown == null) hitInputTermMove(downPos) else null+ val outTermMoveAtDown = if (outDotAtDown == null && gateAtDown == null && inTermMoveAtDown == null) hitOutputTermMove(downPos) else null+ val downTime = System.currentTimeMillis()+ var longPressHandled = false++ while (true) {+ val event = awaitPointerEvent()+ val main = event.changes.firstOrNull { it.id == down.id } ?: break+ if (main.changedToUpIgnoreConsumed()) {+ if (!isDragStarted && !longPressHandled) {+ // Tap handling+ if (latestWiringFrom != null || wiringStart != null) {+ val dst = hitInputDot(main.position)+ if (dst != null) {+ val from = latestWiringFrom ?: wiringStart?.end+ if (from != null && from.instanceId != dst.end.instanceId) currentOnCreateWire(from, dst.end)+ }+ currentOnCancelWiring()+ wiringStart = null+ dragMode = DragMode.None+ currentOnGhostLine(null)+ } else {+ val outHit = hitOutputDot(main.position)+ if (outHit != null) {+ wiringStart = outHit+ dragMode = DragMode.Wire+ currentOnStartWiring(outHit.end)+ currentOnGhostLine(outHit.pos)+ } else {+ val wire = findClosestWire(main.position)+ if (wire != null) currentOnWireDelete(wire.id)+ else {+ val om = findClosestOutputMap(main.position)+ if (om != null) currentOnOutputMapDelete(om.outputIndex)+ }+ }+ }+ } else if (isDragStarted && mode == DragMode.Wire) {+ val dst = hitInputDot(currentPos)+ if (dst != null && wireStart != null) {+ val from = wireStart.end+ if (from.instanceId != dst.end.instanceId) currentOnCreateWire(from, dst.end)+ }+ currentOnGhostLine(null)+ currentOnCancelWiring()+ wiringStart = null+ dragMode = DragMode.None+ draggedGateId = null+ } else if (isDragStarted) {+ dragMode = DragMode.None+ draggedGateId = null+ }+ break }- } else {- val src = hitOutputPin(tapPos)- if (src != null) onStartWiringOutput(src)++ if (longPressHandled) continue+ val pos = main.position+ totalDrag = pos - downPos++ if (!isDragStarted) {+ val elapsed = System.currentTimeMillis() - downTime+ if (elapsed > 460 && totalDrag.getDistance() < 14f) {+ if (gateAtDown != null) currentOnGateDelete(gateAtDown.instanceId)+ longPressHandled = true+ break+ }+ if (totalDrag.getDistance() > 14f) {+ isDragStarted = true+ when {+ outDotAtDown != null -> {+ mode = DragMode.Wire+ wireStart = outDotAtDown+ wiringStart = outDotAtDown+ dragMode = DragMode.Wire+ currentOnStartWiring(outDotAtDown.end)+ currentOnGhostLine(outDotAtDown.pos)+ }+ inTermMoveAtDown != null -> {+ mode = DragMode.InputTerm+ inputIdx = inTermMoveAtDown.index+ inputStart = inTermMoveAtDown.center+ dragMode = DragMode.InputTerm+ }+ outTermMoveAtDown != null -> {+ mode = DragMode.OutputTerm+ outputIdx = outTermMoveAtDown.index+ outputStart = outTermMoveAtDown.center+ dragMode = DragMode.OutputTerm+ }+ gateAtDown != null -> {+ mode = DragMode.Gate+ gateId = gateAtDown.instanceId+ val gr = latestRects.find { it.chip.instanceId == gateId }+ if (gr != null) {+ gateStartLeft = gr.left+ gateStartTop = gr.top+ }+ draggedGateId = gateAtDown.instanceId+ dragMode = DragMode.Gate+ }+ else -> mode = DragMode.None+ }+ }+ }++ if (isDragStarted) {+ when (mode) {+ DragMode.Gate -> {+ val gid = gateId ?: continue+ // Free placement anywhere – no grid, no clamp+ currentOnGateMove(gid, gateStartLeft + totalDrag.x, gateStartTop + totalDrag.y)+ }+ DragMode.InputTerm -> {+ val idx = inputIdx ?: continue+ currentOnInputMove(idx, inputStart.x + totalDrag.x, inputStart.y + totalDrag.y)+ }+ DragMode.OutputTerm -> {+ val idx = outputIdx ?: continue+ currentOnOutputMove(idx, outputStart.x + totalDrag.x, outputStart.y + totalDrag.y)+ }+ DragMode.Wire -> currentOnGhostLine(pos)+ DragMode.None -> {}+ }+ }+ currentPos = pos }- },- onLongPress = { lp ->- hitGate(lp)?.let { onGateLongPress(it.instanceId) }- }- )- }- .pointerInput(rects) {- detectDragGestures(- onDragStart = { /* handled below via move */ },- onDrag = { change, dragAmount ->- change.consume()- val gate = hitGate(change.position - dragAmount) ?: hitGate(change.position)- if (gate != null) {- val cur = rectById[gate.instanceId] ?: return@detectDragGestures- val nx = (cur.left + dragAmount.x).coerceIn(0f, 820f - cur.width)- val ny = (cur.top + dragAmount.y).coerceIn(0f, 1600f - cur.height)- onGateDrag(gate.instanceId, nx, ny)++ if (dragMode == DragMode.Gate || dragMode == DragMode.InputTerm || dragMode == DragMode.OutputTerm) {+ draggedGateId = null+ dragMode = DragMode.None } }- )+ } } ) {- // grid- val step = 22f- var x = 0f- while (x < size.width) {- var y = 0f- while (y < size.height) {- drawCircle(Color.White.copy(alpha = 0.05f), 0.9f, Offset(x, y))- y += step- }- x += step- }-- // helper resolvers- fun resolveSource(end: WireEnd): Offset? {- if (end.instanceId.startsWith("__IN_")) {- val idx = end.instanceId.removePrefix("__IN_").toIntOrNull() ?: return null- return inputSourcePos(idx)- }- val gr = rectById[end.instanceId] ?: return null- val def = chipDefs[end.instanceId] ?: return null- return gr.outputPos(end.pinIndex.coerceIn(0, max(0, def.outputCount - 1)), def.outputCount)- }- fun resolveSink(end: WireEnd): Offset? {- if (end.instanceId.startsWith("__OUT_")) {- val idx = end.instanceId.removePrefix("__OUT_").toIntOrNull() ?: return null- return outputSinkPos(idx)- }- val gr = rectById[end.instanceId] ?: return null- val def = chipDefs[end.instanceId] ?: return null- return gr.inputPos(end.pinIndex.coerceIn(0, max(0, def.inputCount - 1)), def.inputCount)- }-- // wires+ // No grid per user request – plain background+ drawRect(Color(0xFF0C141D)) for (w in wires) {- val from = resolveSource(w.from) ?: continue- val to = resolveSink(w.to) ?: continue- drawWire(from, to, Color(0xFF7ED8B6))+ val a = resolveSource(w.from) ?: continue+ val b = resolveSink(w.to) ?: continue+ drawWire(a, b, Color(0xFF7ED8B6), false) } for (om in outputMaps) {- val from = resolveSource(om.from) ?: continue- val to = outputSinkPos(om.outputIndex)- drawWire(from, to, Color(0xFFFDE68A))+ val a = resolveSource(om.from) ?: continue+ val b = outputLayouts.find { it.index == om.outputIndex }?.let { dotForOutput(it) } ?: continue+ drawWire(a, b, Color(0xFFFDE68A), false, outToFinal = true) }-- // input nodes- for ((i, name) in level.inputs.withIndex()) {- val p = inputSourcePos(i)- val isActive = wiringFrom?.instanceId == "__IN_$i"- drawCircle(if (isActive) Color.Yellow else Color(0xFF38BDF8), 11f, p)- drawCircle(Color.Black, 4f, p)- drawText(textMeasurer, text = name, topLeft = p + Offset(16f, -8f), style = TextStyle(Color.White, 12.sp))+ val ghostStart = wiringStart?.pos ?: wiringFrom?.let { resolveSource(it) }+ val ghostEnd = dragGhostLineEnd+ if (ghostStart != null && ghostEnd != null) {+ val overValid = hitInputDot(ghostEnd) != null+ drawWire(ghostStart, ghostEnd, if (overValid) Color(0xFFFFFF00) else Color(0x66FFFFFF), true, dash = true)+ } else if (wiringFrom != null) {+ resolveSource(wiringFrom)?.let { drawCircle(Color.Yellow.copy(alpha = 0.30f), 24f, it) } }- for ((i, name) in level.outputs.withIndex()) {- val p = outputSinkPos(i)- drawCircle(Color(0xFFF87171), 11f, p)- drawCircle(Color.Black, 4f, p)- drawText(textMeasurer, text = name, topLeft = p + Offset(-48f - name.length * 2, -8f), style = TextStyle(Color.White, 12.sp))+ for (t in inputLayouts) {+ val isSrc = wiringFrom?.instanceId == "__IN_${t.index}" || wiringStart?.end?.instanceId == "__IN_${t.index}"+ drawTerminalPill(t.center, t.name, if (isSrc) Color(0xFF3A3110) else Color(0xFF17283A), if (isSrc) Color.Yellow else Color(0xFF38BDF8), true, isSrc, textMeasurer)+ }+ for (t in outputLayouts) {+ val isTargeting = dragGhostLineEnd?.let { (it - dotForOutput(t)).getDistance() < termWireDotR + 8f } ?: false+ drawTerminalPill(t.center, t.name, if (isTargeting) Color(0xFF3A1E1E) else Color(0xFF221515), if (isTargeting) Color.Yellow else Color(0xFFF87171), false, isTargeting, textMeasurer) }-- // gates for (gr in rects) {- val def = ChipLibrary.get(gr.chip.chipId)- val boxColor = when (def.category) {+ val def = chipDefs[gr.chip.instanceId] ?: continue+ val isDragged = draggedGateId == gr.chip.instanceId+ val base = when (def.category) { ChipCategory.PRIMITIVE -> Color(0xFF1E3A4A)- ChipCategory.FOUNDATION -> Color(0xFF2A9D8F)- ChipCategory.ROUTING -> Color(0xFFE9C46A)- ChipCategory.ARITH -> Color(0xFFF4A261)- ChipCategory.MEMORY -> Color(0xFF9A7DFF)- ChipCategory.CPU -> Color(0xFFFF4D6D)+ ChipCategory.FOUNDATION -> Color(0xFF1C5A55)+ ChipCategory.ROUTING -> Color(0xFF7A5E1E)+ ChipCategory.ARITH -> Color(0xFF8A4A26)+ ChipCategory.MEMORY -> Color(0xFF4A2E7A)+ ChipCategory.CPU -> Color(0xFF8A2038) }- drawRect(boxColor, Offset(gr.left, gr.top), GeomSize(gr.width, gr.height))- drawRect(Color.White.copy(alpha = 0.25f), Offset(gr.left, gr.top), GeomSize(gr.width, gr.height), style = Stroke(1f))- drawText(textMeasurer, text = def.displayName, topLeft = Offset(gr.left + 6f, gr.top + 4f), style = TextStyle(if (def.category == ChipCategory.ROUTING) Color.Black else Color.White, 11.sp))- drawText(textMeasurer, text = "${def.nandCost}N", topLeft = Offset(gr.left + gr.width - 28f, gr.top + 4f), style = TextStyle(Color.White.copy(alpha = 0.7f), 9.sp))-+ val corner = 12f+ drawRoundRect(Color.Black.copy(alpha = 0.32f), Offset(gr.left + 2f, gr.top + 5f), Size(gr.width, gr.height), CornerRadius(corner, corner))+ drawRoundRect(if (isDragged) base.copy(alpha = 0.98f) else base, Offset(gr.left, gr.top), Size(gr.width, gr.height), CornerRadius(corner, corner))+ drawRoundRect(if (isDragged) Color.White else Color.White.copy(alpha = 0.16f), Offset(gr.left, gr.top), Size(gr.width, gr.height), CornerRadius(corner, corner), style = Stroke(width = if (isDragged) 2.4f else 1f))+ drawRoundRect(Color.White.copy(alpha = 0.06f), Offset(gr.left, gr.top), Size(gr.width, 16f), CornerRadius(corner, corner))+ drawText(textMeasurer, def.displayName, Offset(gr.left + 9f, gr.top + 7f), TextStyle(if (def.category == ChipCategory.ROUTING) Color(0xFFFFE8A0) else Color.White, 11.sp))+ drawText(textMeasurer, "${def.nandCost}N", Offset(gr.left + gr.width - 30f, gr.top + 7f), TextStyle(Color.White.copy(alpha = 0.52f), 9.sp)) for (j in 0 until def.inputCount) { val pp = gr.inputPos(j, def.inputCount)- drawCircle(Color.White, 5.5f, pp)- val lbl = def.inputs[j]- drawText(textMeasurer, text = lbl, topLeft = pp + Offset(8f, -6f), style = TextStyle(Color.White.copy(alpha = 0.8f), 8.sp))+ val hov = dragGhostLineEnd?.let { (it - pp).getDistance() < pinHitR } ?: false+ drawCircle(Color.Black.copy(alpha = 0.55f), 7.5f, pp + Offset(0f, 1f))+ drawCircle(if (hov) Color.Yellow else Color.White, 6.2f, pp)+ drawCircle(if (hov) Color.Yellow else Color(0xFF94A3B8), 2.3f, pp)+ if (def.inputCount <= 6) drawText(textMeasurer, def.inputs[j], pp + Offset(10f, -6f), TextStyle(Color.White.copy(alpha = 0.82f), 8.sp)) } for (j in 0 until def.outputCount) { val pp = gr.outputPos(j, def.outputCount)- val isSrc = wiringFrom?.instanceId == gr.chip.instanceId && wiringFrom.pinIndex == j- drawCircle(if (isSrc) Color.Yellow else Color(0xFFA7F3D0), 5.5f, pp)- val lbl = def.outputs[j]- drawText(textMeasurer, text = lbl, topLeft = pp + Offset(-22f, -6f), style = TextStyle(Color.White.copy(alpha = 0.8f), 8.sp))+ val isSrc = (wiringFrom?.instanceId == gr.chip.instanceId && wiringFrom.pinIndex == j) || (wiringStart?.end?.instanceId == gr.chip.instanceId && wiringStart?.end?.pinIndex == j)+ drawCircle(Color.Black.copy(alpha = 0.55f), 7.5f, pp + Offset(0f, 1f))+ drawCircle(if (isSrc) Color.Yellow else Color(0xFFA7F3D0), 6.8f, pp)+ drawCircle(if (isSrc) Color.Yellow else Color(0xFF22C55E), 2.8f, pp)+ if (isSrc) drawCircle(Color.Yellow.copy(alpha = 0.22f), 16f, pp)+ if (def.outputCount <= 6) {+ val lbl = def.outputs[j]+ drawText(textMeasurer, lbl, pp + Offset(-12f - lbl.length * 5.3f, -6f), TextStyle(Color.White.copy(alpha = 0.82f), 8.sp))+ } } } } } -private fun DrawScope.drawWire(from: Offset, to: Offset, color: Color) {- val midX = (from.x + to.x) * 0.5f- drawLine(color, from, Offset(midX, from.y), strokeWidth = 2.8f)- drawLine(color, Offset(midX, from.y), Offset(midX, to.y), strokeWidth = 2.8f)- drawLine(color, Offset(midX, to.y), to, strokeWidth = 2.8f)- // arrow endpoint- drawCircle(color, 3f, to)+private fun DrawScope.drawTerminalPill(center: Offset, name: String, bg: Color, border: Color, isInput: Boolean, highlight: Boolean, textMeasurer: androidx.compose.ui.text.TextMeasurer) {+ val w = 70f + name.length * 3.6f+ val h = 30f+ val lt = Offset(center.x - w / 2f, center.y - h / 2f)+ drawRoundRect(bg, lt, Size(w, h), CornerRadius(h / 2f, h / 2f))+ drawRoundRect(border, lt, Size(w, h), CornerRadius(h / 2f, h / 2f), style = Stroke(width = if (highlight) 2.3f else 1.2f))+ val dot = if (isInput) Offset(lt.x + w - 10f, center.y) else Offset(lt.x + 10f, center.y)+ val dotCol = if (isInput) Color(0xFF38BDF8) else Color(0xFFF87171)+ drawCircle(Color.Black.copy(alpha = 0.55f), 7f, dot + Offset(0f, 1f))+ drawCircle(if (highlight) Color.Yellow else dotCol, 6f, dot)+ val txtX = if (isInput) lt.x + 10f else lt.x + 22f+ drawText(textMeasurer, name, Offset(txtX, center.y - 7.5f), TextStyle(Color.White, 10.5.sp))+ if (highlight) drawCircle(Color.Yellow.copy(alpha = 0.18f), 28f, center)+}++private fun DrawScope.drawWire(from: Offset, to: Offset, color: Color, isSelected: Boolean, dash: Boolean = false, outToFinal: Boolean = false) {+ val dx = to.x - from.x+ val ctrl = min(180f, max(50f, kotlin.math.abs(dx) * 0.58f))+ val path = Path().apply {+ moveTo(from.x, from.y)+ cubicTo(from.x + ctrl, from.y, to.x - ctrl, to.y, to.x, to.y)+ }+ if (isSelected || color.alpha > 0.5f) drawPath(path, color.copy(alpha = 0.16f), style = Stroke(width = 8f))+ drawPath(path, color, style = Stroke(width = if (isSelected) 3.4f else 2.7f))+ drawCircle(color, 3.6f, to)+ drawCircle(Color.Black.copy(alpha = 0.7f), 1.3f, to)+}++private fun distPointToSegment(p: Offset, a: Offset, b: Offset): Float {+ val ap = p - a+ val ab = b - a+ val ab2 = ab.x * ab.x + ab.y * ab.y+ if (ab2 == 0f) return (p - a).getDistance()+ var t = (ap.x * ab.x + ap.y * ab.y) / ab2+ t = t.coerceIn(0f, 1f)+ val proj = Offset(a.x + ab.x * t, a.y + ab.y * t)+ return (p - proj).getDistance()+}+private fun distPointToBezier(p: Offset, from: Offset, to: Offset): Float {+ val dx = to.x - from.x+ val ctrl = min(180f, max(50f, kotlin.math.abs(dx) * 0.58f))+ var best = Float.MAX_VALUE+ var prev = from+ val steps = 18+ for (i in 1..steps) {+ val t = i / steps.toFloat()+ val mt = 1 - t+ val x = mt * mt * mt * from.x + 3 * mt * mt * t * (from.x + ctrl) + 3 * mt * t * t * (to.x - ctrl) + t * t * t * to.x+ val y = mt * mt * mt * from.y + 3 * mt * mt * t * from.y + 3 * mt * t * t * to.y + t * t * t * to.y+ val cur = Offset(x, y)+ val d = distPointToSegment(p, prev, cur)+ if (d < best) best = d+ prev = cur+ if (best < 2f) return best+ }+ return best+}+private suspend fun androidx.compose.ui.input.pointer.AwaitPointerEventScope.awaitFirstDown(requireUnconsumed: Boolean = true): androidx.compose.ui.input.pointer.PointerInputChange {+ while (true) {+ val event = awaitPointerEvent()+ if (event.type == androidx.compose.ui.input.pointer.PointerEventType.Press) {+ val down = event.changes.firstOrNull { if (requireUnconsumed) !it.isConsumed else true } ?: continue+ return down+ }+ } }
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/Screens.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/Screens.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/Screens.ktindex d8000d0020..5bf30d7102 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/Screens.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/Screens.kt@@ -4,26 +4,27 @@ import androidx.compose.foundation.Canvas import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable+import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.*-import androidx.compose.foundation.lazy.LazyRow-import androidx.compose.foundation.lazy.items import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll-import androidx.compose.runtime.Composable-import androidx.compose.runtime.collectAsState-import androidx.compose.runtime.getValue+import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color+import androidx.compose.ui.input.pointer.changedToUpIgnoreConsumed+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.layout.onGloballyPositioned+import androidx.compose.ui.layout.positionInRoot+import androidx.compose.ui.res.painterResource+import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp-import androidx.compose.ui.res.painterResource-import androidx.compose.ui.text.font.FontWeight import com.vayunmathur.games.logicgate.data.ChapterId import com.vayunmathur.games.logicgate.data.ChipCategory import com.vayunmathur.games.logicgate.data.ChipLibrary@@ -37,9 +38,10 @@ import com.vayunmathur.library.ui.Icon import com.vayunmathur.library.ui.IconButton import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.Scaffold-import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.Text as LibText import com.vayunmathur.library.ui.TopAppBar import com.vayunmathur.library.util.NavBackStack+import kotlin.math.hypot import kotlin.math.min private sealed class TimelineItem {@@ -72,146 +74,64 @@ fun ProgressionScreen( val completed by viewModel.completedIds.collectAsState() val available = Levels.availableLevels(completed) val timelineItems = buildTimelineItems()- Scaffold( topBar = { TopAppBar(- title = { Text("Logic Gate", fontWeight = FontWeight.Bold) },+ title = { LibText(text = "Logic Gate", fontWeight = FontWeight.Bold) }, actions = { IconButton(onClick = { backStack.add(com.vayunmathur.games.logicgate.Route.GameCenter) }) {- Icon(- painterResource(id = android.R.drawable.btn_star_big_on),- contentDescription = "Achievements"- )+ Icon(painterResource(id = android.R.drawable.btn_star_big_on), contentDescription = "Achievements") } } ) } ) { paddingValues ->- BoxWithConstraints(- modifier = Modifier- .fillMaxSize()- .padding(paddingValues)- .background(MaterialTheme.colorScheme.background)- ) {+ BoxWithConstraints(modifier = Modifier.fillMaxSize().padding(paddingValues).background(MaterialTheme.colorScheme.background)) { val sideOffset: Dp = 88.dp val nodeSize: Dp = 68.dp val connectorH: Dp = 38.dp val chapterH: Dp = 58.dp val scroll = rememberScrollState()-- Column(- modifier = Modifier- .fillMaxSize()- .verticalScroll(scroll),- horizontalAlignment = Alignment.CenterHorizontally- ) {- Spacer(Modifier.height(12.dp))- Text(- "Start with NAND. End with a computer.",- style = MaterialTheme.typography.bodySmall,- color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.7f),- modifier = Modifier.padding(horizontal = 16.dp)- )- Spacer(Modifier.height(4.dp))- Text(- "Tap to play • Locked levels need prerequisites • Lines show dependencies",- style = MaterialTheme.typography.labelSmall,- color = Color(0xFF94A3B8),- modifier = Modifier.padding(horizontal = 16.dp)- )- Spacer(Modifier.height(16.dp))-+ Column(modifier = Modifier.fillMaxSize().verticalScroll(scroll), horizontalAlignment = Alignment.CenterHorizontally) {+ Spacer(modifier = Modifier.height(12.dp))+ LibText(text = "Start with NAND. End with a computer.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.7f), modifier = Modifier.padding(horizontal = 16.dp))+ Spacer(modifier = Modifier.height(4.dp))+ LibText(text = "Tap to play • Lines show dependencies", style = MaterialTheme.typography.labelSmall, color = Color(0xFF94A3B8), modifier = Modifier.padding(horizontal = 16.dp))+ Spacer(modifier = Modifier.height(16.dp)) for (idx in timelineItems.indices) { val item = timelineItems[idx] when (item) { is TimelineItem.ChapterHeader -> { if (idx > 0) { val prev = timelineItems[idx - 1]- if (prev is TimelineItem.LevelRow) {- MergeIntoChapterConnector(- fromRow = prev,- sideOffset = sideOffset,- height = connectorH,- completed = completed- )- }+ if (prev is TimelineItem.LevelRow) MergeIntoChapterConnector(prev, sideOffset, connectorH, completed) }-- ChapterDivider(- chapterId = item.chapterId,- completedCount = Levels.chapters.find { it.id == item.chapterId }?.levelIds?.count { it in completed } ?: 0,- totalCount = Levels.chapters.find { it.id == item.chapterId }?.levelIds?.size ?: 0,- modifier = Modifier- .fillMaxWidth()- .height(chapterH)- .padding(horizontal = 12.dp)- )-+ ChapterDivider(item.chapterId, Levels.chapters.find { it.id == item.chapterId }?.levelIds?.count { it in completed } ?: 0, Levels.chapters.find { it.id == item.chapterId }?.levelIds?.size ?: 0, Modifier.fillMaxWidth().height(chapterH).padding(horizontal = 12.dp)) if (idx + 1 < timelineItems.size) { val next = timelineItems[idx + 1]- if (next is TimelineItem.LevelRow) {- BranchOutOfChapterConnector(- toRow = next,- sideOffset = sideOffset,- height = connectorH,- completed = completed- )- }+ if (next is TimelineItem.LevelRow) BranchOutOfChapterConnector(next, sideOffset, connectorH, completed) } }- is TimelineItem.LevelRow -> {- LevelRowContent(- row = item,- completed = completed,- available = available,- nodeSize = nodeSize,- onClickLevel = { lvlId ->- if (lvlId in completed || lvlId in available) {- backStack.add(com.vayunmathur.games.logicgate.Route.Game(lvlId))- }- }- )-+ LevelRowContent(item, completed, available, nodeSize) { lvlId ->+ if (lvlId in completed || lvlId in available) backStack.add(com.vayunmathur.games.logicgate.Route.Game(lvlId))+ } if (idx + 1 < timelineItems.size) { val next = timelineItems[idx + 1]- if (next is TimelineItem.LevelRow) {- RowToRowConnector(- fromRow = item,- toRow = next,- sideOffset = sideOffset,- height = connectorH,- completed = completed- )- }+ if (next is TimelineItem.LevelRow) RowToRowConnector(item, next, sideOffset, connectorH, completed) } } } }-- Spacer(Modifier.height(24.dp))- Card(- modifier = Modifier- .fillMaxWidth()- .padding(horizontal = 16.dp)- ) {- Column(Modifier.padding(16.dp), horizontalAlignment = Alignment.CenterHorizontally) {- Text(- "${completed.size} / ${Levels.all.size} completed",- style = MaterialTheme.typography.titleMedium,- fontWeight = FontWeight.Bold,- color = Color(0xFF7FD8BE)- )- Spacer(Modifier.height(8.dp))- Text(- "Progress is gated by prerequisites. At most 2 paths are open at once (NOR/XNOR, DMUX/MUX4, FULL_ADDER/ADDER_4). Each chapter starts with a thick bar.",- style = MaterialTheme.typography.bodySmall,- color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f)- )+ Spacer(modifier = Modifier.height(24.dp))+ Card(modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp)) {+ Column(modifier = Modifier.padding(16.dp), horizontalAlignment = Alignment.CenterHorizontally) {+ LibText(text = "${completed.size} / ${Levels.all.size} completed", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold, color = Color(0xFF7FD8BE))+ Spacer(modifier = Modifier.height(8.dp))+ LibText(text = "Progress is gated by prerequisites. At most 2 paths are open at once. Each chapter starts with a thick bar.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f)) } }- Spacer(Modifier.height(32.dp))+ Spacer(modifier = Modifier.height(32.dp)) } } }@@ -221,261 +141,102 @@ fun ProgressionScreen( private fun ChapterDivider(chapterId: ChapterId, completedCount: Int, totalCount: Int, modifier: Modifier = Modifier) { val chapter = Levels.chapters.find { it.id == chapterId } ?: return Column(modifier = modifier, verticalArrangement = Arrangement.Center) {- Box(- modifier = Modifier- .fillMaxWidth()- .height(10.dp)- .clip(RoundedCornerShape(6.dp))- .background(Color(0xFF7FD8BE).copy(alpha = 0.95f))- )- Spacer(Modifier.height(6.dp))- Row(- Modifier.fillMaxWidth(),- horizontalArrangement = Arrangement.SpaceBetween,- verticalAlignment = Alignment.CenterVertically- ) {- Text(- "${chapter.name.uppercase()} — ${chapter.desc}",- fontSize = 13.sp,- fontWeight = FontWeight.ExtraBold,- letterSpacing = 0.8.sp,- color = Color(0xFF7FD8BE),- modifier = Modifier.padding(start = 4.dp)- )- Text(- "$completedCount/$totalCount",- fontSize = 11.sp,- fontWeight = FontWeight.Bold,- color = Color(0xFF94A3B8)- )+ Box(modifier = Modifier.fillMaxWidth().height(10.dp).clip(RoundedCornerShape(6.dp)).background(Color(0xFF7FD8BE).copy(alpha = 0.95f)))+ Spacer(modifier = Modifier.height(6.dp))+ Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {+ LibText(text = "${chapter.name.uppercase()} — ${chapter.desc}", fontSize = 13.sp, fontWeight = FontWeight.ExtraBold, letterSpacing = 0.8.sp, color = Color(0xFF7FD8BE), modifier = Modifier.padding(start = 4.dp))+ LibText(text = "$completedCount/$totalCount", fontSize = 11.sp, fontWeight = FontWeight.Bold, color = Color(0xFF94A3B8)) } } } @Composable-private fun LevelRowContent(- row: TimelineItem.LevelRow,- completed: Set<String>,- available: Set<String>,- nodeSize: Dp,- onClickLevel: (String) -> Unit-) {- Row(- modifier = Modifier- .fillMaxWidth()- .height(110.dp),- horizontalArrangement = Arrangement.Center,- verticalAlignment = Alignment.CenterVertically- ) {- if (row.levelIds.size == 1) {- LevelNode(- levelId = row.levelIds[0],- isCompleted = row.levelIds[0] in completed,- isAvailable = row.levelIds[0] in available,- size = nodeSize,- onClick = onClickLevel- )- } else {- row.levelIds.forEachIndexed { idx, lvlId ->- LevelNode(- levelId = lvlId,- isCompleted = lvlId in completed,- isAvailable = lvlId in available,- size = nodeSize,- onClick = onClickLevel- )- if (idx == 0) Spacer(Modifier.width(56.dp))- }+private fun LevelRowContent(row: TimelineItem.LevelRow, completed: Set<String>, available: Set<String>, nodeSize: Dp, onClickLevel: (String) -> Unit) {+ Row(modifier = Modifier.fillMaxWidth().height(110.dp), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically) {+ if (row.levelIds.size == 1) LevelNode(row.levelIds[0], row.levelIds[0] in completed, row.levelIds[0] in available, nodeSize, onClickLevel)+ else row.levelIds.forEachIndexed { idx, lvlId ->+ LevelNode(lvlId, lvlId in completed, lvlId in available, nodeSize, onClickLevel)+ if (idx == 0) Spacer(modifier = Modifier.width(56.dp)) } } } @Composable-private fun LevelNode(- levelId: String,- isCompleted: Boolean,- isAvailable: Boolean,- size: Dp,- onClick: (String) -> Unit-) {+private fun LevelNode(levelId: String, isCompleted: Boolean, isAvailable: Boolean, size: Dp, onClick: (String) -> Unit) { val def = Levels.byId[levelId] ?: return val isLocked = !isCompleted && !isAvailable-- val bg = when {- isCompleted -> Color(0xFF1E3A2F)- isAvailable -> Color(0xFF1B2E41)- else -> Color(0xFF242A33)- }- val borderCol = when {- isCompleted -> Color(0xFF22C55E)- isAvailable -> Color(0xFF7FD8BE)- else -> Color(0xFF4B5563)- }+ val bg = when { isCompleted -> Color(0xFF1E3A2F); isAvailable -> Color(0xFF1B2E41); else -> Color(0xFF242A33) }+ val borderCol = when { isCompleted -> Color(0xFF22C55E); isAvailable -> Color(0xFF7FD8BE); else -> Color(0xFF4B5563) } val borderW = if (isAvailable) 3.5.dp else 2.dp-- Column(horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.widthIn(min = 96.dp)) {- Box(- modifier = Modifier- .size(size)- .clip(CircleShape)- .background(bg)- .border(borderW, borderCol, CircleShape)- .clickable(enabled = !isLocked) { onClick(levelId) },- contentAlignment = Alignment.Center- ) {+ Column(modifier = Modifier.widthIn(min = 96.dp), horizontalAlignment = Alignment.CenterHorizontally) {+ Box(modifier = Modifier.size(size).clip(CircleShape).background(bg).border(borderW, borderCol, CircleShape).clip(CircleShape).clickable(enabled = !isLocked) { onClick(levelId) }, contentAlignment = Alignment.Center) { Column(horizontalAlignment = Alignment.CenterHorizontally) {- Text(- def.displayName.take(7),- fontSize = 11.sp,- fontWeight = FontWeight.ExtraBold,- color = when {- isLocked -> Color(0xFF6B7280)- isCompleted -> Color(0xFF86EFAC)- else -> Color.White- }- )- Spacer(Modifier.height(2.dp))+ LibText(text = def.displayName.take(7), fontSize = 11.sp, fontWeight = FontWeight.ExtraBold, color = when { isLocked -> Color(0xFF6B7280); isCompleted -> Color(0xFF86EFAC); else -> Color.White })+ Spacer(modifier = Modifier.height(2.dp)) when {- isLocked -> Text("LOCK", fontSize = 9.sp, fontWeight = FontWeight.Bold, color = Color(0xFF6B7280))- isCompleted -> Text("DONE", fontSize = 9.sp, fontWeight = FontWeight.Bold, color = Color(0xFF22C55E))- else -> Text("PLAY", fontSize = 9.sp, fontWeight = FontWeight.Bold, color = Color(0xFF7FD8BE))+ isLocked -> LibText(text = "LOCK", fontSize = 9.sp, fontWeight = FontWeight.Bold, color = Color(0xFF6B7280))+ isCompleted -> LibText(text = "DONE", fontSize = 9.sp, fontWeight = FontWeight.Bold, color = Color(0xFF22C55E))+ else -> LibText(text = "PLAY", fontSize = 9.sp, fontWeight = FontWeight.Bold, color = Color(0xFF7FD8BE)) } } }- Spacer(Modifier.height(6.dp))- Text(- def.displayName,- fontSize = 12.sp,- fontWeight = FontWeight.SemiBold,- color = if (isLocked) Color(0xFF6B7280) else MaterialTheme.colorScheme.onBackground- )- if (isLocked) {- val need = def.prereqs.joinToString(", ") { Levels.byId[it]?.displayName ?: it }- Text(- "needs $need",- fontSize = 9.sp,- color = Color(0xFF6B7280),- modifier = Modifier.padding(horizontal = 4.dp)- )- }+ Spacer(modifier = Modifier.height(6.dp))+ LibText(text = def.displayName, fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = if (isLocked) Color(0xFF6B7280) else MaterialTheme.colorScheme.onBackground) } } @Composable-private fun RowToRowConnector(- fromRow: TimelineItem.LevelRow,- toRow: TimelineItem.LevelRow,- sideOffset: Dp,- height: Dp,- completed: Set<String>-) {- Canvas(- modifier = Modifier- .fillMaxWidth()- .height(height)- ) {+private fun RowToRowConnector(fromRow: TimelineItem.LevelRow, toRow: TimelineItem.LevelRow, sideOffset: Dp, height: Dp, completed: Set<String>) {+ Canvas(modifier = Modifier.fillMaxWidth().height(height)) { val cx = center.x val leftX = cx - sideOffset.toPx() val rightX = cx + sideOffset.toPx()-- fun xFor(id: String, row: TimelineItem.LevelRow): Float {- return if (row.levelIds.size == 1) cx- else if (row.levelIds[0] == id) leftX else rightX- }-+ fun xFor(id: String, row: TimelineItem.LevelRow) = if (row.levelIds.size == 1) cx else if (row.levelIds[0] == id) leftX else rightX for (toId in toRow.levelIds) { val def = Levels.byId[toId] ?: continue val toX = xFor(toId, toRow)- for (pr in def.prereqs) {- if (pr in fromRow.levelIds) {- val fromX = xFor(pr, fromRow)- drawLine(- color = if (pr in completed) Color(0xFF7FD8BE) else Color(0xFF374151),- start = Offset(fromX, 0f),- end = Offset(toX, size.height),- strokeWidth = 6f- )- }+ for (pr in def.prereqs) if (pr in fromRow.levelIds) {+ val fromX = xFor(pr, fromRow)+ drawLine(if (pr in completed) Color(0xFF7FD8BE) else Color(0xFF374151), Offset(fromX, 0f), Offset(toX, size.height), strokeWidth = 6f) } } } } @Composable-private fun MergeIntoChapterConnector(- fromRow: TimelineItem.LevelRow,- sideOffset: Dp,- height: Dp,- completed: Set<String>-) {+private fun MergeIntoChapterConnector(fromRow: TimelineItem.LevelRow, sideOffset: Dp, height: Dp, completed: Set<String>) { Canvas(modifier = Modifier.fillMaxWidth().height(height)) { val cx = center.x val leftX = cx - sideOffset.toPx() val rightX = cx + sideOffset.toPx()-- fun xFor(id: String): Float {- return if (fromRow.levelIds.size == 1) cx- else if (fromRow.levelIds[0] == id) leftX else rightX- }-- for (id in fromRow.levelIds) {- drawLine(- color = if (id in completed) Color(0xFF7FD8BE) else Color(0xFF374151),- start = Offset(xFor(id), 0f),- end = Offset(cx, size.height),- strokeWidth = 6f- )- }+ fun xFor(id: String) = if (fromRow.levelIds.size == 1) cx else if (fromRow.levelIds[0] == id) leftX else rightX+ for (id in fromRow.levelIds) drawLine(if (id in completed) Color(0xFF7FD8BE) else Color(0xFF374151), Offset(xFor(id), 0f), Offset(cx, size.height), strokeWidth = 6f) } } @Composable-private fun BranchOutOfChapterConnector(- toRow: TimelineItem.LevelRow,- sideOffset: Dp,- height: Dp,- completed: Set<String>-) {+private fun BranchOutOfChapterConnector(toRow: TimelineItem.LevelRow, sideOffset: Dp, height: Dp, completed: Set<String>) { Canvas(modifier = Modifier.fillMaxWidth().height(height)) { val cx = center.x val leftX = cx - sideOffset.toPx() val rightX = cx + sideOffset.toPx()-- fun xFor(id: String): Float {- return if (toRow.levelIds.size == 1) cx- else if (toRow.levelIds[0] == id) leftX else rightX- }-+ fun xFor(id: String) = if (toRow.levelIds.size == 1) cx else if (toRow.levelIds[0] == id) leftX else rightX for (id in toRow.levelIds) { val def = Levels.byId[id] ?: continue val unlocked = def.prereqs.all { it in completed }- drawLine(- color = if (unlocked) Color(0xFF7FD8BE) else Color(0xFF374151),- start = Offset(cx, 0f),- end = Offset(xFor(id), size.height),- strokeWidth = 6f- )+ drawLine(if (unlocked) Color(0xFF7FD8BE) else Color(0xFF374151), Offset(cx, 0f), Offset(xFor(id), size.height), strokeWidth = 6f) } } } -// --- TruthTable + Inventory ---- @Composable-fun TruthTableView(- level: LevelDef,- failingRows: List<Int>,- modifier: Modifier = Modifier-) {+fun TruthTableView(level: LevelDef, failingRows: List<Int>, modifier: Modifier = Modifier) { val target = ChipLibrary.get(level.targetChipId)- val rows = if (level.inputs.size <= 10) {- CircuitEvaluator.generateTruthTable(target, level.inputs.size, level.outputs.size, limit = 64)- } else {+ val rows = if (level.inputs.size <= 10) CircuitEvaluator.generateTruthTable(target, level.inputs.size, level.outputs.size, limit = 64)+ else { val rnd = java.util.Random(1) val vecs = mutableListOf<List<Boolean>>().apply {- add(List(level.inputs.size) { false })- add(List(level.inputs.size) { true })- repeat(20) { add(List(level.inputs.size) { rnd.nextBoolean() }) }+ add(List(level.inputs.size) { false }); add(List(level.inputs.size) { true }); repeat(20) { add(List(level.inputs.size) { rnd.nextBoolean() }) } } vecs.map { target.eval(it).take(level.outputs.size) } }@@ -483,44 +244,39 @@ fun TruthTableView( Column(modifier = modifier.verticalScroll(scroll).background(Color(0xFF0E141B), RoundedCornerShape(8.dp)).padding(8.dp)) { if (level.inputs.size <= 10) { Row {- level.inputs.take(6).forEach { Text(it.take(3), Modifier.width(28.dp), fontSize = 9.sp, fontWeight = FontWeight.Bold, color = Color(0xFF7DD3FC)) }- if (level.inputs.size > 6) Text("…", Modifier.width(16.dp), fontSize = 9.sp, color = Color.Gray)- Text(" | ", fontSize = 9.sp, color = Color.Gray)- level.outputs.take(5).forEach { Text(it.take(4), Modifier.width(36.dp), fontSize = 9.sp, fontWeight = FontWeight.Bold, color = Color(0xFFFDE68A)) }+ level.inputs.take(6).forEach { LibText(text = it.take(3), modifier = Modifier.width(28.dp), fontSize = 9.sp, fontWeight = FontWeight.Bold, color = Color(0xFF7DD3FC)) }+ if (level.inputs.size > 6) LibText(text = "…", modifier = Modifier.width(16.dp), fontSize = 9.sp, color = Color.Gray)+ LibText(text = " | ", fontSize = 9.sp, color = Color.Gray)+ level.outputs.take(5).forEach { LibText(text = it.take(4), modifier = Modifier.width(36.dp), fontSize = 9.sp, fontWeight = FontWeight.Bold, color = Color(0xFFFDE68A)) } }- Spacer(Modifier.height(4.dp))+ Spacer(modifier = Modifier.height(4.dp)) rows.forEachIndexed { idx, outVals -> val isFail = idx in failingRows val bg = if (isFail) Color(0x44FF4444) else Color.Transparent- Row(Modifier.fillMaxWidth().background(bg, RoundedCornerShape(4.dp)).padding(vertical = 1.dp)) {+ Row(modifier = Modifier.fillMaxWidth().background(bg, RoundedCornerShape(4.dp)).padding(vertical = 1.dp)) { for (b in 0 until minOf(level.inputs.size, 6)) { val v = ((idx shr b) and 1) == 1- Text(if (v) "1" else "0", Modifier.width(28.dp), fontSize = 10.sp, color = Color.White)- }- if (level.inputs.size > 6) Text("…", Modifier.width(16.dp), fontSize = 10.sp)- Text(" | ", fontSize = 10.sp, color = Color.Gray)- outVals.take(5).forEach { v ->- Text(if (v) "1" else "0", Modifier.width(36.dp), fontSize = 10.sp, color = if (isFail) Color(0xFFFF8A80) else Color(0xFF86EFAC))+ LibText(text = if (v) "1" else "0", modifier = Modifier.width(28.dp), fontSize = 10.sp, color = Color.White) }- if (isFail) Text(" ✗", fontSize = 10.sp, color = Color(0xFFFF8A80))+ if (level.inputs.size > 6) LibText(text = "…", modifier = Modifier.width(16.dp), fontSize = 10.sp)+ LibText(text = " | ", fontSize = 10.sp, color = Color.Gray)+ outVals.take(5).forEach { v -> LibText(text = if (v) "1" else "0", modifier = Modifier.width(36.dp), fontSize = 10.sp, color = if (isFail) Color(0xFFFF8A80) else Color(0xFF86EFAC)) }+ if (isFail) LibText(text = " ✗", fontSize = 10.sp, color = Color(0xFFFF8A80)) } } } else {- Text("Sampled ${rows.size} cases", fontSize = 9.sp, color = Color.Gray)- Spacer(Modifier.height(6.dp))+ LibText(text = "Sampled ${rows.size} cases", fontSize = 9.sp, color = Color.Gray)+ Spacer(modifier = Modifier.height(6.dp)) rows.take(24).forEachIndexed { idx, outVals -> val isFail = idx in failingRows- Row(Modifier.background(if (isFail) Color(0x44FF4444) else Color.Transparent, RoundedCornerShape(4.dp)).padding(vertical = 1.dp)) {- outVals.forEach { v ->- Text(if (v) "1" else "0", Modifier.width(18.dp), fontSize = 10.sp, color = if (isFail) Color(0xFFFF8A80) else Color(0xFF86EFAC))- }- if (isFail) Text(" ✗", fontSize = 10.sp, color = Color(0xFFFF8A80))+ Row(modifier = Modifier.background(if (isFail) Color(0x44FF4444) else Color.Transparent, RoundedCornerShape(4.dp)).padding(vertical = 1.dp)) {+ outVals.forEach { v -> LibText(text = if (v) "1" else "0", modifier = Modifier.width(18.dp), fontSize = 10.sp, color = if (isFail) Color(0xFFFF8A80) else Color(0xFF86EFAC)) }+ if (isFail) LibText(text = " ✗", fontSize = 10.sp, color = Color(0xFFFF8A80)) } } } if (failingRows.isNotEmpty()) {- Spacer(Modifier.height(6.dp))- Text("${failingRows.size} failing", fontSize = 10.sp, color = Color(0xFFFF8A80))+ Spacer(modifier = Modifier.height(6.dp)); LibText(text = "${failingRows.size} failing", fontSize = 10.sp, color = Color(0xFFFF8A80)) } } }@@ -529,32 +285,105 @@ fun TruthTableView( fun InventoryBar( allowed: List<String>, unlockedChips: Set<String>,- onAddGate: (String) -> Unit,+ onChipDragStart: (chipId: String, global: Offset) -> Unit,+ onChipDrag: (chipId: String, global: Offset) -> Unit,+ onChipDrop: (chipId: String, global: Offset) -> Unit, modifier: Modifier = Modifier ) {- Column(modifier.background(Color(0xFF151E28), RoundedCornerShape(topStart = 12.dp, topEnd = 12.dp)).padding(8.dp)) {- Text("Tap chip to place • Tap dot→dot to wire • Long-press to delete", fontSize = 10.sp, color = Color(0xFF94A3B8), modifier = Modifier.padding(bottom = 6.dp))- LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {- items(allowed.filter { it in unlockedChips }.sortedBy { ChipLibrary.get(it).nandCost }) { chipId ->- val def = ChipLibrary.get(chipId)- val col = when (def.category) {- ChipCategory.PRIMITIVE -> Color(0xFF1E3A4A)- ChipCategory.FOUNDATION -> Color(0xFF14532D)- ChipCategory.ROUTING -> Color(0xFF713F12)- ChipCategory.ARITH -> Color(0xFF7C2D12)- ChipCategory.MEMORY -> Color(0xFF3B0764)- ChipCategory.CPU -> Color(0xFF881337)- }- Box(- modifier = Modifier.background(col, RoundedCornerShape(8.dp)).clickable { onAddGate(chipId) }.padding(horizontal = 10.dp, vertical = 6.dp),- contentAlignment = Alignment.Center- ) {- Column(horizontalAlignment = Alignment.CenterHorizontally) {- Text(def.displayName, fontSize = 11.sp, fontWeight = FontWeight.Bold, color = Color.White)- Text("${def.inputs.size}→${def.outputs.size}", fontSize = 9.sp, color = Color.White.copy(alpha = 0.6f))+ var draggingChip by remember { mutableStateOf<String?>(null) }+ val rowScroll = rememberScrollState()+ Column(modifier = modifier.background(Color(0xFF131C26), RoundedCornerShape(topStart = 14.dp, topEnd = 14.dp)).padding(8.dp)) {+ LibText(text = "Drag chip onto board • Drag gates & I/O to move • Drag output dot → input dot to wire • Tap wire to delete • Long-press gate to delete", fontSize = 10.sp, color = Color(0xFF94A3B8), modifier = Modifier.padding(bottom = 8.dp))+ Row(+ modifier = if (draggingChip != null) Modifier else Modifier.horizontalScroll(rowScroll),+ horizontalArrangement = Arrangement.spacedBy(8.dp)+ ) {+ allowed.filter { it in unlockedChips }.sortedBy { ChipLibrary.get(it).nandCost }.forEach { chipId ->+ DraggableChipItem(+ chipId = chipId,+ onDragStart = { id, g -> draggingChip = id; onChipDragStart(id, g) },+ onDrag = { id, g -> onChipDrag(id, g) },+ onDrop = { id, g -> draggingChip = null; onChipDrop(id, g) }+ )+ }+ }+ }+}++@Composable+private fun DraggableChipItem(+ chipId: String,+ onDragStart: (String, Offset) -> Unit,+ onDrag: (String, Offset) -> Unit,+ onDrop: (String, Offset) -> Unit+) {+ val def = ChipLibrary.get(chipId)+ val col = when (def.category) {+ ChipCategory.PRIMITIVE -> Color(0xFF1E3A4A)+ ChipCategory.FOUNDATION -> Color(0xFF14532D)+ ChipCategory.ROUTING -> Color(0xFF713F12)+ ChipCategory.ARITH -> Color(0xFF7C2D12)+ ChipCategory.MEMORY -> Color(0xFF3B0764)+ ChipCategory.CPU -> Color(0xFF881337)+ }+ var chipPosInRoot by remember { mutableStateOf(Offset.Zero) }+ val chipPosRef by rememberUpdatedState(chipPosInRoot)+ var isDragging by remember { mutableStateOf(false) }++ Box(+ modifier = Modifier+ .onGloballyPositioned { c -> chipPosInRoot = c.positionInRoot() }+ .background(col, RoundedCornerShape(9.dp))+ .border(if (isDragging) 2.dp else 0.dp, if (isDragging) Color.White else Color.Transparent, RoundedCornerShape(9.dp))+ .pointerInput(Unit) {+ awaitPointerEventScope {+ while (true) {+ val down = awaitFirstDownGlobal()+ val startGlobal = chipPosRef + down.position+ var dragActive = false+ var curGlobal = startGlobal++ while (true) {+ val ev = awaitPointerEvent()+ val ch = ev.changes.firstOrNull { it.id == down.id } ?: break+ if (ch.changedToUpIgnoreConsumed()) {+ if (dragActive) onDrop(chipId, curGlobal)+ if (isDragging) isDragging = false+ break+ }+ val total = ch.position - down.position+ curGlobal = startGlobal + total+ if (!dragActive && total.getDistance() > 14f) {+ dragActive = true+ isDragging = true+ onDragStart(chipId, curGlobal)+ }+ if (dragActive) {+ ch.consume()+ onDrag(chipId, curGlobal)+ }+ } } } }+ .padding(horizontal = 12.dp, vertical = 8.dp),+ contentAlignment = Alignment.Center+ ) {+ Column(horizontalAlignment = Alignment.CenterHorizontally) {+ LibText(text = def.displayName, fontSize = 11.sp, fontWeight = FontWeight.Bold, color = Color.White)+ LibText(text = "${def.inputs.size}→${def.outputs.size} • ${def.nandCost}N", fontSize = 9.sp, color = Color.White.copy(alpha = 0.65f)) } } }++private suspend fun androidx.compose.ui.input.pointer.AwaitPointerEventScope.awaitFirstDownGlobal(): androidx.compose.ui.input.pointer.PointerInputChange {+ while (true) {+ val ev = awaitPointerEvent()+ if (ev.type == androidx.compose.ui.input.pointer.PointerEventType.Press) {+ val d = ev.changes.firstOrNull { !it.isConsumed } ?: continue+ return d+ }+ }+}++private fun Offset.getDistance(): Float = hypot(x, y)
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/util/LogicViewModel.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/util/LogicViewModel.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/util/LogicViewModel.ktindex 70f0ee76b0..93e3089e42 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/util/LogicViewModel.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/util/LogicViewModel.kt@@ -2,6 +2,7 @@ package com.vayunmathur.games.logicgate.util import android.app.Application import android.content.Context+import androidx.compose.ui.geometry.Offset import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import com.vayunmathur.games.logicgate.data.*@@ -18,7 +19,7 @@ import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import java.util.UUID -// Serializable persistence of circuit per level+// ----- Persisted format ----- @Serializable data class PersistedWire(val id: String, val fromInstance: String, val fromPin: Int, val toInstance: String, val toPin: Int) @Serializable@@ -26,7 +27,15 @@ data class PersistedGate(val instanceId: String, val chipId: String, val x: Floa @Serializable data class PersistedOutputMap(val outputIndex: Int, val fromInstance: String, val fromPin: Int) @Serializable-data class PersistedCircuit(val gates: List<PersistedGate>, val wires: List<PersistedWire>, val outputs: List<PersistedOutputMap>)+data class PersistedIoPos(val x: Float, val y: Float)+@Serializable+data class PersistedCircuit(+ val gates: List<PersistedGate>,+ val wires: List<PersistedWire>,+ val outputs: List<PersistedOutputMap>,+ val inputPos: Map<Int, PersistedIoPos> = emptyMap(),+ val outputPos: Map<Int, PersistedIoPos> = emptyMap()+) @Serializable data class AllSavedCircuits(val map: Map<String, PersistedCircuit> = emptyMap()) @@ -37,7 +46,14 @@ data class UiState( val evalStatus: EvalStatus = EvalStatus.Idle, val selectedGateInstanceId: String? = null, val wiringFrom: WireEnd? = null,- val showTruthTable: Boolean = true+ val dragGhostLineEnd: Offset? = null,+ val showTruthTable: Boolean = true,+ val draggedChipGhost: DraggedChipGhost? = null+)++data class DraggedChipGhost(+ val chipId: String,+ val offset: Offset ) sealed class EvalStatus {@@ -68,7 +84,6 @@ class LogicViewModel(application: Application) : AndroidViewModel(application) { private val _uiState = MutableStateFlow(UiState()) val uiState: StateFlow<UiState> = _uiState.asStateFlow() - // persisted circuits cache private var allCircuits: MutableMap<String, Circuit> = mutableMapOf() init {@@ -85,7 +100,7 @@ class LogicViewModel(application: Application) : AndroidViewModel(application) { parsed.map.forEach { (lvlId, pc) -> allCircuits[lvlId] = pc.toCircuit() }- } catch (_: Exception) { /* ignore */ }+ } catch (_: Exception) { } } private fun saveAllCircuits() {@@ -99,7 +114,7 @@ class LogicViewModel(application: Application) : AndroidViewModel(application) { fun selectLevel(levelId: String) { val loaded = allCircuits[levelId] ?: Circuit() _uiState.update {- it.copy(currentLevelId = levelId, circuit = loaded, evalStatus = EvalStatus.Idle, wiringFrom = null, selectedGateInstanceId = null)+ it.copy(currentLevelId = levelId, circuit = loaded, evalStatus = EvalStatus.Idle, wiringFrom = null, selectedGateInstanceId = null, dragGhostLineEnd = null) } evaluateCurrent() }@@ -108,15 +123,21 @@ class LogicViewModel(application: Application) : AndroidViewModel(application) { _uiState.update { it.copy(selectedChapter = id) } } + // --- Gates --- fun addGate(chipId: String) {+ addGateAt(chipId, null, null)+ }++ fun addGateAt(chipId: String, x: Float?, y: Float?): String { val state = _uiState.value val newId = "G_${UUID.randomUUID().toString().take(6)}"- val chipDef = ChipLibrary.get(chipId)- // auto layout: random pile but near center val existingCount = state.circuit.gates.size- val gate = PlacedChip(newId, chipId, x = 80f + (existingCount % 4) * 140f, y = 100f + (existingCount / 4) * 110f)+ val px = x ?: (80f + (existingCount % 4) * 140f)+ val py = y ?: (100f + (existingCount / 4) * 110f)+ val gate = PlacedChip(newId, chipId, x = px, y = py) val newCircuit = state.circuit.copy(gates = state.circuit.gates + gate) updateCircuit(newCircuit)+ return newId } fun removeGate(instanceId: String) {@@ -134,7 +155,6 @@ class LogicViewModel(application: Application) : AndroidViewModel(application) { fun onGateMoved(instanceId: String, x: Float, y: Float) { val s = _uiState.value.circuit val newGates = s.gates.map { if (it.instanceId == instanceId) it.copy(x = x, y = y) else it }- // don't trigger eval on move val lvlId = _uiState.value.currentLevelId if (lvlId != null) { allCircuits[lvlId] = s.copy(gates = newGates)@@ -143,33 +163,70 @@ class LogicViewModel(application: Application) : AndroidViewModel(application) { _uiState.update { it.copy(circuit = it.circuit.copy(gates = newGates)) } } + // --- IO terminal moves ---+ fun onInputMoved(idx: Int, x: Float, y: Float) {+ val s = _uiState.value.circuit+ val newMap = s.inputPositions.toMutableMap()+ newMap[idx] = IoPos(x, y)+ val newCircuit = s.copy(inputPositions = newMap)+ val lvlId = _uiState.value.currentLevelId+ if (lvlId != null) {+ allCircuits[lvlId] = newCircuit+ saveAllCircuits()+ }+ _uiState.update { it.copy(circuit = newCircuit) }+ }++ fun onOutputMoved(idx: Int, x: Float, y: Float) {+ val s = _uiState.value.circuit+ val newMap = s.outputPositions.toMutableMap()+ newMap[idx] = IoPos(x, y)+ val newCircuit = s.copy(outputPositions = newMap)+ val lvlId = _uiState.value.currentLevelId+ if (lvlId != null) {+ allCircuits[lvlId] = newCircuit+ saveAllCircuits()+ }+ _uiState.update { it.copy(circuit = newCircuit) }+ }++ // --- Wiring --- fun startWiring(from: WireEnd) { _uiState.update { it.copy(wiringFrom = from) } } fun cancelWiring() {- _uiState.update { it.copy(wiringFrom = null) }+ _uiState.update { it.copy(wiringFrom = null, dragGhostLineEnd = null) } } - /**- * Complete a wiring attempt.- * Rules:- * - If to is __OUT_<idx>, create OutputMapping- * - Else if to is gate input, create wire (allow fan-out, single driver per pin? we allow overwriting)- */- fun completeWiring(to: WireEnd) {- val from = _uiState.value.wiringFrom ?: return+ fun updateGhostLine(end: Offset?) {+ _uiState.update { it.copy(dragGhostLineEnd = end) }+ }++ fun createWire(from: WireEnd, to: WireEnd) { val s = _uiState.value.circuit- if (from.instanceId == to.instanceId) { _uiState.update { it.copy(wiringFrom = null) }; return }+ if (from.instanceId == to.instanceId) {+ _uiState.update { it.copy(wiringFrom = null, dragGhostLineEnd = null) }+ return+ }+ // validate direction: from must be output (source), to must be input (sink)+ val fromIsOutput = isOutputEnd(from)+ val toIsInput = isInputEnd(to)+ if (!fromIsOutput || !toIsInput) {+ // try swapped?+ // Only allow output -> input, not input -> output or output -> output etc.+ _uiState.update { it.copy(wiringFrom = null, dragGhostLineEnd = null) }+ return+ } if (to.instanceId.startsWith("__OUT_")) {- val outIdx = to.instanceId.removePrefix("__OUT_").toIntOrNull() ?: run { _uiState.update { it.copy(wiringFrom = null) }; return }+ val outIdx = to.instanceId.removePrefix("__OUT_").toIntOrNull() ?: run {+ _uiState.update { it.copy(wiringFrom = null, dragGhostLineEnd = null) }; return+ } val existing = s.outputMappings.filterNot { it.outputIndex == outIdx } val newMap = existing + OutputMapping(outIdx, from) updateCircuit(s.copy(outputMappings = newMap)) } else {- // destination is gate input or (allow wiring INTO __IN_? no)- // Remove any existing wire to that destination pin (only one driver per input pin) val existingWires = s.wires.filterNot { it.to == to } val newWire = Wire( id = "W_${UUID.randomUUID().toString().take(6)}",@@ -178,7 +235,30 @@ class LogicViewModel(application: Application) : AndroidViewModel(application) { ) updateCircuit(s.copy(wires = existingWires + newWire)) }- _uiState.update { it.copy(wiringFrom = null) }+ _uiState.update { it.copy(wiringFrom = null, dragGhostLineEnd = null) }+ }++ // classify ends+ private fun isOutputEnd(end: WireEnd): Boolean {+ if (end.instanceId.startsWith("__IN_")) return true // input terminals are sources+ if (end.instanceId.startsWith("__OUT_")) return false+ // gate: determine by checking chip def+ val gate = _uiState.value.circuit.gates.find { it.instanceId == end.instanceId } ?: return false+ val def = ChipLibrary.get(gate.chipId)+ return end.pinIndex in 0 until def.outputCount+ }+ private fun isInputEnd(end: WireEnd): Boolean {+ if (end.instanceId.startsWith("__OUT_")) return true+ if (end.instanceId.startsWith("__IN_")) return false+ val gate = _uiState.value.circuit.gates.find { it.instanceId == end.instanceId } ?: return false+ val def = ChipLibrary.get(gate.chipId)+ return end.pinIndex in 0 until def.inputCount+ }++ // backward compat+ fun completeWiring(to: WireEnd) {+ val from = _uiState.value.wiringFrom ?: return+ createWire(from, to) } fun removeWire(wireId: String) {@@ -191,6 +271,21 @@ class LogicViewModel(application: Application) : AndroidViewModel(application) { updateCircuit(s.copy(outputMappings = s.outputMappings.filterNot { it.outputIndex == outIdx })) } + // --- Drag ghost for palette ---+ fun onChipPaletteDragStart(chipId: String, offset: Offset) {+ _uiState.update { it.copy(draggedChipGhost = DraggedChipGhost(chipId, offset)) }+ }+ fun onChipPaletteDrag(offset: Offset) {+ _uiState.update { it.copy(draggedChipGhost = it.draggedChipGhost?.copy(offset = offset)) }+ }+ fun onChipPaletteDragEnd(canvasX: Float?, canvasY: Float?) {+ val ghost = _uiState.value.draggedChipGhost+ _uiState.update { it.copy(draggedChipGhost = null) }+ if (ghost != null && canvasX != null && canvasY != null) {+ addGateAt(ghost.chipId, canvasX, canvasY)+ }+ }+ private fun updateCircuit(newCircuit: Circuit) { val lvlId = _uiState.value.currentLevelId if (lvlId != null) {@@ -263,13 +358,17 @@ private fun PersistedCircuit.toCircuit(): Circuit { return Circuit( gates = gates.map { PlacedChip(it.instanceId, it.chipId, it.x, it.y) }, wires = wires.map { Wire(it.id, WireEnd(it.fromInstance, it.fromPin), WireEnd(it.toInstance, it.toPin)) },- outputMappings = outputs.map { OutputMapping(it.outputIndex, WireEnd(it.fromInstance, it.fromPin)) }+ outputMappings = outputs.map { OutputMapping(it.outputIndex, WireEnd(it.fromInstance, it.fromPin)) },+ inputPositions = inputPos.mapValues { IoPos(it.value.x, it.value.y) },+ outputPositions = outputPos.mapValues { IoPos(it.value.x, it.value.y) } ) } private fun Circuit.toPersisted(): PersistedCircuit { return PersistedCircuit( gates = gates.map { PersistedGate(it.instanceId, it.chipId, it.x, it.y) }, wires = wires.map { PersistedWire(it.id, it.from.instanceId, it.from.pinIndex, it.to.instanceId, it.to.pinIndex) },- outputs = outputMappings.map { PersistedOutputMap(it.outputIndex, it.from.instanceId, it.from.pinIndex) }+ outputs = outputMappings.map { PersistedOutputMap(it.outputIndex, it.from.instanceId, it.from.pinIndex) },+ inputPos = inputPositions.mapValues { PersistedIoPos(it.value.x, it.value.y) },+ outputPos = outputPositions.mapValues { PersistedIoPos(it.value.x, it.value.y) } ) }