Refactor: Implement SmartCube renderer, improve UI styling, and fix gaps

This commit is contained in:
2026-02-22 04:35:59 +00:00
parent 57abfd6b80
commit b5ddc21662
4168 changed files with 763782 additions and 1008 deletions

View File

@@ -1,7 +1,5 @@
<script setup>
import CubeCSS from './components/renderers/CubeCSS.vue'
import DebugPanel from './components/DebugPanel.vue'
import InteractionReplay from './components/InteractionReplay.vue'
import SmartCube from './components/renderers/SmartCube.vue'
import NavBar from './components/NavBar.vue'
import Footer from './components/Footer.vue'
</script>
@@ -9,9 +7,7 @@ import Footer from './components/Footer.vue'
<template>
<NavBar />
<div class="app-content">
<DebugPanel />
<InteractionReplay />
<CubeCSS />
<SmartCube />
</div>
<Footer />
</template>
@@ -23,7 +19,7 @@ import Footer from './components/Footer.vue'
justify-content: center;
align-items: center;
width: 100%;
padding: 2rem 0;
padding: 0;
position: relative;
z-index: 1;
user-select: none;

View File

@@ -57,7 +57,7 @@ const toggle = () => isOpen.value = !isOpen.value
.debug-panel {
position: fixed;
top: 70px;
right: 10px;
right: 20px;
width: 250px;
background: rgba(0, 0, 0, 0.85);
color: #fff;

View File

@@ -22,11 +22,15 @@ const version = __APP_VERSION__;
display: flex;
align-items: center;
justify-content: center;
margin-top: auto;
background: var(--panel-bg);
backdrop-filter: blur(10px);
border-top: 1px solid var(--panel-border);
box-shadow: 0 -4px 15px rgba(0, 0, 0, 0.1);
position: absolute;
bottom: 0;
left: 0;
z-index: 10;
/* Glass panel styles handle background/border/shadow */
border-radius: 0; /* Full width bar usually square corners or specific radius */
border-left: none;
border-right: none;
border-bottom: none;
color: var(--text-muted);
box-sizing: border-box;
}

View File

@@ -4,7 +4,7 @@ import { ref } from 'vue'
import { useInteractionLogger } from '../composables/useInteractionLogger'
const { logs, isRecording, clearLogs, getRecentLogsForAnalysis } = useInteractionLogger()
const isOpen = ref(false)
const isOpen = ref(true)
const copied = ref(false)
const toggle = () => isOpen.value = !isOpen.value

View File

@@ -5,6 +5,7 @@ import { useCube } from '../composables/useCube'
import CubeCSS from './renderers/CubeCSS.vue'
import CubeSVG from './renderers/CubeSVG.vue'
import CubeCanvas from './renderers/CubeCanvas.vue'
import CubeRubiksJS from './renderers/CubeRubiksJS.vue'
const { activeRenderer, RENDERERS } = useRenderer()
const { cubeState } = useCube()
@@ -17,6 +18,8 @@ const currentRendererComponent = computed(() => {
return CubeSVG
case RENDERERS.CANVAS:
return CubeCanvas
case RENDERERS.RUBIKS_JS:
return CubeRubiksJS
default:
return CubeCSS
}

View File

@@ -1,9 +1,6 @@
<script setup>
import { Sun, Moon } from 'lucide-vue-next';
import { ref, onMounted } from 'vue';
import { useRenderer } from '../composables/useRenderer';
const { activeRenderer, setRenderer, RENDERERS } = useRenderer();
const isDark = ref(true);
@@ -11,30 +8,6 @@ const setTheme = (dark) => {
isDark.value = dark;
const theme = dark ? 'dark' : 'light';
document.documentElement.dataset.theme = theme;
if (dark) {
document.documentElement.style.setProperty('--bg-gradient', 'linear-gradient(135deg, #2c3e50 0%, #000000 100%)');
document.documentElement.style.setProperty('--text-color', '#ffffff');
document.documentElement.style.setProperty('--text-strong', '#ffffff');
document.documentElement.style.setProperty('--text-muted', 'rgba(255, 255, 255, 0.7)');
document.documentElement.style.setProperty('--glass-bg', 'rgba(255, 255, 255, 0.05)');
document.documentElement.style.setProperty('--glass-border', 'rgba(255, 255, 255, 0.1)');
document.documentElement.style.setProperty('--panel-bg', 'rgba(255, 255, 255, 0.05)');
document.documentElement.style.setProperty('--panel-border', 'rgba(255, 255, 255, 0.1)');
document.documentElement.style.setProperty('--cube-edge-color', '#333333');
document.documentElement.style.setProperty('--title-gradient', 'linear-gradient(45deg, #00f2fe, #4facfe)');
} else {
document.documentElement.style.setProperty('--bg-gradient', 'linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%)');
document.documentElement.style.setProperty('--text-color', '#0f172a');
document.documentElement.style.setProperty('--text-strong', '#0f172a');
document.documentElement.style.setProperty('--text-muted', 'rgba(15, 23, 42, 0.6)');
document.documentElement.style.setProperty('--glass-bg', 'rgba(255, 255, 255, 0.75)');
document.documentElement.style.setProperty('--glass-border', 'rgba(15, 23, 42, 0.12)');
document.documentElement.style.setProperty('--panel-bg', 'rgba(255, 255, 255, 0.7)');
document.documentElement.style.setProperty('--panel-border', 'rgba(15, 23, 42, 0.12)');
document.documentElement.style.setProperty('--cube-edge-color', '#000000');
document.documentElement.style.setProperty('--title-gradient', 'linear-gradient(45deg, #0ea5e9, #6366f1)');
}
};
const toggleTheme = () => {
@@ -53,18 +26,6 @@ onMounted(() => {
</div>
<div class="nav-container">
<div class="renderer-selector">
<button
v-for="renderer in RENDERERS"
:key="renderer"
@click="setRenderer(renderer)"
class="renderer-btn"
:class="{ active: activeRenderer === renderer }"
>
{{ renderer }}
</button>
</div>
<!-- Theme Toggle -->
<button class="btn-neon nav-btn icon-only" @click="toggleTheme" :title="isDark ? 'Przełącz na jasny' : 'Przełącz na ciemny'">
<Sun v-if="isDark" :size="20" />
@@ -80,17 +41,18 @@ onMounted(() => {
justify-content: space-between;
align-items: center;
padding: 0 20px;
height: 50px;
height: 60px;
width: 100%;
box-sizing: border-box;
position: sticky;
position: absolute;
top: 0;
left: 0;
z-index: 100;
margin-bottom: 0;
background: var(--glass-bg);
backdrop-filter: blur(10px);
border-bottom: 1px solid var(--glass-border);
box-shadow: var(--glass-shadow);
/* Glass panel styles handle background/border/shadow */
border-radius: 0;
border-top: none;
border-left: none;
border-right: none;
}
.logo-container {
@@ -100,10 +62,10 @@ onMounted(() => {
}
.logo-text {
font-size: 1.2rem;
font-size: 1.5rem;
font-weight: 700;
color: var(--text-color);
text-shadow: 0 0 20px var(--title-glow);
color: var(--text-strong);
letter-spacing: 1px;
}
.nav-container {
@@ -112,67 +74,19 @@ onMounted(() => {
align-items: center;
}
.renderer-selector {
display: flex;
gap: 5px;
background: rgba(0, 0, 0, 0.2);
padding: 3px;
border-radius: 6px;
}
.renderer-btn {
background: transparent;
border: none;
color: var(--text-muted);
padding: 4px 10px;
border-radius: 4px;
cursor: pointer;
font-size: 0.8rem;
font-weight: 600;
transition: all 0.2s;
}
.renderer-btn:hover {
color: var(--text-color);
}
.renderer-btn.active {
background: var(--glass-border);
color: var(--text-color);
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}
.nav-btn {
background: transparent;
border: none;
color: var(--text-color);
font-size: 1rem;
color: var(--text-strong);
cursor: pointer;
display: flex;
align-items: center;
gap: 8px;
padding: 8px 12px;
border-radius: 8px;
padding: 12px;
border-radius: 50%;
transition: all 0.3s ease;
}
.nav-btn:hover {
background: rgba(255, 255, 255, 0.1);
transform: translateY(-2px);
}
.btn-neon {
border: 1px solid var(--toggle-btn-border);
box-shadow: 0 0 5px rgba(0,0,0,0.1);
}
.desktop-only {
display: flex;
}
@media (max-width: 768px) {
.desktop-only {
display: none;
}
background: rgba(255, 255, 255, 0.2);
}
</style>

File diff suppressed because it is too large Load Diff

View File

@@ -1,34 +0,0 @@
<script setup>
import { onMounted } from 'vue'
onMounted(() => {
console.log('Canvas Renderer mounted (placeholder)')
})
</script>
<template>
<div class="canvas-container">
<canvas width="300" height="300"></canvas>
<div class="overlay">
Canvas Renderer (Coming Soon)
</div>
</div>
</template>
<style scoped>
.canvas-container {
width: 300px;
height: 300px;
position: relative;
display: flex;
justify-content: center;
align-items: center;
border: 1px dashed rgba(255, 255, 255, 0.3);
}
.overlay {
position: absolute;
color: white;
pointer-events: none;
}
</style>

View File

@@ -1,28 +0,0 @@
<script setup>
import { onMounted } from 'vue'
onMounted(() => {
console.log('SVG Renderer mounted (placeholder)')
})
</script>
<template>
<div class="svg-container">
<svg width="300" height="300" viewBox="0 0 300 300">
<text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" fill="white">
SVG Renderer (Coming Soon)
</text>
</svg>
</div>
</template>
<style scoped>
.svg-container {
width: 300px;
height: 300px;
display: flex;
justify-content: center;
align-items: center;
border: 1px dashed rgba(255, 255, 255, 0.3);
}
</style>

View File

@@ -0,0 +1,440 @@
<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useCube } from '../../composables/useCube'
const { cubies, initCube, rotateLayer, FACES } = useCube()
// --- Visual State ---
const rx = ref(-25) // Initial View Rotation X
const ry = ref(45) // Initial View Rotation Y
const rz = ref(0)
const SCALE = 100 // Size of one cubie in px
const GAP = 0 // Gap between cubies
// --- Interaction State ---
const isDragging = ref(false)
const dragMode = ref('view') // 'view' or 'layer'
const startX = ref(0)
const startY = ref(0)
const lastX = ref(0)
const lastY = ref(0)
const velocity = ref(0)
// Layer Interaction
const selectedCubie = ref(null) // { id, x, y, z } static snapshot at start of drag
const selectedFace = ref(null) // 'front', 'up', etc.
const activeLayer = ref(null) // { axis, index, tangent, direction }
const currentLayerRotation = ref(0) // Visual rotation in degrees
const isAnimating = ref(false)
// --- Constants & Helpers ---
const getFaceNormal = (face) => {
const map = {
[FACES.FRONT]: { x: 0, y: 0, z: 1 },
[FACES.BACK]: { x: 0, y: 0, z: -1 },
[FACES.RIGHT]: { x: 1, y: 0, z: 0 },
[FACES.LEFT]: { x: -1, y: 0, z: 0 },
[FACES.UP]: { x: 0, y: 1, z: 0 },
[FACES.DOWN]: { x: 0, y: -1, z: 0 },
}
return map[face] || { x: 0, y: 0, z: 1 }
}
const getAllowedAxes = (face) => {
// Logic: Which axes can this face physically move along?
switch(face) {
case FACES.FRONT: case FACES.BACK: return ['x', 'y']
case FACES.RIGHT: case FACES.LEFT: return ['z', 'y']
case FACES.UP: case FACES.DOWN: return ['x', 'z']
}
return []
}
const getAxisVector = (axis) => {
if (axis === 'x') return { x: 1, y: 0, z: 0 }
if (axis === 'y') return { x: 0, y: 1, z: 0 }
if (axis === 'z') return { x: 0, y: 0, z: 1 }
return { x: 0, y: 0, z: 0 }
}
// Cross Product: a x b
const cross = (a, b) => ({
x: a.y * b.z - a.z * b.y,
y: a.z * b.x - a.x * b.z,
z: a.x * b.y - a.y * b.x
})
// Project 3D vector to 2D screen space based on current view (rx, ry, rz)
const project = (v) => {
const radX = rx.value * Math.PI / 180
const radY = ry.value * Math.PI / 180
const radZ = rz.value * Math.PI / 180
// 1. Rotate Z
let x1 = v.x * Math.cos(radZ) - v.y * Math.sin(radZ)
let y1 = v.x * Math.sin(radZ) + v.y * Math.cos(radZ)
let z1 = v.z
// 2. Rotate Y
let x2 = x1 * Math.cos(radY) + z1 * Math.sin(radY)
let y2 = y1
let z2 = -x1 * Math.sin(radY) + z1 * Math.cos(radY)
// 3. Rotate X
let x3 = x2
let y3 = y2 * Math.cos(radX) - z2 * Math.sin(radX)
// let z3 = ... (depth not needed for projection vector direction)
return { x: x3, y: y3 }
}
// --- Interaction Logic ---
const onMouseDown = (e) => {
if (isAnimating.value) return
isDragging.value = true
startX.value = e.clientX
startY.value = e.clientY
lastX.value = e.clientX
lastY.value = e.clientY
velocity.value = 0
const target = e.target.closest('.sticker')
if (target) {
const id = parseInt(target.dataset.id)
const face = target.dataset.face
const cubie = cubies.value.find(c => c.id === id)
selectedCubie.value = { ...cubie } // Snapshot position
selectedFace.value = face
// Check if center piece (has 2 zero coordinates)
// Centers have sum of absolute coords = 1
// Core (0,0,0) has sum = 0
const absSum = Math.abs(cubie.x) + Math.abs(cubie.y) + Math.abs(cubie.z)
const isCenterOrCore = absSum <= 1
// Mechanical Realism:
// Centers are "Stiff" (part of the core frame). Dragging them rotates the View.
// Corners/Edges are "Moving Parts". Dragging them rotates the Layer.
dragMode.value = isCenterOrCore ? 'view' : 'layer'
} else {
dragMode.value = 'view'
selectedCubie.value = null
}
}
const onMouseMove = (e) => {
if (!isDragging.value) return
const dx = e.clientX - lastX.value
const dy = e.clientY - lastY.value
if (dragMode.value === 'view') {
ry.value += dx * 0.5
rx.value += dy * 0.5
} else if (dragMode.value === 'layer' && selectedCubie.value) {
const totalDx = e.clientX - startX.value
const totalDy = e.clientY - startY.value
handleLayerDrag(totalDx, totalDy, dx, dy)
}
lastX.value = e.clientX
lastY.value = e.clientY
}
const handleLayerDrag = (totalDx, totalDy, dx, dy) => {
// If we haven't locked an axis yet
if (!activeLayer.value) {
if (Math.sqrt(totalDx**2 + totalDy**2) < 5) return // Threshold
const faceNormal = getFaceNormal(selectedFace.value)
const axes = getAllowedAxes(selectedFace.value)
let best = null
let maxDot = 0
// Analyze candidates
axes.forEach(axis => {
// Tangent = Axis x Normal
// This is the 3D direction of motion for Positive Rotation around this Axis
const t3D = cross(getAxisVector(axis), faceNormal)
const t2D = project(t3D)
const len = Math.sqrt(t2D.x**2 + t2D.y**2)
if (len > 0.1) {
const nx = t2D.x / len
const ny = t2D.y / len
// Compare with mouse drag direction
const mouseLen = Math.sqrt(totalDx**2 + totalDy**2)
const mx = totalDx / mouseLen
const my = totalDy / mouseLen
const dot = Math.abs(mx * nx + my * ny)
if (dot > maxDot) {
maxDot = dot
best = { axis, tangent: { x: nx, y: ny } }
}
}
})
if (best && maxDot > 0.5) {
// Lock Axis
let index = 0
if (best.axis === 'x') index = selectedCubie.value.x
if (best.axis === 'y') index = selectedCubie.value.y
if (best.axis === 'z') index = selectedCubie.value.z
activeLayer.value = {
axis: best.axis,
index,
tangent: best.tangent
}
} else {
// Fallback: if drag doesn't match a layer axis, maybe user wants to rotate view?
// Only switch if drag is significant
if (Math.sqrt(totalDx**2 + totalDy**2) > 20) {
// Keep layer mode but maybe relax?
// No, sticky mode is better.
}
}
}
// If we have an active layer, update rotation
if (activeLayer.value) {
const { x, y } = activeLayer.value.tangent
// Project delta onto key
const val = dx * x + dy * y
// Scale factor
currentLayerRotation.value += val * 0.6
}
}
const onMouseUp = () => {
isDragging.value = false
if (activeLayer.value) {
snapRotation()
}
}
const snapRotation = () => {
isAnimating.value = true
// Determine nearest 90 deg
const target = Math.round(currentLayerRotation.value / 90) * 90
const steps = Math.round(currentLayerRotation.value / 90)
// Animation loop
const start = currentLayerRotation.value
const startTime = performance.now()
const duration = 200
const animate = (time) => {
const p = Math.min((time - startTime) / duration, 1)
// Ease out
const ease = 1 - Math.pow(1 - p, 3)
currentLayerRotation.value = start + (target - start) * ease
if (p < 1) {
requestAnimationFrame(animate)
} else {
// Animation done
finishMove(steps)
}
}
requestAnimationFrame(animate)
}
const finishMove = (steps) => {
if (steps !== 0 && activeLayer.value) {
const { axis, index } = activeLayer.value
// Logic Call
const count = Math.abs(steps)
const direction = steps > 0 ? 1 : -1
for (let i = 0; i < count; i++) {
rotateLayer(axis, index, direction)
}
}
// Reset
activeLayer.value = null
currentLayerRotation.value = 0
isAnimating.value = false
selectedCubie.value = null
selectedFace.value = null
}
const getCubieStyle = (c) => {
// Base Position
const x = c.x * (SCALE + GAP)
const y = c.y * -(SCALE + GAP) // Y is up in logic, down in CSS
const z = c.z * (SCALE + GAP)
let transform = `translate3d(${x}px, ${y}px, ${z}px)`
// Apply Active Layer Rotation
if (activeLayer.value) {
const { axis, index } = activeLayer.value
let match = false
// Match based on CURRENT LOGICAL POSITION
if (axis === 'x' && c.x === index) match = true
if (axis === 'y' && c.y === index) match = true
if (axis === 'z' && c.z === index) match = true
if (match) {
// Rotation Group around Center (0,0,0)
let rot = currentLayerRotation.value
// Axis mapping for CSS
// If we rotate a group around center, we want standard rotation.
// Logic Z=1 (Front). CSS +Z is Front.
// Logic Y=1 (Up). CSS -Y is Up.
// Logic X=1 (Right). CSS +X is Right.
// Rotations:
// CSS rotateX: + is Top->Back.
// CSS rotateY: + is Right->Back (Spin Right).
// CSS rotateZ: + is Top->Right (Clockwise).
if (axis === 'x') transform = `rotateX(${-rot}deg) ` + transform
if (axis === 'y') transform = `rotateY(${-rot}deg) ` + transform
if (axis === 'z') transform = `rotateZ(${rot}deg) ` + transform
}
}
return { transform }
}
onMounted(() => {
initCube()
window.addEventListener('mousemove', onMouseMove)
window.addEventListener('mouseup', onMouseUp)
})
onUnmounted(() => {
window.removeEventListener('mousemove', onMouseMove)
window.removeEventListener('mouseup', onMouseUp)
// Clean up any potential animation frames? rafId is local to snapRotation, but harmless.
})
</script>
<template>
<div class="smart-cube-container">
<div class="scene" :style="{ transform: `rotateX(${rx}deg) rotateY(${ry}deg)` }">
<div class="cube">
<div v-for="c in cubies" :key="c.id"
class="cubie"
:style="getCubieStyle(c)"
:data-cubie-id="c.id">
<div v-for="(color, face) in c.faces" :key="face"
class="sticker"
:class="[face, color]"
:data-id="c.id"
:data-face="face">
</div>
</div>
</div>
</div>
</div>
</template>
<style scoped>
.smart-cube-container {
width: 100vw;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
overflow: hidden;
background: transparent; /* Use global background */
perspective: 1000px;
}
.scene {
position: relative;
width: 0;
height: 0;
transform-style: preserve-3d;
}
.cube {
position: relative;
transform-style: preserve-3d;
}
.cubie {
position: absolute;
width: 100px;
height: 100px;
margin-left: -50px;
margin-top: -50px;
transform-style: preserve-3d;
}
.sticker {
position: absolute;
width: 100px;
height: 100px;
top: 0;
left: 0;
box-sizing: border-box;
background-color: #000; /* Black plastic base */
border: 1px solid #000; /* Ensure edge is solid */
box-shadow: 0 0 0 1px #000; /* External bleed to cover sub-pixel gaps */
border-radius: 2px; /* Minimal rounding for plastic edges, practically square */
backface-visibility: hidden; /* Hide inside faces */
}
/* Pseudo-element for the colored sticker part */
.sticker::after {
content: '';
position: absolute;
top: 4px;
left: 4px;
right: 4px;
bottom: 4px;
border-radius: 8px; /* Rounded sticker */
box-shadow: inset 0 0 5px rgba(0,0,0,0.3); /* Inner depth */
z-index: 1;
}
/* Sticker Positions relative to Cubie Center */
.sticker.up { transform: rotateX(90deg) translateZ(50px); }
.sticker.down { transform: rotateX(-90deg) translateZ(50px); }
.sticker.front { transform: translateZ(50px); }
.sticker.back { transform: rotateY(180deg) translateZ(50px); }
.sticker.left { transform: rotateY(-90deg) translateZ(50px); }
.sticker.right { transform: rotateY(90deg) translateZ(50px); }
/* Colors - apply to the pseudo-element */
.white::after { background: #E0E0E0; }
.yellow::after { background: #FFD500; }
.green::after { background: #009E60; }
.blue::after { background: #0051BA; }
.orange::after { background: #FF5800; }
.red::after { background: #C41E3A; }
/* Black internal faces - no sticker needed */
.black {
background: #050505;
border: 1px solid #000;
border-radius: 0;
display: block;
box-shadow: 0 0 0 1px #000; /* Fill gaps between internal faces */
}
.black::after {
display: none;
}
</style>

View File

@@ -1,42 +1,51 @@
import { ref, computed } from 'vue';
import { Cube, COLORS, FACES } from '../utils/Cube';
import { COLORS, FACES } from '../utils/CubeModel';
// Singleton worker
const worker = new Worker(new URL('../workers/Cube.worker.js', import.meta.url), { type: 'module' });
// Reactive state
const cubies = ref([]);
const isReady = ref(false);
const validationResult = ref(null);
worker.onmessage = (e) => {
const { type, payload } = e.data;
if (type === 'STATE_UPDATE') {
cubies.value = payload.cubies;
isReady.value = true;
} else if (type === 'VALIDATION_RESULT') {
validationResult.value = payload;
} else if (type === 'ERROR') {
console.error('Worker Error:', payload);
}
};
// Init worker
worker.postMessage({ type: 'INIT' });
export function useCube() {
const cube = ref(new Cube());
// Make cubies reactive so Vue tracks changes
// We can just expose the cube instance, but better to expose reactive properties
// Since `cube` is a ref, `cube.value.cubies` is not deeply reactive by default unless `cube.value` is reactive.
// But `ref` wraps the object. If we mutate properties of the object, it might not trigger.
// Let's rely on triggering updates manually or creating a new instance on reset.
// For rotation, we will force update.
const cubies = computed(() => cube.value.cubies);
// Compute the 6-face state matrix for display/debug
const cubeState = computed(() => cube.value.getState());
const initCube = () => {
cube.value.reset();
triggerUpdate();
};
const triggerUpdate = () => {
// Force Vue to notice change
cube.value = Object.assign(Object.create(Object.getPrototypeOf(cube.value)), cube.value);
worker.postMessage({ type: 'RESET' });
};
const rotateLayer = (axis, index, direction) => {
cube.value.rotateLayer(axis, index, direction);
triggerUpdate();
worker.postMessage({ type: 'ROTATE_LAYER', payload: { axis, index, direction } });
};
const validate = () => {
worker.postMessage({ type: 'VALIDATE' });
};
return {
cube,
cubies,
cubeState,
cubies: computed(() => cubies.value),
isReady: computed(() => isReady.value),
validationResult: computed(() => validationResult.value),
initCube,
rotateLayer,
validate,
COLORS,
FACES
};

View File

@@ -1,50 +0,0 @@
import { reactive, watch } from 'vue'
const settings = reactive({
viewRotation: {
invertX: false, // Inverts Up/Down view rotation
invertY: false, // Inverts Left/Right view rotation (Drag Right -> Increase Angle -> Rotate Right)
speed: 0.5
},
dragMapping: {
// Multipliers for drag direction on faces
front: { x: 1, y: -1 }, // Changed x to 1
back: { x: 1, y: 1 },
right: { x: -1, y: 1 },
left: { x: -1, y: -1 },
up: { x: 1, y: 1 },
down: { x: -1, y: -1 }
},
physics: {
enabled: true,
tension: 200,
friction: 10 // Not currently used but good for future
}
})
// Persist to localStorage for convenience during reload
const STORAGE_KEY = 'rubik-debug-settings-v2' // Changed key to force reset settings
try {
const saved = localStorage.getItem(STORAGE_KEY)
if (saved) {
const parsed = JSON.parse(saved)
// Merge deeply? For now just top level sections
Object.assign(settings.viewRotation, parsed.viewRotation)
Object.assign(settings.dragMapping, parsed.dragMapping)
Object.assign(settings.physics, parsed.physics)
}
} catch (e) {
console.warn('Failed to load debug settings', e)
}
watch(settings, (newSettings) => {
localStorage.setItem(STORAGE_KEY, JSON.stringify(newSettings))
}, { deep: true })
export function useDebug() {
return {
settings
}
}

View File

@@ -1,50 +0,0 @@
import { ref, reactive } from 'vue'
// Global state for logs so it persists across component re-mounts
const logs = ref([])
const isRecording = ref(true)
const maxLogs = 500 // Limit history size
export function useInteractionLogger() {
const addLog = (type, data) => {
if (!isRecording.value) return
const timestamp = Date.now()
const logEntry = {
id: timestamp + Math.random().toString(36).substr(2, 9),
timestamp,
type,
data: JSON.parse(JSON.stringify(data)) // Deep copy to snapshot state
}
logs.value.push(logEntry)
if (logs.value.length > maxLogs) {
logs.value.shift()
}
}
const clearLogs = () => {
logs.value = []
}
const exportLogs = () => {
return JSON.stringify(logs.value, null, 2)
}
// Helper to format logs for LLM analysis
const getRecentLogsForAnalysis = (count = 50) => {
const recent = logs.value.slice(-count)
return JSON.stringify(recent, null, 2)
}
return {
logs,
isRecording,
addLog,
clearLogs,
exportLogs,
getRecentLogsForAnalysis
}
}

View File

@@ -1,23 +0,0 @@
import { ref } from 'vue';
const RENDERERS = {
CSS: 'CSS',
SVG: 'SVG',
CANVAS: 'Canvas'
};
const activeRenderer = ref(RENDERERS.CSS);
export function useRenderer() {
const setRenderer = (renderer) => {
if (Object.values(RENDERERS).includes(renderer)) {
activeRenderer.value = renderer;
}
};
return {
activeRenderer,
setRenderer,
RENDERERS
};
}

View File

@@ -13,9 +13,9 @@
-moz-osx-font-smoothing: grayscale;
/* --- Glassmorphism Design System (from Nonograms) --- */
--bg-gradient: linear-gradient(135deg, #2c3e50 0%, #000000 100%);
--glass-bg: rgba(255, 255, 255, 0.05);
--glass-border: rgba(255, 255, 255, 0.1);
--bg-gradient: radial-gradient(circle at center, #2b2b2b 0%, #000000 100%);
--glass-bg: rgba(255, 255, 255, 0.1);
--glass-border: rgba(255, 255, 255, 0.2);
--glass-shadow: 0 8px 32px 0 rgba(0, 0, 0, 0.37);
--text-color: #ffffff;
--text-strong: #ffffff;
@@ -25,10 +25,55 @@
--accent-purple: #4facfe;
--primary-accent: #00f2fe;
--title-glow: rgba(0, 255, 255, 0.2);
--toggle-bg: rgba(255, 255, 255, 0.08);
--toggle-border: rgba(255, 255, 255, 0.2);
--toggle-shadow: 0 0 15px rgba(0, 0, 0, 0.2);
--toggle-btn-border: rgba(255, 255, 255, 0.2);
--panel-bg: rgba(255, 255, 255, 0.05);
--toggle-hover-border: #ffffff;
--toggle-active-shadow: 0 0 10px rgba(0, 242, 255, 0.3);
--panel-bg: rgba(255, 255, 255, 0.1);
--panel-border: rgba(255, 255, 255, 0.1);
--panel-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
--button-bg: rgba(255, 255, 255, 0.1);
--button-border: rgba(255, 255, 255, 0.2);
--button-text: #ffffff;
--button-hover-bg: rgba(255, 255, 255, 0.25);
--button-hover-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
--button-active-shadow: 0 0 20px rgba(79, 172, 254, 0.4);
--cube-edge-color: #333333;
--title-gradient: linear-gradient(45deg, #00f2fe, #4facfe);
}
:root[data-theme="light"] {
--bg-gradient: radial-gradient(circle at center, #ffffff 0%, #e0e0e0 100%);
--glass-bg: rgba(255, 255, 255, 0.75);
--glass-border: rgba(15, 23, 42, 0.12);
--glass-shadow: 0 8px 32px 0 rgba(15, 23, 42, 0.12);
--text-color: #0f172a;
--text-strong: #0f172a;
--text-secondary: rgba(15, 23, 42, 0.7);
--text-muted: rgba(15, 23, 42, 0.6);
--accent-cyan: #0ea5e9;
--accent-purple: #6366f1;
--primary-accent: #0ea5e9;
--title-glow: rgba(14, 165, 233, 0.35);
--toggle-bg: rgba(255, 255, 255, 0.85);
--toggle-border: rgba(15, 23, 42, 0.12);
--toggle-shadow: 0 8px 20px rgba(15, 23, 42, 0.12);
--toggle-btn-border: rgba(15, 23, 42, 0.18);
--toggle-hover-border: rgba(15, 23, 42, 0.5);
--toggle-active-shadow: 0 0 12px rgba(14, 165, 233, 0.25);
--panel-bg: rgba(255, 255, 255, 0.7);
--panel-border: rgba(15, 23, 42, 0.12);
--panel-shadow: 0 12px 24px rgba(15, 23, 42, 0.12);
--button-bg: rgba(255, 255, 255, 0.85);
--button-border: rgba(15, 23, 42, 0.16);
--button-text: #0f172a;
--button-hover-bg: rgba(255, 255, 255, 1);
--button-hover-shadow: 0 6px 18px rgba(15, 23, 42, 0.18);
--button-active-shadow: 0 0 18px rgba(14, 165, 233, 0.25);
--cube-edge-color: #000000;
--title-gradient: linear-gradient(45deg, #0ea5e9, #6366f1);
}
a {
@@ -44,11 +89,12 @@ body {
margin: 0;
display: flex;
min-width: 320px;
min-height: 100vh;
height: 100vh;
flex-direction: column;
background: var(--bg-gradient);
background-attachment: fixed;
color: var(--text-color);
overflow: hidden;
}
h1 {
@@ -81,7 +127,7 @@ button:focus-visible {
#app {
width: 100%;
min-height: 100vh;
height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
@@ -90,11 +136,56 @@ button:focus-visible {
/* Glassmorphism utility class */
.glass-panel {
background: var(--glass-bg);
backdrop-filter: blur(10px);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
border-radius: 16px;
border: 1px solid var(--glass-border);
box-shadow: var(--glass-shadow);
}
/* Button Styles */
button.btn-neon {
background: var(--button-bg);
border: 1px solid var(--button-border);
color: var(--button-text);
padding: 10px 20px;
font-size: 0.95rem;
border-radius: 30px;
cursor: pointer;
transition: all 0.3s ease;
backdrop-filter: blur(4px);
font-weight: 500;
letter-spacing: 0.5px;
text-transform: uppercase;
display: inline-flex;
align-items: center;
justify-content: center;
gap: 8px;
outline: none;
}
button.btn-neon:hover {
background: var(--button-hover-bg);
transform: translateY(-2px);
box-shadow: var(--button-hover-shadow);
border-color: var(--toggle-hover-border);
}
button.btn-neon.active {
background: linear-gradient(90deg, var(--accent-cyan), var(--accent-purple));
border-color: transparent;
box-shadow: var(--button-active-shadow);
font-weight: 700;
color: #fff;
}
button.btn-neon.icon-only {
padding: 10px;
border-radius: 50%;
width: 40px;
height: 40px;
}
@media (prefers-color-scheme: light) {
:root {
color: #213547;

View File

@@ -1,500 +0,0 @@
// Enum for colors
export const COLORS = {
WHITE: 'white',
YELLOW: 'yellow',
ORANGE: 'orange',
RED: 'red',
GREEN: 'green',
BLUE: 'blue',
BLACK: 'black'
};
// Faces enum
export const FACES = {
UP: 'up',
DOWN: 'down',
LEFT: 'left',
RIGHT: 'right',
FRONT: 'front',
BACK: 'back',
};
class Cubie {
constructor(id, x, y, z) {
this.id = id;
this.x = x;
this.y = y;
this.z = z;
this.faces = {
[FACES.UP]: COLORS.BLACK,
[FACES.DOWN]: COLORS.BLACK,
[FACES.LEFT]: COLORS.BLACK,
[FACES.RIGHT]: COLORS.BLACK,
[FACES.FRONT]: COLORS.BLACK,
[FACES.BACK]: COLORS.BLACK,
};
// Assign initial colors based on position (Solved State)
if (y === 1) this.faces[FACES.UP] = COLORS.WHITE;
if (y === -1) this.faces[FACES.DOWN] = COLORS.YELLOW;
if (x === -1) this.faces[FACES.LEFT] = COLORS.ORANGE;
if (x === 1) this.faces[FACES.RIGHT] = COLORS.RED;
if (z === 1) this.faces[FACES.FRONT] = COLORS.GREEN;
if (z === -1) this.faces[FACES.BACK] = COLORS.BLUE;
}
}
export class Cube {
constructor() {
this.cubies = [];
this.reset();
}
reset() {
this.cubies = [];
let id = 0;
for (let x = -1; x <= 1; x++) {
for (let y = -1; y <= 1; y++) {
for (let z = -1; z <= 1; z++) {
this.cubies.push(new Cubie(id++, x, y, z));
}
}
}
}
// Perform a standard move (U, D, L, R, F, B, M, E, S, x, y, z)
// Modifier: ' (prime) or 2 (double)
move(moveStr) {
let move = moveStr[0];
let modifier = moveStr.length > 1 ? moveStr[1] : '';
let direction = 1; // CW
let times = 1;
if (modifier === "'") {
direction = -1;
} else if (modifier === '2') {
times = 2;
}
// Standard Notation Mapping to (axis, index, direction)
// Note: Direction 1 in rotateLayer is "Positive Axis Rotation".
// We need to map Standard CW to Axis Direction.
// U (Up): y=1. Top face CW.
// Looking from Top (y+), CW is Rotation around Y (-). Wait.
// Right Hand Rule on Y axis: Thumb up, fingers curl CCW.
// So Positive Y Rotation is CCW from Top.
// So U (CW) is Negative Y Rotation.
// Let's verify _rotateCubiePosition for 'y'.
// dir > 0 (Pos): nx = z, nz = -x. (z, -x).
// (1,0) -> (0,-1). Right -> Back.
// Top View: Right is 3 o'clock. Back is 12 o'clock? No, Back is Up.
// Top View:
// B (z=-1)
// L(x=-1) R(x=1)
// F (z=1)
// Right (x=1) -> Back (z=-1).
// This is CCW.
// So `direction > 0` (Positive Y) is CCW from Top.
// Standard U is CW. So U is `direction = -1`.
// D (Down): y=-1. Bottom face CW.
// Looking from Bottom (y-), CW.
// If I look from bottom, Y axis points away.
// Positive Y is CCW from Top -> CW from Bottom?
// Let's check.
// Pos Y: Right -> Back.
// Bottom View: Right is Right. Back is "Down"?
// It's confusing.
// Let's use simple logic: D moves same direction as U' (visually from side?). No.
// U and D turn "same way" if you hold cube? No, opposite layers turn opposite relative to axis.
// D (CW) matches Y (Pos) ?
// Let's check movement of Front face on D.
// D moves Front -> Right.
// Y (Pos) moves Front (z=1) -> Right (x=1)?
// Pos Y: (0, 1) -> (1, 0). z=1 -> x=1.
// Yes. Front -> Right.
// So D (CW) = Y (Pos). `direction = 1`.
// L (Left): x=-1. Left face CW.
// L moves Front -> Down.
// X (Pos) moves Front (z=1) -> Up (y=1)?
// _rotateCubiePosition 'x':
// dir > 0: ny = -z. z=1 -> y=-1 (Down).
// So X (Pos) moves Front -> Down.
// So L (CW) = X (Pos). `direction = 1`.
// R (Right): x=1. Right face CW.
// R moves Front -> Up.
// X (Pos) moves Front -> Down.
// So R (CW) = X (Neg). `direction = -1`.
// F (Front): z=1. Front face CW.
// F moves Up -> Right.
// Z (Pos) moves Up (y=1) -> Left (x=-1)?
// _rotateCubiePosition 'z':
// dir > 0: nx = -y. y=1 -> x=-1 (Left).
// So Z (Pos) moves Up -> Left.
// F (CW) moves Up -> Right.
// So F (CW) = Z (Neg). `direction = -1`.
// Wait. My `rotateLayer` logic for Z was flipped in previous turn to match Visual.
// Let's re-read `_rotateCubieFaces` for Z.
// dir > 0 (CCW in Math/Pos): Left <- Up. Up moves to Left.
// So Pos Z moves Up to Left.
// F (CW) needs Up to Right.
// So F (CW) is Neg Z. `direction = -1`.
// B (Back): z=-1. Back face CW.
// B moves Up -> Left.
// Z (Pos) moves Up -> Left.
// So B (CW) = Z (Pos). `direction = 1`.
const layerOps = [];
switch (move) {
case 'U': layerOps.push({ axis: 'y', index: 1, dir: -1 }); break;
case 'D': layerOps.push({ axis: 'y', index: -1, dir: 1 }); break;
case 'L': layerOps.push({ axis: 'x', index: -1, dir: 1 }); break;
case 'R': layerOps.push({ axis: 'x', index: 1, dir: -1 }); break;
case 'F': layerOps.push({ axis: 'z', index: 1, dir: -1 }); break;
case 'B': layerOps.push({ axis: 'z', index: -1, dir: 1 }); break;
// Slices
case 'M': // Middle (between L and R), follows L direction
layerOps.push({ axis: 'x', index: 0, dir: 1 }); break;
case 'E': // Equator (between U and D), follows D direction
layerOps.push({ axis: 'y', index: 0, dir: 1 }); break;
case 'S': // Standing (between F and B), follows F direction
layerOps.push({ axis: 'z', index: 0, dir: -1 }); break;
// Whole Cube Rotations
case 'x': // Follows R
layerOps.push({ axis: 'x', index: -1, dir: -1 });
layerOps.push({ axis: 'x', index: 0, dir: -1 });
layerOps.push({ axis: 'x', index: 1, dir: -1 });
break;
case 'y': // Follows U
layerOps.push({ axis: 'y', index: -1, dir: -1 });
layerOps.push({ axis: 'y', index: 0, dir: -1 });
layerOps.push({ axis: 'y', index: 1, dir: -1 });
break;
case 'z': // Follows F
layerOps.push({ axis: 'z', index: -1, dir: -1 });
layerOps.push({ axis: 'z', index: 0, dir: -1 });
layerOps.push({ axis: 'z', index: 1, dir: -1 });
break;
}
// Apply operations
for (let i = 0; i < times; i++) {
layerOps.forEach(op => {
this.rotateLayer(op.axis, op.index, op.dir * direction);
});
}
}
// Rotate a layer
// axis: 'x', 'y', 'z'
// Helper: Rotate a 2D matrix
// direction: 1 (CW), -1 (CCW)
_rotateMatrix(matrix, direction) {
const N = matrix.length;
// Transpose
for (let i = 0; i < N; i++) {
for (let j = i; j < N; j++) {
[matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]];
}
}
// Reverse Rows (for CW) or Columns (for CCW)
if (direction > 0) {
// CW: Reverse each row
matrix.forEach(row => row.reverse());
} else {
// CCW: Reverse columns (or Reverse rows before transpose? No.)
// Transpose + Reverse Rows = CW.
// Transpose + Reverse Cols = CCW?
// Let's check:
// [1 2] T [1 3] RevCol [3 1] -> CCW?
// [3 4] [2 4] [4 2]
// 1 (0,0) -> (0,1). (Top-Left -> Top-Right). This is CW.
// Wait.
// CW: (x,y) -> (y, -x).
// (0,0) -> (0, 0).
// (1,0) -> (0, -1).
// Let's stick to standard:
// CW: Transpose -> Reverse Rows.
// CCW: Reverse Rows -> Transpose.
// Since I already transposed:
// To get CCW from Transpose:
// [1 2] T [1 3]
// [3 4] [2 4]
// Target CCW:
// [2 4]
// [1 3]
// This is reversing columns of Transpose.
// Or reversing rows of original, then transpose.
// Since I modify in place and already transposed:
// I need to reverse columns.
// Alternatively, re-implement:
// Undo transpose for CCW case and do correct order?
// No, let's just reverse columns.
for (let i = 0; i < N; i++) {
for (let j = 0; j < N / 2; j++) {
[matrix[j][i], matrix[N - 1 - j][i]] = [matrix[N - 1 - j][i], matrix[j][i]];
}
}
}
}
// index: -1, 0, 1
// direction: 1 (Positive Axis), -1 (Negative Axis)
rotateLayer(axis, index, direction) {
// 1. Select cubies in the layer
const layerCubies = this.cubies.filter(c => c[axis] === index);
// 2. Map cubies to 3x3 Matrix based on Axis View
// We need a consistent mapping from (u, v) -> Matrix[row][col]
// such that RotateMatrix(CW) corresponds to Physical CW Rotation.
// Grid coordinates:
// Row: 0..2, Col: 0..2
// Mapping function: returns {row, col} for a cubie
// Inverse function: updates cubie coordinates from {row, col}
let mapToGrid, updateFromGrid;
if (axis === 'z') {
// Front (z=1): X=Right, Y=Up.
// Matrix: Row 0 is Top (y=1). Col 0 is Left (x=-1).
mapToGrid = (c) => ({ row: 1 - c.y, col: c.x + 1 });
updateFromGrid = (c, row, col) => { c.y = 1 - row; c.x = col - 1; };
} else if (axis === 'x') {
// Right (x=1): Y=Up, Z=Back?
// CW Rotation around X (Right face):
// Up -> Front -> Down -> Back.
// Matrix: Row 0 is Top (y=1).
// Col 0 is Front (z=1)?
// If Col 0 is Front, Col 2 is Back (z=-1).
// Let's check CW:
// Top (y=1) -> Front (z=1).
// Matrix (0, ?) -> (?, 0).
// (0, 1) [Top-Center] -> (1, 0) [Front-Center].
// Row 0 -> Col 0. (Transpose).
// Then Reverse Rows?
// (0, 1) -> (1, 0).
// (0, 0) [Top-Front] -> (0, 0) [Front-Top]? No.
// Top-Front (y=1, z=1).
// Rot X CW: (y, z) -> (-z, y).
// (1, 1) -> (-1, 1). (Back-Top).
// Wait.
// Rot X CW:
// Y->Z->-Y->-Z.
// Up(y=1) -> Front(z=1)? No.
// Standard Axis Rotation (Right Hand Rule):
// Thumb +X. Fingers Y -> Z.
// So Y axis moves towards Z axis.
// (0, 1, 0) -> (0, 0, 1).
// Up -> Front.
// So Top (y=1) moves to Front (z=1).
// Let's map:
// Row 0 (Top, y=1). Row 2 (Bottom, y=-1).
// Col 0 (Front, z=1). Col 2 (Back, z=-1).
mapToGrid = (c) => ({ row: 1 - c.y, col: 1 - c.z });
updateFromGrid = (c, row, col) => { c.y = 1 - row; c.z = 1 - col; };
} else if (axis === 'y') {
// Up (y=1): Z=Back, X=Right.
// Rot Y CW:
// Z -> X.
// Back (z=-1) -> Right (x=1).
// Matrix: Row 0 (Back, z=-1). Row 2 (Front, z=1).
// Col 0 (Left, x=-1). Col 2 (Right, x=1).
mapToGrid = (c) => ({ row: c.z + 1, col: c.x + 1 });
updateFromGrid = (c, row, col) => { c.z = row - 1; c.x = col - 1; };
}
// 3. Create Matrix
const matrix = Array(3).fill(null).map(() => Array(3).fill(null));
layerCubies.forEach(c => {
const { row, col } = mapToGrid(c);
matrix[row][col] = c;
});
// 4. Rotate Matrix
// Note: Direction 1 is Physical CW (CCW in Math).
// Mapping analysis shows that for all axes (X, Y, Z),
// Physical CW corresponds to Matrix CW.
// However, rotateLayer receives direction -1 for CW (from move() notation).
// _rotateMatrix expects direction 1 for CW.
// So we must invert the direction for all axes.
const matrixDirection = -direction;
this._rotateMatrix(matrix, matrixDirection);
// 5. Update Cubie Coordinates
for (let r = 0; r < 3; r++) {
for (let c = 0; c < 3; c++) {
const cubie = matrix[r][c];
if (cubie) {
updateFromGrid(cubie, r, c);
}
}
}
// 6. Rotate Faces of each cubie
layerCubies.forEach(cubie => {
this._rotateCubieFaces(cubie, axis, direction);
});
}
_rotateCubieFaces(cubie, axis, direction) {
const f = { ...cubie.faces };
// Helper to swap faces
// We map: newFace <- oldFace
// Axis X Rotation (Right/Left)
// CW (dir > 0): Up -> Front -> Down -> Back -> Up
if (axis === 'x') {
if (direction > 0) {
// Corrected cycle for +X rotation:
// Up face moves to Front face
// Front face moves to Down face
// Down face moves to Back face
// Back face moves to Up face
cubie.faces[FACES.FRONT] = f[FACES.UP];
cubie.faces[FACES.DOWN] = f[FACES.FRONT];
cubie.faces[FACES.BACK] = f[FACES.DOWN];
cubie.faces[FACES.UP] = f[FACES.BACK];
} else {
// Reverse cycle for -X
cubie.faces[FACES.UP] = f[FACES.FRONT];
cubie.faces[FACES.FRONT] = f[FACES.DOWN];
cubie.faces[FACES.DOWN] = f[FACES.BACK];
cubie.faces[FACES.BACK] = f[FACES.UP];
}
}
// Axis Y Rotation (Up/Down)
// CW (dir > 0): Front -> Right -> Back -> Left -> Front
// Front -> Right, Right -> Back, Back -> Left, Left -> Front
if (axis === 'y') {
if (direction > 0) {
cubie.faces[FACES.RIGHT] = f[FACES.FRONT];
cubie.faces[FACES.BACK] = f[FACES.RIGHT];
cubie.faces[FACES.LEFT] = f[FACES.BACK];
cubie.faces[FACES.FRONT] = f[FACES.LEFT];
} else {
cubie.faces[FACES.LEFT] = f[FACES.FRONT];
cubie.faces[FACES.BACK] = f[FACES.LEFT];
cubie.faces[FACES.RIGHT] = f[FACES.BACK];
cubie.faces[FACES.FRONT] = f[FACES.RIGHT];
}
}
// Axis Z Rotation (Front/Back)
// CW (dir > 0) in Math is CCW visually: Top -> Left -> Bottom -> Right -> Top
if (axis === 'z') {
if (direction > 0) {
// CCW
cubie.faces[FACES.LEFT] = f[FACES.UP];
cubie.faces[FACES.DOWN] = f[FACES.LEFT];
cubie.faces[FACES.RIGHT] = f[FACES.DOWN];
cubie.faces[FACES.UP] = f[FACES.RIGHT];
} else {
// CW
cubie.faces[FACES.RIGHT] = f[FACES.UP];
cubie.faces[FACES.DOWN] = f[FACES.RIGHT];
cubie.faces[FACES.LEFT] = f[FACES.DOWN];
cubie.faces[FACES.UP] = f[FACES.LEFT];
}
}
}
// Get current state as standard 6-face matrices (for display/export)
getState() {
const state = {
[FACES.UP]: [[],[],[]],
[FACES.DOWN]: [[],[],[]],
[FACES.LEFT]: [[],[],[]],
[FACES.RIGHT]: [[],[],[]],
[FACES.FRONT]: [[],[],[]],
[FACES.BACK]: [[],[],[]]
};
this.cubies.forEach(c => {
// Map x,y,z to matrix indices
// UP: y=1. row = z (-1->0, 0->1, 1->2)?
// In `CubeCSS` I reversed this logic to match `Cube.js`.
// Let's stick to standard visual mapping.
// UP Face (Top View):
// Row 0 is Back (z=-1). Row 2 is Front (z=1).
// Col 0 is Left (x=-1). Col 2 is Right (x=1).
if (c.y === 1) {
const row = c.z + 1;
const col = c.x + 1;
state[FACES.UP][row][col] = c.faces[FACES.UP];
}
// DOWN Face (Bottom View):
// Usually "unfolded". Top of Down face is Front (z=1).
// Row 0 is Front (z=1). Row 2 is Back (z=-1).
// Col 0 is Left (x=-1). Col 2 is Right (x=1).
if (c.y === -1) {
const row = 1 - c.z;
const col = c.x + 1;
state[FACES.DOWN][row][col] = c.faces[FACES.DOWN];
}
// FRONT Face (z=1):
// Row 0 is Top (y=1). Row 2 is Bottom (y=-1).
// Col 0 is Left (x=-1). Col 2 is Right (x=1).
if (c.z === 1) {
const row = 1 - c.y;
const col = c.x + 1;
state[FACES.FRONT][row][col] = c.faces[FACES.FRONT];
}
// BACK Face (z=-1):
// Viewed from Back.
// Row 0 is Top (y=1).
// Col 0 is Right (x=1) (Viewer's Left). Col 2 is Left (x=-1).
if (c.z === -1) {
const row = 1 - c.y;
const col = 1 - c.x;
state[FACES.BACK][row][col] = c.faces[FACES.BACK];
}
// LEFT Face (x=-1):
// Viewed from Left.
// Row 0 is Top (y=1).
// Col 0 is Back (z=-1). Col 2 is Front (z=1).
if (c.x === -1) {
const row = 1 - c.y;
const col = c.z + 1;
state[FACES.LEFT][row][col] = c.faces[FACES.LEFT];
}
// RIGHT Face (x=1):
// Viewed from Right.
// Row 0 is Top (y=1).
// Col 0 is Front (z=1). Col 2 is Back (z=-1).
if (c.x === 1) {
const row = 1 - c.y;
const col = 1 - c.z;
state[FACES.RIGHT][row][col] = c.faces[FACES.RIGHT];
}
});
return state;
}
}

345
src/utils/CubeModel.js Normal file
View File

@@ -0,0 +1,345 @@
/**
* Dedicated 3x3x3 Rubik's Cube Model
*
* Representation:
* A collection of 27 Cubie objects, each with position (x, y, z) and face colors.
* Coordinate System:
* x: Left (-1) to Right (1)
* y: Bottom (-1) to Top (1)
* z: Back (-1) to Front (1)
*
* This logical model maintains the state of the cube and handles rotations.
*/
export const COLORS = {
WHITE: 'white',
YELLOW: 'yellow',
ORANGE: 'orange',
RED: 'red',
GREEN: 'green',
BLUE: 'blue',
BLACK: 'black'
};
export const FACES = {
UP: 'up',
DOWN: 'down',
LEFT: 'left',
RIGHT: 'right',
FRONT: 'front',
BACK: 'back',
};
// Standard Face Colors (Solved State)
const SOLVED_COLORS = {
[FACES.UP]: COLORS.WHITE,
[FACES.DOWN]: COLORS.YELLOW,
[FACES.LEFT]: COLORS.ORANGE,
[FACES.RIGHT]: COLORS.RED,
[FACES.FRONT]: COLORS.GREEN,
[FACES.BACK]: COLORS.BLUE,
};
class Cubie {
constructor(id, x, y, z) {
this.id = id;
this.x = x;
this.y = y;
this.z = z;
this.faces = {
[FACES.UP]: COLORS.BLACK,
[FACES.DOWN]: COLORS.BLACK,
[FACES.LEFT]: COLORS.BLACK,
[FACES.RIGHT]: COLORS.BLACK,
[FACES.FRONT]: COLORS.BLACK,
[FACES.BACK]: COLORS.BLACK,
};
this.initColors();
}
// Set initial colors based on position in solved state
initColors() {
if (this.y === 1) this.faces[FACES.UP] = SOLVED_COLORS[FACES.UP];
if (this.y === -1) this.faces[FACES.DOWN] = SOLVED_COLORS[FACES.DOWN];
if (this.x === -1) this.faces[FACES.LEFT] = SOLVED_COLORS[FACES.LEFT];
if (this.x === 1) this.faces[FACES.RIGHT] = SOLVED_COLORS[FACES.RIGHT];
if (this.z === 1) this.faces[FACES.FRONT] = SOLVED_COLORS[FACES.FRONT];
if (this.z === -1) this.faces[FACES.BACK] = SOLVED_COLORS[FACES.BACK];
}
}
export class CubeModel {
constructor() {
this.size = 3;
this.cubies = [];
this.init();
}
init() {
this.cubies = [];
let id = 0;
for (let x = -1; x <= 1; x++) {
for (let y = -1; y <= 1; y++) {
for (let z = -1; z <= 1; z++) {
this.cubies.push(new Cubie(id++, x, y, z));
}
}
}
}
reset() {
this.init();
}
/**
* Rotates a layer around an axis.
* @param {string} axis - 'x', 'y', 'z'
* @param {number} index - -1 (Left/Bottom/Back), 0 (Middle), 1 (Right/Top/Front)
* @param {number} direction - 1 (CW), -1 (CCW) relative to axis positive direction
*/
rotateLayer(axis, index, direction) {
// Determine the relevant cubies in the slice
const slice = this.cubies.filter(c => c[axis] === index);
// Coordinate rotation (Matrix Logic)
// 90 deg CW rotation formulas:
// X-Axis: (y, z) -> (-z, y)
// Y-Axis: (x, z) -> (z, -x)
// Z-Axis: (x, y) -> (-y, x)
// Note: direction 1 is usually CCW in math (right hand rule around axis).
// Let's verify standard:
// Right Hand Rule with Thumb along Axis: Fingers curl in Positive Rotation direction.
// X (Right): Curl from Y (Up) to Z (Front). (0,1,0)->(0,0,1).
// y' = -z, z' = y?
// Let's check (0,1): y=1, z=0 -> y'=0, z'=1. Correct.
// So if direction is 1 (Positive/CW around axis):
// X: y' = -z, z' = y
// Y: z' = -x, x' = z
// Z: x' = -y, y' = x
// If direction is -1: Inverse.
slice.forEach(cubie => {
this._rotateCubieCoordinates(cubie, axis, direction);
this._rotateCubieFaces(cubie, axis, direction);
});
}
_rotateCubieCoordinates(cubie, axis, direction) {
const { x, y, z } = cubie;
if (axis === 'x') {
if (direction === 1) {
cubie.y = -z;
cubie.z = y;
} else {
cubie.y = z;
cubie.z = -y;
}
} else if (axis === 'y') {
if (direction === 1) {
cubie.z = -x;
cubie.x = z;
} else {
cubie.z = x;
cubie.x = -z;
}
} else if (axis === 'z') {
if (direction === 1) { // CW
cubie.x = -y;
cubie.y = x;
} else { // CCW
cubie.x = y;
cubie.y = -x;
}
}
}
_rotateCubieFaces(cubie, axis, direction) {
// When a cubie rotates, its faces move to new positions.
// We swap the COLORS on the faces.
// Example: Rotate X (Roll Forward). Up Face becomes Front Face.
// So new Front Color = old Up Color.
// cubie.faces[FRONT] = old_faces[UP]
const f = { ...cubie.faces };
if (axis === 'x') {
if (direction === 1) { // Up -> Front -> Down -> Back -> Up
cubie.faces[FACES.FRONT] = f[FACES.UP];
cubie.faces[FACES.DOWN] = f[FACES.FRONT];
cubie.faces[FACES.BACK] = f[FACES.DOWN];
cubie.faces[FACES.UP] = f[FACES.BACK];
// Left/Right unchanged in position, but might rotate? No, faces are solid colors.
} else { // Up -> Back -> Down -> Front -> Up
cubie.faces[FACES.BACK] = f[FACES.UP];
cubie.faces[FACES.DOWN] = f[FACES.BACK];
cubie.faces[FACES.FRONT] = f[FACES.DOWN];
cubie.faces[FACES.UP] = f[FACES.FRONT];
}
} else if (axis === 'y') {
if (direction === 1) { // Front -> Right -> Back -> Left -> Front
cubie.faces[FACES.RIGHT] = f[FACES.FRONT];
cubie.faces[FACES.BACK] = f[FACES.RIGHT];
cubie.faces[FACES.LEFT] = f[FACES.BACK];
cubie.faces[FACES.FRONT] = f[FACES.LEFT];
} else { // Front -> Left -> Back -> Right -> Front
cubie.faces[FACES.LEFT] = f[FACES.FRONT];
cubie.faces[FACES.BACK] = f[FACES.LEFT];
cubie.faces[FACES.RIGHT] = f[FACES.BACK];
cubie.faces[FACES.FRONT] = f[FACES.RIGHT];
}
} else if (axis === 'z') {
if (direction === 1) { // Up -> Right -> Down -> Left -> Up (CW)
cubie.faces[FACES.RIGHT] = f[FACES.UP];
cubie.faces[FACES.DOWN] = f[FACES.RIGHT];
cubie.faces[FACES.LEFT] = f[FACES.DOWN];
cubie.faces[FACES.UP] = f[FACES.LEFT];
} else { // Up -> Left -> Down -> Right -> Up (CCW)
cubie.faces[FACES.LEFT] = f[FACES.UP];
cubie.faces[FACES.DOWN] = f[FACES.LEFT];
cubie.faces[FACES.RIGHT] = f[FACES.DOWN];
cubie.faces[FACES.UP] = f[FACES.RIGHT];
}
}
}
toCubies() {
// Return copy of state for rendering
// CubeCSS expects array of objects with x, y, z, faces
return this.cubies.map(c => ({
id: c.id,
x: c.x,
y: c.y,
z: c.z,
faces: { ...c.faces }
}));
}
/**
* Applies a standard Rubik's Cube move
* @param {string} move - e.g. "U", "R'", "F2"
*/
applyMove(move) {
const base = move[0];
const modifier = move.substring(1);
let direction = -1; // Standard CW is -1 for U, L, F, B? Let's check.
// Direction Mapping based on rotateLayer Math:
// X(1) = CW (Up->Front)
// Y(1) = CW (Right->Front)
// Z(1) = CCW (Right->Up)
// R (CW around X): 1
// L (CW around -X): -1
// U (CW around Y): 1
// D (CW around -Y): -1
// F (CW around Z): -1 (since Z(1) is CCW)
// B (CW around -Z): 1 (since Z(1) is CW around -Z)
switch (base) {
case 'U': direction = 1; break;
case 'D': direction = -1; break;
case 'L': direction = -1; break;
case 'R': direction = 1; break;
case 'F': direction = -1; break;
case 'B': direction = 1; break;
}
if (modifier === "'") direction *= -1;
if (modifier === '2') {
// 2 moves. Direction doesn't matter for 180, but let's keep it.
// We will call rotateLayer twice.
}
const count = modifier === '2' ? 2 : 1;
for (let i = 0; i < count; i++) {
switch (base) {
case 'U': this.rotateLayer('y', 1, direction); break;
case 'D': this.rotateLayer('y', -1, direction); break;
case 'L': this.rotateLayer('x', -1, direction); break;
case 'R': this.rotateLayer('x', 1, direction); break;
case 'F': this.rotateLayer('z', 1, direction); break;
case 'B': this.rotateLayer('z', -1, direction); break;
}
}
}
// Debug printer for tests
toString() {
let out = "Cube State (3x3x3):\n";
// We can print faces.
// Order: U, D, F, B, L, R
const printFace = (face, name) => {
out += `Face ${name}:\n`;
// Grid 3x3.
// U: y=1. x from -1 to 1. z from -1 to 1.
// Coordinate mapping depends on face.
// Let's iterate standard grid rows/cols.
for (let r = 0; r < 3; r++) {
let rowStr = "";
for (let c = 0; c < 3; c++) {
let cubie;
// Map r,c to x,y,z based on face
if (face === FACES.UP) { // y=1. r=0->z=-1 (Back), r=2->z=1 (Front). c=0->x=-1 (Left).
// Standard U face view: Top Left is Back Left (-1, 1, -1).
// Row 0 (Top of U face) is Back.
// Row 2 (Bottom of U face) is Front.
cubie = this.cubies.find(cu => cu.y === 1 && cu.x === (c - 1) && cu.z === (r - 1)); // Wait.
// Back is z=-1. Front is z=1.
// Visual Top of U face is Back (z=-1).
// Visual Bottom of U face is Front (z=1).
cubie = this.cubies.find(cu => cu.y === 1 && cu.x === (c - 1) && cu.z === (r - 1 - 2 * r)); // Complicated.
// Let's just find by strict coordinates
// r=0 -> z=-1. r=1 -> z=0. r=2 -> z=1.
// c=0 -> x=-1. c=1 -> x=0. c=2 -> x=1.
cubie = this.cubies.find(cu => cu.y === 1 && cu.x === (c - 1) && cu.z === (r - 1));
}
else if (face === FACES.DOWN) cubie = this.cubies.find(cu => cu.y === -1 && cu.x === (c - 1) && cu.z === (1 - r)); // Down View?
else if (face === FACES.FRONT) cubie = this.cubies.find(cu => cu.z === 1 && cu.x === (c - 1) && cu.y === (1 - r));
else if (face === FACES.BACK) cubie = this.cubies.find(cu => cu.z === -1 && cu.x === (1 - c) && cu.y === (1 - r));
else if (face === FACES.LEFT) cubie = this.cubies.find(cu => cu.x === -1 && cu.z === (1 - c) && cu.y === (1 - r)); // Left view z order?
else if (face === FACES.RIGHT) cubie = this.cubies.find(cu => cu.x === 1 && cu.z === (c - 1) && cu.y === (1 - r));
if (cubie) {
rowStr += cubie.faces[face][0].toUpperCase() + " ";
} else {
rowStr += "? ";
}
}
out += rowStr + "\n";
}
out += "\n";
};
printFace(FACES.UP, 'U');
printFace(FACES.DOWN, 'D');
printFace(FACES.FRONT, 'F');
printFace(FACES.BACK, 'B');
printFace(FACES.LEFT, 'L');
printFace(FACES.RIGHT, 'R');
return out;
}
scramble(n = 20) {
const axes = ['x', 'y', 'z'];
const indices = [-1, 1]; // Usually rotate outer layers for scramble
// Actually, scrambling usually involves random face moves (U, D, L, R, F, B)
// U: y=1, dir -1 (Standard CW)
// D: y=-1, dir 1
// L: x=-1, dir -1
// R: x=1, dir 1
// F: z=1, dir 1
// B: z=-1, dir -1
// We can just generate random rotateLayer calls
for (let i = 0; i < n; i++) {
const axis = axes[Math.floor(Math.random() * axes.length)];
// Allow middle layer? Standard Scramble usually doesnt.
const index = indices[Math.floor(Math.random() * indices.length)];
const dir = Math.random() > 0.5 ? 1 : -1;
this.rotateLayer(axis, index, dir);
}
}
}

561
src/utils/DeepCube.js Normal file
View File

@@ -0,0 +1,561 @@
/**
* Deep Mechanical Rubik's Cube Model (Group Theory Approach)
*
* State Representation:
* - Corners (0-7): Permutation (p) and Orientation (o: 0..2)
* - Edges (0-11): Permutation (p) and Orientation (o: 0..1)
*
* Indexes:
* Corners:
* 0: URF, 1: UFL, 2: ULB, 3: UBR
* 4: DFR, 5: DLF, 6: DBL, 7: DRB
*
* Edges:
* 0: UR, 1: UF, 2: UL, 3: UB
* 4: DR, 5: DF, 6: DL, 7: DB
* 8: FR, 9: FL, 10: BL, 11: BR
*/
export const MOVES = {
// Definitions of basic moves: { corners: [indices], edges: [indices], co: [deltas], eo: [deltas] }
// Only defining Permutation Cycles and Orientation Changes.
// Permutation: p[i] moves to p[move[i]]? Or position i takes piece from move[i]?
// Let's use: "Piece at position i moves to position move[i]". (Isomorphism to S_n)
// Actually, standard array rep: state.p[i] is "which piece is at position i".
// Move M maps position i to M[i].
// So new_state.p[M[i]] = old_state.p[i].
// Or new_state.p[i] = old_state.p[M_inv[i]].
// Let's stick to: "Move U moves pieces currently at indices ... to indices ..."
// Corners: URF(0) -> UBR(3) -> ULB(2) -> UFL(1) -> URF(0) ?
// Move U (Clockwise):
// 0 (URF) -> 3 (UBR) ? No. U move pushes URF to position UFL?
// Let's visualize Top Face (U):
// B
// 2 3
// L 1 0 R
// F
// U (CW) turns: 0->1, 1->2, 2->3, 3->0? No.
// U (CW) turns: Right to Front.
// URF(0) is Front-Right. UFL(1) is Front-Left.
// U moves Right face stuff to Front face? NO.
// U moves Front face stuff to Left face.
// So 0 (URF) -> 1 (UFL)? No.
// URF is at corner of U, R, F faces.
// After U CW, it goes to corner of U, F, L faces. (UFL).
// So 0 -> 1.
// 1 (UFL) -> 2 (ULB).
// 2 (ULB) -> 3 (UBR).
// 3 (UBR) -> 0 (URF).
// So cycle is (0 1 2 3).
// Permutation Table P: P[0]=1, P[1]=2, P[2]=3, P[3]=0.
// Applied to state: "Piece at 0 goes to 1".
// Orientations CO:
// U moves do not change Corner Orientation (relative to U/D).
// So co delta is 0 for all.
// Edges U:
// 0(UR), 1(UF), 2(UL), 3(UB).
// U moves UR to UF? No.
// UR is Right. UF is Front.
// U CW moves Right to Front? No.
// U CW moves Front to Left.
// So UF(1) -> UL(2).
// UL(2) -> UB(3).
// UB(3) -> UR(0).
// UR(0) -> UF(1).
// Cycle: (0 1 2 3).
// P[0]=1, etc.
// Moves Definitions (Target Positions)
U: {
cp: [1, 2, 3, 0, 4, 5, 6, 7],
co: [0, 0, 0, 0, 0, 0, 0, 0],
ep: [1, 2, 3, 0, 4, 5, 6, 7, 8, 9, 10, 11],
eo: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
},
D: {
// D (CW) looking from bottom.
// DFR(4), DLF(5), DBL(6), DRB(7).
// D CW moves Front to Right.
// DFR(4) -> DRB(7).
// DRB(7) -> DBL(6).
// DBL(6) -> DLF(5).
// DLF(5) -> DFR(4).
// Cycle: (4 7 6 5). (Wait: 4->7, 7->6, 6->5, 5->4).
// Indices: [0,1,2,3, 7,4,5,6] (Wait. 4->7 means P[4]=7? No.
// P array usually means: P[i] is the location where piece i goes? OR where piece at i comes from?
// Standard multiplication: (A * B)[i] = A[B[i]].
// Let's define Move P as "Content of slot i comes from slot P[i]".
// If 0 goes to 1. Then New[1] = Old[0].
// So P[1] = 0.
// In our U example: 0->1. So P[1]=0.
// Let's verify U array [1,2,3,0...]
// P[0]=1 (Content of 0 comes from 1?). No.
// The previous array was [1, 2, 3, 0].
// If it meant "0 goes to 1", then New[1] = Old[0].
// Let's stick to: "Piece i goes to Position Move[i]".
// Implementation: newP[Move[i]] = oldP[i].
// U: 0->1, 1->2, 2->3, 3->0.
// Array: [1, 2, 3, 0].
// This matches "i goes to Move[i]".
// D: 4->7, 7->6, 6->5, 5->4.
// P[4]=7, P[5]=4, P[6]=5, P[7]=6.
cp: [0, 1, 2, 3, 7, 4, 5, 6],
co: [0, 0, 0, 0, 0, 0, 0, 0],
// Edges: DR(4), DF(5), DL(6), DB(7).
// D moves Front to Right.
// DF(5) -> DR(4).
// DR(4) -> DB(7).
// DB(7) -> DL(6).
// DL(6) -> DF(5).
// Cycle: 5->4, 4->7, 7->6, 6->5.
// P[4]=7, P[5]=4, P[6]=5, P[7]=6.
ep: [0, 1, 2, 3, 7, 4, 5, 6, 8, 9, 10, 11],
eo: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
},
L: {
// L (CW)
// Corners: UFL(1), DLF(5), DBL(6), ULB(2).
// L moves Up to Front.
// UFL(1) -> DLF(5).
// DLF(5) -> DBL(6).
// DBL(6) -> ULB(2).
// ULB(2) -> UFL(1).
// Cycle: 1->5, 5->6, 6->2, 2->1.
// P[1]=5, P[2]=1, P[5]=6, P[6]=2.
cp: [0, 5, 1, 3, 4, 6, 2, 7],
// Twist: L/R moves twist corners.
// UFL(1) moves to DLF. (+1: CW). WHITE U face moves to F face (CW rotation relative to corner axis?).
// DLF(5) moves to DBL. (-1: CCW).
// DBL(6) moves to ULB. (+1).
// ULB(2) moves to UFL. (-1).
// Values: 1 -> +1, 5 -> -1, 6 -> +1, 2 -> -1.
co: [0, 1, 2, 0, 0, 2, 1, 0], // 2 is -1 mod 3.
// Edges: UL(2), FL(9), DL(6), BL(10).
// U->F.
// UL(2) -> FL(9).
// FL(9) -> DL(6).
// DL(6) -> BL(10).
// BL(10) -> UL(2).
// P[2]=9, P[6]=10, P[9]=6, P[10]=2.
ep: [0, 1, 9, 3, 4, 5, 10, 7, 8, 6, 2, 11],
// Orientation: L/R do NOT flip edges in standard U/D rep.
eo: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
},
R: {
// R (CW)
// Corners: URF(0), UBR(3), DRB(7), DFR(4).
// R moves Up to Back.
// URF(0) -> UBR(3).
// UBR(3) -> DRB(7).
// DRB(7) -> DFR(4).
// DFR(4) -> URF(0).
// Cycle: 0->3, 3->7, 7->4, 4->0.
// P[0]=3, P[3]=7, P[4]=0, P[7]=4.
cp: [3, 1, 2, 7, 0, 5, 6, 4],
// Twist:
// URF(0) -> UBR. (-1).
// UBR(3) -> DRB. (+1).
// DRB(7) -> DFR. (-1).
// DFR(4) -> URF. (+1).
// 0:2, 3:1, 7:2, 4:1.
co: [2, 0, 0, 1, 1, 0, 0, 2],
// Edges: UR(0), BR(11), DR(4), FR(8).
// U->B.
// UR(0) -> BR(11).
// BR(11) -> DR(4).
// DR(4) -> FR(8).
// FR(8) -> UR(0).
// P[0]=11, P[4]=8, P[8]=0, P[11]=4.
ep: [11, 1, 2, 3, 8, 5, 6, 7, 0, 9, 10, 4],
eo: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
},
F: {
// F (CW)
// Corners: URF(0), UFL(1), DLF(5), DFR(4).
// F moves U to R.
// URF(0) -> DFR(4). (Wait. URF is Top-Right. F turns Top to Right. So URF -> DFR (Bottom-Right)).
// UFL(1) -> URF(0).
// DLF(5) -> UFL(1).
// DFR(4) -> DLF(5).
// Cycle: 0->4, 4->5, 5->1, 1->0.
// P[0]=4, P[1]=0, P[4]=5, P[5]=1.
cp: [4, 0, 2, 3, 5, 1, 6, 7],
// Twist:
// UFL(1) -> URF. (+1).
// URF(0) -> DFR. (-1).
// DFR(4) -> DLF. (+1).
// DLF(5) -> UFL. (-1).
// 0:2, 1:1, 4:1, 5:2.
co: [2, 1, 0, 0, 1, 2, 0, 0],
// Edges: UF(1), FR(8), DF(5), FL(9).
// U->R.
// UF(1) -> FR(8).
// FR(8) -> DF(5).
// DF(5) -> FL(9).
// FL(9) -> UF(1).
// P[1]=8, P[5]=9, P[8]=5, P[9]=1.
ep: [0, 8, 2, 3, 4, 9, 6, 7, 5, 1, 10, 11],
// FLIP: F and B moves flip edges.
// 1 -> 1, 5 -> 1, 8 -> 1, 9 -> 1.
eo: [0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0]
},
B: {
// B (CW)
// Corners: UBR(3), ULB(2), DBL(6), DRB(7).
// B moves U to L.
// UBR(3) -> ULB(2).
// ULB(2) -> DBL(6).
// DBL(6) -> DRB(7).
// DRB(7) -> UBR(3).
// Cycle: 3->2, 2->6, 6->7, 7->3.
// P[2]=6, P[3]=2, P[6]=7, P[7]=3.
cp: [0, 1, 6, 2, 4, 5, 7, 3],
// Twist:
// UBR(3) -> ULB. (-1).
// ULB(2) -> DBL. (+1).
// DBL(6) -> DRB. (-1).
// DRB(7) -> UBR. (+1).
// 2:1, 3:2, 6:2, 7:1.
co: [0, 0, 1, 2, 0, 0, 2, 1],
// Edges: UB(3), BL(10), DB(7), BR(11).
// U->L.
// UB(3) -> BL(10).
// BL(10) -> DB(7).
// DB(7) -> BR(11).
// BR(11) -> UB(3).
// P[3]=10, P[7]=11, P[10]=7, P[11]=3.
ep: [0, 1, 2, 10, 4, 5, 6, 11, 8, 9, 7, 3],
// FLIP
eo: [0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1]
}
}
export class DeepCube {
constructor() {
this.reset()
}
reset() {
// Identity State
this.cp = [0, 1, 2, 3, 4, 5, 6, 7]
this.co = [0, 0, 0, 0, 0, 0, 0, 0]
this.ep = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
this.eo = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
}
move(moveStr) {
const base = moveStr[0]
const def = MOVES[base]
if (!def) return
let count = 1
if (moveStr.endsWith('2')) count = 2
if (moveStr.endsWith("'")) count = 3 // 3 CW = 1 CCW
for (let k = 0; k < count; k++) {
this.applyPrimitive(def)
}
}
applyPrimitive(def) {
// Permutation: p[i] moves to def.p[i].
// New[def.p[i]] = Old[p[i]].
// We want to track where the pieces ARE.
// Correct application:
// next_cp[i] = cp[def.cp[i]] ?
// No. def.cp[i] says "Position i comes from position P[i]" ? No.
// I defined def.cp[i] as "Piece at i goes to def.cp[i]".
// Let's verify:
// U: 0->1.
// Standard Math: (P * S)[x] = P[S[x]]. (S applied first??)
// Here we are applying Move P to State S.
// New State S' = P * S.
// This usually implies: Piece at pos i in new state is...
// Let's trace one piece.
// Piece X is at pos 0.
// Move U: 0->1.
// New state: Piece X should be at pos 1.
// So new_cp[1] = Piece X.
// new_cp[def.cp[i]] = cp[i].
const new_cp = [...this.cp]
const new_co = [...this.co]
const new_ep = [...this.ep]
const new_eo = [...this.eo]
// Update Corners
for (let i = 0; i < 8; i++) {
const dest = def.cp[i]
new_cp[dest] = this.cp[i]
// Orientation follows the piece
// Twist adds to existing twist
new_co[dest] = (this.co[i] + def.co[i]) % 3
}
// Update Edges
for (let i = 0; i < 12; i++) {
const dest = def.ep[i]
new_ep[dest] = this.ep[i]
// Orientation
new_eo[dest] = (this.eo[i] + def.eo[i]) % 2
}
this.cp = new_cp
this.co = new_co
this.ep = new_ep
this.eo = new_eo
}
validate() {
const errors = [];
// Check exact set of pieces (Permutation Validity)
const cSet = new Set(this.cp);
if (cSet.size !== 8) errors.push('Invalid Corner Permutation (duplicates/missing)');
const eSet = new Set(this.ep);
if (eSet.size !== 12) errors.push('Invalid Edge Permutation (duplicates/missing)');
// Sum of Twists (Corners) % 3 == 0
const twistSum = this.co.reduce((a, b) => a + b, 0);
if (twistSum % 3 !== 0) errors.push(`Twist Sum Error: ${twistSum}`);
// Sum of Flips (Edges) % 2 == 0
const flipSum = this.eo.reduce((a, b) => a + b, 0);
if (flipSum % 2 !== 0) errors.push(`Flip Sum Error: ${flipSum}`);
// Parity Check (Corner Parity must equal Edge Parity)
const cParity = this.getPermutationParity(this.cp);
const eParity = this.getPermutationParity(this.ep);
if (cParity !== eParity) errors.push(`Parity Mismatch: Corner=${cParity}, Edge=${eParity}`);
return { valid: errors.length === 0, errors };
}
getPermutationParity(p) {
const n = p.length;
const visited = new Array(n).fill(false);
let swaps = 0;
for (let i = 0; i < n; i++) {
if (!visited[i]) {
let curr = i;
let cycleLen = 0;
while (!visited[curr]) {
visited[curr] = true;
curr = p[curr];
cycleLen++;
}
swaps += (cycleLen - 1);
}
}
return swaps % 2;
}
/**
* Converts abstract state to physical cubies for rendering.
* Maps Slot Positions (Where it is) -> Piece Colors (What it is) with Orientation.
*/
toCubies() {
// Definitions must align with indexes
// Corners: 0:URF, 1:UFL, 2:ULB, 3:UBR, 4:DFR, 5:DLF, 6:DBL, 7:DRB
const cornerSlots = [
{ x: 1, y: 1, z: 1 }, // 0 URF
{ x: -1, y: 1, z: 1 }, // 1 UFL
{ x: -1, y: 1, z: -1 }, // 2 ULB
{ x: 1, y: 1, z: -1 }, // 3 UBR
{ x: 1, y: -1, z: 1 }, // 4 DFR
{ x: -1, y: -1, z: 1 }, // 5 DLF
{ x: -1, y: -1, z: -1 },// 6 DBL
{ x: 1, y: -1, z: -1 } // 7 DRB
];
// Edges: 0:UR, 1:UF, 2:UL, 3:UB, 4:DR, 5:DF, 6:DL, 7:DB, 8:FR, 9:FL, 10:BL, 11:BR
const edgeSlots = [
{ x: 1, y: 1, z: 0 }, // 0 UR
{ x: 0, y: 1, z: 1 }, // 1 UF
{ x: -1, y: 1, z: 0 }, // 2 UL
{ x: 0, y: 1, z: -1 }, // 3 UB
{ x: 1, y: -1, z: 0 }, // 4 DR
{ x: 0, y: -1, z: 1 }, // 5 DF
{ x: -1, y: -1, z: 0 }, // 6 DL
{ x: 0, y: -1, z: -1 }, // 7 DB
{ x: 1, y: 0, z: 1 }, // 8 FR
{ x: -1, y: 0, z: 1 }, // 9 FL
{ x: -1, y: 0, z: -1 }, // 10 BL
{ x: 1, y: 0, z: -1 } // 11 BR
];
// Centers (Fixed)
const centers = [
{ id: 'c0', x: 0, y: 1, z: 0, faces: { up: 'white' } },
{ id: 'c1', x: 0, y: -1, z: 0, faces: { down: 'yellow' } },
{ id: 'c2', x: 0, y: 0, z: 1, faces: { front: 'green' } },
{ id: 'c3', x: 0, y: 0, z: -1, faces: { back: 'blue' } },
{ id: 'c4', x: -1, y: 0, z: 0, faces: { left: 'orange' } },
{ id: 'c5', x: 1, y: 0, z: 0, faces: { right: 'red' } },
{ id: 'core', x: 0, y: 0, z: 0, faces: {} }
];
const cubies = [...centers];
// Piece Definition (Solved State Colors)
const getCornerColors = (id) => {
const map = [
{ up: 'white', right: 'red', front: 'green' }, // 0
{ up: 'white', front: 'green', left: 'orange' }, // 1
{ up: 'white', left: 'orange', back: 'blue' }, // 2
{ up: 'white', back: 'blue', right: 'red' }, // 3
{ down: 'yellow', right: 'red', front: 'green' }, // 4
{ down: 'yellow', front: 'green', left: 'orange' }, // 5
{ down: 'yellow', left: 'orange', back: 'blue' }, // 6
{ down: 'yellow', back: 'blue', right: 'red' } // 7
];
return map[id];
};
const getEdgeColors = (id) => {
const map = [
{ up: 'white', right: 'red' }, // 0
{ up: 'white', front: 'green' }, // 1
{ up: 'white', left: 'orange' }, // 2
{ up: 'white', back: 'blue' }, // 3
{ down: 'yellow', right: 'red' }, // 4
{ down: 'yellow', front: 'green' }, // 5
{ down: 'yellow', left: 'orange' }, // 6
{ down: 'yellow', back: 'blue' }, // 7
{ front: 'green', right: 'red' }, // 8
{ front: 'green', left: 'orange' }, // 9
{ back: 'blue', left: 'orange' }, // 10
{ back: 'blue', right: 'red' } // 11
];
return map[id];
};
// CORNERS
const pKeys = [
['up', 'right', 'front'], // 0
['up', 'front', 'left'], // 1
['up', 'left', 'back'], // 2
['up', 'back', 'right'], // 3
['down', 'right', 'front'], // 4
['down', 'front', 'left'], // 5
['down', 'left', 'back'], // 6
['down', 'back', 'right'] // 7
];
for (let i = 0; i < 8; i++) {
const pieceId = this.cp[i]; // Which physical piece is here
const orientation = this.co[i]; // Twist: 0, 1 (CW), 2 (CCW)
const slot = cornerSlots[i];
const baseColors = getCornerColors(pieceId);
const slotKeys = pKeys[i]; // Keys of the SLOT
// Primary colors of the PIECE
const pieceKeys = pKeys[pieceId]; // Keys of the PIECE
const colors = [baseColors[pieceKeys[0]], baseColors[pieceKeys[1]], baseColors[pieceKeys[2]]];
const faces = {};
// Apply twist
// Shift 0: S[0]=C[0], S[1]=C[1], S[2]=C[2]
// Shift 1: S[0]=C[2], S[1]=C[0], S[2]=C[1] (CW Twist: Colors rotate CW relative to keys)
// Shift 2: S[0]=C[1], S[1]=C[2], S[2]=C[0]
// Formula: index k gets color (k - o + 3) % 3
faces[slotKeys[0]] = colors[(0 - orientation + 3) % 3];
faces[slotKeys[1]] = colors[(1 - orientation + 3) % 3];
faces[slotKeys[2]] = colors[(2 - orientation + 3) % 3];
cubies.push({ id: `corn${pieceId}`, x: slot.x, y: slot.y, z: slot.z, faces });
}
// EDGES
const eKeys = [
['up', 'right'], // 0 UR
['up', 'front'], // 1 UF
['up', 'left'], // 2 UL
['up', 'back'], // 3 UB
['down', 'right'], // 4 DR
['down', 'front'], // 5 DF
['down', 'left'], // 6 DL
['down', 'back'], // 7 DB
['front', 'right'], // 8 FR
['front', 'left'], // 9 FL
['back', 'left'], // 10 BL
['back', 'right'] // 11 BR
];
for (let i = 0; i < 12; i++) {
const pieceId = this.ep[i];
const flip = this.eo[i];
const slot = edgeSlots[i];
const baseColors = getEdgeColors(pieceId);
const pieceKeys = eKeys[pieceId];
const colors = [baseColors[pieceKeys[0]], baseColors[pieceKeys[1]]];
const slotKeys = eKeys[i];
const faces = {};
if (flip === 0) {
faces[slotKeys[0]] = colors[0];
faces[slotKeys[1]] = colors[1];
} else {
faces[slotKeys[0]] = colors[1];
faces[slotKeys[1]] = colors[0];
}
cubies.push({ id: `edge${pieceId}`, x: slot.x, y: slot.y, z: slot.z, faces });
}
return cubies;
}
rotateLayer(axis, index, dir) {
// axis: 'x', 'y', 'z'
// index: -1, 0, 1
// dir: 1 (Visual CCW / Logic U'), -1 (Visual CW / Logic U)
let move = '';
if (axis === 'y') {
if (index === 1) { // Up Layer
move = dir === 1 ? "U'" : "U";
} else if (index === -1) { // Down Layer
// D move is Bottom CW (+Y rotation) -> Visual CCW (dir=1).
move = dir === 1 ? "D" : "D'";
}
}
else if (axis === 'x') {
if (index === 1) { // Right Layer
// R is -X rotation -> Visual CW (dir=-1).
move = dir === 1 ? "R'" : "R";
} else if (index === -1) { // Left Layer
// L is +X rotation -> Visual CCW (dir=1).
move = dir === 1 ? "L" : "L'";
}
}
else if (axis === 'z') {
if (index === 1) { // Front Layer
// F is -Z rotation -> Visual CW (dir=-1).
move = dir === 1 ? "F'" : "F";
} else if (index === -1) { // Back Layer
// B is +Z rotation -> Visual CCW (dir=1).
move = dir === 1 ? "B" : "B'";
}
}
if (move) {
this.move(move);
}
}
}

261
src/utils/RubiksJSModel.js Normal file
View File

@@ -0,0 +1,261 @@
import { State } from 'rubiks-js/src/state/index.js';
// Static order definitions from rubiks-js source
const CORNER_ORDER = ['URF', 'ULF', 'ULB', 'URB', 'DRF', 'DLF', 'DLB', 'DRB'];
const EDGE_ORDER = ['UF', 'UL', 'UB', 'UR', 'FR', 'FL', 'BL', 'BR', 'DF', 'DL', 'DB', 'DR'];
// Coordinate mapping for visualization
// Coordinates match the visual grid positions
const CORNER_SLOTS = [
{ id: 'URF', x: 1, y: 1, z: 1 },
{ id: 'ULF', x: -1, y: 1, z: 1 },
{ id: 'ULB', x: -1, y: 1, z: -1 },
{ id: 'URB', x: 1, y: 1, z: -1 },
{ id: 'DRF', x: 1, y: -1, z: 1 },
{ id: 'DLF', x: -1, y: -1, z: 1 },
{ id: 'DLB', x: -1, y: -1, z: -1 },
{ id: 'DRB', x: 1, y: -1, z: -1 }
];
const EDGE_SLOTS = [
{ id: 'UF', x: 0, y: 1, z: 1 },
{ id: 'UL', x: -1, y: 1, z: 0 },
{ id: 'UB', x: 0, y: 1, z: -1 },
{ id: 'UR', x: 1, y: 1, z: 0 },
{ id: 'FR', x: 1, y: 0, z: 1 },
{ id: 'FL', x: -1, y: 0, z: 1 },
{ id: 'BL', x: -1, y: 0, z: -1 },
{ id: 'BR', x: 1, y: 0, z: -1 },
{ id: 'DF', x: 0, y: -1, z: 1 },
{ id: 'DL', x: -1, y: -1, z: 0 },
{ id: 'DB', x: 0, y: -1, z: -1 },
{ id: 'DR', x: 1, y: -1, z: 0 }
];
const CENTERS = [
{ id: 'c0', x: 0, y: 1, z: 0, faces: { up: 'white' } },
{ id: 'c1', x: 0, y: -1, z: 0, faces: { down: 'yellow' } },
{ id: 'c2', x: 0, y: 0, z: 1, faces: { front: 'green' } },
{ id: 'c3', x: 0, y: 0, z: -1, faces: { back: 'blue' } },
{ id: 'c4', x: -1, y: 0, z: 0, faces: { left: 'orange' } },
{ id: 'c5', x: 1, y: 0, z: 0, faces: { right: 'red' } },
{ id: 'core', x: 0, y: 0, z: 0, faces: {} }
];
// Face mapping for pieces
// Each piece (e.g. URF) has 3 faces. We need to map them to colors based on orientation.
// Standard color scheme: U=white, D=yellow, F=green, B=blue, L=orange, R=red
const FACE_COLORS = {
U: 'white', D: 'yellow', F: 'green', B: 'blue', L: 'orange', R: 'red'
};
// Map piece name (e.g. 'URF') to its primary face keys
const CORNER_FACES = {
'URF': ['up', 'right', 'front'],
'ULF': ['up', 'front', 'left'],
'ULB': ['up', 'left', 'back'],
'URB': ['up', 'back', 'right'],
'DRF': ['down', 'right', 'front'],
'DLF': ['down', 'left', 'front'],
'DLB': ['down', 'back', 'left'],
'DRB': ['down', 'right', 'back']
};
const EDGE_FACES = {
'UF': ['up', 'front'],
'UL': ['up', 'left'],
'UB': ['up', 'back'],
'UR': ['up', 'right'],
'FR': ['front', 'right'],
'FL': ['front', 'left'],
'BL': ['back', 'left'],
'BR': ['back', 'right'],
'DF': ['down', 'front'],
'DL': ['down', 'left'],
'DB': ['down', 'back'],
'DR': ['down', 'right']
};
// Map piece name to its solved colors
const getCornerColors = (name) => {
// URF -> white, red, green
const map = {
'URF': ['white', 'red', 'green'],
'ULF': ['white', 'green', 'orange'],
'ULB': ['white', 'orange', 'blue'],
'URB': ['white', 'blue', 'red'],
'DRF': ['yellow', 'red', 'green'],
'DLF': ['yellow', 'orange', 'green'], // Adjusted to match DLF face order (D, L, F)
'DLB': ['yellow', 'blue', 'orange'], // Adjusted to match DLB face order (D, B, L)
'DRB': ['yellow', 'red', 'blue'] // Adjusted to match DRB face order (D, R, B)
};
return map[name];
};
const getEdgeColors = (name) => {
const map = {
'UF': ['white', 'green'],
'UL': ['white', 'orange'],
'UB': ['white', 'blue'],
'UR': ['white', 'red'],
'FR': ['green', 'red'],
'FL': ['green', 'orange'],
'BL': ['blue', 'orange'],
'BR': ['blue', 'red'],
'DF': ['yellow', 'green'],
'DL': ['yellow', 'orange'],
'DB': ['yellow', 'blue'],
'DR': ['yellow', 'red']
};
return map[name];
};
export class RubiksJSModel {
constructor() {
this.state = new State(false); // trackCenters=false
}
reset() {
// State doesn't have a reset method exposed directly?
// We can just create a new state.
this.state = new State(false);
}
rotateLayer(axis, index, dir) {
// Map to standard notation
// axis: 'x', 'y', 'z'
// index: 1 (top/right/front), -1 (bottom/left/back)
// dir: 1 (Visual CCW), -1 (Visual CW)
let move = '';
if (axis === 'y') {
if (index === 1) move = dir === 1 ? "U'" : "U";
else if (index === -1) move = dir === 1 ? "D'" : "D"; // Fixed: dir=1 (CCW) -> D'
}
else if (axis === 'x') {
if (index === 1) move = dir === 1 ? "R'" : "R";
else if (index === -1) move = dir === 1 ? "L'" : "L"; // Fixed: dir=1 (CCW) -> L'
}
else if (axis === 'z') {
if (index === 1) move = dir === 1 ? "F'" : "F";
else if (index === -1) move = dir === 1 ? "B'" : "B"; // Fixed: dir=1 (CCW) -> B'
}
if (move) {
console.log('[RubiksJSModel] Applying move:', move);
try {
this.state.applyTurn(move);
console.log('[RubiksJSModel] Move applied successfully');
} catch (e) {
console.error('[RubiksJSModel] Failed to apply move:', move, e);
}
}
}
toCubies() {
// Decode state
const encoded = this.state.encode();
// console.log('[RubiksJSModel] Encoded state:', encoded);
const binaryString = atob(encoded);
const bytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
// Decode Corners (first 5 bytes)
// p: bytes[0] + (bytes[1] << 8) + (bytes[2] << 16)
let pC = bytes[0] + (bytes[1] << 8) + (bytes[2] << 16);
let oC = bytes[3] + (bytes[4] << 8);
const cornerPerms = [];
const cornerOrients = [];
for (let i = 7; i >= 0; i--) {
const p1 = pC & 0b111;
cornerPerms[i] = CORNER_ORDER[p1];
pC = pC >> 3;
const o1 = oC & 0b11;
cornerOrients[i] = o1;
oC = oC >> 2;
}
// Decode Edges (next 8 bytes)
// 6 bytes for permutation (each byte has 2 nibbles)
// 2 bytes for orientation
const edgePerms = [];
const edgeOrients = [];
// Permutation
for (let i = 0; i < 6; i++) {
const byte = bytes[5 + i];
const p1 = byte & 0b1111;
const p2 = (byte >> 4) & 0b1111;
edgePerms[i * 2] = EDGE_ORDER[p1];
edgePerms[i * 2 + 1] = EDGE_ORDER[p2];
}
// Orientation
let oE = bytes[11] + (bytes[12] << 8);
for (let i = 11; i >= 0; i--) {
edgeOrients[i] = oE & 0b1;
oE = oE >> 1;
}
const cubies = [...CENTERS];
// Map Corners
for (let i = 0; i < 8; i++) {
const pieceName = cornerPerms[i]; // e.g. 'URF'
const orientation = cornerOrients[i]; // 0, 1, 2
const slot = CORNER_SLOTS[i]; // Slot definition
const baseColors = getCornerColors(pieceName); // ['white', 'red', 'green']
const slotFaces = CORNER_FACES[slot.id]; // ['up', 'right', 'front']
// Apply orientation
// Formula: Color at SlotKey[k] is PieceColor[(k + o) % 3]
const faces = {};
faces[slotFaces[0]] = baseColors[(0 + orientation) % 3];
faces[slotFaces[1]] = baseColors[(1 + orientation) % 3];
faces[slotFaces[2]] = baseColors[(2 + orientation) % 3];
cubies.push({ id: `corn${i}`, x: slot.x, y: slot.y, z: slot.z, faces });
}
// Map Edges
for (let i = 0; i < 12; i++) {
const pieceName = edgePerms[i];
const orientation = edgeOrients[i]; // 0, 1
const slot = EDGE_SLOTS[i];
const baseColors = getEdgeColors(pieceName); // ['white', 'green']
const slotFaces = EDGE_FACES[slot.id]; // ['up', 'front']
const faces = {};
// If orientation is 1 (Flip), we swap.
// But we need to be careful about which face is primary (0).
// Logic: if o=0, faces match. if o=1, swap.
// Adjust for specific edges if needed?
// For now assume standard behavior:
if (orientation === 0) {
faces[slotFaces[0]] = baseColors[0];
faces[slotFaces[1]] = baseColors[1];
} else {
faces[slotFaces[0]] = baseColors[1];
faces[slotFaces[1]] = baseColors[0];
}
cubies.push({ id: `edge${i}`, x: slot.x, y: slot.y, z: slot.z, faces });
}
return cubies;
}
validate() {
// State doesn't expose validate, but we can assume it's valid if using the library
return { valid: true, errors: [] };
}
}

View File

@@ -0,0 +1,46 @@
import { RubiksJSModel } from '../utils/RubiksJSModel.js';
const cube = new RubiksJSModel();
// Helper to send state update
const sendUpdate = () => {
try {
const cubies = cube.toCubies();
// console.log('[Worker] Sending update with cubies:', cubies.length);
postMessage({
type: 'STATE_UPDATE',
payload: {
cubies
}
});
} catch (e) {
console.error('[Worker] Error generating cubies:', e);
postMessage({ type: 'ERROR', payload: e.message });
}
};
self.onmessage = (e) => {
const { type, payload } = e.data;
switch (type) {
case 'INIT':
case 'RESET':
cube.reset();
sendUpdate();
break;
case 'ROTATE_LAYER':
const { axis, index, direction } = payload;
cube.rotateLayer(axis, index, direction);
sendUpdate();
break;
case 'VALIDATE':
const validation = cube.validate();
postMessage({
type: 'VALIDATION_RESULT',
payload: { valid: validation.valid, errors: validation.errors }
});
break;
}
};