All files / integration cubeExport.ts

100% Statements 72/72
100% Branches 0/0
100% Functions 0/0
100% Lines 72/72

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214                                            38x 38x                     38x                   4x 3x 1x 1x 1x 2x 2x       1x   2x       13x   128x           12x   120x 120x   1x   11x   101x       10x 10x 90x 90x 465x   90x   10x       10x 10x 100x 470x     10x         5x       5x 55x 5x       5x 5x 5x 60x 60x   5x         7x 6x 6x 6x 5x   5x 5x 5x     5x         2x                 4x 4x 216x 216x 4x         1x 1x         1x 1x                                                 14x 13x   3x   1x   4x   1x   2x   1x   1x   1x   1x      
import type { SmartCubeCubieState } from '@wstein/regrip-core/bindings/smartCubeTransport';
import type { ColorScheme } from '../adapters/three/faceColors';
 
import * as CubeFacelets from '@wstein/regrip-core/domain/CubeFacelets';
import { formatSingmasterCycles, formatSupersetEngPermutation } from './cubeInfo';
 
export type CubeExportFormat =
  | 'compact-facelets'
  | 'spaced-facelets'
  | 'color-facelets'
  | 'singmaster-cycles'
  | 'sse-permutation'
  | 'cubie-coordinates'
  | 'kpattern-json'
  | 'regrip-state-json'
  | 'orbit64';
/**
 * Physical cube state normalized to the protocol's canonical URFDLB body frame.
 * Virtual solver-frame regrips must never be applied to this export source.
 */
export type CubeExportSource = { facelets: string; state?: SmartCubeCubieState };
 
const base64url = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
const westernFaceletColors: Readonly<Record<string, string>> = {
  U: 'W',
  R: 'R',
  F: 'G',
  D: 'Y',
  L: 'O',
  B: 'B',
};
 
// The Japanese scheme keeps the standard arrangement where blue (B) and yellow (D)
// swap places relative to Western (white opposite blue, green opposite yellow).
const japaneseFaceletColors: Readonly<Record<string, string>> = {
  ...westernFaceletColors,
  B: westernFaceletColors.D,
  D: westernFaceletColors.B,
};
 
function faceletColorsFor(
  scheme: ColorScheme,
  custom?: Partial<Record<string, string>>,
): Readonly<Record<string, string>> {
  if (scheme === 'japanese') return japaneseFaceletColors;
  if (scheme === 'custom') {
    const result = { ...westernFaceletColors };
    if (custom) {
      for (const [key, value] of Object.entries(custom)) {
        if (typeof value === 'string') {
          result[key] = value;
        }
      }
    }
    return result;
  }
  return westernFaceletColors;
}
 
function validPermutation(values: number[], length: number): boolean {
  return (
    values.length === length &&
    values.every((value) => Number.isInteger(value) && value >= 0 && value < length) &&
    new Set(values).size === length
  );
}
 
function orientationRank(values: number[], count: number, radix: number): bigint | undefined {
  if (
    values.length !== count + 1 ||
    values.some((value) => !Number.isInteger(value) || value < 0 || value >= radix) ||
    values.reduce((sum, value) => sum + value, 0) % radix !== 0
  ) {
    return undefined;
  }
  return values
    .slice(0, count)
    .reduce((rank, value, index) => rank + BigInt(value) * BigInt(radix) ** BigInt(index), 0n);
}
 
function permutationRank(permutation: number[], count = permutation.length): bigint {
  let rank = 0n;
  for (let index = 0; index < count; index += 1) {
    let smaller = 0;
    for (let later = index + 1; later < permutation.length; later += 1) {
      if (permutation[later] < permutation[index]) smaller += 1;
    }
    rank = rank * BigInt(permutation.length - index) + BigInt(smaller);
  }
  return rank;
}
 
function parity(permutation: number[]): number {
  let inversions = 0;
  for (let index = 0; index < permutation.length; index += 1) {
    for (let later = index + 1; later < permutation.length; later += 1) {
      if (permutation[index] > permutation[later]) inversions += 1;
    }
  }
  return inversions % 2;
}
 
/** Orbit64's compact rank within one fixed permutation parity class. */
function permutationRankWithParity(permutation: number[]): bigint {
  return permutationRank(permutation, permutation.length - 2);
}
 
function factorial(value: number): bigint {
  let result = 1n;
  for (let factor = 2; factor <= value; factor += 1) result *= BigInt(factor);
  return result;
}
 
function toBase64url(value: bigint, width: number): string {
  let result = '';
  let remaining = value;
  for (let index = 0; index < width; index += 1) {
    result = `${base64url[Number(remaining % 64n)]}${result}`;
    remaining /= 64n;
  }
  return result;
}
 
/** Canonical-frame Orbit64 3×3×3 token from smartcube CP/CO/EP/EO data. */
export function formatOrbit64(state: SmartCubeCubieState): string | undefined {
  if (!validPermutation(state.CP, 8) || !validPermutation(state.EP, 12)) return undefined;
  const cornerOrientation = orientationRank(state.CO, 7, 3);
  const edgeOrientation = orientationRank(state.EO, 11, 2);
  if (cornerOrientation === undefined || edgeOrientation === undefined) return undefined;
  if (parity(state.CP) !== parity(state.EP)) return undefined;
 
  const cornerRank = permutationRank(state.CP) * 2187n + cornerOrientation;
  const edgeRank = permutationRankWithParity(state.EP) * 2048n + edgeOrientation;
  const midgeRadix = (factorial(12) / 2n) * 2048n;
  // Orbit64 stores a 24-way whole-cube frame after the coordinate rank. Copy
  // exports use the normalized Kociemba URFDLB body frame.
  return toBase64url((cornerRank * midgeRadix + edgeRank) * 24n, 12);
}
 
/** Copy-ready raw cubie coordinates in Kociemba / smart-cube order. */
export function formatCubieCoordinates(state: SmartCubeCubieState): string {
  return `CP: ${state.CP.join(',')}\nCO: ${state.CO.join(',')}\nEP: ${state.EP.join(',')}\nEO: ${state.EO.join(',')}`;
}
 
/** Sticker colors in canonical URFDLB face order, grouped by face. */
export function formatColorFacelets(
  facelets: string,
  scheme: ColorScheme = 'western',
  custom?: Partial<Record<string, string>>,
): string | undefined {
  if (facelets.length !== 54) return undefined;
  const faceletColors = faceletColorsFor(scheme, custom);
  const colors = Array.from(facelets, (facelet) => faceletColors[facelet]);
  if (colors.some((color) => color === undefined)) return undefined;
  return colors.join('').match(/.{9}/g)?.join(' ');
}
 
/** cubing.js-compatible KPatternData serialized with stable indentation. */
export function formatKPatternJson(facelets: string): string | undefined {
  const decoded = CubeFacelets.faceletsToPatternData(facelets);
  return decoded.TAG === 'Ok' ? JSON.stringify(decoded._0, null, 2) : undefined;
}
 
/** Versioned Regrip state document in the normalized Kociemba body frame. */
export function formatRegripStateJson(source: CubeExportSource): string | undefined {
  if (!source.state) return undefined;
  return JSON.stringify(
    {
      format: 'regrip-state',
      version: 1,
      puzzle: '3x3x3',
      faceletOrder: 'URFDLB',
      facelets: source.facelets,
      cubies: {
        CP: source.state.CP,
        CO: source.state.CO,
        EP: source.state.EP,
        EO: source.state.EO,
      },
    },
    null,
    2,
  );
}
 
export function formatCubeExport(
  source: CubeExportSource | undefined,
  format: CubeExportFormat,
  colorScheme: ColorScheme = 'western',
  customColors?: Partial<Record<string, string>>,
): string | undefined {
  if (!source || source.facelets.length !== 54) return undefined;
  switch (format) {
    case 'compact-facelets':
      return source.facelets;
    case 'spaced-facelets':
      return source.facelets.match(/.{1,9}/g)?.join(' ');
    case 'color-facelets':
      return formatColorFacelets(source.facelets, colorScheme, customColors);
    case 'singmaster-cycles':
      return source.state ? formatSingmasterCycles(source.state) : undefined;
    case 'sse-permutation':
      return source.state ? formatSupersetEngPermutation(source.state) : undefined;
    case 'cubie-coordinates':
      return source.state ? formatCubieCoordinates(source.state) : undefined;
    case 'kpattern-json':
      return formatKPatternJson(source.facelets);
    case 'regrip-state-json':
      return formatRegripStateJson(source);
    case 'orbit64':
      return source.state ? formatOrbit64(source.state) : undefined;
  }
}