File size: 7,892 Bytes
7d70895
1afe868
7d70895
20ba9a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1afe868
20ba9a1
1afe868
 
 
20ba9a1
1afe868
 
 
20ba9a1
1afe868
 
 
20ba9a1
1afe868
 
 
20ba9a1
8d694b6
1afe868
 
20ba9a1
8d694b6
1afe868
 
20ba9a1
 
 
 
 
 
 
 
 
 
 
a2c7a31
c6ef322
 
 
 
 
 
 
 
 
 
 
8d694b6
 
c6ef322
 
 
 
 
 
 
 
 
 
 
 
 
 
52b5f8d
a2c7a31
 
 
 
 
52b5f8d
 
 
a2c7a31
c6ef322
 
20ba9a1
 
 
d23d56a
7d70895
d23d56a
 
20ba9a1
 
 
 
7994c21
 
 
 
 
 
 
 
 
 
20ba9a1
 
 
 
 
 
 
 
 
 
 
 
1afe868
20ba9a1
1afe868
20ba9a1
1afe868
20ba9a1
4c67d79
 
8d694b6
20ba9a1
8d694b6
20ba9a1
 
 
 
52b5f8d
8d694b6
52b5f8d
 
 
 
 
 
 
 
 
7d70895
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d694b6
7d70895
 
 
 
 
 
 
 
 
 
 
4c67d79
 
a2c7a31
0b3d91e
 
 
 
 
 
 
 
 
4c67d79
0b3d91e
c6ef322
 
20ba9a1
 
 
 
7d70895
 
 
 
20ba9a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1afe868
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
import { Group, Mesh, MeshStandardMaterial, Vector3 } from 'three';

import { Actions, Color2Index, FacingDirection, RotationStep } from './consts';

export class RotationController {
  private static instance: RotationController;

  private cubeGroup?: Group;
  private cubes: Array<Mesh>;
  private cubeSpeed: number;
  private rotationSteps: Array<RotationStep>;
  private rotatingStep: RotationStep | null;
  private rotatingGroup: Group;

  constructor() {
    this.cubes = [];
    this.cubeSpeed = 2;
    this.rotationSteps = [];
    this.rotatingStep = null;
    this.rotatingGroup = new Group();
  }

  private rotate(step: RotationStep, group: Group, delta: number) {
    let sign = 0;
    let axis: 'x' | 'y' | 'z' = 'x';
    switch (step.faceDirection) {
      case 'front':
        sign = step.direction === 'clockwise' ? -1 : 1;
        axis = 'z';
        break;
      case 'back':
        sign = step.direction === 'clockwise' ? 1 : -1;
        axis = 'z';
        break;
      case 'left':
        sign = step.direction === 'clockwise' ? 1 : -1;
        axis = 'x';
        break;
      case 'right':
        sign = step.direction === 'clockwise' ? -1 : 1;
        axis = 'x';
        break;
      case 'up':
        sign = step.direction === 'clockwise' ? -1 : 1;
        axis = 'y';
        break;
      case 'down':
        sign = step.direction === 'clockwise' ? 1 : -1;
        axis = 'y';
        break;
    }

    group.rotation[axis] += sign * delta * this.cubeSpeed;
    if (Math.abs(group.rotation[axis]) > Math.PI / 2) {
      group.rotation[axis] = (Math.PI / 2) * sign;
      return true;
    }
    return false;
  }

  private getCubeFaceData(mesh: Mesh, faceDirection: FacingDirection) {
    const faces = mesh.children.filter((child) => child.userData.isFace);
    let axis: 'x' | 'y' | 'z' = 'x';
    switch (faceDirection) {
      case 'front':
      case 'back':
        axis = 'z';
        break;
      case 'right':
      case 'left':
        axis = 'x';
        break;
      case 'up':
      case 'down':
        axis = 'y';
        break;
    }
    let maxFace: Mesh | null = null;
    let maxValue = -Infinity;
    for (const face of faces) {
      const worldPosition = new Vector3();
      face.getWorldPosition(worldPosition);
      const axisValue = Math.abs(worldPosition[axis]);
      if (axisValue > maxValue) {
        maxValue = axisValue;
        maxFace = face as Mesh;
      }
    }
    if (!maxFace) throw new Error('maxFace is null'); // this should never happen
    const worldPosition = new Vector3();
    maxFace.getWorldPosition(worldPosition);
    const axis2 = ['x', 'y', 'z'].filter((x) => x !== axis) as Array<'x' | 'y' | 'z'>;
    const rank = worldPosition[axis2[0]] * 100 + worldPosition[axis2[1]] * 10;
    return {
      face: maxFace,
      worldPosition,
      rank,
    };
  }

  static getInstance() {
    if (!RotationController.instance) {
      RotationController.instance = new RotationController();
      if (typeof window !== 'undefined') {
        // @ts-expect-error window is defined
        window.rotationController = RotationController.instance;
      }
    }
    return RotationController.instance;
  }

  stopRotation(cb: () => void) {
    this.rotationSteps = [];
    const cancel = setInterval(() => {
      if (!this.rotatingStep) {
        clearInterval(cancel);
        cb();
      }
    }, 50);
  }

  setCubeGroup(cubeGroup: Group) {
    this.cubeGroup = cubeGroup;
  }

  addCube(cube: Mesh) {
    if (!this.cubes.includes(cube)) {
      this.cubes.push(cube);
    }
  }

  getCubes(faceDirection: FacingDirection) {
    switch (faceDirection) {
      case 'front':
        return this.cubes.filter((m) => m.position.z > 0);
      case 'back':
        return this.cubes.filter((m) => m.position.z < 0);
      case 'right':
        return this.cubes.filter((m) => m.position.x > 0);
      case 'left':
        return this.cubes.filter((m) => m.position.x < 0);
      case 'up':
        return this.cubes.filter((m) => m.position.y > 0);
      case 'down':
        return this.cubes.filter((m) => m.position.y < 0);
    }
  }

  initializeFaces() {
    ['front', 'back', 'right', 'left', 'up', 'down'].forEach((f) => {
      const faceDirection = f as FacingDirection;
      const cubes = this.getCubes(faceDirection);
      const indices = cubes.map((cube) => this.getCubeFaceData(cube, faceDirection)).sort((a, b) => a.rank - b.rank);
      indices.forEach((i, index) => {
        i.face.userData.name = `${faceDirection[0].toUpperCase()}${index}`;
      });
    });
  }

  setState(stateArray: Array<Array<number>>) {
    const colors = ['', '', '', '', '', ''];
    Object.entries(Color2Index).forEach(([c, i]) => {
      colors[i] = c;
    });
    ['front', 'back', 'right', 'left', 'up', 'down'].forEach((f, idx1) => {
      const faceDirection = f as FacingDirection;
      const cubes = this.getCubes(faceDirection);
      const indices = cubes.map((cube) => this.getCubeFaceData(cube, faceDirection)).sort((a, b) => a.rank - b.rank);
      indices.forEach((i, idx2) => {
        const colorIdx = stateArray[idx1][idx2];
        i.face.userData.faceColor = colors[colorIdx];
        i.face.userData.faceColorIndex = colorIdx;
        const material = i.face.material as MeshStandardMaterial;
        material.color.set(colors[colorIdx]);
      });
    });
    this.initializeFaces();
  }

  getState() {
    const status = ['front', 'back', 'right', 'left', 'up', 'down'].map((f) => {
      const faceDirection = f as FacingDirection;
      const cubes = this.getCubes(faceDirection);
      const indices = cubes.map((cube) => this.getCubeFaceData(cube, faceDirection)).sort((a, b) => a.rank - b.rank);
      return indices.map((i) => i.face.userData.faceColorIndex);
    });
    return status;
  }

  _printStateTransitions() {
    const rotationsPy: Array<string> = [];
    ['front', 'back', 'right', 'left', 'up', 'down'].forEach((f) => {
      const faceDirection = f as FacingDirection;
      const cubes = this.getCubes(faceDirection);
      const indices = cubes.map((cube) => this.getCubeFaceData(cube, faceDirection)).sort((a, b) => a.rank - b.rank);
      const positionNames = indices.map((i) => i.face.userData.name);
      for (let i = 0; i < positionNames.length; i++) {
        const positionName = positionNames[i];
        if (positionName[0] !== f[0].toUpperCase() || positionName[1] !== i.toString()) {
          rotationsPy.push(
            `new_state[${f[0].toUpperCase()}, ${i}] = self.state[${positionName[0]}, ${positionName[1]}]`,
          );
        }
      }
    });
    console.log(rotationsPy.join('\n'));
  }

  setCubeSpeed(cubeSpeed: number) {
    this.cubeSpeed = cubeSpeed;
  }

  addRotationStepCode(...codes: Array<number>) {
    this.addRotationStep(...codes.map((code) => Actions[code]));
  }

  addRotationStep(...step: Array<RotationStep>) {
    this.rotationSteps.push(...step);
  }

  frameCallback(state: unknown, delta: number) {
    if (!this.cubeGroup) return;
    if (this.rotationSteps.length === 0 && !this.rotatingStep) return;
    if (!this.rotatingStep) {
      const step = this.rotationSteps.shift();
      if (!step) return;
      this.rotatingStep = step;
      const cubes = this.getCubes(step.faceDirection);
      this.rotatingGroup = new Group();
      this.cubeGroup?.add(this.rotatingGroup);
      cubes.forEach((cube) => this.rotatingGroup.attach(cube));
    }

    const done = this.rotate(this.rotatingStep, this.rotatingGroup, delta);
    if (done) {
      this.rotatingStep = null;
      const children = [...this.rotatingGroup.children];
      children.forEach((child) => this.cubeGroup?.attach(child));
      this.cubeGroup?.remove(this.rotatingGroup);
    }
  }
}

export const rotationController = RotationController.getInstance();
export const frameCallback = rotationController.frameCallback.bind(rotationController);