Last active
January 11, 2022 18:30
-
-
Save SalatielSauer/abe02d095bbce56696dc42ab0c1f5398 to your computer and use it in GitHub Desktop.
JavaScript functions to get the position or index of a cube following the Sauerbraten octree structure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// example: getCubeIndex(256, 256, 512, 8) // returns: 35 | |
function getCubeIndex(x, y, z, gridpower) { | |
let index = 0; | |
let size = 1<<gridpower; | |
index += parseInt((x / size).toString(2), 8); | |
index += parseInt((y / size).toString(2), 8) * 2; | |
index += parseInt((z / size).toString(2), 8) * 4; | |
return index; | |
} | |
// example: getCubePos(35, 8) // returns: [256, 256, 512] | |
function getCubePos(index, gridpower) { | |
let octal = index.toString(8); | |
let size = 1<<gridpower; | |
let position = [0, 0, 0]; | |
for (i = 0; i < octal.length; i++) { | |
let digit = parseInt(octal[octal.length - i - 1], 8); | |
position[0] += (Math.floor(digit / 1) % 2) * (2 ** i) * size; | |
position[1] += (Math.floor(digit / 2) % 2) * (2 ** i) * size; | |
position[2] += (Math.floor(digit / 4) % 2) * (2 ** i) * size; | |
} | |
return position; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment