Move all business logic code under template folder
[oam.git] / code / network-generator / network_generation / model / python / cube.py
1 # Copyright 2023 highstreet technologies GmbH
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #     http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 #
15 # inspired by http://www.redblobgames.com/grids/hexagons/
16
17 #!/usr/bin/python
18 from network_generation.model.python.hexagon import Hex
19
20
21 class Cube:
22     @staticmethod
23     def direction_vectors() -> list[Hex]:
24         q, r, s = 1, 0, -1
25         return [
26             Hex(q, r, s),
27             Hex(-s, -q, -r),
28             Hex(r, s, q),
29             Hex(-q, -r, -s),
30             Hex(s, q, r),
31             Hex(-r, -s, -q),
32         ]
33
34     @staticmethod
35     def direction(direction: int) -> Hex:
36         if direction < 0 or direction > 5:
37             raise ValueError(
38                 "Invalid direction. The direction value must be in the range of [0..5]."
39             )
40         return Cube.direction_vectors()[direction]
41
42     @staticmethod
43     def add(hex: Hex, vec: Hex) -> Hex:
44         return Hex(hex.q + vec.q, hex.r + vec.r, hex.s + vec.s)
45
46     @staticmethod
47     def neighbor(cube: Hex, direction: int) -> Hex:
48         return Cube.add(cube, Cube.direction(direction))
49
50     @staticmethod
51     def scale(hex: Hex, factor: int) -> Hex:
52         return Hex(hex.q * factor, hex.r * factor, hex.s * factor)
53
54     @staticmethod
55     def ring(center: Hex, radius: int) -> list[Hex]:
56         if not (radius > 0):
57             raise ValueError(
58                 "Invalid radius. The radius around the hex center must be greater than 0 rings."
59             )
60         results: list[Hex] = []
61         hex: Hex = Cube.add(center, Cube.scale(Cube.direction(4), radius))
62         for i in range(6):
63             for j in range(radius):
64                 results.append(hex)
65                 hex = Cube.neighbor(hex, i)
66         return results
67
68     @staticmethod
69     def spiral(center: Hex, radius: int) -> list[Hex]:
70         result: list[Hex] = [center]
71         for k in range(1, radius + 1):
72             result.extend(Cube.ring(center, k))
73         return result