File size: 1,503 Bytes
ec43676
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"use client";

import { FacingDirection } from "@/components/consts";
import { createContext, RefObject, useContext, useRef } from "react";
import { Mesh } from "three";

export type CubeMeshRef = RefObject<Mesh | null>;

type CubesContextType = {
  addCube: (cubeMeshRef: CubeMeshRef) => void;
  getCubes: (faceDirection: FacingDirection) => Mesh[];
};

const CubesContext = createContext<CubesContextType>({
  addCube: () => {},
  getCubes: () => [],
});

export const useCubesContext = () => useContext(CubesContext);

export const CubesProvider = ({ children }: { children: React.ReactNode }) => {
  const cubes = useRef<CubeMeshRef[]>([]);

  const addCube = (cubeMeshRef: CubeMeshRef) => {
    cubes.current.push(cubeMeshRef);
  };

  const getCubes = (faceDirection: FacingDirection) => {
    const meshes = cubes.current
      .map((c) => c.current)
      .filter((m) => m !== null);
    switch (faceDirection) {
      case "front":
        return meshes.filter((m) => m.position.z > 0);
      case "back":
        return meshes.filter((m) => m.position.z < 0);
      case "left":
        return meshes.filter((m) => m.position.x < 0);
      case "right":
        return meshes.filter((m) => m.position.x > 0);
      case "top":
        return meshes.filter((m) => m.position.y > 0);
      case "bottom":
        return meshes.filter((m) => m.position.y < 0);
    }
  };

  return (
    <CubesContext.Provider value={{ addCube, getCubes }}>
      {children}
    </CubesContext.Provider>
  );
};