logicgate: fix the dragging out
- Commit
edda2f1913c8829e67c5ffcca150e7412029df90- Author
- Vayun Mathur <[email protected]>
- When
- 2026-07-27 21:32 UTC (4 months ago)
- Parents
33bfb1e
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 f81909a8b7..6bbcf65353 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,27 +4,43 @@ 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.animation.Crossfade 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.rememberScrollState+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.*+import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier-import androidx.compose.ui.geometry.CornerRadius+import androidx.compose.ui.draw.clip 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.input.pointer.AwaitPointerEventScope+import androidx.compose.ui.input.pointer.PointerEventType+import androidx.compose.ui.input.pointer.PointerInputChange+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.layout.positionInWindow+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.lifecycle.viewmodel.compose.viewModel+import com.vayunmathur.games.logicgate.data.ChipCategory+import com.vayunmathur.games.logicgate.data.ChipLibrary+import com.vayunmathur.games.logicgate.data.CircuitEvaluator+import com.vayunmathur.games.logicgate.data.EvalResult+import com.vayunmathur.games.logicgate.data.Levels import com.vayunmathur.games.logicgate.ui.CircuitCanvas-import com.vayunmathur.games.logicgate.ui.InventoryBar import com.vayunmathur.games.logicgate.ui.LogicGateTheme import com.vayunmathur.games.logicgate.ui.ProgressionScreen-import com.vayunmathur.games.logicgate.ui.TruthTableView import com.vayunmathur.games.logicgate.util.AppBackupAgent import com.vayunmathur.games.logicgate.util.EvalStatus import com.vayunmathur.games.logicgate.util.LogicViewModel@@ -43,7 +59,7 @@ import com.vayunmathur.library.util.NavKey import com.vayunmathur.library.util.rememberNavBackStack import kotlinx.serialization.Serializable import androidx.compose.ui.res.stringResource-import com.vayunmathur.games.logicgate.R+import kotlin.math.roundToInt class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) {@@ -81,10 +97,18 @@ fun Navigation(viewModel: LogicViewModel) { } } +enum class ChipGroup { BIT, WORD, CUSTOM }++private fun groupForCategory(cat: ChipCategory): ChipGroup = when (cat) {+ ChipCategory.PRIMITIVE, ChipCategory.FOUNDATION, ChipCategory.ROUTING -> ChipGroup.BIT+ ChipCategory.BUS, ChipCategory.ARITH -> ChipGroup.WORD+ ChipCategory.MEMORY, ChipCategory.CPU -> ChipGroup.CUSTOM+}+ @OptIn(ExperimentalMaterial3Api::class) @Composable fun GameScreen(backStack: NavBackStack<Route>, viewModel: LogicViewModel, levelId: String) {- val level = com.vayunmathur.games.logicgate.data.Levels.get(levelId)+ val level = Levels.get(levelId) val uiState by viewModel.uiState.collectAsState() val unlocked by viewModel.unlockedChips.collectAsState() val completed by viewModel.completedIds.collectAsState()@@ -92,9 +116,82 @@ fun GameScreen(backStack: NavBackStack<Route>, viewModel: LogicViewModel, levelI LaunchedEffect(levelId) { viewModel.selectLevel(levelId) } val isCurrent = uiState.currentLevelId == levelId - var canvasRect by remember { mutableStateOf(Rect.Zero) }+ var canvasPosInWindow by remember { mutableStateOf(Offset.Zero) }+ var canvasSize by remember { mutableStateOf(Size.Zero) } var draggingChipId by remember { mutableStateOf<String?>(null) }- var draggingChipGlobal by remember { mutableStateOf(Offset.Zero) }+ var draggingChipWindowPos by remember { mutableStateOf(Offset.Zero) }+ var selectedGroup by remember { mutableStateOf<ChipGroup?>(null) }+ val density = LocalDensity.current++ // ---- Representative test vector for live I/O values (mirrors evaluator seed 1234) ----+ val totalInBits = level.totalInputBits+ val displayLimit = if (totalInBits <= 10) minOf(64, (1 shl totalInBits)) else 28+ val inputVectors: List<List<Boolean>> = remember(totalInBits, displayLimit) {+ val seed = 1234L+ if (totalInBits <= 10) (0 until (1 shl totalInBits)).take(displayLimit).map { c -> List(totalInBits) { i -> ((c shr i) and 1) == 1 } }+ else {+ val rnd = java.util.Random(seed)+ val vs = mutableListOf<List<Boolean>>()+ vs.add(List(totalInBits) { false })+ vs.add(List(totalInBits) { true })+ vs.add(List(totalInBits) { it % 2 == 0 })+ while (vs.size < displayLimit) vs.add(List(totalInBits) { rnd.nextBoolean() })+ vs+ }+ }+ val selectedIdx = remember(uiState.evalStatus, inputVectors) {+ val failing = (uiState.evalStatus as? EvalStatus.Ok)?.failingRows+ if (failing != null && failing.isNotEmpty()) failing.first() % inputVectors.size else 0+ }+ val flatInSelected = remember(inputVectors, selectedIdx) { inputVectors.getOrNull(selectedIdx) ?: emptyList() }+ val inputDecimals: Map<Int, Int> = remember(flatInSelected, level) {+ level.inputs.indices.associateWith { idx ->+ val off = level.inputBitOffset(idx); val w = level.inputWidth(idx)+ val slice = if (off + w <= flatInSelected.size) flatInSelected.slice(off until off + w) else List(w) { false }+ ChipLibrary.bitsToInt(slice)+ }+ }+ val inputBitSlices: Map<Int, List<Boolean>> = remember(flatInSelected, level) {+ level.inputs.indices.associateWith { idx ->+ val off = level.inputBitOffset(idx); val w = level.inputWidth(idx)+ if (off + w <= flatInSelected.size) flatInSelected.slice(off until off + w) else List(w) { false }+ }+ }+ val targetDef = remember(level.targetChipId) { try { ChipLibrary.get(level.targetChipId) } catch (_: Exception) { null } }+ val desiredFlatOut: List<Boolean> = remember(flatInSelected, targetDef, level) {+ targetDef?.let { it.eval(flatInSelected).take(level.totalOutputBits) } ?: emptyList()+ }+ val desiredDecimals: Map<Int, Int> = remember(desiredFlatOut, level) {+ level.outputs.indices.associateWith { oi ->+ val off = level.outputBitOffset(oi); val w = level.outputWidth(oi)+ val slice = if (off + w <= desiredFlatOut.size) desiredFlatOut.slice(off until off + w) else List(w) { false }+ ChipLibrary.bitsToInt(slice)+ }+ }+ val desiredBitSlices: Map<Int, List<Boolean>> = remember(desiredFlatOut, level) {+ level.outputs.indices.associateWith { oi ->+ val off = level.outputBitOffset(oi); val w = level.outputWidth(oi)+ if (off + w <= desiredFlatOut.size) desiredFlatOut.slice(off until off + w) else List(w) { false }+ }+ }+ val actualEvalRows: List<List<Boolean>>? = remember(uiState.circuit, level) {+ val res = CircuitEvaluator.evaluate(level, uiState.circuit)+ if (res is EvalResult.Success) res.rows else null+ }+ val actualFlatOut: List<Boolean> = remember(actualEvalRows, selectedIdx) { actualEvalRows?.getOrNull(selectedIdx) ?: emptyList() }+ val actualDecimals: Map<Int, Int> = remember(actualFlatOut, level) {+ level.outputs.indices.associateWith { oi ->+ val off = level.outputBitOffset(oi); val w = level.outputWidth(oi)+ val slice = if (off + w <= actualFlatOut.size) actualFlatOut.slice(off until off + w) else List(w) { false }+ ChipLibrary.bitsToInt(slice)+ }+ }+ val actualBitSlices: Map<Int, List<Boolean>> = remember(actualFlatOut, level) {+ level.outputs.indices.associateWith { oi ->+ val off = level.outputBitOffset(oi); val w = level.outputWidth(oi)+ if (off + w <= actualFlatOut.size) actualFlatOut.slice(off until off + w) else List(w) { false }+ }+ } Scaffold( topBar = {@@ -105,49 +202,64 @@ fun GameScreen(backStack: NavBackStack<Route>, viewModel: LogicViewModel, levelI Row(modifier = Modifier.padding(end = 6.dp), horizontalArrangement = Arrangement.spacedBy(6.dp)) { if (uiState.canUndo) Button(onClick = { viewModel.undo() }) { Text(stringResource(R.string.undo), fontSize = 10.sp) } if (uiState.canRedo) Button(onClick = { viewModel.redo() }) { Text(stringResource(R.string.redo), fontSize = 10.sp) }- Button(onClick = { viewModel.toggleTruthTable() }) { Text(text = if (uiState.showTruthTable) stringResource(R.string.hide_tt) else stringResource(R.string.show_tt), fontSize = 10.sp) }+ Button(onClick = { viewModel.toggleTruthTable() }) { Text(text = if (uiState.showTruthTable) "Hide" else "Show", fontSize = 10.sp) } } } ) }, bottomBar = { if (isCurrent) {- InventoryBar(- allowed = level.allowedChipIds,- unlockedChips = unlocked,- 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)) {- viewModel.addGateAt(chipId, local.x, local.y)+ Column(modifier = Modifier.fillMaxWidth().background(Color(0xFF1E2433))) {+ // BIT / WORD / CUSTOM filter — horizontal for mobile (like screenshot right vertical tabs)+ Row(+ modifier = Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).padding(horizontal = 8.dp, vertical = 6.dp),+ horizontalArrangement = Arrangement.spacedBy(6.dp)+ ) {+ listOf<Pair<ChipGroup?, String>>(null to "ALL", ChipGroup.BIT to "BIT", ChipGroup.WORD to "WORD", ChipGroup.CUSTOM to "CUSTOM").forEach { (g, label) ->+ val isSel = selectedGroup == g+ Button(onClick = { selectedGroup = g }) {+ Text(text = label, fontSize = 10.sp, color = if (isSel) Color(0xFF2BE4B8) else Color(0xFF9AA3BB))+ } }- draggingChipId = null- draggingChipGlobal = Offset.Zero- },- modifier = Modifier.fillMaxWidth()- )+ }+ TuringInventoryBar(+ allowed = level.allowedChipIds,+ unlockedChips = unlocked,+ selectedGroup = selectedGroup,+ onChipDragStart = { chipId, windowOffset ->+ draggingChipId = chipId+ draggingChipWindowPos = windowOffset+ },+ onChipDrag = { chipId, windowOffset ->+ draggingChipId = chipId+ draggingChipWindowPos = windowOffset+ },+ onChipDrop = { chipId, windowOffset ->+ val local = Offset(windowOffset.x - canvasPosInWindow.x, windowOffset.y - canvasPosInWindow.y)+ val isOver = local.x >= 0f && local.x <= canvasSize.width && local.y >= 0f && local.y <= canvasSize.height+ if (isOver) viewModel.addGateAt(chipId, local.x, local.y)+ draggingChipId = null+ draggingChipWindowPos = Offset.Zero+ },+ modifier = Modifier.fillMaxWidth()+ )+ } } } ) { padding -> if (!isCurrent) {- Box(modifier = Modifier.fillMaxSize().padding(padding), contentAlignment = androidx.compose.ui.Alignment.Center) { Text(stringResource(R.string.loading)) }+ Box(modifier = Modifier.fillMaxSize().padding(padding), contentAlignment = Alignment.Center) { Text(stringResource(R.string.loading)) } return@Scaffold } - Column(modifier = Modifier.fillMaxSize().padding(padding).background(Color(0xFF0B1218))) {+ Column(modifier = Modifier.fillMaxSize().padding(padding).background(Color(0xFF0F1E2D))) {+ val isWiring = uiState.wiringFrom != null 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.Ok -> if (s.isFullyCorrect) "✓ CORRECT — ${level.unlocksChipId?.let { "Unlocked $it!" } ?: "PASS"}"+ else "${s.passingRows}/${s.totalRows} — ${s.failingRows.size} failing • sel #${selectedIdx}" is EvalStatus.Error -> "Error: ${s.msg}"- is EvalStatus.Cycle -> "Cycle: ${s.ids.take(3).joinToString()} — SR_LATCH needs 2 NOR cross-coupled feedback"- else -> "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 • Undo/Redo in top bar"+ is EvalStatus.Cycle -> "Cycle: ${s.ids.take(3).joinToString()} — needs latch"+ else -> "Drag from inventory • Move items on grid • Tap output→input to wire • Tap wire to delete • Long-press gate delete" } val statusColor = when { uiState.evalStatus is EvalStatus.Ok && (uiState.evalStatus as EvalStatus.Ok).isFullyCorrect -> Color(0xFF22C55E)@@ -155,121 +267,464 @@ fun GameScreen(backStack: NavBackStack<Route>, viewModel: LogicViewModel, levelI else -> Color(0xFF94A3B8) } - Box(modifier = Modifier.fillMaxWidth().background(Color(0xFF16202B)).padding(horizontal = 12.dp, vertical = 7.dp)) {- Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {+ // Status bar — dark compact with wiring crossfade (like Alchemist trash vs inventory)+ Box(modifier = Modifier.fillMaxWidth().background(Color(0xFF16202B)).padding(horizontal = 10.dp, vertical = 6.dp)) {+ Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { 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(stringResource(R.string.hint_1, level.hint), fontSize = 10.sp, color = Color(0xFF64748B))+ Crossfade(targetState = isWiring, label = "wiring_cf") { wiring ->+ if (wiring) Text(text = "Wiring: tap input dot (yellow) or empty to cancel", fontSize = 11.sp, color = Color(0xFFFFFF00))+ else Text(text = statusText, fontSize = 11.sp, color = statusColor)+ }+ Row(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically) {+ LegendDot(Color(0xFF22C55E), "1b ON") // green = 1 like screenshot+ LegendDot(Color(0xFFEF4444), "0 OFF")+ LegendDot(Color(0xFFFFA126), "4b")+ LegendDot(Color(0xFF4FC3FF), "8b")+ Text(text = level.description.take(52), fontSize = 9.sp, color = Color(0xFF6B7D96))+ } }- Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {- Button(onClick = { viewModel.clearCircuit() }) { Text(stringResource(R.string.clear), fontSize = 10.sp) }- if (uiState.wiringFrom != null) Button(onClick = { viewModel.cancelWiring() }) { Text(stringResource(R.string.cancel_wire), fontSize = 10.sp) }- Card(modifier = Modifier.padding(start = 4.dp)) { Text(stringResource(R.string.gates, uiState.circuit.gates.size), fontSize = 11.sp, modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp)) }+ Row(horizontalArrangement = Arrangement.spacedBy(4.dp), verticalAlignment = Alignment.CenterVertically) {+ Button(onClick = { viewModel.clearCircuit() }) { Text(stringResource(R.string.clear), fontSize = 9.sp) }+ if (isWiring) Button(onClick = { viewModel.cancelWiring() }) { Text(stringResource(R.string.cancel_wire), fontSize = 9.sp) }+ Card(modifier = Modifier.padding(start = 2.dp)) {+ Text(stringResource(R.string.gates, uiState.circuit.gates.size), fontSize = 10.sp, modifier = Modifier.padding(horizontal = 5.dp, vertical = 2.dp))+ } } } } BoxWithConstraints(modifier = Modifier.weight(1f).fillMaxWidth()) { val wide = maxWidth > maxHeight- 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) },- onGateMoveFinished = { id, x, y -> viewModel.onGateMoveFinished(id, x, y) },- onInputTermMove = { idx, x, y -> viewModel.onInputMoved(idx, x, y) },- onInputTermMoveFinished = { idx, x, y -> viewModel.onInputMoveFinished(idx, x, y) },- onOutputTermMove = { idx, x, y -> viewModel.onOutputMoved(idx, x, y) },- onOutputTermMoveFinished = { idx, x, y -> viewModel.onOutputMoveFinished(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()- )++ @Composable+ fun GameCanvas(mod: Modifier) {+ 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) },+ onGateMoveFinished = { id, x, y -> viewModel.onGateMoveFinished(id, x, y) },+ onInputTermMove = { idx, x, y -> viewModel.onInputMoved(idx, x, y) },+ onInputTermMoveFinished = { idx, x, y -> viewModel.onInputMoveFinished(idx, x, y) },+ onOutputTermMove = { idx, x, y -> viewModel.onOutputMoved(idx, x, y) },+ onOutputTermMoveFinished = { idx, x, y -> viewModel.onOutputMoveFinished(idx, x, y) },+ onGateDelete = { viewModel.removeGate(it) },+ onWireDelete = { viewModel.removeWire(it) },+ onOutputMapDelete = { viewModel.removeOutputMapping(it) },+ dragGhostLineEnd = uiState.dragGhostLineEnd,+ onGhostLine = { viewModel.updateGhostLine(it) },+ inputValues = inputDecimals,+ desiredOutputValues = desiredDecimals,+ outputValues = actualDecimals,+ modifier = mod+ )+ }++ // Wide: Row [I/O panel | toolbar | canvas | truth panel]+ // Portrait: Column [canvas with floating toolbar | truth panel]+ if (wide) {+ Row(modifier = Modifier.fillMaxSize()) {+ TuringIOPanel(+ level = level,+ inputDecimals = inputDecimals,+ inputBitSlices = inputBitSlices,+ desiredDecimals = desiredDecimals,+ desiredBitSlices = desiredBitSlices,+ actualDecimals = actualDecimals,+ actualBitSlices = actualBitSlices,+ modifier = Modifier.width(150.dp).fillMaxHeight().background(Color(0xFF1B2636))+ )+ TuringVerticalToolbar(+ onClear = { viewModel.clearCircuit() },+ onUndo = { viewModel.undo() },+ onRedo = { viewModel.redo() },+ canUndo = uiState.canUndo,+ canRedo = uiState.canRedo,+ modifier = Modifier.width(52.dp).fillMaxHeight().background(Color(0xFF121B27))+ )+ // Canvas Box tracks its own positionInWindow for inventory drop — fixes wide misalignment+ Box(+ modifier = Modifier.weight(1f).fillMaxHeight().onGloballyPositioned { coords ->+ canvasPosInWindow = coords.positionInWindow()+ canvasSize = Size(coords.size.width.toFloat(), coords.size.height.toFloat()) }- if (uiState.showTruthTable) {- val failing = (uiState.evalStatus as? EvalStatus.Ok)?.failingRows ?: emptyList()- TruthTableView(level, failing, modifier = Modifier.width(260.dp).fillMaxHeight().background(Color(0xFF0E141B)))+ ) {+ GameCanvas(Modifier.fillMaxSize())+ // Global ghost overlay inside canvas Box (Alchemist IntOffset pattern)+ draggingChipId?.let { chipId ->+ val localOffset = Offset(draggingChipWindowPos.x - canvasPosInWindow.x, draggingChipWindowPos.y - canvasPosInWindow.y)+ val isOver = localOffset.x >= 0f && localOffset.x <= canvasSize.width && localOffset.y >= 0f && localOffset.y <= canvasSize.height+ val def = try { ChipLibrary.get(chipId) } catch (_: Exception) { null }+ val ghostW = 96.dp; val ghostH = 44.dp+ Box(+ modifier = Modifier.offset {+ IntOffset(+ (localOffset.x - with(density) { ghostW.toPx() } / 2f).roundToInt(),+ (localOffset.y - with(density) { ghostH.toPx() } / 2f).roundToInt()+ )+ }.size(ghostW, ghostH)+ .background(if (isOver) Color(0xFFD1FAE5).copy(alpha = 0.92f) else Color(0xFF4B5563).copy(alpha = 0.7f), RoundedCornerShape(8.dp))+ .border(if (isOver) 2.dp else 1.dp, if (isOver) Color(0xFF22C55E) else Color.White.copy(alpha = 0.28f), RoundedCornerShape(8.dp)),+ contentAlignment = Alignment.Center+ ) { def?.let { Text(text = it.displayName.take(8), fontSize = 10.sp, color = if (isOver) Color(0xFF14532D) else Color.White) } } } }- } else {- Column(modifier = Modifier.fillMaxSize()) {- if (uiState.showTruthTable) {- val failing = (uiState.evalStatus as? EvalStatus.Ok)?.failingRows ?: emptyList()- TruthTableView(level, failing, modifier = Modifier.fillMaxWidth().height(200.dp).background(Color(0xFF0E141B)))+ if (uiState.showTruthTable) {+ TuringBottomTruthPanel(+ level = level,+ selectedIdx = selectedIdx,+ inputDecimals = inputDecimals,+ inputBitSlices = inputBitSlices,+ desiredDecimals = desiredDecimals,+ desiredBitSlices = desiredBitSlices,+ actualDecimals = actualDecimals,+ actualBitSlices = actualBitSlices,+ failingCount = (uiState.evalStatus as? EvalStatus.Ok)?.failingRows?.size ?: 0,+ modifier = Modifier.width(260.dp).fillMaxHeight().background(Color(0xFF212636))+ )+ }+ }+ } else {+ Column(modifier = Modifier.fillMaxSize()) {+ Box(+ modifier = Modifier.weight(1f).fillMaxWidth().onGloballyPositioned { coords ->+ canvasPosInWindow = coords.positionInWindow()+ canvasSize = Size(coords.size.width.toFloat(), coords.size.height.toFloat()) }- 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) },- onGateMoveFinished = { id, x, y -> viewModel.onGateMoveFinished(id, x, y) },- onInputTermMove = { idx, x, y -> viewModel.onInputMoved(idx, x, y) },- onInputTermMoveFinished = { idx, x, y -> viewModel.onInputMoveFinished(idx, x, y) },- onOutputTermMove = { idx, x, y -> viewModel.onOutputMoved(idx, x, y) },- onOutputTermMoveFinished = { idx, x, y -> viewModel.onOutputMoveFinished(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()- )+ ) {+ GameCanvas(Modifier.fillMaxSize())+ // Floating vertical toolbar top-start for portrait (like screenshot left of canvas icons)+ Column(+ modifier = Modifier.align(Alignment.TopStart).padding(6.dp).background(Color(0xFF1B2636).copy(alpha = 0.92f), RoundedCornerShape(8.dp)).padding(4.dp),+ verticalArrangement = Arrangement.spacedBy(4.dp)+ ) {+ ToolbarIcon("🗑", onClick = { viewModel.clearCircuit() })+ if (uiState.canUndo) ToolbarIcon("↩", onClick = { viewModel.undo() })+ if (uiState.canRedo) ToolbarIcon("↪", onClick = { viewModel.redo() })+ ToolbarIcon("8") {} }+ draggingChipId?.let { chipId ->+ val localOffset = Offset(draggingChipWindowPos.x - canvasPosInWindow.x, draggingChipWindowPos.y - canvasPosInWindow.y)+ val isOver = localOffset.x >= 0f && localOffset.x <= canvasSize.width && localOffset.y >= 0f && localOffset.y <= canvasSize.height+ val def = try { ChipLibrary.get(chipId) } catch (_: Exception) { null }+ val ghostW = 96.dp; val ghostH = 44.dp+ Box(+ modifier = Modifier.offset {+ IntOffset(+ (localOffset.x - with(density) { ghostW.toPx() } / 2f).roundToInt(),+ (localOffset.y - with(density) { ghostH.toPx() } / 2f).roundToInt()+ )+ }.size(ghostW, ghostH)+ .background(if (isOver) Color(0xFFD1FAE5).copy(alpha = 0.92f) else Color(0xFF4B5563).copy(alpha = 0.7f), RoundedCornerShape(8.dp))+ .border(if (isOver) 2.dp else 1.dp, if (isOver) Color(0xFF22C55E) else Color.White.copy(alpha = 0.28f), RoundedCornerShape(8.dp)),+ contentAlignment = Alignment.Center+ ) { def?.let { Text(text = it.displayName.take(8), fontSize = 10.sp, color = if (isOver) Color(0xFF14532D) else Color.White) } }+ }+ }+ if (uiState.showTruthTable) {+ TuringBottomTruthPanel(+ level = level,+ selectedIdx = selectedIdx,+ inputDecimals = inputDecimals,+ inputBitSlices = inputBitSlices,+ desiredDecimals = desiredDecimals,+ desiredBitSlices = desiredBitSlices,+ actualDecimals = actualDecimals,+ actualBitSlices = actualBitSlices,+ failingCount = (uiState.evalStatus as? EvalStatus.Ok)?.failingRows?.size ?: 0,+ modifier = Modifier.fillMaxWidth().height(150.dp).background(Color(0xFF212636))+ ) } }+ }+ }+ }+ }+} - 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)- )- 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)- )+@Composable+private fun LegendDot(col: Color, label: String) {+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(2.dp)) {+ Box(modifier = Modifier.size(6.dp).clip(CircleShape).background(col))+ Text(text = label, fontSize = 8.sp, color = Color(0xFF8AA0BA))+ }+}++@Composable+private fun TuringVerticalToolbar(+ onClear: () -> Unit,+ onUndo: () -> Unit,+ onRedo: () -> Unit,+ canUndo: Boolean,+ canRedo: Boolean,+ modifier: Modifier = Modifier+) {+ Column(modifier = modifier.padding(4.dp), verticalArrangement = Arrangement.spacedBy(6.dp), horizontalAlignment = Alignment.CenterHorizontally) {+ ToolbarIcon("⌕") {}+ ToolbarIcon("▶") {}+ ToolbarIcon("■", onClick = onClear)+ Box(modifier = Modifier.height(1.dp).fillMaxWidth().background(Color(0xFF2A3A50)))+ ToolbarIcon("⬚") {}+ ToolbarIcon("🗑", onClick = onClear)+ ToolbarIcon("✎") {}+ ToolbarIcon("🎨") {}+ if (canUndo) ToolbarIcon("↩", onClick = onUndo)+ if (canRedo) ToolbarIcon("↪", onClick = onRedo)+ Spacer(modifier = Modifier.weight(1f))+ Box(modifier = Modifier.size(28.dp).clip(RoundedCornerShape(6.dp)).background(Color(0xFF2A3042)), contentAlignment = Alignment.Center) {+ Text("8", fontSize = 10.sp, color = Color.White)+ }+ }+}++@Composable+private fun ToolbarIcon(symbol: String, onClick: () -> Unit = {}) {+ Box(+ modifier = Modifier.size(32.dp).clip(RoundedCornerShape(6.dp)).background(Color(0xFF222C3E)).border(0.6.dp, Color(0xFF32415C), RoundedCornerShape(6.dp)).clickable { onClick() },+ contentAlignment = Alignment.Center+ ) { Text(symbol, fontSize = 12.sp, color = Color(0xFF9AA3BB)) }+}++@Composable+private fun TuringIOPanel(+ level: com.vayunmathur.games.logicgate.data.LevelDef,+ inputDecimals: Map<Int, Int>,+ inputBitSlices: Map<Int, List<Boolean>>,+ desiredDecimals: Map<Int, Int>,+ desiredBitSlices: Map<Int, List<Boolean>>,+ actualDecimals: Map<Int, Int>,+ actualBitSlices: Map<Int, List<Boolean>>,+ modifier: Modifier = Modifier+) {+ Column(modifier = modifier.verticalScroll(rememberScrollState()).padding(6.dp)) {+ Text("Inputs", fontSize = 11.sp, color = Color.White, modifier = Modifier.padding(bottom = 4.dp))+ level.inputs.forEachIndexed { idx, name ->+ val dec = inputDecimals[idx] ?: 0+ val bits = inputBitSlices[idx] ?: emptyList()+ IOPanelRow(name, dec, bits, Color(0xFF38BDF8))+ Spacer(modifier = Modifier.height(6.dp))+ }+ Spacer(modifier = Modifier.height(8.dp))+ Text("Outputs", fontSize = 11.sp, color = Color.White, modifier = Modifier.padding(bottom = 4.dp))+ level.outputs.forEachIndexed { idx, name ->+ val decD = desiredDecimals[idx] ?: 0+ val bitsD = desiredBitSlices[idx] ?: emptyList()+ IOPanelRow("$name exp", decD, bitsD, Color(0xFFFBBF24))+ val decA = actualDecimals[idx] ?: 0+ val bitsA = actualBitSlices[idx] ?: emptyList()+ IOPanelRow("$name cur", decA, bitsA, Color(0xFF22C55E))+ Spacer(modifier = Modifier.height(6.dp))+ }+ }+}++@Composable+private fun IOPanelRow(name: String, dec: Int, bits: List<Boolean>, col: Color) {+ Column(modifier = Modifier.fillMaxWidth()) {+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {+ Box(modifier = Modifier.size(5.dp).clip(CircleShape).background(col))+ Text(text = name.take(14), fontSize = 9.sp, color = Color.White)+ }+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(2.dp), modifier = Modifier.padding(start = 4.dp, top = 2.dp)) {+ BitDotRow(bits, dotSize = 6.dp)+ }+ Text(text = "$dec", fontSize = 9.sp, color = Color(0xFF9AA3BB), modifier = Modifier.padding(start = 8.dp))+ }+}++@Composable+private fun TuringBottomTruthPanel(+ level: com.vayunmathur.games.logicgate.data.LevelDef,+ selectedIdx: Int,+ inputDecimals: Map<Int, Int>,+ inputBitSlices: Map<Int, List<Boolean>>,+ desiredDecimals: Map<Int, Int>,+ desiredBitSlices: Map<Int, List<Boolean>>,+ actualDecimals: Map<Int, Int>,+ actualBitSlices: Map<Int, List<Boolean>>,+ failingCount: Int,+ modifier: Modifier = Modifier+) {+ Column(modifier = modifier.padding(8.dp).verticalScroll(rememberScrollState())) {+ Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {+ Text("Test #${selectedIdx} • ${level.displayName} • fail $failingCount", fontSize = 9.sp, color = Color(0xFF94A3B8))+ Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {+ Text("Tick 0", fontSize = 8.sp, color = Color(0xFF6B7D96))+ Text("0hz", fontSize = 8.sp, color = Color(0xFF6B7D96))+ }+ }+ Spacer(modifier = Modifier.height(6.dp))+ level.inputs.forEachIndexed { idx, name ->+ val dec = inputDecimals[idx] ?: 0+ val bits = inputBitSlices[idx] ?: emptyList()+ Row(modifier = Modifier.fillMaxWidth().padding(vertical = 2.dp), verticalAlignment = Alignment.CenterVertically) {+ Text(text = name, fontSize = 10.sp, color = Color(0xFFFBBF24), modifier = Modifier.width(86.dp))+ Text(text = "$dec", fontSize = 10.sp, color = Color.White, modifier = Modifier.width(34.dp))+ BitDotRow(bits, dotSize = 8.dp)+ }+ }+ Box(modifier = Modifier.fillMaxWidth().height(1.dp).background(Color(0xFF2A3042)))+ Spacer(modifier = Modifier.height(4.dp))+ level.outputs.forEachIndexed { idx, name ->+ val decD = desiredDecimals[idx] ?: 0+ val bitsD = desiredBitSlices[idx] ?: emptyList()+ val decA = actualDecimals[idx] ?: 0+ val bitsA = actualBitSlices[idx] ?: emptyList()+ Row(modifier = Modifier.fillMaxWidth().padding(vertical = 2.dp), verticalAlignment = Alignment.CenterVertically) {+ Text(text = "Desired $name", fontSize = 9.sp, color = Color(0xFFF59E0B), modifier = Modifier.width(86.dp))+ Text(text = "$decD", fontSize = 9.sp, color = Color.White, modifier = Modifier.width(34.dp))+ BitDotRow(bitsD, dotSize = 8.dp)+ }+ Row(modifier = Modifier.fillMaxWidth().padding(vertical = 2.dp), verticalAlignment = Alignment.CenterVertically) {+ val match = decD == decA+ Text(text = "Current $name", fontSize = 9.sp, color = if (match) Color(0xFF22C55E) else Color(0xFFFF8A80), modifier = Modifier.width(86.dp))+ Text(text = "$decA", fontSize = 9.sp, color = if (match) Color(0xFF86EFAC) else Color(0xFFFF8A80), modifier = Modifier.width(34.dp))+ BitDotRow(bitsA, dotSize = 8.dp)+ if (!match) Text(text = " ✗", fontSize = 10.sp, color = Color(0xFFFF8A80))+ }+ }+ }+}++@Composable+fun BitDot(isOne: Boolean, dotSize: androidx.compose.ui.unit.Dp = 8.dp) {+ // Green = 1 (ON) matches Turing Complete screenshot where green dot = 1+ Box(modifier = Modifier.size(dotSize).clip(CircleShape).background(if (isOne) Color(0xFF22C55E) else Color(0xFFEF4444)))+}++@Composable+fun BitDotRow(bits: List<Boolean>, dotSize: androidx.compose.ui.unit.Dp = 7.dp, maxDots: Int = 8) {+ val display = if (bits.size > 1) bits.reversed() else bits // MSB left like screenshot+ Row(horizontalArrangement = Arrangement.spacedBy(3.dp), verticalAlignment = Alignment.CenterVertically) {+ display.take(maxDots).forEach { b -> BitDot(b, dotSize) }+ if (display.size > maxDots) Text(text = "+${display.size - maxDots}", fontSize = 8.sp, color = Color(0xFF6B7D96))+ }+}++@Composable+fun TuringInventoryBar(+ allowed: List<String>,+ unlockedChips: Set<String>,+ selectedGroup: ChipGroup?,+ onChipDragStart: (chipId: String, global: Offset) -> Unit,+ onChipDrag: (chipId: String, global: Offset) -> Unit,+ onChipDrop: (chipId: String, global: Offset) -> Unit,+ modifier: Modifier = Modifier+) {+ val rowScroll = rememberScrollState()+ Column(modifier = modifier.background(Color(0xFF131C26), RoundedCornerShape(topStart = 10.dp, topEnd = 10.dp)).padding(6.dp)) {+ Row(+ modifier = Modifier.fillMaxWidth().horizontalScroll(rowScroll),+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ verticalAlignment = Alignment.CenterVertically+ ) {+ val filtered = allowed.filter { it in unlockedChips }.filter { chipId ->+ if (selectedGroup == null) true else {+ val def = try { ChipLibrary.get(chipId) } catch (_: Exception) { null }+ def?.let { groupForCategory(it.category) == selectedGroup } ?: true+ }+ }.sortedBy { try { ChipLibrary.get(it).nandCost } catch (_: Exception) { 999 } }++ filtered.forEach { chipId ->+ TuringDraggableChipItem(+ chipId = chipId,+ chipOnDragStart = { id, g -> onChipDragStart(id, g) },+ chipOnDrag = { id, g -> onChipDrag(id, g) },+ chipOnDrop = { id, g -> onChipDrop(id, g) }+ )+ }+ if (filtered.isEmpty()) {+ Text("No chips in filter • select ALL", fontSize = 10.sp, color = Color(0xFF6B7D96), modifier = Modifier.padding(8.dp))+ }+ }+ }+}++@Composable+private fun TuringDraggableChipItem(+ chipId: String,+ chipOnDragStart: (String, Offset) -> Unit,+ chipOnDrag: (String, Offset) -> Unit,+ chipOnDrop: (String, Offset) -> Unit+) {+ val def = ChipLibrary.get(chipId)+ val baseCol = when (def.category) {+ ChipCategory.PRIMITIVE -> Color(0xFF1B3A4A)+ ChipCategory.FOUNDATION -> Color(0xFF134E2D)+ ChipCategory.ROUTING -> Color(0xFF5A3812)+ ChipCategory.BUS -> Color(0xFF312A4A)+ ChipCategory.ARITH -> Color(0xFF6B2A12)+ ChipCategory.MEMORY -> Color(0xFF3A1A52)+ ChipCategory.CPU -> Color(0xFF6B1437)+ }+ val busW = def.dominantBusWidth()+ val busColor = when (busW) { 4 -> Color(0xFFFFA126); 8 -> Color(0xFF4FC3FF); else -> Color(0xFF2BE4B8) }++ var chipPosInWindow by remember { mutableStateOf(Offset.Zero) }+ var isDragging by remember { mutableStateOf(false) }++ Box(+ modifier = Modifier+ .onGloballyPositioned { c -> chipPosInWindow = c.positionInWindow() }+ .clip(RoundedCornerShape(8.dp))+ .background(baseCol)+ .border(if (isDragging) 1.6.dp else if (def.isBus) 1.dp else 0.6.dp, if (isDragging) Color.White else busColor.copy(alpha = if (def.isBus) 0.7f else 0.25f), RoundedCornerShape(8.dp))+ .pointerInput(chipId) {+ awaitPointerEventScope {+ while (true) {+ val down = awaitFirstDownGlobal()+ val startWindow = chipPosInWindow + down.position+ var dragActive = false+ var curWindow = startWindow+ while (true) {+ val ev = awaitPointerEvent()+ val ch = ev.changes.firstOrNull { it.id == down.id } ?: break+ if (ch.changedToUpIgnoreConsumed()) {+ if (dragActive) chipOnDrop(chipId, curWindow)+ isDragging = false+ break+ }+ val total = ch.position - down.position+ curWindow = startWindow + total+ if (!dragActive && total.getDistance() > 14f) {+ dragActive = true+ isDragging = true+ chipOnDragStart(chipId, curWindow)+ }+ if (dragActive) {+ ch.consume()+ chipOnDrag(chipId, curWindow)+ } } } } }+ .padding(horizontal = 10.dp, vertical = 7.dp),+ contentAlignment = Alignment.Center+ ) {+ Column(horizontalAlignment = Alignment.CenterHorizontally) {+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(3.dp)) {+ if (busW > 1) Box(modifier = Modifier.size(5.dp).clip(CircleShape).background(busColor))+ Text(text = def.displayName, fontSize = 10.sp, color = Color.White)+ }+ Text(text = "${def.inputs.size}→${def.outputs.size} ${def.nandCost}N", fontSize = 8.sp, color = Color.White.copy(alpha = 0.6f))+ }+ }+}++private suspend fun AwaitPointerEventScope.awaitFirstDownGlobal(): PointerInputChange {+ while (true) {+ val ev = awaitPointerEvent()+ if (ev.type == PointerEventType.Press) {+ val d = ev.changes.firstOrNull { !it.isConsumed } ?: continue+ return d } } }
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 b9ee5a5032..da9663688c 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@@ -304,15 +304,28 @@ object CircuitEvaluator { return if (order.size == nodes.size) order else null } + // Shared sampling util — same sequence used by evaluator and TruthTableView (Phase 3 fix: seed alignment)+ // Previously TruthTableView used seed 1 + %3 pattern vs evaluator seed 1234 — failingRows indices mismatched display+ fun generateSampleVectors(totalInputBits: Int, limit: Int = 256, seed: Long = 1234L): List<List<Boolean>> {+ return if (totalInputBits <= 10) {+ (0 until (1 shl totalInputBits)).map { c -> List(totalInputBits) { i -> ((c shr i) and 1) == 1 } }.take(limit)+ } else {+ val rnd = java.util.Random(seed)+ val vs = mutableListOf<List<Boolean>>()+ vs.add(List(totalInputBits) { false })+ vs.add(List(totalInputBits) { true })+ vs.add(List(totalInputBits) { it % 2 == 0 })+ while (vs.size < limit) vs.add(List(totalInputBits) { rnd.nextBoolean() })+ vs+ }+ }+ fun generateTruthTable(target: ChipDef, inputBits: Int, outputBits: Int, limit: Int = 256): List<List<Boolean>> { val total = if (inputBits <= 10) (1 shl inputBits) else minOf(limit, 1 shl minOf(inputBits, 20)) return if (inputBits <= 10) { (0 until total).map { c -> val inp = List(inputBits) { i -> ((c shr i) and 1) == 1 }; target.eval(inp).take(outputBits) } } else {- val rnd = java.util.Random(42)- val vecs = mutableListOf<List<Boolean>>()- vecs.add(List(inputBits) { false }); vecs.add(List(inputBits) { true }); vecs.add(List(inputBits) { it % 2 == 0 })- while (vecs.size < minOf(limit, total)) vecs.add(List(inputBits) { rnd.nextBoolean() })+ val vecs = generateSampleVectors(inputBits, minOf(limit, total), 1234L) vecs.map { inp -> target.eval(inp).take(outputBits) } } }
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/CanvasTransform.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/CanvasTransform.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/CanvasTransform.ktindex 2ebb01b9ed..d0d4ba6d0f 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/CanvasTransform.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/CanvasTransform.kt@@ -2,27 +2,43 @@ package com.vayunmathur.games.logicgate.ui import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size+import androidx.compose.ui.unit.Density+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp /**- * Viewport + clamping. World can be larger than screen; canvas responsive.- * Fixes bug: hardcoded 920f output terminals off-screen portrait.+ * Viewport + clamping — density-aware refactor from plan Phase 2+4.+ * Fixes bug: hardcoded 12f px in clampGate, hardcoded 920f output off-screen portrait. */ data class CanvasViewport(val offset: Offset = Offset.Zero, val scale: Float = 1f) { fun worldToScreen(p: Offset): Offset = (p - offset) * scale fun screenToWorld(p: Offset): Offset = p / scale + offset } -fun clampGate(pos: Offset, w: Float, h: Float, canvasSize: Size): Offset {+fun clampGate(+ pos: Offset,+ w: Float,+ h: Float,+ canvasSize: Size,+ padding: Dp = 12.dp,+ density: Density? = null+): Offset { if (canvasSize.width <= 0f || canvasSize.height <= 0f) return Offset(pos.x.coerceAtLeast(0f), pos.y.coerceAtLeast(0f))- val half = 12f- val minX = half- val minY = half- val maxX = (canvasSize.width - w - half).coerceAtLeast(minX)- val maxY = (canvasSize.height - h - half).coerceAtLeast(minY)+ val padPx = density?.let { with(it) { padding.toPx() } } ?: 12f+ val minX = padPx+ val minY = padPx+ val maxX = (canvasSize.width - w - padPx).coerceAtLeast(minX)+ val maxY = (canvasSize.height - h - padPx).coerceAtLeast(minY) return Offset(pos.x.coerceIn(minX, maxX), pos.y.coerceIn(minY, maxY)) } -fun clampTerm(center: Offset, pillW: Float, canvasSize: Size, padding: Float): Offset {+fun clampTerm(+ center: Offset,+ pillW: Float,+ canvasSize: Size,+ padding: Float,+ density: Density? = null+): Offset { if (canvasSize.width <= 0f || canvasSize.height <= 0f) return center val half = pillW / 2f + padding val maxX = (canvasSize.width - half).coerceAtLeast(half)@@ -33,7 +49,7 @@ fun clampTerm(center: Offset, pillW: Float, canvasSize: Size, padding: Float): O } /**- * Responsive default positions for I/O terminals – fixes portrait off-screen bug.+ * Responsive default positions for I/O terminals — fixes portrait off-screen bug. * Inputs left side, outputs right edge relative to current canvasSize. */ fun defaultInputPos(idx: Int, canvasSize: Size, pillW: Float = 86f): Offset {
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 76d2cd12bc..e05930f1d2 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,9 +2,21 @@ package com.vayunmathur.games.logicgate.ui import androidx.compose.foundation.Canvas import androidx.compose.foundation.background+import androidx.compose.foundation.border+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.RoundedCornerShape 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.CornerRadius import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size@@ -13,23 +25,40 @@ import androidx.compose.ui.graphics.Path import androidx.compose.ui.graphics.PathEffect import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.graphics.drawscope.Stroke-import androidx.compose.ui.hapticfeedback.HapticFeedbackType import androidx.compose.ui.input.pointer.changedToUpIgnoreConsumed import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.platform.LocalDensity-import androidx.compose.ui.platform.LocalHapticFeedback import androidx.compose.ui.text.TextStyle-import androidx.compose.ui.text.drawText import androidx.compose.ui.text.rememberTextMeasurer import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp+import com.vayunmathur.games.logicgate.R import com.vayunmathur.games.logicgate.data.* import kotlin.math.abs-import kotlin.math.hypot import kotlin.math.max import kotlin.math.min +// ----- Palette: Turing Complete mobile -----+private object Turing {+ val bg = Color(0xFF111E2E) // canvas deep+ val grid = Color(0xFF1E344A) // grid line+ val gridDot = Color(0x14FFFFFF)+ val inputRed = Color(0xFFD44A4A) // big I/O circles+ val inputBorder = Color(0xFFFF8A8A)+ val outputRed = Color(0xFFD44A4A)+ val outputBorder = Color(0xFFFF8A8A)+ val gateBgDefault = Color(0xFF0F6D62)+ val gateStroke = Color(0xFF46E6CF)+ val bit = Color(0xFF7EE8C0)+ val bus4 = Color(0xFFFFA231)+ val bus8 = Color(0xFF60C0FF)+ val ghostOk = Color(0xFFFFFF00)+ val ghostBad = Color(0x66FFFFFF)+ val pinOut = Color(0xFFA7F3D0)+ val pinIn = Color.White+}+ data class GateBox(val chip: PlacedChip, val left: Float, val top: Float, val w: Float, val h: Float) { fun inputPos(i: Int, count: Int): Offset { if (count <= 1) return Offset(left, top + h / 2f)@@ -41,6 +70,16 @@ data class GateBox(val chip: PlacedChip, val left: Float, val top: Float, val w: val gap = h / (count + 1) return Offset(left + w, top + gap * (i + 1)) }+ fun inputPosLocal(i: Int, count: Int): Offset {+ if (count <= 1) return Offset(0f, h / 2f)+ val gap = h / (count + 1)+ return Offset(0f, gap * (i + 1))+ }+ fun outputPosLocal(i: Int, count: Int): Offset {+ if (count <= 1) return Offset(w, h / 2f)+ val gap = h / (count + 1)+ return Offset(w, gap * (i + 1))+ } fun bodyContains(p: Offset): Boolean = p.x in left..left + w && p.y in top..top + h } @@ -48,14 +87,6 @@ data class TerminalBox(val idx: Int, val center: Offset, val name: String, val i data class HitOutput(val end: WireEnd, val pos: Offset) data class HitInput(val end: WireEnd, val pos: Offset) -sealed class DragMode {- object None : DragMode()- data class Gate(val id: String, val grabOffset: Offset, val start: Offset, val startLeft: Float, val startTop: Float) : DragMode()- data class InputTerm(val idx: Int, val start: Offset) : DragMode()- data class OutputTerm(val idx: Int, val start: Offset) : DragMode()- data class Wiring(val from: WireEnd, val fromPos: Offset, var cur: Offset) : DragMode()-}- @Composable fun CircuitCanvas( level: LevelDef,@@ -79,22 +110,28 @@ fun CircuitCanvas( onOutputMapDelete: (Int) -> Unit, dragGhostLineEnd: Offset?, onGhostLine: (Offset?) -> Unit,+ inputValues: Map<Int, Int> = emptyMap(),+ desiredOutputValues: Map<Int, Int> = emptyMap(),+ outputValues: Map<Int, Int> = emptyMap(), modifier: Modifier = Modifier ) { val density = LocalDensity.current- val haptic = LocalHapticFeedback.current val textMeasurer = rememberTextMeasurer() var canvasSizePx by remember { mutableStateOf(Size.Zero) } - val pinHitR = with(density) { 24.dp.toPx() }- val termMoveHitR = with(density) { 40.dp.toPx() }- val termWireDotR = with(density) { 20.dp.toPx() }- val wireHitThreshold = with(density) { 32.dp.toPx() }+ val pinHitR = with(density) { 28.dp.toPx() }+ val termMoveHitR = with(density) { 56.dp.toPx() }+ val termWireDotR = with(density) { 26.dp.toPx() }+ val wireHitThreshold = with(density) { 34.dp.toPx() } fun gateSizeFor(def: ChipDef): Pair<Float, Float> { val maxPins = max(def.inputCount, def.outputCount)- val wDp = when { maxPins > 8 -> 154.dp; maxPins > 4 -> 134.dp; else -> 118.dp }- val hDp = if (maxPins <= 2) 54.dp else (19.dp * maxPins + 28.dp).coerceAtLeast(54.dp)+ val wDp = when {+ maxPins > 8 -> 128.dp+ maxPins > 4 -> 104.dp+ else -> 88.dp+ }+ val hDp = if (maxPins <= 2) 46.dp else (18.dp * maxPins + 18.dp).coerceAtLeast(46.dp) return with(density) { wDp.toPx() to hDp.toPx() } } @@ -108,7 +145,15 @@ fun CircuitCanvas( val rectById = remember(gateBoxes) { gateBoxes.associateBy { it.chip.instanceId } } val chipDefs = remember(gates) { gates.associate { it.instanceId to ChipLibrary.get(it.chipId) } } - fun pillW(name: String): Float = with(density) { 72.dp.toPx() + name.length * 3.6f }+ fun pillW(name: String): Float {+ val measured = try {+ val layout = textMeasurer.measure(name, TextStyle(fontSize = 10.sp))+ layout.size.width.toFloat()+ } catch (_: Exception) {+ name.length * 9f+ }+ return (with(density) { 54.dp.toPx() } + measured).coerceIn(with(density) { 68.dp.toPx() }, with(density) { 132.dp.toPx() })+ } val inputLayouts: List<TerminalBox> = remember(level.inputs, inputPositions, canvasSizePx) { level.inputs.mapIndexed { i, name ->@@ -130,73 +175,52 @@ fun CircuitCanvas( fun dotForInput(t: TerminalBox): Offset = Offset(t.center.x + t.pillW / 2f - with(density) { 10.dp.toPx() }, t.center.y) fun dotForOutput(t: TerminalBox): Offset = Offset(t.center.x - t.pillW / 2f + with(density) { 10.dp.toPx() }, t.center.y) - fun resolveSource(end: WireEnd): Offset? {+ fun resolveSourceWith(boxes: Map<String, GateBox>, inLayouts: List<TerminalBox>, end: WireEnd): Offset? { if (end.instanceId.startsWith("__IN_")) { val idx = end.instanceId.removePrefix("__IN_").toIntOrNull() ?: return null- return inputLayouts.find { it.idx == idx }?.let { dotForInput(it) }+ return inLayouts.find { it.idx == idx }?.let { dotForInput(it) } }- val gr = rectById[end.instanceId] ?: return null+ val gr = boxes[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? {+ fun resolveSinkWith(boxes: Map<String, GateBox>, outLayouts: List<TerminalBox>, end: WireEnd): Offset? { if (end.instanceId.startsWith("__OUT_")) { val idx = end.instanceId.removePrefix("__OUT_").toIntOrNull() ?: return null- return outputLayouts.find { it.idx == idx }?.let { dotForOutput(it) }+ return outLayouts.find { it.idx == idx }?.let { dotForOutput(it) } }- val gr = rectById[end.instanceId] ?: return null+ val gr = boxes[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) } - fun hitOutputDot(pos: Offset): HitOutput? {- for (t in inputLayouts) if ((pos - dotForInput(t)).getDistance() < termWireDotR) return HitOutput(WireEnd("__IN_${t.idx}", 0), dotForInput(t))- for (box in gateBoxes) {- val def = chipDefs[box.chip.instanceId] ?: continue- for (j in 0 until def.outputCount) {- val pp = box.outputPos(j, def.outputCount)- if ((pos - pp).getDistance() < pinHitR) return HitOutput(WireEnd(box.chip.instanceId, j), pp)- }- }- return null- }- fun hitInputDot(pos: Offset): HitInput? {- for (box in gateBoxes) {- val def = chipDefs[box.chip.instanceId] ?: continue- for (j in 0 until def.inputCount) {- val pp = box.inputPos(j, def.inputCount)- if ((pos - pp).getDistance() < pinHitR) return HitInput(WireEnd(box.chip.instanceId, j), pp)- }- }- for (t in outputLayouts) if ((pos - dotForOutput(t)).getDistance() < termWireDotR) return HitInput(WireEnd("__OUT_${t.idx}", 0), dotForOutput(t))- return null- }- fun hitGateBody(pos: Offset): GateBox? = gateBoxes.reversed().firstOrNull { it.bodyContains(pos) }- fun hitInputTermMove(pos: Offset): TerminalBox? = inputLayouts.firstOrNull { (pos - it.center).getDistance() < termMoveHitR }- fun hitOutputTermMove(pos: Offset): TerminalBox? = outputLayouts.firstOrNull { (pos - it.center).getDistance() < termMoveHitR }+ fun resolveSource(end: WireEnd): Offset? = resolveSourceWith(rectById, inputLayouts, end)+ fun resolveSink(end: WireEnd): Offset? = resolveSinkWith(rectById, outputLayouts, end) - fun findClosestWire(pos: Offset): Wire? {- var best: Wire? = null; var bestD = wireHitThreshold- for (w in wires) {- 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 = wireHitThreshold- for (om in outputMaps) {- val a = resolveSource(om.from) ?: continue- val b = outputLayouts.find { it.idx == om.outputIndex }?.let { dotForOutput(it) } ?: continue- val d = distPointToBezier(pos, a, b)- if (d < bestD) { bestD = d; best = om }- }- return best- }+ // Live refs for background canvas gesture (so pointerInput(Unit) still sees latest)+ val gateBoxesRef = remember { mutableStateOf(gateBoxes) }+ val rectByIdRef = remember { mutableStateOf(rectById) }+ val chipDefsRef = remember { mutableStateOf(chipDefs) }+ val inputLayoutsRef = remember { mutableStateOf(inputLayouts) }+ val outputLayoutsRef = remember { mutableStateOf(outputLayouts) }+ val wiresRef = remember { mutableStateOf(wires) }+ val outputMapsRef = remember { mutableStateOf(outputMaps) }+ val canvasSizeRef = remember { mutableStateOf(canvasSizePx) }+ val wiringFromRef = remember { mutableStateOf(wiringFrom) }+ val dragGhostEndRef = remember { mutableStateOf(dragGhostLineEnd) } - var draggedGateId by remember { mutableStateOf<String?>(null) }- var wiringStartLocal by remember { mutableStateOf<HitOutput?>(null) }+ LaunchedEffect(gateBoxes, rectById, chipDefs, inputLayouts, outputLayouts, wires, outputMaps, canvasSizePx, wiringFrom, dragGhostLineEnd) {+ gateBoxesRef.value = gateBoxes+ rectByIdRef.value = rectById+ chipDefsRef.value = chipDefs+ inputLayoutsRef.value = inputLayouts+ outputLayoutsRef.value = outputLayouts+ wiresRef.value = wires+ outputMapsRef.value = outputMaps+ canvasSizeRef.value = canvasSizePx+ wiringFromRef.value = wiringFrom+ dragGhostEndRef.value = dragGhostLineEnd+ } val currentOnCreateWire by rememberUpdatedState(onCreateWire) val currentOnStartWiring by rememberUpdatedState(onStartWiring)@@ -211,287 +235,697 @@ fun CircuitCanvas( val currentOnWireDelete by rememberUpdatedState(onWireDelete) val currentOnOutputMapDelete by rememberUpdatedState(onOutputMapDelete) val currentOnGhostLine by rememberUpdatedState(onGhostLine)- val latestWiringFrom by rememberUpdatedState(wiringFrom) - Canvas(+ // Canvas size tracking Box+ Box( modifier = modifier .fillMaxSize()- .background(Color(0xFF0C141D))+ .background(Turing.bg) .onSizeChanged { canvasSizePx = Size(it.width.toFloat(), it.height.toFloat()) }- .pointerInput(gates, wires, inputPositions, outputPositions, canvasSizePx) {- 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 = DragMode.None- var gateStartLeft = 0f- var gateStartTop = 0f- var inputStart = Offset.Zero- var outputStart = Offset.Zero- var wireStart: HitOutput? = null-- val outDotAtDown = hitOutputDot(downPos)- val inDotAtDown = hitInputDot(downPos)- val gateBoxAtDown = if (outDotAtDown == null && inDotAtDown == null) hitGateBody(downPos) else null- val gateAtDown = gateBoxAtDown?.chip- 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-- if (outDotAtDown != null) {- wireStart = outDotAtDown- wiringStartLocal = outDotAtDown- mode = DragMode.Wiring(outDotAtDown.end, outDotAtDown.pos, outDotAtDown.pos)- currentOnStartWiring(outDotAtDown.end)- currentOnGhostLine(outDotAtDown.pos)+ ) {+ // Bottom layer: grid + wires + ghost+ Canvas(+ modifier = Modifier+ .fillMaxSize()+ .pointerInput(Unit) {+ fun resolveSrcLive(end: WireEnd): Offset? = resolveSourceWith(rectByIdRef.value, inputLayoutsRef.value, end)+ fun resolveSnkLive(end: WireEnd): Offset? = resolveSinkWith(rectByIdRef.value, outputLayoutsRef.value, end)+ fun closestWireLive(pos: Offset): Wire? {+ var best: Wire? = null; var bestD = wireHitThreshold+ for (w in wiresRef.value) {+ val a = resolveSrcLive(w.from) ?: continue; val b = resolveSnkLive(w.to) ?: continue+ val d = distPointToBezier(pos, a, b)+ if (d < bestD) { bestD = d; best = w }+ }+ return best+ }+ fun closestOMLive(pos: Offset): OutputMapping? {+ var best: OutputMapping? = null; var bestD = wireHitThreshold+ for (om in outputMapsRef.value) {+ val a = resolveSrcLive(om.from) ?: continue+ val b = outputLayoutsRef.value.find { it.idx == om.outputIndex }?.let { dotForOutput(it) } ?: continue+ val d = distPointToBezier(pos, a, b)+ if (d < bestD) { bestD = d; best = om } }+ return best+ }+ fun hitInputLive(pos: Offset): HitInput? {+ val boxes = gateBoxesRef.value+ val cDefs = chipDefsRef.value+ val outLayouts = outputLayoutsRef.value+ for (box in boxes) {+ val def = cDefs[box.chip.instanceId] ?: continue+ for (j in 0 until def.inputCount) {+ val pp = box.inputPos(j, def.inputCount)+ if ((pos - pp).getDistance() < pinHitR) return HitInput(WireEnd(box.chip.instanceId, j), pp)+ }+ }+ for (t in outLayouts) if ((pos - dotForOutput(t)).getDistance() < termWireDotR) return HitInput(WireEnd("__OUT_${t.idx}", 0), dotForOutput(t))+ return null+ } + awaitPointerEventScope { while (true) {- val event = awaitPointerEvent()- val main = event.changes.firstOrNull { it.id == down.id } ?: break- if (main.changedToUpIgnoreConsumed()) {- if (!isDragStarted && !longPressHandled) {- if (latestWiringFrom != null || wiringStartLocal != null) {- val dst = hitInputDot(main.position)- if (dst != null) {- val from = latestWiringFrom ?: wiringStartLocal?.end- if (from != null && from.instanceId != dst.end.instanceId) currentOnCreateWire(from, dst.end)- }- currentOnCancelWiring(); wiringStartLocal = null; currentOnGhostLine(null)- } else {- val outHit = hitOutputDot(main.position)- if (outHit != null) { wiringStartLocal = outHit; 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 is DragMode.Wiring) {- 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(); wiringStartLocal = null; draggedGateId = null- } else if (isDragStarted) {- when (mode) {- is DragMode.Gate -> {- val gid = (mode as DragMode.Gate).id- val box = rectById[gid]- if (box != null) {- val clamped = clampGate(Offset(box.left, box.top), box.w, box.h, canvasSizePx)- currentOnGateMoveFinished(gid, clamped.x, clamped.y)- }- }- is DragMode.InputTerm -> {- val idx = (mode as DragMode.InputTerm).idx- val term = inputLayouts.find { it.idx == idx }- term?.let {- val clamped = clampTerm(it.center, it.pillW, canvasSizePx, 8f)- currentOnInputMoveFinished(idx, clamped.x, clamped.y)- }- }- is DragMode.OutputTerm -> {- val idx = (mode as DragMode.OutputTerm).idx- val term = outputLayouts.find { it.idx == idx }- term?.let {- val clamped = clampTerm(it.center, it.pillW, canvasSizePx, 8f)- currentOnOutputMoveFinished(idx, clamped.x, clamped.y)- }- }- else -> {}- }- draggedGateId = null+ val down = awaitFirstDown(requireUnconsumed = false)+ val downPos = down.position+ val cw = closestWireLive(downPos)+ if (cw != null) {+ currentOnWireDelete(cw.id)+ // consume up+ while (true) {+ val ev = awaitPointerEvent()+ val ch = ev.changes.firstOrNull { it.id == down.id } ?: break+ if (ch.changedToUpIgnoreConsumed()) break }- break+ continue }- if (longPressHandled) continue- val pos = main.position- totalDrag = pos - downPos- if (!isDragStarted) {- val elapsed = System.currentTimeMillis() - downTime- if (mode is DragMode.None && gateAtDown != null && elapsed > 500 && totalDrag.getDistance() < 12f) {- try { haptic.performHapticFeedback(HapticFeedbackType.LongPress) } catch (_: Exception) {}- currentOnGateDelete(gateAtDown.instanceId); longPressHandled = true; break+ val om = closestOMLive(downPos)+ if (om != null) {+ currentOnOutputMapDelete(om.outputIndex)+ while (true) {+ val ev = awaitPointerEvent()+ val ch = ev.changes.firstOrNull { it.id == down.id } ?: break+ if (ch.changedToUpIgnoreConsumed()) break }- if (totalDrag.getDistance() > 12f) {- if (mode is DragMode.Wiring) isDragStarted = true else {- isDragStarted = true- when {- outDotAtDown != null -> {- mode = DragMode.Wiring(outDotAtDown.end, outDotAtDown.pos, pos)- wireStart = outDotAtDown; wiringStartLocal = outDotAtDown- if (latestWiringFrom == null) currentOnStartWiring(outDotAtDown.end)- currentOnGhostLine(pos)- }- inTermMoveAtDown != null -> { mode = DragMode.InputTerm(inTermMoveAtDown.idx, inTermMoveAtDown.center); inputStart = inTermMoveAtDown.center }- outTermMoveAtDown != null -> { mode = DragMode.OutputTerm(outTermMoveAtDown.idx, outTermMoveAtDown.center); outputStart = outTermMoveAtDown.center }- gateAtDown != null && gateBoxAtDown != null -> {- val grabOff = downPos - Offset(gateBoxAtDown.left, gateBoxAtDown.top)- mode = DragMode.Gate(gateAtDown.instanceId, grabOff, Offset(gateBoxAtDown.left, gateBoxAtDown.top), gateBoxAtDown.left, gateBoxAtDown.top)- gateStartLeft = gateBoxAtDown.left; gateStartTop = gateBoxAtDown.top; draggedGateId = gateAtDown.instanceId- }- else -> mode = DragMode.None- }- }+ continue+ }+ // If wiring active, tap empty cancels or completes to input+ if (wiringFromRef.value != null) {+ val hitIn = hitInputLive(downPos)+ if (hitIn != null && wiringFromRef.value!!.instanceId != hitIn.end.instanceId) {+ currentOnCreateWire(wiringFromRef.value!!, hitIn.end)+ } else {+ currentOnCancelWiring()+ }+ currentOnGhostLine(null)+ while (true) {+ val ev = awaitPointerEvent()+ val ch = ev.changes.firstOrNull { it.id == down.id } ?: break+ if (ch.changedToUpIgnoreConsumed()) break }+ continue }- if (isDragStarted) {- when (mode) {- is DragMode.Gate -> {- val gMode = mode as DragMode.Gate- val newLeft = gMode.startLeft + totalDrag.x- val newTop = gMode.startTop + totalDrag.y- val box = rectById[gMode.id]- val clamped = if (box != null) clampGate(Offset(newLeft, newTop), box.w, box.h, canvasSizePx) else Offset(newLeft.coerceAtLeast(0f), newTop.coerceAtLeast(0f))- currentOnGateMove(gMode.id, clamped.x, clamped.y)- }- is DragMode.InputTerm -> {- val idx = (mode as DragMode.InputTerm).idx- val newCenter = inputStart + totalDrag- val term = inputLayouts.find { it.idx == idx }- val clamped = if (term != null) clampTerm(newCenter, term.pillW, canvasSizePx, 8f) else newCenter- currentOnInputMove(idx, clamped.x, clamped.y)- }- is DragMode.OutputTerm -> {- val idx = (mode as DragMode.OutputTerm).idx- val newCenter = outputStart + totalDrag- val term = outputLayouts.find { it.idx == idx }- val clamped = if (term != null) clampTerm(newCenter, term.pillW, canvasSizePx, 8f) else newCenter- currentOnOutputMove(idx, clamped.x, clamped.y)+ // Ghost drag tracking when wiring active (second finger move after start)+ var cur = downPos+ var tracking = wiringFromRef.value != null+ while (true) {+ val ev = awaitPointerEvent()+ val ch = ev.changes.firstOrNull { it.id == down.id } ?: break+ if (ch.changedToUpIgnoreConsumed()) {+ if (tracking) {+ val hitIn = hitInputLive(cur)+ if (hitIn != null && wiringFromRef.value != null && wiringFromRef.value!!.instanceId != hitIn.end.instanceId) {+ currentOnCreateWire(wiringFromRef.value!!, hitIn.end)+ }+ currentOnCancelWiring()+ currentOnGhostLine(null) }- is DragMode.Wiring -> { (mode as DragMode.Wiring).cur = pos; currentOnGhostLine(pos) }- else -> {}+ break+ }+ cur = ch.position+ if (wiringFromRef.value != null) {+ currentOnGhostLine(cur)+ tracking = true } }- currentPos = pos }- if (mode is DragMode.Gate) draggedGateId = null } }+ ) {+ val cs = canvasSizePx+ // grid+ val gridStep = 68f+ if (cs.width > 1f && cs.height > 1f) {+ var x = 0f+ while (x <= cs.width) {+ drawLine(Turing.grid, Offset(x, 0f), Offset(x, cs.height), strokeWidth = 1.1f)+ x += gridStep+ }+ var y = 0f+ while (y <= cs.height) {+ drawLine(Turing.grid, Offset(0f, y), Offset(cs.width, y), strokeWidth = 1.1f)+ y += gridStep+ }+ var gx = 0f+ while (gx < cs.width) {+ var gy = 0f+ while (gy < cs.height) { drawCircle(Turing.gridDot, 1f, Offset(gx, gy)); gy += gridStep }+ gx += gridStep+ } }- ) {- drawRect(Color(0xFF0C141D))- val gridSpacing = 36f- if (canvasSizePx.width > 0) {- var gx = 0f- while (gx < canvasSizePx.width) {- var gy = 0f- while (gy < canvasSizePx.height) { drawCircle(Color.White.copy(alpha = 0.05f), 1.2f, Offset(gx, gy)); gy += gridSpacing }- gx += gridSpacing+ // wires+ for (w in wires) {+ val a = resolveSource(w.from) ?: continue; val b = resolveSink(w.to) ?: continue+ val (col, thick) = wireStyleForWidth(w.busWidth)+ drawWire(a, b, col, false, thick)+ }+ for (om in outputMaps) {+ val a = resolveSource(om.from) ?: continue+ val b = outputLayouts.find { it.idx == om.outputIndex }?.let { dotForOutput(it) } ?: continue+ val srcWidth = try {+ val gate = gateBoxes.find { it.chip.instanceId == om.from.instanceId }+ val def = gate?.let { chipDefs[it.chip.instanceId] }+ def?.outputPinWidth(om.from.pinIndex) ?: 1+ } catch (_: Exception) { 1 }+ val (_, thick) = wireStyleForWidth(srcWidth)+ drawWire(a, b, Color(0xFFFDE68A), false, thick)+ }+ // ghost+ val gStart = wiringFrom?.let { resolveSource(it) }+ val gEnd = dragGhostLineEnd+ if (gStart != null && gEnd != null) {+ val isOverInput = run {+ var found = false+ for (box in gateBoxes) {+ val def = chipDefs[box.chip.instanceId] ?: continue+ for (j in 0 until def.inputCount) {+ val pp = box.inputPos(j, def.inputCount)+ if ((gEnd - pp).getDistance() < pinHitR) { found = true; break }+ }+ }+ if (!found) for (t in outputLayouts) if ((gEnd - dotForOutput(t)).getDistance() < termWireDotR + 6f) { found = true; break }+ found+ }+ drawWire(gStart, gEnd, if (isOverInput) Turing.ghostOk else Turing.ghostBad, true, 3f, dash = true)+ } else if (wiringFrom != null) {+ resolveSource(wiringFrom)?.let { drawCircle(Color.Yellow.copy(alpha = 0.28f), 22f, it) } } }- for (w in wires) {- val a = resolveSource(w.from) ?: continue; val b = resolveSink(w.to) ?: continue- val (color, thick) = wireStyleForWidth(w.busWidth); drawWire(a, b, color, false, thickPx = thick)- }- for (om in outputMaps) {- val a = resolveSource(om.from) ?: continue- val b = outputLayouts.find { it.idx == om.outputIndex }?.let { dotForOutput(it) } ?: continue- val srcWidth = try {- val gate = gateBoxes.find { it.chip.instanceId == om.from.instanceId }- val def = gate?.let { chipDefs[it.chip.instanceId] }- def?.outputPinWidth(om.from.pinIndex) ?: 1- } catch (_: Exception) { 1 }- val (_, thick) = wireStyleForWidth(srcWidth); drawWire(a, b, Color(0xFFFDE68A), false, thickPx = thick)- }- val ghostStart = wiringStartLocal?.pos ?: wiringFrom?.let { resolveSource(it) }- val ghostEnd = dragGhostLineEnd- if (ghostStart != null && ghostEnd != null) {- val overValid = hitInputDot(ghostEnd) != null- val ghostColor = if (overValid) Color(0xFFFFFF00) else Color(0x66FFFFFF)- drawWire(ghostStart, ghostEnd, ghostColor, true, thickPx = 3.2f, dash = true)- } else if (wiringFrom != null) {- resolveSource(wiringFrom)?.let { drawCircle(Color.Yellow.copy(alpha = 0.30f), 24f, it) }++ // Terminal layers (draggable circles)+ inputLayouts.forEach { t ->+ DraggableTerminal(+ box = t,+ isInput = true,+ decimal = inputValues[t.idx],+ canvasSize = canvasSizePx,+ wiringFrom = wiringFrom,+ ghostEnd = dragGhostLineEnd,+ onMove = { idx, x, y -> currentOnInputMove(idx, x, y) },+ onMoveFinished = { idx, x, y -> currentOnInputMoveFinished(idx, x, y) },+ onStartWiring = { end -> currentOnStartWiring(end); currentOnGhostLine(resolveSource(end)) },+ onCompleteWiring = { from, to -> currentOnCreateWire(from, to); currentOnGhostLine(null) },+ onGhost = { off -> currentOnGhostLine(off) },+ onCancel = { currentOnCancelWiring(); currentOnGhostLine(null) },+ density = density,+ textMeasurer = textMeasurer,+ pinHitR = pinHitR,+ termWireDotR = termWireDotR,+ hitInputLive = { pos ->+ val boxes = gateBoxesRef.value+ val cDefs = chipDefsRef.value+ val outLayouts = outputLayoutsRef.value+ for (box in boxes) {+ val def = cDefs[box.chip.instanceId] ?: continue+ for (j in 0 until def.inputCount) {+ val pp = box.inputPos(j, def.inputCount)+ if ((pos - pp).getDistance() < pinHitR) return@DraggableTerminal HitInput(WireEnd(box.chip.instanceId, j), pp)+ }+ }+ for (ot in outLayouts) if ((pos - dotForOutput(ot)).getDistance() < termWireDotR) return@DraggableTerminal HitInput(WireEnd("__OUT_${ot.idx}", 0), dotForOutput(ot))+ null+ },+ dotForOutputLocal = { tt -> dotForOutput(tt) },+ dotForInputLocal = { tt -> dotForInput(tt) }+ ) }- for (t in inputLayouts) {- val isSrc = wiringFrom?.instanceId == "__IN_${t.idx}" || wiringStartLocal?.end?.instanceId == "__IN_${t.idx}"- drawTerminalPill(t.center, t.name, if (isSrc) Color(0xFF3A3110) else Color(0xFF17283A), if (isSrc) Color.Yellow else Color(0xFF38BDF8), true, isSrc, textMeasurer)+ outputLayouts.forEach { t ->+ DraggableTerminal(+ box = t,+ isInput = false,+ decimal = outputValues[t.idx] ?: desiredOutputValues[t.idx],+ canvasSize = canvasSizePx,+ wiringFrom = wiringFrom,+ ghostEnd = dragGhostLineEnd,+ onMove = { idx, x, y -> currentOnOutputMove(idx, x, y) },+ onMoveFinished = { idx, x, y -> currentOnOutputMoveFinished(idx, x, y) },+ onStartWiring = { end -> currentOnStartWiring(end) },+ onCompleteWiring = { from, to -> currentOnCreateWire(from, to); currentOnGhostLine(null) },+ onGhost = { off -> currentOnGhostLine(off) },+ onCancel = { currentOnCancelWiring(); currentOnGhostLine(null) },+ density = density,+ textMeasurer = textMeasurer,+ pinHitR = pinHitR,+ termWireDotR = termWireDotR,+ hitInputLive = { pos ->+ val boxes = gateBoxesRef.value+ val cDefs = chipDefsRef.value+ val outLayouts = outputLayoutsRef.value+ for (box in boxes) {+ val def = cDefs[box.chip.instanceId] ?: continue+ for (j in 0 until def.inputCount) {+ val pp = box.inputPos(j, def.inputCount)+ if ((pos - pp).getDistance() < pinHitR) return@DraggableTerminal HitInput(WireEnd(box.chip.instanceId, j), pp)+ }+ }+ for (ot in outLayouts) if ((pos - dotForOutput(ot)).getDistance() < termWireDotR) return@DraggableTerminal HitInput(WireEnd("__OUT_${ot.idx}", 0), dotForOutput(ot))+ null+ },+ dotForOutputLocal = { tt -> dotForOutput(tt) },+ dotForInputLocal = { tt -> dotForInput(tt) }+ ) }- 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 layer — each gate is its own draggable Box (guaranteed move works, like Alchemist DraggableElement)+ gateBoxes.forEach { gBox ->+ DraggableGate(+ gateBox = gBox,+ chipDef = chipDefs[gBox.chip.instanceId],+ canvasSize = canvasSizePx,+ wiringFrom = wiringFrom,+ ghostEnd = dragGhostLineEnd,+ onMove = { id, x, y -> currentOnGateMove(id, x, y) },+ onMoveFinished = { id, x, y -> currentOnGateMoveFinished(id, x, y) },+ onDelete = { id -> currentOnGateDelete(id) },+ onStartWiring = { end -> currentOnStartWiring(end) },+ onCompleteWiring = { from, to -> currentOnCreateWire(from, to) },+ onGhost = { off -> currentOnGhostLine(off) },+ onCancel = { currentOnCancelWiring(); currentOnGhostLine(null) },+ density = density,+ textMeasurer = textMeasurer,+ pinHitR = pinHitR,+ hitInputLive = { pos ->+ val boxes = gateBoxesRef.value+ val cDefs = chipDefsRef.value+ val outLayouts = outputLayoutsRef.value+ for (box in boxes) {+ val def = cDefs[box.chip.instanceId] ?: continue+ for (j in 0 until def.inputCount) {+ val pp = box.inputPos(j, def.inputCount)+ if ((pos - pp).getDistance() < pinHitR) return@DraggableGate HitInput(WireEnd(box.chip.instanceId, j), pp)+ }+ }+ for (ot in outLayouts) if ((pos - dotForOutput(ot)).getDistance() < termWireDotR) return@DraggableGate HitInput(WireEnd("__OUT_${ot.idx}", 0), dotForOutput(ot))+ null+ },+ gateBoxesRef = gateBoxesRef,+ rectByIdRef = rectByIdRef,+ dotForOutputLocal = { tt -> dotForOutput(tt) },+ ) }- for (box in gateBoxes) {- val def = chipDefs[box.chip.instanceId] ?: continue- val isDragged = draggedGateId == box.chip.instanceId- val base = when (def.category) {- ChipCategory.PRIMITIVE -> Color(0xFF1E3A4A)- ChipCategory.FOUNDATION -> Color(0xFF14532D)- ChipCategory.ROUTING -> Color(0xFF713F12)- ChipCategory.BUS -> Color(0xFF3B2E4A)- ChipCategory.ARITH -> Color(0xFF7C2D12)- ChipCategory.MEMORY -> Color(0xFF3B0764)- ChipCategory.CPU -> Color(0xFF881337)+ }+}++@Composable+private fun DraggableGate(+ gateBox: GateBox,+ chipDef: ChipDef?,+ canvasSize: Size,+ wiringFrom: WireEnd?,+ ghostEnd: Offset?,+ onMove: (String, Float, Float) -> Unit,+ onMoveFinished: (String, Float, Float) -> Unit,+ onDelete: (String) -> Unit,+ onStartWiring: (WireEnd) -> Unit,+ onCompleteWiring: (WireEnd, WireEnd) -> Unit,+ onGhost: (Offset?) -> Unit,+ onCancel: () -> Unit,+ density: androidx.compose.ui.unit.Density,+ textMeasurer: androidx.compose.ui.text.TextMeasurer,+ pinHitR: Float,+ hitInputLive: (Offset) -> HitInput?,+ gateBoxesRef: MutableState<List<GateBox>>,+ rectByIdRef: MutableState<Map<String, GateBox>>,+ dotForOutputLocal: (TerminalBox) -> Offset,+) {+ val def = chipDef ?: return+ val id = gateBox.chip.instanceId+ var localPos by remember(id) { mutableStateOf(Offset(gateBox.left, gateBox.top)) }+ var dragging by remember(id) { mutableStateOf(false) }+ // Sync from VM when not dragging+ LaunchedEffect(gateBox.left, gateBox.top) {+ if (!dragging) localPos = Offset(gateBox.left, gateBox.top)+ }+ val w = gateBox.w+ val h = gateBox.h++ Box(+ modifier = Modifier+ .offset { androidx.compose.ui.unit.IntOffset(localPos.x.toInt(), localPos.y.toInt()) }+ .size(with(density) { w.toDp() }, with(density) { h.toDp() })+ .clip(RoundedCornerShape(8.dp))+ .background(+ when (def.category) {+ ChipCategory.PRIMITIVE -> Color(0xFF114A52)+ ChipCategory.FOUNDATION -> Color(0xFF14523E)+ ChipCategory.ROUTING -> Color(0xFF2A5A35)+ ChipCategory.BUS -> Color(0xFF342A68)+ ChipCategory.ARITH -> Color(0xFF6E3514)+ ChipCategory.MEMORY -> Color(0xFF4A1C6B)+ ChipCategory.CPU -> Color(0xFF7E163C)+ }+ )+ .border(1.2.dp, if (dragging) Color.White else Turing.gateStroke.copy(alpha = 0.5f), RoundedCornerShape(8.dp))+ .pointerInput(id) {+ awaitPointerEventScope {+ while (true) {+ val down = awaitFirstDown(requireUnconsumed = false)+ // If down near a pin, let pin composable handle wiring (child will consume first)+ // Check if down is very close to a pin — if so skip gate drag to allow wiring+ var nearPin = false+ for (j in 0 until def.inputCount) {+ val lp = gateBox.inputPosLocal(j, def.inputCount)+ if ((down.position - lp).getDistance() < pinHitR) { nearPin = true; break }+ }+ if (!nearPin) {+ for (j in 0 until def.outputCount) {+ val lp = gateBox.outputPosLocal(j, def.outputCount)+ if ((down.position - lp).getDistance() < pinHitR) { nearPin = true; break }+ }+ }+ if (nearPin) {+ // let child handle; wait for up+ while (true) {+ val ev = awaitPointerEvent()+ val ch = ev.changes.firstOrNull { it.id == down.id } ?: break+ if (ch.changedToUpIgnoreConsumed()) break+ }+ continue+ }+ val start = localPos+ var total = Offset.Zero+ dragging = true+ val downTime = System.currentTimeMillis()+ var longHandled = false+ while (true) {+ val ev = awaitPointerEvent()+ val ch = ev.changes.firstOrNull { it.id == down.id } ?: break+ if (ch.changedToUpIgnoreConsumed()) {+ if (!longHandled) {+ if (total.getDistance() > 4f) {+ val clamped = clampGate(start + total, w, h, canvasSize, 12.dp, density)+ localPos = clamped+ onMoveFinished(id, clamped.x, clamped.y)+ }+ }+ break+ }+ total = ch.position - down.position+ val elapsed = System.currentTimeMillis() - downTime+ if (!longHandled && elapsed > 500 && total.getDistance() < 12f) {+ longHandled = true+ onDelete(id)+ break+ }+ if (total.getDistance() > 8f) {+ ch.consume()+ val newP = start + total+ val clamped = clampGate(newP, w, h, canvasSize, 12.dp, density)+ localPos = clamped+ onMove(id, clamped.x, clamped.y)+ }+ }+ dragging = false+ }+ } }- val corner = 12f- drawRoundRect(Color.Black.copy(alpha = 0.32f), Offset(box.left + 2f, box.top + 5f), Size(box.w, box.h), CornerRadius(corner, corner))- drawRoundRect(if (isDragged) base.copy(alpha = 0.98f) else base, Offset(box.left, box.top), Size(box.w, box.h), CornerRadius(corner, corner))- drawRoundRect(if (isDragged) Color.White else Color.White.copy(alpha = 0.16f), Offset(box.left, box.top), Size(box.w, box.h), CornerRadius(corner, corner), style = Stroke(width = if (isDragged) 2.4f else 1f))- drawRoundRect(Color.White.copy(alpha = 0.06f), Offset(box.left, box.top), Size(box.w, 16f), CornerRadius(corner, corner))- drawText(textMeasurer, def.displayName, Offset(box.left + 9f, box.top + 7f), TextStyle(if (def.category == ChipCategory.ROUTING) Color(0xFFFFE8A0) else Color.White, 11.sp))- drawText(textMeasurer, "${def.nandCost}N", Offset(box.left + box.w - 30f, box.top + 7f), TextStyle(Color.White.copy(alpha = 0.52f), 9.sp))+ ) {+ // Gate label+ Box(modifier = Modifier.fillMaxSize()) {+ androidx.compose.foundation.Canvas(modifier = Modifier.fillMaxSize()) {+ // subtle top highlight like screenshot+ drawRoundRect(Color.White.copy(alpha = 0.06f), Offset(0f, 0f), Size(w, 14f), CornerRadius(8f, 8f))+ }+ // Name+ androidx.compose.material3.Text(+ text = def.displayName.take(9),+ fontSize = 10.sp,+ color = Color.White,+ modifier = Modifier.align(Alignment.TopStart).padding(start = 6.dp, top = 4.dp)+ )+ androidx.compose.material3.Text(+ text = "${def.nandCost}N",+ fontSize = 7.sp,+ color = Color.White.copy(alpha = 0.5f),+ modifier = Modifier.align(Alignment.TopEnd).padding(end = 5.dp, top = 5.dp)+ )+ // Input pins with wiring drag for (j in 0 until def.inputCount) {- val pp = box.inputPos(j, def.inputCount)- 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.inputPinLabelFull(j), pp + Offset(10f, -6f), TextStyle(Color.White.copy(alpha = 0.82f), 8.sp))+ val lp = gateBox.inputPosLocal(j, def.inputCount)+ // Hover highlight when ghost near+ val isHover = ghostEnd?.let { ge ->+ val absPos = localPos + lp+ (ge - absPos).getDistance() < pinHitR+ } ?: false+ Box(+ modifier = Modifier+ .offset { androidx.compose.ui.unit.IntOffset((lp.x - 10f).toInt(), (lp.y - 10f).toInt()) }+ .size(20.dp)+ .clip(CircleShape)+ .background(if (isHover) Color.Yellow else Color.Transparent)+ .border(1.dp, if (isHover) Color.Yellow else Color.White.copy(alpha = 0.2f), CircleShape)+ .pointerInput(id, j) {+ awaitPointerEventScope {+ while (true) {+ val d = awaitFirstDown(requireUnconsumed = false)+ if ((d.position - Offset(10f, 10f)).getDistance() > pinHitR) {+ // not on pin center, let parent drag handle+ while (true) {+ val ev = awaitPointerEvent()+ val ch = ev.changes.firstOrNull { it.id == d.id } ?: break+ if (ch.changedToUpIgnoreConsumed()) break+ }+ continue+ }+ // Pin tap: if wiring active, completes wire+ if (wiringFrom != null && wiringFrom.instanceId != id) {+ onCompleteWiring(wiringFrom, WireEnd(id, j))+ onGhost(null)+ } else {+ onCancel()+ }+ while (true) {+ val ev = awaitPointerEvent()+ val ch = ev.changes.firstOrNull { it.id == d.id } ?: break+ if (ch.changedToUpIgnoreConsumed()) break+ }+ }+ }+ },+ contentAlignment = Alignment.Center+ ) {+ Box(modifier = Modifier.size(8.dp).clip(CircleShape).background(if (isHover) Color.Yellow else Color.White))+ } }+ // Output pins with wiring drag start for (j in 0 until def.outputCount) {- val pp = box.outputPos(j, def.outputCount)- val isSrc = (wiringFrom?.instanceId == box.chip.instanceId && wiringFrom.pinIndex == j) || (wiringStartLocal?.end?.instanceId == box.chip.instanceId && wiringStartLocal?.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.outputPinLabelFull(j)- drawText(textMeasurer, lbl, pp + Offset(-12f - lbl.length * 5.3f, -6f), TextStyle(Color.White.copy(alpha = 0.82f), 8.sp))+ val lp = gateBox.outputPosLocal(j, def.outputCount)+ val isSrc = wiringFrom?.instanceId == id && wiringFrom.pinIndex == j+ val isHoverOut = ghostEnd == null && isSrc // glow when source active+ Box(+ modifier = Modifier+ .offset { androidx.compose.ui.unit.IntOffset((lp.x - 10f).toInt(), (lp.y - 10f).toInt()) }+ .size(20.dp)+ .clip(CircleShape)+ .background(Color.Transparent)+ .pointerInput(id, j) {+ awaitPointerEventScope {+ while (true) {+ val down = awaitFirstDown(requireUnconsumed = false)+ if ((down.position - Offset(10f, 10f)).getDistance() > pinHitR) {+ while (true) {+ val ev = awaitPointerEvent()+ val ch = ev.changes.firstOrNull { it.id == down.id } ?: break+ if (ch.changedToUpIgnoreConsumed()) break+ }+ continue+ }+ val pinAbs = localPos + lp+ onStartWiring(WireEnd(id, j))+ onGhost(pinAbs)+ var cur = pinAbs+ var total = Offset.Zero+ while (true) {+ val ev = awaitPointerEvent()+ val ch = ev.changes.firstOrNull { it.id == down.id } ?: break+ if (ch.changedToUpIgnoreConsumed()) {+ // try create to input+ val hit = hitInputLive(cur)+ if (hit != null && hit.end.instanceId != id) {+ onCompleteWiring(WireEnd(id, j), hit.end)+ } else {+ onCancel()+ }+ onGhost(null)+ break+ }+ total = ch.position - down.position+ cur = pinAbs + total+ onGhost(cur)+ ch.consume()+ }+ }+ }+ },+ contentAlignment = Alignment.Center+ ) {+ Box(modifier = Modifier.size(if (isSrc) 22.dp else 0.dp).clip(CircleShape).background(Color.Yellow.copy(alpha = 0.16f)))+ Box(modifier = Modifier.size(10.dp).clip(CircleShape).background(if (isSrc) Color.Yellow else Turing.pinOut).border(1.dp, Color.Black.copy(alpha = 0.3f), CircleShape)) } } } } } -private fun wireStyleForWidth(busWidth: Int): Pair<Color, Float> = when (busWidth) {- 4 -> Color(0xFFF59E0B) to 4.2f- 8 -> Color(0xFF60A5FA) to 6.0f- else -> Color(0xFF7ED8B6) to 2.7f+@Composable+private fun DraggableTerminal(+ box: TerminalBox,+ isInput: Boolean,+ decimal: Int?,+ canvasSize: Size,+ wiringFrom: WireEnd?,+ ghostEnd: Offset?,+ onMove: (Int, Float, Float) -> Unit,+ onMoveFinished: (Int, Float, Float) -> Unit,+ onStartWiring: (WireEnd) -> Unit,+ onCompleteWiring: (WireEnd, WireEnd) -> Unit,+ onGhost: (Offset?) -> Unit,+ onCancel: () -> Unit,+ density: androidx.compose.ui.unit.Density,+ textMeasurer: androidx.compose.ui.text.TextMeasurer,+ pinHitR: Float,+ termWireDotR: Float,+ hitInputLive: (Offset) -> HitInput?,+ dotForOutputLocal: (TerminalBox) -> Offset,+ dotForInputLocal: (TerminalBox) -> Offset,+) {+ var center by remember(box.idx, box.center) { mutableStateOf(box.center) }+ var dragging by remember(box.idx) { mutableStateOf(false) }+ LaunchedEffect(box.center) { if (!dragging) center = box.center }++ val radius = 40f+ val diameter = radius * 2f+ val radiusDp = with(density) { radius.toDp() }+ val diamDp = with(density) { diameter.toDp() }++ Box(+ modifier = Modifier+ .offset { androidx.compose.ui.unit.IntOffset((center.x - radius).toInt(), (center.y - radius).toInt()) }+ .size(diamDp)+ .clip(CircleShape)+ .background(Turing.inputRed)+ .border(if (wiringFrom?.instanceId == "__${if (isInput) "IN" else "OUT"}_${box.idx}") 2.4.dp else 1.4.dp, if (wiringFrom?.instanceId == "__${if (isInput) "IN" else "OUT"}_${box.idx}" || (ghostEnd?.let { (it - center).getDistance() < termWireDotR + 10f } == true)) Color.Yellow else if (isInput) Turing.inputBorder else Turing.outputBorder, CircleShape)+ .pointerInput(box.idx) {+ awaitPointerEventScope {+ while (true) {+ val down = awaitFirstDown(requireUnconsumed = false)+ val isNearDot = run {+ val dotLocal = if (isInput) Offset(diameter - 10f, radius) else Offset(10f, radius)+ (down.position - dotLocal).getDistance() < termWireDotR+ }+ if (isNearDot) {+ // Let dot handler manage (child) — wait for up to avoid double handling+ while (true) {+ val ev = awaitPointerEvent()+ val ch = ev.changes.firstOrNull { it.id == down.id } ?: break+ if (ch.changedToUpIgnoreConsumed()) break+ }+ continue+ }+ val start = center+ var total = Offset.Zero+ dragging = true+ while (true) {+ val ev = awaitPointerEvent()+ val ch = ev.changes.firstOrNull { it.id == down.id } ?: break+ if (ch.changedToUpIgnoreConsumed()) {+ val clamped = clampTerm(start + total, diameter, canvasSize, 8f, density)+ center = clamped+ onMoveFinished(box.idx, clamped.x, clamped.y)+ break+ }+ total = ch.position - down.position+ val newC = start + total+ val clamped = clampTerm(newC, diameter, canvasSize, 8f, density)+ center = clamped+ onMove(box.idx, clamped.x, clamped.y)+ ch.consume()+ }+ dragging = false+ }+ }+ },+ contentAlignment = Alignment.Center+ ) {+ // Label + decimal like screenshot red circles: value big, name small below+ androidx.compose.foundation.layout.Column(horizontalAlignment = Alignment.CenterHorizontally) {+ androidx.compose.material3.Text(text = decimal?.toString() ?: box.name.take(4), fontSize = 10.sp, color = Color.White, maxLines = 1)+ androidx.compose.material3.Text(text = box.name.take(7), fontSize = 7.sp, color = Color.White.copy(alpha = 0.8f), maxLines = 1)+ }+ // Dot at edge+ val dotOffset = if (isInput) Modifier.align(Alignment.CenterEnd).offset(x = (-4).dp) else Modifier.align(Alignment.CenterStart).offset(x = 4.dp)+ Box(+ modifier = Modifier+ .then(dotOffset)+ .size(14.dp)+ .clip(CircleShape)+ .background(if (wiringFrom?.instanceId == "__${if (isInput) "IN" else "OUT"}_${box.idx}") Color.Yellow else if (isInput) Color(0xFF38BDF8) else Color(0xFFF87171))+ .border(1.dp, Color.Black.copy(alpha = 0.4f), CircleShape)+ .pointerInput(box.idx, isInput) {+ awaitPointerEventScope {+ while (true) {+ val down = awaitFirstDown(requireUnconsumed = false)+ val dotAbs = if (isInput) center + Offset(radius - 6f, 0f) else center + Offset(-radius + 6f, 0f)+ if (isInput) {+ // source: start wiring drag+ onStartWiring(WireEnd("__IN_${box.idx}", 0))+ onGhost(dotAbs)+ var cur = dotAbs+ var total = Offset.Zero+ while (true) {+ val ev = awaitPointerEvent()+ val ch = ev.changes.firstOrNull { it.id == down.id } ?: break+ if (ch.changedToUpIgnoreConsumed()) {+ val hit = hitInputLive(cur)+ if (hit != null) {+ onCompleteWiring(WireEnd("__IN_${box.idx}", 0), hit.end)+ } else {+ onCancel()+ }+ onGhost(null)+ break+ }+ total = ch.position - down.position+ cur = dotAbs + total+ onGhost(cur)+ ch.consume()+ }+ } else {+ // sink: if wiring active, completes+ if (wiringFrom != null) {+ onCompleteWiring(wiringFrom, WireEnd("__OUT_${box.idx}", 0))+ onGhost(null)+ } else {+ onCancel()+ }+ while (true) {+ val ev = awaitPointerEvent()+ val ch = ev.changes.firstOrNull { it.id == down.id } ?: break+ if (ch.changedToUpIgnoreConsumed()) break+ }+ }+ }+ }+ }+ )+ } } -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 wireStyleForWidth(busWidth: Int): Pair<Color, Float> = when (busWidth) {+ 4 -> Turing.bus4 to 4.2f+ 8 -> Turing.bus8 to 5.8f+ else -> Turing.bit to 2.8f } -private fun DrawScope.drawWire(from: Offset, to: Offset, color: Color, isSelected: Boolean, thickPx: Float = 2.7f, dash: Boolean = false) {+private fun DrawScope.drawWire(from: Offset, to: Offset, color: Color, isSelected: Boolean, thickPx: Float, dash: Boolean = false) { val dx = to.x - from.x val ctrl = min(180f, max(50f, 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 = thickPx + 5.3f))+ if (isSelected || color.alpha > 0.5f) drawPath(path, color.copy(alpha = 0.14f), style = Stroke(width = thickPx + 5.2f)) if (dash) drawPath(path, color, style = Stroke(width = thickPx, pathEffect = PathEffect.dashPathEffect(floatArrayOf(12f, 8f), 0f))) else drawPath(path, color, style = Stroke(width = thickPx))- drawCircle(color, thickPx * 0.75f + 1.2f, to)- drawCircle(Color.Black.copy(alpha = 0.7f), 1.3f, to)+ drawCircle(color, thickPx * 0.68f + 1f, to)+ drawCircle(Color.Black.copy(alpha = 0.55f), 1.2f, to) } private fun distPointToSegment(p: Offset, a: Offset, b: Offset): Float {@@ -507,7 +941,7 @@ private fun distPointToBezier(p: Offset, from: Offset, to: Offset): Float { 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 y = mt * mt * mt * from.y + 3 * mt * mt * t * from.y + 3 * mt * 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@@ -520,29 +954,3 @@ private suspend fun androidx.compose.ui.input.pointer.AwaitPointerEventScope.awa } } }-private fun Offset.getDistance(): Float = hypot(x, y)--@Composable-fun CircuitCanvas(- level: LevelDef,- gates: List<PlacedChip>,- wires: List<Wire>,- outputMaps: List<OutputMapping>,- inputPositions: Map<Int, IoPos>,- outputPositions: Map<Int, IoPos>,- wiringFrom: WireEnd?,- 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-) {- CircuitCanvas(level, gates, wires, outputMaps, inputPositions, outputPositions, wiringFrom, onCreateWire, onStartWiring, onCancelWiring, onGateMove, onGateMove, onInputTermMove, onInputTermMove, onOutputTermMove, onOutputTermMove, onGateDelete, onWireDelete, onOutputMapDelete, dragGhostLineEnd, onGhostLine, modifier)-}
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 3d8b3de1d6..69c1ecbfd0 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@@ -19,7 +19,7 @@ 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.layout.positionInWindow import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.Dp@@ -28,7 +28,6 @@ import androidx.compose.ui.unit.sp import com.vayunmathur.games.logicgate.data.ChapterId import com.vayunmathur.games.logicgate.data.ChipCategory import com.vayunmathur.games.logicgate.data.ChipLibrary-import com.vayunmathur.games.logicgate.data.CircuitEvaluator import com.vayunmathur.games.logicgate.data.LevelDef import com.vayunmathur.games.logicgate.data.Levels import com.vayunmathur.games.logicgate.util.LogicViewModel@@ -41,8 +40,6 @@ import com.vayunmathur.library.ui.Scaffold 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 import androidx.compose.ui.res.stringResource import com.vayunmathur.games.logicgate.R @@ -88,54 +85,51 @@ fun ProgressionScreen( ) } ) { paddingValues ->- BoxWithConstraints(modifier = Modifier.fillMaxSize().padding(paddingValues).background(MaterialTheme.colorScheme.background)) {- val calculatedSide = (maxWidth * 0.22f).coerceIn(48.dp, 96.dp)- val sideOffset: Dp = calculatedSide- 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 = Modifier.height(12.dp))- LibText(stringResource(R.string.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(stringResource(R.string.tap_to_play_lines_show_dependencies_36_l), 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(prev, sideOffset, connectorH, completed)- }- 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(next, sideOffset, connectorH, completed)- }+ val nodeSize: Dp = 68.dp+ val sideOffset: Dp = nodeSize / 2 + 28.dp+ val connectorH: Dp = 38.dp+ val chapterH: Dp = 58.dp+ val scroll = rememberScrollState()+ Column(
Diff truncated.