Compare commits
13 Commits
3e9bad8929
...
paul/wip
Author | SHA1 | Date | |
---|---|---|---|
ac63fd8349 | |||
de55283839 | |||
9d503d53cc | |||
9bb162e7d5 | |||
f86697aad8 | |||
c709b1308e | |||
925550308f | |||
7354dcb929 | |||
b6cc6ca35b | |||
e27151b796 | |||
b0a39bb1ce | |||
216ef470c5 | |||
2fccb1fb7c |
324
skycraft/chunk.ts
Normal file
324
skycraft/chunk.ts
Normal file
@@ -0,0 +1,324 @@
|
||||
import { makeFace } from '../geometry';
|
||||
import * as linalg from './linalg';
|
||||
import {memoize} from '../memoize';
|
||||
|
||||
type direction = ('-x' | '+x' | '-y' | '+y' | '-z' | '+z');
|
||||
|
||||
const BlockType = {
|
||||
UNDEFINED: 0,
|
||||
AIR: 1,
|
||||
DIRT: 2,
|
||||
GRASS: 3,
|
||||
STONE: 4,
|
||||
WATER: 5,
|
||||
TREE: 6,
|
||||
LEAVES: 7,
|
||||
SUN: 8,
|
||||
};
|
||||
|
||||
const CHUNKSIZE = 32;
|
||||
|
||||
|
||||
/** seed: some kind of number uniquely defining the body
|
||||
* x, y, z: space coordinates in the body's frame
|
||||
*
|
||||
* returns: a chunk
|
||||
*/
|
||||
function makeDirtBlock(seed: number) {
|
||||
// XXX: for now, return a premade chunk: a 24x24x24 cube of dirt
|
||||
// surrounded by 4 blocks of air all around
|
||||
const cs = CHUNKSIZE;
|
||||
|
||||
if (seed !== 1337) {
|
||||
return {};
|
||||
}
|
||||
// if (Math.abs
|
||||
|
||||
const blocks = new Array(cs * cs * cs);
|
||||
blocks.fill(BlockType.AIR);
|
||||
|
||||
const dirt = new Array(24).fill(BlockType.DIRT);
|
||||
|
||||
for (let i = 0; i < 24; i++) {
|
||||
for (let j = 4; j < 28; j++) {
|
||||
const offset = cs * cs * (i + 4) + cs * j;
|
||||
blocks.splice(offset + 4, 24, ...dirt);
|
||||
}
|
||||
}
|
||||
|
||||
const half = cs / 2;
|
||||
|
||||
return {
|
||||
position: [-half, -half, -half],
|
||||
blocks,
|
||||
underground: false,
|
||||
seed,
|
||||
};
|
||||
}
|
||||
|
||||
function makeSunChunk(seed: number, i: number, j: number, k: number) {
|
||||
const cs = CHUNKSIZE;
|
||||
const radius = 42;
|
||||
if (Math.abs(cs * i) > radius
|
||||
|| Math.abs(cs * j) > radius
|
||||
|| Math.abs(cs * k) > radius) {
|
||||
return undefined;
|
||||
}
|
||||
const half = cs / 2;
|
||||
const blocks = new Array(cs**3);
|
||||
blocks.fill(BlockType.SUN);
|
||||
|
||||
let underground = true;
|
||||
|
||||
for (let x = 0; x < cs; x++) {
|
||||
for (let y = 0; y < cs; y++) {
|
||||
for (let z = 0; z < cs; z++) {
|
||||
const pos = [
|
||||
x + i * cs - half,
|
||||
y + j * cs - half,
|
||||
z + k * cs - half,
|
||||
];
|
||||
const idx = (
|
||||
z * cs * cs +
|
||||
y * cs +
|
||||
x
|
||||
);
|
||||
if (pos[0]**2 + pos[1]**2 + pos[2]**2 > radius**2) {
|
||||
blocks[idx] = BlockType.AIR;
|
||||
underground = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
position: [i * cs - half, j * cs - half, k * cs - half],
|
||||
layout: [i, j, k],
|
||||
blocks,
|
||||
seed,
|
||||
underground,
|
||||
};
|
||||
}
|
||||
|
||||
function _getChunk(seed: number, chunkX: number, chunkY: number, chunkZ: number) {
|
||||
if (seed === 0) {
|
||||
return makeSunChunk(seed, chunkX, chunkY, chunkZ);
|
||||
}
|
||||
if (chunkX === 0 && chunkY === 0 && chunkZ === 0) {
|
||||
return makeDirtBlock(seed); // x, y, z unused right now
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
const getChunk = memoize(_getChunk);
|
||||
|
||||
function faceTexture(type: number, dir: direction) {
|
||||
switch (type) {
|
||||
case BlockType.GRASS:
|
||||
switch (dir) {
|
||||
case '+y': return [0, 15];
|
||||
case '-y': return [2, 15];
|
||||
default: return [1, 15];
|
||||
}
|
||||
case BlockType.DIRT: return [2, 15];
|
||||
case BlockType.STONE: return [3, 15];
|
||||
case BlockType.WATER: return [4, 15];
|
||||
case BlockType.TREE:
|
||||
switch (dir) {
|
||||
case '+y':
|
||||
case '-y':
|
||||
return [5, 15];
|
||||
default: return [6, 15];
|
||||
}
|
||||
case BlockType.LEAVES: return [7, 15];
|
||||
case BlockType.SUN: return [0, 4];
|
||||
default: return [0, 0];
|
||||
}
|
||||
}
|
||||
|
||||
function* makeChunkFaces(chunk, getChunk) {
|
||||
const cs = CHUNKSIZE;
|
||||
|
||||
console.log(`make chunk faces for ${chunk.seed} at ${chunk.position}`);
|
||||
|
||||
function faceCenter(pos: linalg.Vec3, dir: direction) {
|
||||
switch (dir) {
|
||||
case '-x': return [pos[0] - 0.5, pos[1], pos[2]];
|
||||
case '+x': return [pos[0] + 0.5, pos[1], pos[2]];
|
||||
case '-y': return [pos[0], pos[1] - 0.5, pos[2]];
|
||||
case '+y': return [pos[0], pos[1] + 0.5, pos[2]];
|
||||
case '-z': return [pos[0], pos[1], pos[2] - 0.5];
|
||||
case '+z': return [pos[0], pos[1], pos[2] + 0.5];
|
||||
}
|
||||
}
|
||||
|
||||
function neighborChunk(dir: direction) {
|
||||
const [chunkX, chunkY, chunkZ] = chunk.layout;
|
||||
if (chunk.neighbors === undefined) {
|
||||
chunk.neighbors = {};
|
||||
}
|
||||
if (!(dir in chunk.neighbors)) {
|
||||
switch (dir) {
|
||||
case '-x':
|
||||
chunk.neighbors[dir] = getChunk(chunk.seed, chunkX - 1, chunkY, chunkZ);
|
||||
break;
|
||||
case '+x':
|
||||
chunk.neighbors[dir] = getChunk(chunk.seed, chunkX + 1, chunkY, chunkZ);
|
||||
break;
|
||||
case '-y':
|
||||
chunk.neighbors[dir] = getChunk(chunk.seed, chunkX, chunkY - 1, chunkZ);
|
||||
break;
|
||||
case '+y':
|
||||
chunk.neighbors[dir] = getChunk(chunk.seed, chunkX, chunkY + 1, chunkZ);
|
||||
break;
|
||||
case '-z':
|
||||
chunk.neighbors[dir] = getChunk(chunk.seed, chunkX, chunkY, chunkZ - 1);
|
||||
break;
|
||||
case '+z':
|
||||
chunk.neighbors[dir] = getChunk(chunk.seed, chunkX, chunkY, chunkZ + 1);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return chunk.neighbors[dir];
|
||||
}
|
||||
|
||||
const neighborIndices = {
|
||||
'-x': (x, y, z) => z * cs * cs + y * cs + (cs - 1),
|
||||
'+x': (x, y, z) => z * cs * cs + y * cs + 0,
|
||||
'-y': (x, y, z) => z * cs * cs + (cs - 1) * cs + x,
|
||||
'+y': (x, y, z) => z * cs * cs + 0 * cs + x,
|
||||
'-z': (x, y, z) => (cs - 1) * cs * cs + y * cs + x,
|
||||
'+z': (x, y, z) => 0 * cs * cs + y * cs + x,
|
||||
};
|
||||
|
||||
function neighborBlock(dir: direction, x, y, z) {
|
||||
const neighbor = neighborChunk(dir);
|
||||
let block;
|
||||
if (neighbor === undefined) {
|
||||
block = BlockType.AIR;
|
||||
} else {
|
||||
block = neighbor.blocks[neighborIndices[dir](x, y, z)];
|
||||
}
|
||||
return { dir, block };
|
||||
}
|
||||
|
||||
function* neighbors(x, y, z) {
|
||||
const idx = (
|
||||
z * cs * cs +
|
||||
y * cs +
|
||||
x
|
||||
);
|
||||
if (x > 0) {
|
||||
yield {
|
||||
block: chunk.blocks[idx - 1],
|
||||
dir: '-x',
|
||||
};
|
||||
} else {
|
||||
yield neighborBlock('-x', x, y, z);
|
||||
}
|
||||
if (x < cs - 1) {
|
||||
yield {
|
||||
block: chunk.blocks[idx + 1],
|
||||
dir: '+x',
|
||||
};
|
||||
} else {
|
||||
yield neighborBlock('+x', x, y, z);
|
||||
}
|
||||
if (y > 0) {
|
||||
yield {
|
||||
block: chunk.blocks[idx - cs],
|
||||
dir: '-y',
|
||||
};
|
||||
} else {
|
||||
yield neighborBlock('-y', x, y, z);
|
||||
}
|
||||
if (y < cs - 1) {
|
||||
yield {
|
||||
block: chunk.blocks[idx + cs],
|
||||
dir: '+y',
|
||||
};
|
||||
} else {
|
||||
yield neighborBlock('+y', x, y, z);
|
||||
}
|
||||
if (z > 0) {
|
||||
yield {
|
||||
block: chunk.blocks[idx - cs * cs],
|
||||
dir: '-z',
|
||||
};
|
||||
} else {
|
||||
yield neighborBlock('-z', x, y, z);
|
||||
}
|
||||
if (z < cs - 1) {
|
||||
yield {
|
||||
block: chunk.blocks[idx + cs * cs],
|
||||
dir: '+z',
|
||||
};
|
||||
} else {
|
||||
yield neighborBlock('+z', x, y, z);
|
||||
}
|
||||
}
|
||||
|
||||
for (let x = 0; x < cs; x++) {
|
||||
for (let y = 0; y < cs; y++) {
|
||||
for (let z = 0; z < cs; z++) {
|
||||
const idx = (
|
||||
z * cs * cs +
|
||||
y * cs +
|
||||
x
|
||||
);
|
||||
const chpos = chunk.position;
|
||||
const bkpos = [
|
||||
chpos[0] + x,
|
||||
chpos[1] + y,
|
||||
chpos[2] + z,
|
||||
];
|
||||
const bt = chunk.blocks[idx];
|
||||
if (bt === BlockType.AIR) {
|
||||
continue;
|
||||
}
|
||||
for (const { block, dir } of neighbors(x, y, z)) {
|
||||
if (block !== BlockType.AIR) {
|
||||
continue;
|
||||
}
|
||||
yield makeFace(dir, faceTexture(bt, dir), faceCenter(bkpos, dir));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function getBodyChunks(seed: number) {
|
||||
const chunks = [];
|
||||
const toCheck = [[0, 0, 0]];
|
||||
while (toCheck.length > 0) {
|
||||
const [chunkX, chunkY, chunkZ] = toCheck.pop();
|
||||
const thisChunk = getChunk(seed, chunkX, chunkY, chunkZ);
|
||||
if (thisChunk === undefined || chunks.includes(thisChunk)) {
|
||||
continue;
|
||||
}
|
||||
chunks.push(thisChunk);
|
||||
toCheck.push([chunkX - 1, chunkY, chunkZ]);
|
||||
toCheck.push([chunkX + 1, chunkY, chunkZ]);
|
||||
toCheck.push([chunkX, chunkY - 1, chunkZ]);
|
||||
toCheck.push([chunkX, chunkY + 1, chunkZ]);
|
||||
toCheck.push([chunkX, chunkY, chunkZ - 1]);
|
||||
toCheck.push([chunkX, chunkY, chunkZ + 1]);
|
||||
}
|
||||
return chunks;
|
||||
}
|
||||
|
||||
export function getBodyGeometry(chunks) {
|
||||
function lookup(seed: number, chunkX: number, chunkY: number, chunkZ: number) {
|
||||
for (const chunk of chunks) {
|
||||
const [cx, cy, cz] = chunk.layout;
|
||||
if (chunkX == cx && chunkY == cy && chunkZ == cz) {
|
||||
return chunk;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const faces = chunks
|
||||
.filter(chunk => !chunk.underground)
|
||||
.map(chunk => [...makeChunkFaces(chunk, memoize(lookup))]);
|
||||
|
||||
return faces.reduce((a, b) => a.concat(b));
|
||||
}
|
15
skycraft/client.ts
Normal file
15
skycraft/client.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
const backend = 'http://localhost:8080/api/';
|
||||
|
||||
/** Get all chunks for the given body */
|
||||
export async function getBody(seed: number) {
|
||||
const resp = await fetch(backend + `body/${seed}`);
|
||||
|
||||
return await resp.json();
|
||||
}
|
||||
|
||||
/** Get a complete solar system */
|
||||
export async function getSystem(seed: number) {
|
||||
const resp = await fetch(backend + `system/${seed}`);
|
||||
|
||||
return await resp.json();
|
||||
}
|
344
skycraft/draw.ts
Normal file
344
skycraft/draw.ts
Normal file
@@ -0,0 +1,344 @@
|
||||
import {makeBufferFromFaces } from '../geometry';
|
||||
import { loadTexture, makeProgram } from '../gl';
|
||||
import * as linalg from './linalg';
|
||||
import * as se3 from '../se3';
|
||||
import { makeOrbitObject } from './orbit';
|
||||
|
||||
const VSHADER = `
|
||||
attribute vec3 aPosition;
|
||||
attribute vec3 aNormal;
|
||||
attribute vec2 aTextureCoord;
|
||||
|
||||
uniform mat4 uProjection;
|
||||
uniform mat4 uModel;
|
||||
uniform mat4 uView;
|
||||
uniform vec3 uLightDirection;
|
||||
uniform float uAmbiantLight;
|
||||
uniform vec3 uGlowColor;
|
||||
|
||||
varying highp vec2 vTextureCoord;
|
||||
varying lowp vec3 vLighting;
|
||||
varying lowp vec3 vRay;
|
||||
varying lowp vec3 vLightDir;
|
||||
varying lowp vec3 vNormal;
|
||||
|
||||
highp mat3 transpose(in highp mat3 inmat) {
|
||||
highp vec3 x = inmat[0];
|
||||
highp vec3 y = inmat[1];
|
||||
highp vec3 z = inmat[2];
|
||||
|
||||
return mat3(
|
||||
vec3(x.x, y.x, z.x),
|
||||
vec3(x.y, y.y, z.y),
|
||||
vec3(x.z, y.z, z.z)
|
||||
);
|
||||
}
|
||||
|
||||
void main() {
|
||||
highp mat4 modelview = uView * uModel;
|
||||
|
||||
gl_Position = uProjection * modelview * vec4(aPosition, 1.0);
|
||||
|
||||
lowp vec3 normal = mat3(uModel) * aNormal;
|
||||
lowp float diffuseAmount = max(dot(-uLightDirection, normal), 0.0);
|
||||
lowp vec3 ambiant = uAmbiantLight * vec3(1.0, 1.0, 0.9);
|
||||
vLighting = ambiant + vec3(1.0, 1.0, 1.0) * diffuseAmount + uGlowColor;
|
||||
|
||||
vTextureCoord = aTextureCoord;
|
||||
|
||||
lowp vec3 camPos = -transpose(mat3(uView))*(uView * vec4(0.0, 0.0, 0.0, 1.0)).xyz;
|
||||
vRay = -normalize((uModel * vec4(aPosition, 1.0)).xyz - camPos);
|
||||
vLightDir = -uLightDirection;
|
||||
vNormal = normal;
|
||||
}
|
||||
`;
|
||||
|
||||
const FSHADER = `
|
||||
uniform sampler2D uSampler;
|
||||
|
||||
varying highp vec2 vTextureCoord;
|
||||
varying lowp vec3 vLighting;
|
||||
varying lowp vec3 vRay;
|
||||
varying lowp vec3 vLightDir;
|
||||
varying lowp vec3 vNormal;
|
||||
|
||||
void main() {
|
||||
highp vec4 color = texture2D(uSampler, vTextureCoord);
|
||||
if (color.a < 0.1) {
|
||||
discard;
|
||||
}
|
||||
lowp vec3 specularDir = 2.0 * dot(vLightDir, vNormal) * vNormal - vLightDir;
|
||||
lowp float specularAmount = smoothstep(0.92, 1.0, dot(vRay, specularDir));
|
||||
lowp vec3 specular = 0.8 * specularAmount * vec3(1.0, 1.0, 0.8);
|
||||
gl_FragColor = vec4(vLighting * color.rgb + specular, color.a);
|
||||
}
|
||||
`;
|
||||
|
||||
export async function initWorldGl(gl: WebGLRenderingContext) {
|
||||
const program = makeProgram(gl, VSHADER, FSHADER);
|
||||
const texture = await loadTexture(gl, 'texture.png');
|
||||
|
||||
// load those ahead of time
|
||||
const viewLoc = gl.getUniformLocation(program, 'uView');
|
||||
const modelLoc = gl.getUniformLocation(program, 'uModel');
|
||||
const projLoc = gl.getUniformLocation(program, 'uProjection');
|
||||
const samplerLoc = gl.getUniformLocation(program, 'uSampler');
|
||||
const lightDirectionLoc = gl.getUniformLocation(program, 'uLightDirection');
|
||||
const ambiantLoc = gl.getUniformLocation(program, 'uAmbiantLight');
|
||||
const glowColorLoc = gl.getUniformLocation(program, 'uGlowColor');
|
||||
|
||||
const positionLoc = gl.getAttribLocation(program, 'aPosition');
|
||||
const normalLoc = gl.getAttribLocation(program, 'aNormal');
|
||||
const textureLoc = gl.getAttribLocation(program, 'aTextureCoord');
|
||||
|
||||
const setupScene = (sceneParams) => {
|
||||
const {
|
||||
projectionMatrix,
|
||||
viewMatrix,
|
||||
ambiantLightAmount,
|
||||
} = sceneParams;
|
||||
|
||||
gl.useProgram(program);
|
||||
|
||||
gl.uniformMatrix4fv(projLoc, false, new Float32Array(projectionMatrix));
|
||||
gl.uniformMatrix4fv(viewLoc, false, new Float32Array(viewMatrix));
|
||||
gl.uniform1f(ambiantLoc, ambiantLightAmount);
|
||||
|
||||
// doing this here because it's the same for all world stuff
|
||||
gl.uniformMatrix4fv(modelLoc, false, new Float32Array(se3.identity()));
|
||||
gl.uniform1i(samplerLoc, 0);
|
||||
|
||||
gl.enableVertexAttribArray(positionLoc);
|
||||
gl.enableVertexAttribArray(normalLoc);
|
||||
gl.enableVertexAttribArray(textureLoc);
|
||||
gl.activeTexture(gl.TEXTURE0);
|
||||
gl.bindTexture(gl.TEXTURE_2D, texture);
|
||||
};
|
||||
|
||||
const drawObject = (objectParams) => {
|
||||
const {
|
||||
position,
|
||||
orientation,
|
||||
glBuffer,
|
||||
numVertices,
|
||||
lightDirection,
|
||||
glowColor,
|
||||
} = objectParams;
|
||||
|
||||
gl.uniformMatrix4fv(modelLoc, false, new Float32Array(se3.product(
|
||||
se3.translation(...position), orientation)));
|
||||
gl.uniform3fv(lightDirectionLoc, lightDirection);
|
||||
gl.uniform3fv(glowColorLoc, glowColor);
|
||||
|
||||
gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer);
|
||||
|
||||
gl.vertexAttribPointer(positionLoc, 3, gl.FLOAT, false, 20, 0);
|
||||
gl.vertexAttribPointer(normalLoc, 3, gl.BYTE, true, 20, 12);
|
||||
gl.vertexAttribPointer(textureLoc, 2, gl.UNSIGNED_SHORT, true, 20, 16);
|
||||
|
||||
gl.drawArrays(gl.TRIANGLES, 0, numVertices);
|
||||
};
|
||||
|
||||
return {
|
||||
setupScene,
|
||||
drawObject,
|
||||
};
|
||||
}
|
||||
|
||||
const ORBIT_VSHADER = `
|
||||
attribute vec3 aPosition;
|
||||
attribute vec2 aValue;
|
||||
|
||||
uniform mat4 uProjection;
|
||||
uniform mat4 uModel;
|
||||
uniform mat4 uView;
|
||||
|
||||
varying lowp vec2 vCoords;
|
||||
|
||||
void main() {
|
||||
highp mat4 modelview = uView * uModel;
|
||||
gl_Position = uProjection * modelview * vec4(aPosition, 1.0);
|
||||
|
||||
vCoords = aValue;
|
||||
}
|
||||
`;
|
||||
|
||||
const ORBIT_FSHADER = `
|
||||
varying lowp vec2 vCoords;
|
||||
|
||||
void main() {
|
||||
lowp float x = vCoords.x;
|
||||
lowp float y = vCoords.y;
|
||||
|
||||
lowp float f = sqrt(x * x + y * y);
|
||||
|
||||
if (f > 1.01) {
|
||||
discard;
|
||||
} else if (f < 0.99) {
|
||||
discard;
|
||||
}
|
||||
gl_FragColor = vec4(1, .5, 0, 0.5);
|
||||
}
|
||||
`;
|
||||
|
||||
export function getOrbitDrawContext(gl: WebGLRenderingContext) {
|
||||
const program = makeProgram(gl, ORBIT_VSHADER, ORBIT_FSHADER);
|
||||
|
||||
// load those ahead of time
|
||||
const viewLoc = gl.getUniformLocation(program, 'uView');
|
||||
const modelLoc = gl.getUniformLocation(program, 'uModel');
|
||||
const projLoc = gl.getUniformLocation(program, 'uProjection');
|
||||
|
||||
const positionLoc = gl.getAttribLocation(program, 'aPosition');
|
||||
const valueLoc = gl.getAttribLocation(program, 'aValue');
|
||||
|
||||
const setupScene = (sceneParams) => {
|
||||
const {
|
||||
projectionMatrix,
|
||||
viewMatrix,
|
||||
} = sceneParams;
|
||||
|
||||
gl.useProgram(program);
|
||||
|
||||
gl.uniformMatrix4fv(projLoc, false, new Float32Array(projectionMatrix));
|
||||
gl.uniformMatrix4fv(viewLoc, false, new Float32Array(viewMatrix));
|
||||
|
||||
// doing this here because it's the same for all world stuff
|
||||
gl.uniformMatrix4fv(modelLoc, false, new Float32Array(se3.identity()));
|
||||
|
||||
gl.enableVertexAttribArray(positionLoc);
|
||||
gl.enableVertexAttribArray(valueLoc);
|
||||
};
|
||||
|
||||
const drawObject = (objectParams) => {
|
||||
const {
|
||||
position,
|
||||
orientation,
|
||||
value,
|
||||
glBuffer,
|
||||
} = objectParams;
|
||||
|
||||
gl.uniformMatrix4fv(modelLoc, false, new Float32Array(se3.product(
|
||||
se3.translation(...position), orientation)));
|
||||
|
||||
gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer);
|
||||
|
||||
gl.vertexAttribPointer(positionLoc, 3, gl.FLOAT, false, 20, 0);
|
||||
gl.vertexAttribPointer(valueLoc, 2, gl.FLOAT, false, 20, 12);
|
||||
|
||||
gl.disable(gl.CULL_FACE);
|
||||
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
|
||||
gl.enable(gl.CULL_FACE);
|
||||
};
|
||||
|
||||
return {
|
||||
setupScene,
|
||||
drawObject,
|
||||
};
|
||||
}
|
||||
|
||||
function getObjects(context, body, parentPosition = undefined) {
|
||||
const objects = [];
|
||||
const {gl, glContext, player} = context;
|
||||
const {position, orientation, glowColor} = body;
|
||||
|
||||
if (body.glBuffer === undefined) {
|
||||
body.glBuffer = makeBufferFromFaces(gl, body.geometry);
|
||||
}
|
||||
|
||||
objects.push({
|
||||
geometry: body.glBuffer,
|
||||
orientation,
|
||||
position,
|
||||
glContext,
|
||||
glowColor,
|
||||
});
|
||||
if (parentPosition !== undefined) {
|
||||
const orbitObject = makeOrbitObject(gl, context.orbitGlContext, body.orbit, parentPosition);
|
||||
objects.push(orbitObject);
|
||||
} else {
|
||||
const shipOrientation = [
|
||||
se3.rotationOnly(player.tf),
|
||||
//se3.rotationOnly(context.camera.tf),
|
||||
se3.rotxyz(-Math.PI / 2, Math.PI / 2, Math.PI / 2),
|
||||
].reduce(se3.product);
|
||||
const shipPos = player.position;
|
||||
objects.push({
|
||||
geometry: makeBufferFromFaces(gl, context.spaceship),
|
||||
orientation: shipOrientation,
|
||||
position: shipPos,
|
||||
glContext,
|
||||
});
|
||||
}
|
||||
|
||||
if (body.children !== undefined) {
|
||||
for (const child of body.children) {
|
||||
objects.push(...getObjects(context, child, position));
|
||||
}
|
||||
}
|
||||
|
||||
return objects;
|
||||
}
|
||||
|
||||
function sunDirection(position: linalg.Vec3) {
|
||||
return linalg.scale(position, 1/linalg.norm(position));
|
||||
}
|
||||
|
||||
export function draw(context) {
|
||||
const {gl, camera, player, universe, orbit, orbitGlContext, orbitBody} = context;
|
||||
const {skyColor, ambiantLight, projMatrix} = context;
|
||||
const objects = getObjects(context, universe);
|
||||
if (orbit !== undefined && orbit.excentricity < 1) {
|
||||
objects.push(makeOrbitObject(gl, orbitGlContext, orbit, orbitBody.position));
|
||||
}
|
||||
|
||||
gl.clearColor(...skyColor, 1.0);
|
||||
gl.clearDepth(1.0);
|
||||
gl.enable(gl.DEPTH_TEST);
|
||||
gl.depthFunc(gl.LEQUAL);
|
||||
|
||||
gl.enable(gl.CULL_FACE);
|
||||
gl.cullFace(gl.BACK);
|
||||
gl.enable(gl.BLEND);
|
||||
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
|
||||
|
||||
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
|
||||
|
||||
let camtf;
|
||||
if (camera.overhead) {
|
||||
camtf = [
|
||||
se3.translation(0, 500, 0),
|
||||
se3.rotx(-Math.PI / 2),
|
||||
].reduce(se3.product);
|
||||
} else {
|
||||
camtf = [
|
||||
player.tf, // player position & orientation
|
||||
camera.tf, // camera orientation relative to player
|
||||
se3.translation(0, 1, 4), // step back from the player
|
||||
].reduce(se3.product)
|
||||
}
|
||||
const viewMatrix = se3.inverse(camtf);
|
||||
let lastGlContext;
|
||||
|
||||
for (const {position, orientation, geometry, glContext, glowColor} of objects) {
|
||||
if (glContext !== lastGlContext) {
|
||||
glContext.setupScene({
|
||||
projectionMatrix: projMatrix,
|
||||
viewMatrix,
|
||||
ambiantLightAmount: ambiantLight,
|
||||
});
|
||||
}
|
||||
|
||||
lastGlContext = glContext;
|
||||
const lightDirection = sunDirection(position);
|
||||
|
||||
glContext.drawObject({
|
||||
position,
|
||||
orientation,
|
||||
glBuffer: geometry.glBuffer,
|
||||
numVertices: geometry.numVertices,
|
||||
lightDirection,
|
||||
glowColor: glowColor || [0, 0, 0],
|
||||
});
|
||||
}
|
||||
}
|
@@ -1,710 +0,0 @@
|
||||
//import { initUiListeners, setupParamPanel, tick } from './game';
|
||||
//import { initWorldGl, makeWorld } from './world';
|
||||
import * as se3 from '../se3';
|
||||
import {loadTexture, makeProgram} from '../gl';
|
||||
import {makeFace, makeBufferFromFaces} from '../geometry';
|
||||
|
||||
const VSHADER = `
|
||||
attribute vec3 aPosition;
|
||||
attribute vec3 aNormal;
|
||||
attribute vec2 aTextureCoord;
|
||||
|
||||
uniform mat4 uProjection;
|
||||
uniform mat4 uModel;
|
||||
uniform mat4 uView;
|
||||
uniform vec3 uLightDirection;
|
||||
uniform float uAmbiantLight;
|
||||
|
||||
varying highp vec2 vTextureCoord;
|
||||
varying lowp vec3 vLighting;
|
||||
varying lowp float vDistance;
|
||||
|
||||
void main() {
|
||||
highp mat4 modelview = uView * uModel;
|
||||
|
||||
gl_Position = uProjection * modelview * vec4(aPosition, 1.0);
|
||||
|
||||
lowp vec3 normal = mat3(uModel) * aNormal;
|
||||
lowp float diffuseAmount = max(dot(-uLightDirection, normal), 0.0);
|
||||
lowp vec3 ambiant = uAmbiantLight * vec3(1.0, 1.0, 0.9);
|
||||
vLighting = ambiant + vec3(1.0, 1.0, 1.0) * diffuseAmount;
|
||||
|
||||
vTextureCoord = aTextureCoord;
|
||||
|
||||
vDistance = length(modelview * vec4(aPosition, 1.0));
|
||||
}
|
||||
`;
|
||||
|
||||
const FSHADER = `
|
||||
uniform sampler2D uSampler;
|
||||
uniform lowp vec3 uFogColor;
|
||||
|
||||
varying highp vec2 vTextureCoord;
|
||||
varying lowp vec3 vLighting;
|
||||
varying lowp float vDistance;
|
||||
|
||||
void main() {
|
||||
highp vec4 color = texture2D(uSampler, vTextureCoord);
|
||||
if (color.a < 0.1) {
|
||||
discard;
|
||||
}
|
||||
lowp float fogamount = 0.0; //smoothstep(80.0, 100.0, vDistance);
|
||||
gl_FragColor = mix(vec4(vLighting * color.rgb, color.a), vec4(uFogColor, 1.0), fogamount);
|
||||
}
|
||||
`;
|
||||
|
||||
const kEpoch = 0;
|
||||
|
||||
async function initWorldGl(gl) {
|
||||
const program = makeProgram(gl, VSHADER, FSHADER);
|
||||
const texture = await loadTexture(gl, 'texture.png');
|
||||
|
||||
// load those ahead of time
|
||||
const viewLoc = gl.getUniformLocation(program, 'uView');
|
||||
const modelLoc = gl.getUniformLocation(program, 'uModel');
|
||||
const projLoc = gl.getUniformLocation(program, 'uProjection');
|
||||
const samplerLoc = gl.getUniformLocation(program, 'uSampler');
|
||||
const fogColorLoc = gl.getUniformLocation(program, 'uFogColor');
|
||||
const lightDirectionLoc = gl.getUniformLocation(program, 'uLightDirection');
|
||||
const ambiantLoc = gl.getUniformLocation(program, 'uAmbiantLight');
|
||||
|
||||
const positionLoc = gl.getAttribLocation(program, 'aPosition');
|
||||
const normalLoc = gl.getAttribLocation(program, 'aNormal');
|
||||
const textureLoc = gl.getAttribLocation(program, 'aTextureCoord');
|
||||
|
||||
const setupScene = (sceneParams) => {
|
||||
const {
|
||||
projectionMatrix,
|
||||
viewMatrix,
|
||||
fogColor,
|
||||
lightDirection,
|
||||
ambiantLightAmount,
|
||||
} = sceneParams;
|
||||
|
||||
gl.useProgram(program);
|
||||
|
||||
gl.uniformMatrix4fv(projLoc, false, new Float32Array(projectionMatrix));
|
||||
gl.uniformMatrix4fv(viewLoc, false, new Float32Array(viewMatrix));
|
||||
gl.uniform3fv(fogColorLoc, fogColor);
|
||||
gl.uniform3fv(lightDirectionLoc, lightDirection);
|
||||
gl.uniform1f(ambiantLoc, ambiantLightAmount);
|
||||
|
||||
// doing this here because it's the same for all world stuff
|
||||
gl.uniformMatrix4fv(modelLoc, false, new Float32Array(se3.identity()));
|
||||
gl.uniform1i(samplerLoc, 0);
|
||||
|
||||
gl.enableVertexAttribArray(positionLoc);
|
||||
gl.enableVertexAttribArray(normalLoc);
|
||||
gl.enableVertexAttribArray(textureLoc);
|
||||
gl.activeTexture(gl.TEXTURE0);
|
||||
gl.bindTexture(gl.TEXTURE_2D, texture);
|
||||
};
|
||||
|
||||
const drawObject = (objectParams) => {
|
||||
const {
|
||||
position,
|
||||
orientation,
|
||||
glBuffer,
|
||||
numVertices,
|
||||
} = objectParams;
|
||||
|
||||
gl.uniformMatrix4fv(modelLoc, false, new Float32Array(se3.product(
|
||||
se3.translation(...position), orientation)));
|
||||
|
||||
gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer);
|
||||
|
||||
gl.vertexAttribPointer(positionLoc, 3, gl.FLOAT, false, 20, 0);
|
||||
gl.vertexAttribPointer(normalLoc, 3, gl.BYTE, true, 20, 12);
|
||||
gl.vertexAttribPointer(textureLoc, 2, gl.UNSIGNED_SHORT, true, 20, 16);
|
||||
|
||||
gl.drawArrays(gl.TRIANGLES, 0, numVertices);
|
||||
};
|
||||
|
||||
return {
|
||||
setupScene,
|
||||
drawObject,
|
||||
};
|
||||
}
|
||||
|
||||
const ORBIT_VSHADER = `
|
||||
attribute vec3 aPosition;
|
||||
attribute vec2 aValue;
|
||||
|
||||
uniform mat4 uProjection;
|
||||
uniform mat4 uModel;
|
||||
uniform mat4 uView;
|
||||
|
||||
varying lowp vec2 vCoords;
|
||||
|
||||
void main() {
|
||||
highp mat4 modelview = uView * uModel;
|
||||
gl_Position = uProjection * modelview * vec4(aPosition, 1.0);
|
||||
|
||||
vCoords = aValue;
|
||||
}
|
||||
`;
|
||||
|
||||
const ORBIT_FSHADER = `
|
||||
varying lowp vec2 vCoords;
|
||||
|
||||
void main() {
|
||||
lowp float x = vCoords.x;
|
||||
lowp float y = vCoords.y;
|
||||
|
||||
lowp float f = sqrt(x * x + y * y);
|
||||
|
||||
if (f > 1.00) {
|
||||
discard;
|
||||
} else if (f < 0.98) {
|
||||
discard;
|
||||
}
|
||||
gl_FragColor = vec4(1, .5, 0, 0.5);
|
||||
}
|
||||
`;
|
||||
|
||||
function getOrbitDrawContext(gl) {
|
||||
const program = makeProgram(gl, ORBIT_VSHADER, ORBIT_FSHADER);
|
||||
|
||||
// load those ahead of time
|
||||
const viewLoc = gl.getUniformLocation(program, 'uView');
|
||||
const modelLoc = gl.getUniformLocation(program, 'uModel');
|
||||
const projLoc = gl.getUniformLocation(program, 'uProjection');
|
||||
|
||||
const positionLoc = gl.getAttribLocation(program, 'aPosition');
|
||||
const valueLoc = gl.getAttribLocation(program, 'aValue');
|
||||
|
||||
const setupScene = (sceneParams) => {
|
||||
const {
|
||||
projectionMatrix,
|
||||
viewMatrix,
|
||||
} = sceneParams;
|
||||
|
||||
gl.useProgram(program);
|
||||
|
||||
gl.uniformMatrix4fv(projLoc, false, new Float32Array(projectionMatrix));
|
||||
gl.uniformMatrix4fv(viewLoc, false, new Float32Array(viewMatrix));
|
||||
|
||||
// doing this here because it's the same for all world stuff
|
||||
gl.uniformMatrix4fv(modelLoc, false, new Float32Array(se3.identity()));
|
||||
|
||||
gl.enableVertexAttribArray(positionLoc);
|
||||
gl.enableVertexAttribArray(valueLoc);
|
||||
};
|
||||
|
||||
const drawObject = (objectParams) => {
|
||||
const {
|
||||
position,
|
||||
orientation,
|
||||
value,
|
||||
glBuffer,
|
||||
} = objectParams;
|
||||
|
||||
gl.uniformMatrix4fv(modelLoc, false, new Float32Array(se3.product(
|
||||
se3.translation(...position), orientation)));
|
||||
|
||||
gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer);
|
||||
|
||||
gl.vertexAttribPointer(positionLoc, 3, gl.FLOAT, false, 20, 0);
|
||||
gl.vertexAttribPointer(valueLoc, 2, gl.FLOAT, false, 20, 12);
|
||||
|
||||
gl.disable(gl.CULL_FACE);
|
||||
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
|
||||
gl.enable(gl.CULL_FACE);
|
||||
};
|
||||
|
||||
return {
|
||||
setupScene,
|
||||
drawObject,
|
||||
};
|
||||
}
|
||||
|
||||
function initUiListeners(canvas, context) {
|
||||
const canvasClickHandler = () => {
|
||||
canvas.requestPointerLock();
|
||||
canvas.onclick = null;
|
||||
// const clickListener = e => {
|
||||
// switch(e.button) {
|
||||
// case 0: // left click
|
||||
// destroySelectedBlock(context);
|
||||
// break;
|
||||
// case 2: // right click
|
||||
// makeDirBlock(context);
|
||||
// break;
|
||||
// }
|
||||
// };
|
||||
const clickListener = e => {};
|
||||
const keyListener = e => {
|
||||
if (e.type === 'keydown') {
|
||||
if (e.repeat) return;
|
||||
context.keys.add(e.code);
|
||||
|
||||
switch (e.code) {
|
||||
case 'KeyF':
|
||||
// context.flying = !context.flying;
|
||||
return false;
|
||||
case 'Space':
|
||||
if (!context.flying) {
|
||||
if (context.jumpAmount > 0) {
|
||||
const amount = context.jumpForce;
|
||||
context.camera.velocity[1] = amount;
|
||||
context.jumpAmount -= 1;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
context.keys.delete(e.code);
|
||||
}
|
||||
};
|
||||
const moveListener = e => {
|
||||
context.camera.orientation[1] -= e.movementX / 500;
|
||||
context.camera.orientation[0] -= e.movementY / 500;
|
||||
|
||||
context.camera.orientation[0] = Math.min(Math.max(
|
||||
context.camera.orientation[0], -Math.PI / 2
|
||||
), Math.PI / 2);
|
||||
};
|
||||
const changeListener = () => {
|
||||
if (document.pointerLockElement === canvas) {
|
||||
return;
|
||||
}
|
||||
document.removeEventListener('pointerdown', clickListener);
|
||||
document.removeEventListener('pointerlockchange', changeListener);
|
||||
document.removeEventListener('pointermove', moveListener);
|
||||
document.removeEventListener('keydown', keyListener);
|
||||
document.removeEventListener('keyup', keyListener);
|
||||
canvas.onclick = canvasClickHandler;
|
||||
};
|
||||
document.addEventListener('pointerdown', clickListener);
|
||||
document.addEventListener('pointerlockchange', changeListener);
|
||||
document.addEventListener('pointermove', moveListener);
|
||||
document.addEventListener('keydown', keyListener);
|
||||
document.addEventListener('keyup', keyListener);
|
||||
};
|
||||
canvas.onclick = canvasClickHandler;
|
||||
document.addEventListener('keydown', e => {
|
||||
if (e.repeat) return;
|
||||
switch (e.code) {
|
||||
case 'F11':
|
||||
canvas.requestFullscreen();
|
||||
break;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function handleInput(context) {
|
||||
const move = (forward, right) => {
|
||||
const dir = [right, 0, -forward, 1.0];
|
||||
const ori = se3.roty(context.camera.orientation[1]);
|
||||
const tf = se3.apply(ori, dir);
|
||||
const maxSpeed = 8;
|
||||
const airMovement = 0.08;
|
||||
|
||||
if (context.flying) {
|
||||
context.camera.position[0] += tf[0] / 60;
|
||||
context.camera.position[2] += tf[2] / 60;
|
||||
}
|
||||
if (context.isOnGround) {
|
||||
context.camera.velocity[0] = tf[0];
|
||||
context.camera.velocity[2] = tf[2];
|
||||
} else {
|
||||
const vel = context.camera.velocity;
|
||||
|
||||
vel[0] += tf[0] * airMovement;
|
||||
vel[2] += tf[2] * airMovement;
|
||||
|
||||
const curVel = Math.sqrt(vel[0] * vel[0] + vel[2] * vel[2]);
|
||||
|
||||
if (curVel > maxSpeed) {
|
||||
vel[0] *= maxSpeed / curVel;
|
||||
vel[2] *= maxSpeed / curVel;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
context.keys.forEach(key => {
|
||||
switch (key) {
|
||||
case 'KeyW':
|
||||
move(8, 0.0);
|
||||
return;
|
||||
case 'KeyA':
|
||||
move(0.0, -8);
|
||||
return;
|
||||
case 'KeyS':
|
||||
move(-8, 0.0);
|
||||
return;
|
||||
case 'KeyD':
|
||||
move(0.0, 8);
|
||||
return;
|
||||
|
||||
case 'Space':
|
||||
if (context.flying) {
|
||||
context.camera.position[1] += 8 / 60;
|
||||
}
|
||||
return;
|
||||
|
||||
case 'ShiftLeft':
|
||||
context.camera.position[1] -= 8 / 60;
|
||||
return;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function updatePhysics(time, context) {
|
||||
}
|
||||
|
||||
function updateGeometry(context, timeout_ms = 10) {
|
||||
}
|
||||
|
||||
function normalizeAngle(theta) {
|
||||
const twopi = 2 * Math.PI;
|
||||
return theta - twopi * Math.floor((theta + twopi) / twopi);
|
||||
}
|
||||
|
||||
/** Let's be honest I should clean this up.
|
||||
*
|
||||
* This is the part that solves Kepler's equation using Newton's method.
|
||||
* For circular-ish orbits, one or two iterations are usually enough.
|
||||
* More excentric orbits can take more (6 or 7?).
|
||||
*
|
||||
* For near-parabolic orbits (and some others?) it often fails to converge...
|
||||
*/
|
||||
function getCartesianState(orbit, mu, time) {
|
||||
const {
|
||||
excentricity: e,
|
||||
semimajorAxis: a,
|
||||
inclination: i,
|
||||
ascendingNodeLongitude: Om,
|
||||
periapsisArgument: w,
|
||||
t0,
|
||||
} = orbit;
|
||||
let n = Math.sqrt(mu/(a**3));
|
||||
if (a < 0) {
|
||||
n = Math.sqrt(mu/-(a**3)); // mean motion
|
||||
}
|
||||
const M = n * (time - t0); // mean anomaly
|
||||
|
||||
// Newton's method
|
||||
var E2 = 0;
|
||||
var E = orbit.lastE || M;
|
||||
let iterations = 0;
|
||||
// a clever guess? https://link.springer.com/article/10.1023/A:1008200607490
|
||||
// doesn't work at all.
|
||||
|
||||
while (Math.abs(E - E2) > 1e-10) {
|
||||
if (e < 0.001) {
|
||||
break;
|
||||
}
|
||||
E = E2;
|
||||
if (e < 1) {
|
||||
E2 = E - (E - e * Math.sin(E) - M) / (1 - e * Math.cos(E));
|
||||
} else if (e > 1) {
|
||||
E2 = E - (-E + e * Math.sinh(E) - M) / (e * Math.cosh(E) - 1);
|
||||
} else {
|
||||
E2 = E - (E + E*E*E/3 - M) / (1 + E*E);
|
||||
}
|
||||
|
||||
iterations++;
|
||||
if (iterations > 100) {
|
||||
console.log('numerical instability');
|
||||
return {};
|
||||
}
|
||||
}
|
||||
orbit.lastE = E;
|
||||
let nu;
|
||||
if (e > 1) {
|
||||
nu = 2 * Math.atan(Math.sqrt((e+1) / (e-1)) * Math.tanh(E/2));
|
||||
} else {
|
||||
nu = 2 * Math.atan(Math.sqrt((1+e) / (1-e)) * Math.tan(E/2));
|
||||
}
|
||||
const p = a * (1 - e**2);
|
||||
const r = p / (1 + e * Math.cos(nu));// * ((a < 0) ? -1 : 1);
|
||||
const rd = e * Math.sqrt(mu / p) * Math.sin(nu);
|
||||
|
||||
if (orbit.tf === undefined) {
|
||||
orbit.tf = [se3.rotz(Om), se3.rotx(i), se3.rotz(w)].reduce(se3.product);
|
||||
}
|
||||
|
||||
const tf = se3.product(orbit.tf, se3.rotz(nu));
|
||||
const pos = se3.apply(tf, [r, 0, 0, 1]);
|
||||
const vel = se3.apply(tf, [rd, Math.sqrt(p * mu) / r, 0, 1]);
|
||||
|
||||
return {
|
||||
position: pos.slice(0, 3),
|
||||
velocity: vel.slice(0, 3),
|
||||
};
|
||||
}
|
||||
|
||||
function getOrientation(body, time) {
|
||||
return se3.rotxyz(
|
||||
body.spin[0] * time,
|
||||
body.spin[1] * time,
|
||||
body.spin[2] * time,
|
||||
);
|
||||
}
|
||||
|
||||
function makeOrbitObject(context, orbit, parentPosition) {
|
||||
const {gl} = context;
|
||||
const position = parentPosition;
|
||||
const glContext = context.orbitGlContext;
|
||||
const orientation = [
|
||||
se3.rotz(orbit.ascendingNodeLongitude),
|
||||
se3.roty(-orbit.inclination),
|
||||
se3.rotz(orbit.periapsisArgument),
|
||||
].reduce(se3.product);
|
||||
|
||||
const buffer = gl.createBuffer();
|
||||
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
|
||||
|
||||
const a = orbit.semimajorAxis;
|
||||
const b = a * Math.sqrt(1 - orbit.excentricity**2);
|
||||
|
||||
const x = - orbit.semimajorAxis * orbit.excentricity;
|
||||
|
||||
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
|
||||
x-a, -b, 0, -1, -1,
|
||||
x-a, +b, 0, -1, +1,
|
||||
x+a, -b, 0, +1, -1,
|
||||
x+a, +b, 0, +1, +1,
|
||||
]), gl.STATIC_DRAW);
|
||||
|
||||
const geometry = {
|
||||
glBuffer: buffer,
|
||||
numVertices: 4,
|
||||
delete: () => gl.deleteBuffer(buffer),
|
||||
};
|
||||
|
||||
return {
|
||||
geometry,
|
||||
orientation,
|
||||
position,
|
||||
glContext,
|
||||
};
|
||||
}
|
||||
|
||||
function getObjects(context, body, time, parentBody, parentPosition) {
|
||||
const kGravitationalConstant = 6.674e-11;
|
||||
const objects = [];
|
||||
const {gl, glContext} = context;
|
||||
let position = [0, 0, 0];
|
||||
if (parentBody !== undefined) {
|
||||
// const mu = kGravitationalConstant * parentBody.mass;
|
||||
const mu = 10;
|
||||
const coord = getCartesianPosition(body.orbit, mu, time);
|
||||
position = [
|
||||
parentPosition[0] + coord[0],
|
||||
parentPosition[1] + coord[1],
|
||||
parentPosition[2] + coord[2],
|
||||
];
|
||||
|
||||
objects.push(makeOrbitObject(context, body.orbit, parentPosition));
|
||||
}
|
||||
|
||||
objects.push({
|
||||
geometry: makeBufferFromFaces(gl, body.geometry),
|
||||
orientation: getOrientation(body, time),
|
||||
position,
|
||||
glContext,
|
||||
});
|
||||
|
||||
if (body.children !== undefined) {
|
||||
for (const child of body.children) {
|
||||
objects.push(...getObjects(context, child, time, body, position));
|
||||
}
|
||||
}
|
||||
|
||||
return objects;
|
||||
}
|
||||
|
||||
function draw(context, time) {
|
||||
const {gl, camera, universe} = context;
|
||||
const objects = getObjects(context, universe, time * 0.001);
|
||||
|
||||
gl.clearColor(...context.skyColor, 1.0);
|
||||
gl.clearDepth(1.0);
|
||||
gl.enable(gl.DEPTH_TEST);
|
||||
gl.depthFunc(gl.LEQUAL);
|
||||
|
||||
gl.enable(gl.CULL_FACE);
|
||||
gl.cullFace(gl.BACK);
|
||||
gl.enable(gl.BLEND);
|
||||
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
|
||||
|
||||
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
|
||||
|
||||
const camrot = camera.orientation;
|
||||
const campos = camera.position;
|
||||
const viewMatrix = se3.product(
|
||||
se3.rotxyz(-camrot[0], -camrot[1], -camrot[2]),
|
||||
se3.translation(-campos[0], -campos[1], -campos[2])
|
||||
);
|
||||
|
||||
let lastGlContext;
|
||||
|
||||
for (const {position, orientation, geometry, glContext} of objects) {
|
||||
if (glContext !== lastGlContext) {
|
||||
glContext.setupScene({
|
||||
projectionMatrix: context.projMatrix,
|
||||
viewMatrix,
|
||||
fogColor: context.skyColor,
|
||||
lightDirection: context.lightDirection,
|
||||
ambiantLightAmount: context.ambiantLight,
|
||||
});
|
||||
}
|
||||
|
||||
lastGlContext = glContext;
|
||||
|
||||
glContext.drawObject({
|
||||
position,
|
||||
orientation,
|
||||
glBuffer: geometry.glBuffer,
|
||||
numVertices: geometry.numVertices,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function tick(time, context) {
|
||||
handleInput(context);
|
||||
updatePhysics(time, context);
|
||||
|
||||
const campos = context.camera.position;
|
||||
|
||||
// world generation / geometry update
|
||||
{
|
||||
// frame time is typically 16.7ms, so this may lag a bit
|
||||
let timeLeft = 10;
|
||||
const start = performance.now();
|
||||
updateGeometry(context, timeLeft);
|
||||
}
|
||||
|
||||
draw(context, time);
|
||||
|
||||
const dt = (time - context.lastFrameTime) * 0.001;
|
||||
context.lastFrameTime = time;
|
||||
|
||||
document.querySelector('#fps').textContent = `${1.0 / dt} fps`;
|
||||
|
||||
requestAnimationFrame(time => tick(time, context));
|
||||
}
|
||||
|
||||
function makeCube(texture) {
|
||||
return [
|
||||
makeFace('-x', texture, [-0.5, 0, 0]),
|
||||
makeFace('+x', texture, [+0.5, 0, 0]),
|
||||
makeFace('-y', texture, [0, -0.5, 0]),
|
||||
makeFace('+y', texture, [0, +0.5, 0]),
|
||||
makeFace('-z', texture, [0, 0, -0.5]),
|
||||
makeFace('+z', texture, [0, 0, +0.5]),
|
||||
];
|
||||
}
|
||||
|
||||
function makeObjects(gl) {
|
||||
const texture = [0, 4];
|
||||
const faces = [
|
||||
makeFace('-x', texture, [-0.5, 0, 0]),
|
||||
makeFace('+x', texture, [+0.5, 0, 0]),
|
||||
makeFace('-y', texture, [0, -0.5, 0]),
|
||||
makeFace('+y', texture, [0, +0.5, 0]),
|
||||
makeFace('-z', texture, [0, 0, -0.5]),
|
||||
makeFace('+z', texture, [0, 0, +0.5]),
|
||||
];
|
||||
return [
|
||||
{
|
||||
geometry: makeBufferFromFaces(gl, faces),
|
||||
orientation: [0, 0, 0],
|
||||
position: [0, 0, 0],
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
function makeSolarSystem(gl) {
|
||||
return {
|
||||
mass: 1.0,
|
||||
spin: [0, 1.0, 0],
|
||||
geometry: makeCube([0, 4]),
|
||||
children: [
|
||||
{
|
||||
mass: 0.1,
|
||||
spin: [0.2, 0.0, 0.0],
|
||||
geometry: makeCube([0, 8]),
|
||||
orbit: {
|
||||
excentricity: 0,
|
||||
semimajorAxis: 3,
|
||||
inclination: 0,
|
||||
ascendingNodeLongitude: 0,
|
||||
periapsisArgument: 0,
|
||||
trueAnomaly: 0,
|
||||
},
|
||||
},
|
||||
{
|
||||
mass: 0.1,
|
||||
spin: [0.2, 0.0, 0.0],
|
||||
geometry: makeCube([0, 1]),
|
||||
orbit: {
|
||||
excentricity: 0.8,
|
||||
semimajorAxis: 5,
|
||||
inclination: 0,
|
||||
ascendingNodeLongitude: 0,
|
||||
periapsisArgument: 0,
|
||||
trueAnomaly: 0,
|
||||
},
|
||||
},
|
||||
{
|
||||
mass: 0.1,
|
||||
spin: [0.0, 0.0, 1.0],
|
||||
geometry: makeCube([9, 9]),
|
||||
orbit: {
|
||||
excentricity: 0.3,
|
||||
semimajorAxis: 5,
|
||||
inclination: 1.0,
|
||||
ascendingNodeLongitude: 0,
|
||||
periapsisArgument: 0,
|
||||
trueAnomaly: 0,
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const canvas = document.querySelector('#game');
|
||||
// adjust canvas aspect ratio to that of the screen
|
||||
canvas.height = screen.height / screen.width * canvas.width;
|
||||
const gl = canvas.getContext('webgl');
|
||||
|
||||
if (gl === null) {
|
||||
console.error('webgl not available')
|
||||
return;
|
||||
}
|
||||
|
||||
const context = {
|
||||
gl,
|
||||
projMatrix: se3.perspective(Math.PI / 3, canvas.clientWidth / canvas.clientHeight, 0.1, 100.0),
|
||||
camera: {
|
||||
position: [0.0, 0.0, 2.0],
|
||||
orientation: [0.0, 0.0, 0.0],
|
||||
velocity: [0, 0, 0],
|
||||
},
|
||||
keys: new Set(),
|
||||
lightDirection: [-0.2, -0.5, 0.4],
|
||||
skyColor: [0.10, 0.15, 0.2],
|
||||
ambiantLight: 0.7,
|
||||
blockSelectDistance: 8,
|
||||
flying: true,
|
||||
isOnGround: false,
|
||||
gravity: -17,
|
||||
jumpForce: 6.5,
|
||||
// objects: makeObjects(gl),
|
||||
universe: makeSolarSystem(gl),
|
||||
};
|
||||
|
||||
context.glContext = await initWorldGl(gl);
|
||||
context.orbitGlContext = getOrbitDrawContext(gl);
|
||||
initUiListeners(canvas, context);
|
||||
|
||||
// setupParamPanel(context);
|
||||
|
||||
requestAnimationFrame(time => tick(time, context));
|
||||
}
|
||||
|
||||
window.onload = main;
|
432
skycraft/index.ts
Normal file
432
skycraft/index.ts
Normal file
@@ -0,0 +1,432 @@
|
||||
import { makeFace } from '../geometry';
|
||||
|
||||
import * as client from './client';
|
||||
import * as linalg from './linalg';
|
||||
import { loadObjModel } from './obj';
|
||||
import * as se3 from '../se3';
|
||||
import { computeOrbit, findSoi, getCartesianState, updateBodyPhysics } from './orbit';
|
||||
import { getBodyGeometry } from './chunk';
|
||||
import { draw, getOrbitDrawContext, initWorldGl } from './draw';
|
||||
import * as quat from './quat';
|
||||
|
||||
const kEpoch = 0;
|
||||
|
||||
function closeToPlanet(context) {
|
||||
const body = findSoi(context.universe, context.player.position);
|
||||
const relativePos = linalg.diff(context.player.position, body.position);
|
||||
|
||||
return linalg.norm(relativePos) < 20;
|
||||
}
|
||||
|
||||
async function getSolarSystem(seed: number) {
|
||||
async function getGeometry(body) {
|
||||
const chunks = await client.getBody(body.seed);
|
||||
console.log(chunks);
|
||||
body.geometry = getBodyGeometry(chunks);
|
||||
console.log(body);
|
||||
for (const child of body.children) {
|
||||
await getGeometry(child);
|
||||
}
|
||||
}
|
||||
|
||||
const system = await client.getSystem(seed);
|
||||
await getGeometry(system);
|
||||
|
||||
return system;
|
||||
}
|
||||
|
||||
function _getSolarSystem(seed: number) {
|
||||
/// XXX: only returns 1 body for now
|
||||
|
||||
return {
|
||||
name: 'Tat',
|
||||
|
||||
mass: 1000.0,
|
||||
spin: [0, 0, 0.2],
|
||||
|
||||
geometry: getBodyGeometry(0),
|
||||
glowColor: [0.5, 0.5, 0.46],
|
||||
|
||||
children: [
|
||||
{
|
||||
name: 'Quicksilver',
|
||||
seed: 1336,
|
||||
|
||||
mass: 0.1,
|
||||
spin: [0.0, 0.0, 0.05],
|
||||
|
||||
geometry: makeCube([0, 4]),
|
||||
|
||||
orbit: {
|
||||
excentricity: 0.0,
|
||||
semimajorAxis: 200,
|
||||
inclination: 0.8,
|
||||
ascendingNodeLongitude: 0,
|
||||
periapsisArgument: 0,
|
||||
t0: 0,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Satourne',
|
||||
seed: 1338,
|
||||
|
||||
mass: 0.1,
|
||||
spin: [0.0, 0.5, 0.0],
|
||||
|
||||
geometry: makeCube([0, 5]),
|
||||
|
||||
orbit: {
|
||||
excentricity: 0.0,
|
||||
semimajorAxis: 900,
|
||||
inclination: 0.0,
|
||||
ascendingNodeLongitude: 0,
|
||||
periapsisArgument: 0,
|
||||
t0: 0,
|
||||
},
|
||||
|
||||
children: [
|
||||
{
|
||||
name: 'Kyoujin',
|
||||
seed: 13381,
|
||||
|
||||
mass: 0.01,
|
||||
spin: [0.0, 0.0, 0.05],
|
||||
|
||||
geometry: makeCube([0, 6]),
|
||||
|
||||
orbit: {
|
||||
excentricity: 0.0,
|
||||
semimajorAxis: 20,
|
||||
inclination: Math.PI / 2,
|
||||
ascendingNodeLongitude: 0,
|
||||
periapsisArgument: 0,
|
||||
t0: 0,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'Tataooine',
|
||||
seed: 1337,
|
||||
|
||||
mass: 50,
|
||||
spin: [0.0, 0.0, 0.05],
|
||||
|
||||
geometry: getBodyGeometry(1337),
|
||||
|
||||
orbit: {
|
||||
excentricity: 0.3,
|
||||
semimajorAxis: 500,
|
||||
inclination: 0.0,
|
||||
ascendingNodeLongitude: 0,
|
||||
periapsisArgument: 0,
|
||||
t0: 0,
|
||||
},
|
||||
|
||||
children: [
|
||||
{
|
||||
name: 'Mun',
|
||||
seed: 13371,
|
||||
|
||||
mass: 0.01,
|
||||
spin: [0.0, 0.0, 0.05],
|
||||
|
||||
geometry: makeCube([0, 7]),
|
||||
|
||||
orbit: {
|
||||
excentricity: 0.0,
|
||||
semimajorAxis: 50,
|
||||
inclination: Math.PI / 2,
|
||||
ascendingNodeLongitude: 0,
|
||||
periapsisArgument: 0,
|
||||
t0: 0,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
function initUiListeners(canvas: HTMLCanvasElement, context) {
|
||||
const canvasClickHandler = () => {
|
||||
canvas.requestPointerLock();
|
||||
canvas.onclick = null;
|
||||
// const clickListener = e => {
|
||||
// switch(e.button) {
|
||||
// case 0: // left click
|
||||
// destroySelectedBlock(context);
|
||||
// break;
|
||||
// case 2: // right click
|
||||
// makeDirBlock(context);
|
||||
// break;
|
||||
// }
|
||||
// };
|
||||
const clickListener = e => {};
|
||||
const keyListener = e => {
|
||||
if (e.type === 'keydown') {
|
||||
if (e.repeat) return;
|
||||
context.keys.add(e.code);
|
||||
|
||||
switch (e.code) {
|
||||
case 'KeyF':
|
||||
context.flying = !context.flying;
|
||||
context.player.velocity = [0, 0, 0];
|
||||
delete context.orbit;
|
||||
return false;
|
||||
case 'KeyL':
|
||||
if (closeToPlanet(context)) {
|
||||
context.landing = True;
|
||||
}
|
||||
return false;
|
||||
|
||||
case 'KeyO':
|
||||
context.camera.overhead ^= 1;
|
||||
return false;
|
||||
case 'Space':
|
||||
if (!context.flying) {
|
||||
if (context.jumpAmount > 0) {
|
||||
const amount = context.jumpForce;
|
||||
context.player.velocity[1] = amount;
|
||||
context.jumpAmount -= 1;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
context.keys.delete(e.code);
|
||||
}
|
||||
};
|
||||
const moveListener = e => {
|
||||
// context.camera.orientation[0] -= e.movementY / 500;
|
||||
// context.camera.orientation[1] -= e.movementX / 500;
|
||||
context.camera.tf =[
|
||||
context.camera.tf,
|
||||
se3.roty(-e.movementX / 500),
|
||||
se3.rotx(-e.movementY / 500),
|
||||
].reduce(se3.product);
|
||||
};
|
||||
const changeListener = () => {
|
||||
if (document.pointerLockElement === canvas) {
|
||||
return;
|
||||
}
|
||||
document.removeEventListener('pointerdown', clickListener);
|
||||
document.removeEventListener('pointerlockchange', changeListener);
|
||||
document.removeEventListener('pointermove', moveListener);
|
||||
document.removeEventListener('keydown', keyListener);
|
||||
document.removeEventListener('keyup', keyListener);
|
||||
canvas.onclick = canvasClickHandler;
|
||||
};
|
||||
document.addEventListener('pointerdown', clickListener);
|
||||
document.addEventListener('pointerlockchange', changeListener);
|
||||
document.addEventListener('pointermove', moveListener);
|
||||
document.addEventListener('keydown', keyListener);
|
||||
document.addEventListener('keyup', keyListener);
|
||||
};
|
||||
canvas.onclick = canvasClickHandler;
|
||||
document.addEventListener('keydown', e => {
|
||||
if (e.repeat) return;
|
||||
switch (e.code) {
|
||||
case 'F11':
|
||||
canvas.requestFullscreen();
|
||||
break;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function handleInput(context) {
|
||||
const move = (forward: number, right: number) => {
|
||||
if (context.keys.has('ShiftLeft')) {
|
||||
forward *= 10;
|
||||
right *= 10;
|
||||
}
|
||||
const tf = se3.product(
|
||||
se3.orientationOnly(context.player.tf),
|
||||
context.camera.tf,
|
||||
);
|
||||
const dir = [right, 0, -forward, 10];
|
||||
if (context.flying) {
|
||||
context.player.tf = [
|
||||
context.player.tf,
|
||||
se3.translation(...dir),
|
||||
].reduce(se3.product);
|
||||
} else {
|
||||
const vel = context.player.velocity;
|
||||
const dv = linalg.scale(se3.apply(tf, dir), 1/dir[3]);
|
||||
context.player.velocity = linalg.add(vel, dv);
|
||||
delete context.orbit;
|
||||
}
|
||||
};
|
||||
|
||||
context.keys.forEach(key => {
|
||||
switch (key) {
|
||||
case 'KeyW':
|
||||
move(0.5, 0.0);
|
||||
return;
|
||||
case 'KeyA':
|
||||
move(0.0, -0.5);
|
||||
return;
|
||||
case 'KeyS':
|
||||
move(-0.5, 0.0);
|
||||
return;
|
||||
case 'KeyD':
|
||||
move(0.0, 0.5);
|
||||
return;
|
||||
case 'KeyR':
|
||||
context.timeOffset += 1;
|
||||
return;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function slerp(current: linalg.Mat4, target: linalg.Mat4, maxVelocity: number) : linalg.Mat4 {
|
||||
const q0 = quat.mat2Quat(current);
|
||||
const q1 = quat.mat2Quat(target);
|
||||
|
||||
const dq = quat.diff(q1, q0);
|
||||
const maxt = maxVelocity / quat.norm(dq);
|
||||
|
||||
const q = quat.normalize(quat.add(q0, quat.scale(dq, Math.min(1, maxt))));
|
||||
return quat.quat2Mat(q);
|
||||
}
|
||||
|
||||
function updatePhysics(time: number, context) {
|
||||
const {player} = context;
|
||||
const dt = time - (context.lastTime || 0);
|
||||
context.lastTime = time;
|
||||
|
||||
player.position = se3.apply(player.tf, [0, 0, 0, 1]);
|
||||
|
||||
updateBodyPhysics(time, context.universe);
|
||||
|
||||
const dr = slerp(se3.identity(), context.camera.tf, 0.007);
|
||||
player.tf = se3.product(player.tf, dr);
|
||||
context.camera.tf = se3.product(context.camera.tf, se3.inverse(dr));
|
||||
|
||||
if (!context.flying) {
|
||||
if (context.orbit === undefined) {
|
||||
const newPos = linalg.add(player.position, linalg.scale(player.velocity, dt));
|
||||
const dx = linalg.diff(newPos, player.position);
|
||||
player.tf = se3.product(se3.translation(...dx), player.tf);
|
||||
|
||||
const body = findSoi(context.universe, context.player.position);
|
||||
context.orbit = computeOrbit(player, body, time);
|
||||
console.log(`orbiting ${body.name}, excentricity: ${context.orbit.excentricity}`);
|
||||
context.orbitBody = body;
|
||||
} else {
|
||||
const {position: orbitPos, velocity: orbitVel} = getCartesianState(
|
||||
context.orbit, context.orbitBody.mass, time);
|
||||
if (orbitPos === undefined) {
|
||||
const newPos = linalg.add(player.position, linalg.scale(player.velocity, dt));
|
||||
const dx = linalg.diff(newPos, player.position);
|
||||
player.tf = se3.product(se3.translation(...dx), player.tf);
|
||||
} else {
|
||||
const position = linalg.add(orbitPos, context.orbitBody.position);
|
||||
const velocity = linalg.add(orbitVel, context.orbitBody.velocity);
|
||||
player.velocity = velocity;
|
||||
const dx = linalg.diff(position, player.position);
|
||||
player.tf = se3.product(se3.translation(...dx), player.tf);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function updateGeometry(context, timeout_ms = 10) {
|
||||
}
|
||||
|
||||
function tick(time: number, context) {
|
||||
time = new Date().getTime();
|
||||
handleInput(context);
|
||||
const simTime = time * 0.001 + context.timeOffset;
|
||||
updatePhysics(simTime, context);
|
||||
|
||||
// world generation / geometry update
|
||||
{
|
||||
// frame time is typically 16.7ms, so this may lag a bit
|
||||
let timeLeft = 10;
|
||||
const start = performance.now();
|
||||
updateGeometry(context, timeLeft);
|
||||
}
|
||||
|
||||
draw(context);
|
||||
|
||||
const dt = (time - context.lastFrameTime) * 0.001;
|
||||
context.lastFrameTime = time;
|
||||
|
||||
document.querySelector('#fps')!.textContent = `${1.0 / dt} fps`;
|
||||
|
||||
requestAnimationFrame(time => tick(time, context));
|
||||
}
|
||||
|
||||
function makeCube(texture) {
|
||||
return [
|
||||
makeFace('-x', texture, [-0.5, 0, 0]),
|
||||
makeFace('+x', texture, [+0.5, 0, 0]),
|
||||
makeFace('-y', texture, [0, -0.5, 0]),
|
||||
makeFace('+y', texture, [0, +0.5, 0]),
|
||||
makeFace('-z', texture, [0, 0, -0.5]),
|
||||
makeFace('+z', texture, [0, 0, +0.5]),
|
||||
];
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const canvas = document.querySelector('#game')! as HTMLCanvasElement;
|
||||
// adjust canvas aspect ratio to that of the screen
|
||||
canvas.height = screen.height / screen.width * canvas.width;
|
||||
const gl = canvas.getContext('webgl');
|
||||
|
||||
if (gl === null) {
|
||||
console.error('webgl not available')
|
||||
return;
|
||||
}
|
||||
|
||||
// TODO
|
||||
// [ ] loading bar
|
||||
// [x] spaceship
|
||||
// [ ] landing
|
||||
// [ ] huge planets
|
||||
// [x] lighting
|
||||
// [x] better lighting
|
||||
// [ ] betterer lighting
|
||||
// [x] optimize geometry generation
|
||||
|
||||
const modelPromise = loadObjModel('spaceship.obj');
|
||||
|
||||
const context = {
|
||||
gl,
|
||||
projMatrix: se3.perspective(Math.PI / 3, canvas.clientWidth / canvas.clientHeight, 0.1, 10000.0),
|
||||
player: {
|
||||
tf: se3.translation(0.0, 0.0, 80.0),
|
||||
position: [0.0, 0.0, 80.0],
|
||||
velocity: [0, 0, 0],
|
||||
},
|
||||
camera: {
|
||||
orientation: [0, 0, 0],
|
||||
tf: se3.identity(),
|
||||
},
|
||||
keys: new Set(),
|
||||
lightDirection: [-0.2, -0.5, 0.4],
|
||||
skyColor: [0.10, 0.15, 0.2],
|
||||
ambiantLight: 0.4,
|
||||
blockSelectDistance: 8,
|
||||
flying: true,
|
||||
isOnGround: false,
|
||||
gravity: -17,
|
||||
jumpForce: 6.5,
|
||||
universe: await getSolarSystem(0),
|
||||
timeOffset: 0,
|
||||
};
|
||||
|
||||
context.glContext = await initWorldGl(gl);
|
||||
context.orbitGlContext = getOrbitDrawContext(gl);
|
||||
initUiListeners(canvas, context);
|
||||
|
||||
const starshipGeom = await modelPromise;
|
||||
console.log(`loaded ${starshipGeom.length} triangles`);
|
||||
|
||||
context.spaceship = starshipGeom;
|
||||
|
||||
requestAnimationFrame(time => tick(time, context));
|
||||
}
|
||||
|
||||
window.onload = main;
|
41
skycraft/linalg.ts
Normal file
41
skycraft/linalg.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
export type Vec3 = [number, number, number];
|
||||
export type Mat4 = number[];
|
||||
|
||||
export function cross(a: Vec3, b: Vec3) : Vec3 {
|
||||
return [
|
||||
a[1] * b[2] - a[2] * b[1],
|
||||
a[2] * b[0] - a[0] * b[2],
|
||||
a[0] * b[1] - a[1] * b[0],
|
||||
];
|
||||
}
|
||||
|
||||
export function diff(a: Vec3, b: Vec3) : Vec3 {
|
||||
return [
|
||||
a[0] - b[0],
|
||||
a[1] - b[1],
|
||||
a[2] - b[2],
|
||||
];
|
||||
}
|
||||
|
||||
export function add(a: Vec3, b: Vec3) : Vec3 {
|
||||
return [
|
||||
a[0] + b[0],
|
||||
a[1] + b[1],
|
||||
a[2] + b[2],
|
||||
];
|
||||
}
|
||||
|
||||
export function norm(a: Vec3) : number {
|
||||
return Math.sqrt(a[0] ** 2 + a[1] ** 2 + a[2] ** 2);
|
||||
}
|
||||
|
||||
export function dot(a: Vec3, b: Vec3) : number {
|
||||
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
|
||||
}
|
||||
export function scale(a: Vec3, s: number) : Vec3 {
|
||||
return [
|
||||
a[0] * s,
|
||||
a[1] * s,
|
||||
a[2] * s,
|
||||
];
|
||||
}
|
74
skycraft/obj.ts
Normal file
74
skycraft/obj.ts
Normal file
@@ -0,0 +1,74 @@
|
||||
function parseObjLine(line: string, obj: any) {
|
||||
line = line.trim();
|
||||
if (line[0] === '#' || line.length < 1) {
|
||||
return;
|
||||
}
|
||||
const elements = line.split(/\s+/);
|
||||
obj[elements[0]].push(elements.slice(1));
|
||||
}
|
||||
|
||||
function getFaces(obj: any) {
|
||||
return obj.f.map(f => {
|
||||
const face = {
|
||||
'vertices': [],
|
||||
'normals': [],
|
||||
'textures': [],
|
||||
};
|
||||
if (f.length === 4) { // add duplicate vertices to make triangles
|
||||
f.splice(3, 0, f[0]);
|
||||
f.splice(4, 0, f[2]);
|
||||
}
|
||||
f.forEach(v => {
|
||||
const [vidx, vtidx, vnidx] = v.split('/');
|
||||
face.vertices.push((obj.v[vidx - 1] || []).map(Number));
|
||||
face.normals.push((obj.vn[vnidx - 1] || []).map(Number));
|
||||
//face.textures.push((obj.vt[vtidx] || []).map(Number));
|
||||
face.textures.push([0, 0]);
|
||||
});
|
||||
return face;
|
||||
});
|
||||
}
|
||||
|
||||
export async function loadObjModel(url: string) {
|
||||
const stlDataStream = (await fetch(url)).body;
|
||||
if (stlDataStream === null) {
|
||||
return Promise.reject(new Error(`Could not fetch ${url}`));
|
||||
}
|
||||
const obj = new Proxy({}, {
|
||||
get: (target, name) =>{
|
||||
if (!(name in target)) {
|
||||
target[name] = [];
|
||||
}
|
||||
return target[name];
|
||||
},
|
||||
});
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
let partialLine = "";
|
||||
const reader = stlDataStream.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
|
||||
function pump() {
|
||||
reader.read().then(({ done, value }) => {
|
||||
if (done) {
|
||||
parseObjLine(partialLine, obj);
|
||||
return resolve(getFaces(obj));
|
||||
}
|
||||
|
||||
const textInput = decoder.decode(value);
|
||||
const lines = textInput.split('\n');
|
||||
|
||||
if (lines.length > 1) {
|
||||
parseObjLine(partialLine + lines[0], obj);
|
||||
partialLine = "";
|
||||
lines.slice(0, -1).forEach(line => {
|
||||
parseObjLine(line, obj);
|
||||
});
|
||||
}
|
||||
partialLine = partialLine + lines.at(-1);
|
||||
pump();
|
||||
});
|
||||
}
|
||||
pump();
|
||||
});
|
||||
}
|
495
skycraft/orbit.html
Normal file
495
skycraft/orbit.html
Normal file
@@ -0,0 +1,495 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Kepler orbit simulation</title>
|
||||
<style>
|
||||
#canvas {
|
||||
border: 1px solid black;
|
||||
margin-right: 10px;
|
||||
width: 500px;
|
||||
height: 500px;
|
||||
}
|
||||
#info {
|
||||
width: 300px;
|
||||
border: 1px solid black;
|
||||
padding: 6px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<table cellspacing="0" cellpadding="0">
|
||||
<tbody>
|
||||
<tr>
|
||||
<td>
|
||||
<canvas id="canvas"></canvas>
|
||||
</td>
|
||||
<td>
|
||||
Kepler orbit simulation<br><br>
|
||||
<div id="info"></div>
|
||||
<br><br>
|
||||
- Press the space bar to start/stop the simulation<br>
|
||||
- Drag the green circle/arrowhead to change the position/velocity<br>
|
||||
- Scroll to zoom in/out<br>
|
||||
- Press the arrow keys to adjust the velocity
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<script>
|
||||
function Point(x, y) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
}
|
||||
|
||||
function State(e, p, u, thp, th0, ccw, E, t) {
|
||||
this.e = e; // eccentricity
|
||||
this.p = p; // semi-latus rectum
|
||||
this.u = u; // G(m_1 + m_2)
|
||||
this.thp = thp; // initial true anomaly
|
||||
this.th0 = th0; //
|
||||
this.ccw = ccw; // counter-clockwise orbit
|
||||
this.t = t; // time since periapsis
|
||||
this.E = E; // eccentric anomaly (redundant with t)
|
||||
|
||||
// redundant info (for performance)
|
||||
this.r = new Point(0, 0); // position
|
||||
this.v = new Point(0, 0); // velocity
|
||||
this.T = 0; // period
|
||||
}
|
||||
|
||||
function norm(v) { return Math.sqrt(v.x * v.x + v.y * v.y); }
|
||||
|
||||
function add(v, w) { return new Point(v.x + w.x, v.y + w.y); }
|
||||
function minus(v, w) { return new Point(v.x - w.x, v.y - w.y); }
|
||||
function mult(v, c) { return new Point(v.x * c, v.y * c); }
|
||||
|
||||
function dot(v, w) { return v.x * w.x + v.y * w.y; }
|
||||
function vccw(v, w) { return v.x * w.y - v.y * w.x; }
|
||||
|
||||
function pow2(x) { return x*x; }
|
||||
function cosh(x) { return (Math.exp(x) + Math.exp(-x)) / 2; }
|
||||
function sinh(x) { return (Math.exp(x) - Math.exp(-x)) / 2; }
|
||||
function tanh(x) { return (Math.exp(x) - Math.exp(-x)) / (Math.exp(x) + Math.exp(-x)); }
|
||||
function atanh(x) { return 0.5 * Math.log((1 + x) / (1 - x)); }
|
||||
|
||||
var G = 6.67384e-11; // gravitational constant
|
||||
var m1 = 5.97219e24; // mass of the center object
|
||||
var m2 = 7.3477e22; // mass of the orbiting object
|
||||
var u = G * (m1 + m2);
|
||||
var st; // the state variable
|
||||
|
||||
(function(){
|
||||
// initial states
|
||||
var a = 384748000;
|
||||
var e=0.0549006, p=a*(1-e*e), thp=0, th0=0, ccw=true;
|
||||
var t=0;
|
||||
var E=0;
|
||||
st = new State(e, p, u, thp, th0, ccw, E, t);
|
||||
})();
|
||||
|
||||
|
||||
var canvas = document.getElementById("canvas");
|
||||
var ctx = canvas.getContext("2d");
|
||||
|
||||
var dpr = window.devicePixelRatio || 1;
|
||||
canvas.width = 500 * dpr;
|
||||
canvas.height = 500 * dpr;
|
||||
ctx.scale(dpr, dpr);
|
||||
|
||||
var vscale = 50000;
|
||||
var drawScale = 1/2000000;
|
||||
|
||||
function toTheta(E, e) {
|
||||
// eccentric anomaly -> true anomaly
|
||||
if (e < 1)
|
||||
return 2 * Math.atan( Math.sqrt((1+e) / (1-e)) * Math.tan(E/2) );
|
||||
if (e > 1)
|
||||
return 2 * Math.atan( Math.sqrt((1+e) / (e-1)) * tanh(E/2) );
|
||||
return 2 * Math.atan(E);
|
||||
}
|
||||
|
||||
function toE(theta, e) {
|
||||
// true anomaly -> eccentric anomaly
|
||||
if (e < 1)
|
||||
return Math.atan2( Math.sqrt(1-e*e) * Math.sin(theta) , e + Math.cos(theta));
|
||||
if (e > 1)
|
||||
return atanh( Math.sqrt(e*e-1) * Math.sin(theta) / ( e +Math.cos(theta)));
|
||||
return Math.tan(theta / 2);
|
||||
}
|
||||
|
||||
function findT(E, e, u, p, ccw) {
|
||||
// eccentric anomaly -> time since periapsis
|
||||
if (!ccw)
|
||||
E = -E;
|
||||
var a = p / (1 - e*e);
|
||||
if (e < 1)
|
||||
return a * Math.sqrt(a / u) * (E - e * Math.sin(E));
|
||||
if (e > 1)
|
||||
return -a * Math.sqrt(-a / u) * (e * sinh(E) - E);
|
||||
return Math.sqrt(p * p * p / (u * 8)) * (E + E*E*E/3);
|
||||
}
|
||||
|
||||
function findE(t, e, u, p, E0, ccw) {
|
||||
// time since periapsis -> eccentric anomaly
|
||||
var E = E0;
|
||||
var a = p / (1 - e*e);
|
||||
if (e < 1)
|
||||
M = Math.sqrt(u / (a*a*a)) * t;
|
||||
else if (e > 1)
|
||||
M = Math.sqrt(u / (-a*a*a)) * t;
|
||||
else
|
||||
M = Math.sqrt((u * 8) / (p * p * p)) * t;
|
||||
|
||||
if (!ccw)
|
||||
M = -M;
|
||||
|
||||
// Newton's method
|
||||
var E2;
|
||||
for (var i = 1; i < 20; ++i) {
|
||||
if (e < 1)
|
||||
E2 = E - (E - e * Math.sin(E) - M) / (1 - e * Math.cos(E));
|
||||
else if (e > 1)
|
||||
E2 = E - (-E + e * sinh(E) - M) / (e * cosh(E) - 1);
|
||||
else
|
||||
E2 = E - (E + E*E*E/3 - M) / (1 + E*E);
|
||||
if (Math.abs(E - E2) < 1e-10)
|
||||
break;
|
||||
E = E2;
|
||||
}
|
||||
return E;
|
||||
}
|
||||
|
||||
function calculateState(r, v, u) {
|
||||
// Find the state variables from initial position and velocity
|
||||
|
||||
var ccw = vccw(r, v);
|
||||
|
||||
// TODO: radial trajectory - this is a non-trivial special case.
|
||||
if (ccw == 0) {
|
||||
v.x += 0.1; // cheat
|
||||
ccw = vccw(r, v);
|
||||
}
|
||||
|
||||
var rs = norm(r);
|
||||
//r1 = new Point(r.x / rs, r.y / rs);
|
||||
//vr = dot(v, r1);
|
||||
//vtt = new Point(v.x - r1.x * vr, v.y - r1.y * vr);
|
||||
//r1 = new Point(r.x / rs, r.y / rs);
|
||||
var vr = dot(v, r) / rs;
|
||||
var k = dot(v, r) / dot(r, r);
|
||||
var vrr = new Point(r.x * k, r.y * k);
|
||||
var vtt = new Point(v.x - vrr.x, v.y - vrr.y);
|
||||
|
||||
var vt = norm(vtt);
|
||||
|
||||
var p = dot(r, r) * dot(vtt, vtt) / u;
|
||||
var v0 = u / Math.sqrt(dot(r, r) * dot(vtt, vtt));
|
||||
var v0inv = Math.sqrt(dot(r, r) * dot(vtt, vtt)) / u;
|
||||
//v0 = u / Math.sqrt();
|
||||
var e = Math.sqrt( pow2(vt*v0inv - 1) + pow2(vr*v0inv) );
|
||||
//v02 = u / p;
|
||||
//e = Math.sqrt( dot(vtt,vtt) - 2*vt*v0 + v02 + (dot(v, r) * dot(v, r) / dot(r, r) )) / v0;
|
||||
|
||||
//e2 = Math.sqrt(dot(vtt,vtt) - 2*vt*v0 + v02 + (dot(v, r) * dot(v, r) / dot(r, r) ));
|
||||
//cos = (vt/v0-1) / e;
|
||||
//sin = (vr / v0) / e;
|
||||
|
||||
//cos = (vt - v0) / e2;
|
||||
//sin = vr / e2;
|
||||
|
||||
var thp = Math.atan2(vr, vt - v0);
|
||||
if (ccw < 0)
|
||||
thp = -thp;
|
||||
|
||||
var th0 = Math.atan2(r.y, r.x);
|
||||
|
||||
return new State(e, p, u, thp, th0, ccw >= 0, st.E, st.t);
|
||||
}
|
||||
|
||||
function findRV(st) {
|
||||
// Find the position and velocity of the current state
|
||||
var e = st.e;
|
||||
var p = st.p;
|
||||
var u = st.u;
|
||||
var thp = st.thp;
|
||||
var th0 = st.th0;
|
||||
var E = st.E;
|
||||
var ccw = st.ccw;
|
||||
|
||||
var theta = toTheta(E, e);
|
||||
var rv = p / (1+e*Math.cos(theta));
|
||||
var r = new Point(rv*Math.cos((th0 - thp) + theta), rv*Math.sin((th0 - thp) + theta));
|
||||
|
||||
var v0 = Math.sqrt(u / p);
|
||||
var vt = (e * Math.cos(theta) + 1) * v0;
|
||||
var vr = e * Math.sin(theta) * v0;
|
||||
var rs = norm(r);
|
||||
var r1 = new Point(r.x / rs, r.y / rs);
|
||||
var t1 = new Point(-r1.y, r1.x);
|
||||
if (!ccw) {
|
||||
vt = -vt;
|
||||
vr = -vr;
|
||||
}
|
||||
|
||||
var v = new Point(vr*r1.x + vt*t1.x, vr*r1.y + vt*t1.y);
|
||||
|
||||
// cache
|
||||
st.r = r;
|
||||
st.v = v;
|
||||
|
||||
return {r:r, v:v};
|
||||
}
|
||||
|
||||
function recalculate(_st, dx, dy) {
|
||||
// Adjust the velocity by (dx, dy)
|
||||
var d = findRV(_st);
|
||||
var r = d.r;
|
||||
var v = d.v;
|
||||
v = new Point(v.x + dx, v.y + dy);
|
||||
|
||||
st = calculateState(r, v, _st.u);
|
||||
st.E = toE(st.thp, st.e);
|
||||
st.t = findT(st.E, st.e, st.u, st.p, st.ccw);
|
||||
}
|
||||
|
||||
|
||||
function redraw(st) {
|
||||
var e = st.e;
|
||||
var p = st.p;
|
||||
var u = st.u;
|
||||
var thp = st.thp;
|
||||
var th0 = st.th0;
|
||||
|
||||
ctx.clearRect(0, 0, 500, 500);
|
||||
|
||||
ctx.save();
|
||||
ctx.translate(250, 250);
|
||||
|
||||
// center
|
||||
ctx.fillStyle="#FF0000";
|
||||
ctx.beginPath();
|
||||
ctx.arc(0, 0, 6, 0, 2*Math.PI);
|
||||
ctx.fill();
|
||||
|
||||
// trace
|
||||
ctx.strokeStyle ="#FF0000";
|
||||
if (e == 0) { // circle
|
||||
ctx.beginPath();
|
||||
ctx.arc(0, 0, p*drawScale, 0, 2*Math.PI);
|
||||
ctx.stroke();
|
||||
} /*else if (e < 1) { // ellipse
|
||||
ctx.save();
|
||||
var a = p / (1 - e*e);
|
||||
ctx.rotate( th0 - thp );
|
||||
ctx.translate(-e * a, 0);
|
||||
ctx.scale(1, Math.sqrt(1 - e*e));
|
||||
ctx.beginPath();
|
||||
ctx.arc(0, 0, a, 0, 2*Math.PI);
|
||||
ctx.stroke();
|
||||
ctx.restore();
|
||||
} */ else {
|
||||
var th;
|
||||
var rv;
|
||||
ctx.beginPath();
|
||||
for (th=-Math.PI; th < Math.PI; th+=0.01) {
|
||||
rv = p / (1+e*Math.cos(th));
|
||||
if (rv <= 0)
|
||||
continue;
|
||||
ctx.lineTo( rv*Math.cos(th + (th0 - thp))*drawScale, rv*Math.sin(th + (th0 - thp))*drawScale );
|
||||
}
|
||||
ctx.stroke();
|
||||
}
|
||||
|
||||
|
||||
var d = findRV(st);
|
||||
var r = d.r;
|
||||
var v = d.v;
|
||||
|
||||
// the orbiting object
|
||||
ctx.fillStyle ="#008000";
|
||||
ctx.beginPath();
|
||||
ctx.arc(r.x * drawScale, r.y * drawScale, 5, 0, 2*Math.PI);
|
||||
ctx.fill();
|
||||
|
||||
// the velocity line
|
||||
ctx.strokeStyle ="#0000FF";
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(r.x * drawScale, r.y * drawScale);
|
||||
ctx.lineTo((r.x + v.x * vscale) * drawScale, (r.y + v.y * vscale) * drawScale);
|
||||
ctx.stroke();
|
||||
|
||||
// arrowhead
|
||||
ctx.save();
|
||||
ctx.translate((r.x + v.x * vscale) * drawScale, (r.y + v.y * vscale) * drawScale);
|
||||
ctx.rotate(-Math.atan2(v.x, v.y));
|
||||
ctx.strokeStyle ="#0000FF";
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(-8, -10);
|
||||
ctx.lineTo(0, 0);
|
||||
ctx.lineTo(8, -10);
|
||||
ctx.stroke();
|
||||
ctx.restore();
|
||||
|
||||
ctx.restore();
|
||||
|
||||
updateInfo();
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
var moving = false;
|
||||
var timer;
|
||||
|
||||
redraw(st);
|
||||
|
||||
|
||||
var state = 0;
|
||||
var r0, v0;
|
||||
var saveMoving;
|
||||
|
||||
canvas.onmousemove = function(event) {
|
||||
var x = event.offsetX == undefined ? event.layerX : event.offsetX;
|
||||
var y = event.offsetY == undefined ? event.layerY : event.offsetY;
|
||||
var p = mult(new Point(x - 250, y - 250), 1/drawScale);
|
||||
var d = findRV(st);
|
||||
var r = d.r;
|
||||
var v = d.v;
|
||||
|
||||
if (state <= 2) {
|
||||
if (norm(minus(p, r)) < 14 / drawScale) {
|
||||
canvas.style.cursor = 'pointer';
|
||||
state = 1;
|
||||
} else if (norm( minus( add(r, mult(v, vscale)) , p ) ) < 14 / drawScale) {
|
||||
canvas.style.cursor = 'pointer';
|
||||
state = 2;
|
||||
} else {
|
||||
canvas.style.cursor = 'default';
|
||||
state = 0;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
if (state == 3) {
|
||||
if (p.x == 0 && p.y == 0)
|
||||
p.x = 0.1;
|
||||
r = p;
|
||||
v = v0;
|
||||
} else if (state == 4) {
|
||||
r = r0;
|
||||
v = mult(minus(p, r), 1/vscale);
|
||||
}
|
||||
|
||||
st = calculateState(r, v, st.u);
|
||||
var thp = st.thp;
|
||||
var th0 = st.th0;
|
||||
|
||||
st.E = toE(thp, st.e); // why only THP ?
|
||||
st.t = findT(st.E, st.e, st.u, st.p, st.ccw);
|
||||
redraw(st);
|
||||
}
|
||||
|
||||
canvas.onmousedown = function(event) {
|
||||
var d = findRV(st);
|
||||
r0 = d.r;
|
||||
v0 = d.v;
|
||||
if (state == 1 || state == 2) {
|
||||
state += 2;
|
||||
saveMoving = moving;
|
||||
stopMoving();
|
||||
}
|
||||
|
||||
canvas.onmousemove(event);
|
||||
event.preventDefault();
|
||||
}
|
||||
|
||||
var mousewheel = function (e) {
|
||||
var delta = e.wheelDelta ? e.wheelDelta : e.detail;
|
||||
console.log(delta);
|
||||
drawScale = drawScale + delta / 10000000000;
|
||||
drawScale = Math.max(drawScale, 0.000000001);
|
||||
redraw(st);
|
||||
e.preventDefault();
|
||||
};
|
||||
|
||||
canvas.addEventListener(canvas.hasOwnProperty("onmousewheel") ?
|
||||
"mousewheel" : "DOMMouseScroll", mousewheel);
|
||||
|
||||
document.onmouseup = function(event) {
|
||||
state = 0;
|
||||
if (saveMoving)
|
||||
startMoving();
|
||||
canvas.style.cursor = 'default';
|
||||
}
|
||||
|
||||
function updateInfo() {
|
||||
function curveType(e) {
|
||||
if (e == 0) return "circle";
|
||||
if (e < 1) return "ellipse";
|
||||
if (e == 1) return "parabola";
|
||||
return "hyperbola";
|
||||
}
|
||||
|
||||
var a = st.p / (1 - st.e*st.e);
|
||||
var T = 2 * Math.PI * a * Math.sqrt(a / st.u);
|
||||
|
||||
var div = document.getElementById("info");
|
||||
s = "";
|
||||
s += "curve = " + curveType(st.e) + "<br>";
|
||||
s += "eccentricity = " + st.e.toFixed(2) + "<br>";
|
||||
s += "altitude = " + Math.round(norm(st.r)/1000) + " km<br>";
|
||||
s += "periapsis = " + Math.round((1-st.e)*a/1000) + " km<br>";
|
||||
// is the apoapsis for parabola/hyperbola really infinity?
|
||||
s += "apoapsis = " + ((st.e < 1) ? (Math.round((1+st.e)*a/1000) + " km") : "∞") + "<br>";
|
||||
s += "velocity = " + Math.round(norm(st.v)/1000 * 10)/10 + " km/s<br>";
|
||||
s += "eccentric anomaly = " + Math.round((((st.E / Math.PI) % 2) + 2) % 2 * 10) / 10 + "π<br>";
|
||||
s += "period = " + ((st.e < 1) ? (Math.round(T / (24*60*60) * 10) / 10 + " days") : "∞") + "<br>";
|
||||
div.innerHTML = s;
|
||||
}
|
||||
|
||||
function animate() {
|
||||
st.t += 24*60*60*0.1;
|
||||
st.E = findE(st.t, st.e, st.u, st.p, st.E, st.ccw);
|
||||
redraw(st);
|
||||
}
|
||||
|
||||
function stopMoving() {
|
||||
clearInterval(timer);
|
||||
moving = false;
|
||||
}
|
||||
|
||||
function startMoving() {
|
||||
if (moving)
|
||||
return;
|
||||
timer = setInterval(animate, 30);
|
||||
moving = true;
|
||||
}
|
||||
|
||||
document.onkeydown = function(event) {
|
||||
var dx=0, dy=0;
|
||||
if (event.keyCode == 38) { // up
|
||||
dy = -1;
|
||||
} else if (event.keyCode == 40) { // down
|
||||
dy = 1;
|
||||
} else if (event.keyCode == 37) { // left
|
||||
dx = -1;
|
||||
} else if (event.keyCode == 39) { // right
|
||||
dx = 1;
|
||||
} else if (event.keyCode == 32) {
|
||||
if (moving) {
|
||||
stopMoving();
|
||||
} else {
|
||||
startMoving();
|
||||
}
|
||||
}
|
||||
if (dx != 0 || dy != 0) {
|
||||
recalculate(st, dx * 10, dy * 10);
|
||||
redraw(st);
|
||||
}
|
||||
}
|
||||
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
284
skycraft/orbit.ts
Normal file
284
skycraft/orbit.ts
Normal file
@@ -0,0 +1,284 @@
|
||||
import * as se3 from '../se3';
|
||||
import * as linalg from './linalg';
|
||||
import {Vec3} from './linalg';
|
||||
|
||||
interface Orbit {
|
||||
excentricity: number,
|
||||
semimajor_axis: number,
|
||||
inclination: number,
|
||||
ascending_node_longitude: number,
|
||||
periapsis_argument: number,
|
||||
t0: number,
|
||||
|
||||
lastE: number | undefined,
|
||||
tf: number[] | undefined,
|
||||
}
|
||||
|
||||
interface Body {
|
||||
position: Vec3,
|
||||
velocity: Vec3,
|
||||
orientation: Vec3,
|
||||
children: Body[],
|
||||
mass: number,
|
||||
orbit: Orbit,
|
||||
spin: Vec3,
|
||||
name: string,
|
||||
}
|
||||
|
||||
export function updateBodyPhysics(time: number, body: Body, parentBody : Body | undefined = undefined) {
|
||||
if (parentBody !== undefined) {
|
||||
const mu = parentBody.mass;
|
||||
const {position, velocity} = getCartesianState(body.orbit, mu, time);
|
||||
body.position = [
|
||||
parentBody.position[0] + position[0],
|
||||
parentBody.position[1] + position[1],
|
||||
parentBody.position[2] + position[2],
|
||||
];
|
||||
body.velocity = [
|
||||
parentBody.velocity[0] + velocity[0],
|
||||
parentBody.velocity[1] + velocity[1],
|
||||
parentBody.velocity[2] + velocity[2],
|
||||
];
|
||||
} else {
|
||||
body.position = [0, 0, 0];
|
||||
body.velocity = [0, 0, 0];
|
||||
}
|
||||
body.orientation = getOrientation(body, time);
|
||||
|
||||
if (body.children !== undefined) {
|
||||
for (const child of body.children) {
|
||||
updateBodyPhysics(time, child, body);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function findSoi(rootBody: Body, position: number[]) : Body {
|
||||
const bodies = [rootBody];
|
||||
let body : Body;
|
||||
while (bodies.length > 0) {
|
||||
body = bodies.shift()!;
|
||||
|
||||
if (body.children === undefined) {
|
||||
return body;
|
||||
}
|
||||
|
||||
for (const child of body.children) {
|
||||
const soi = child.orbit.semimajor_axis * Math.pow(child.mass / body.mass, 2/5);
|
||||
const pos = position;
|
||||
const bod = child.position;
|
||||
const dr = [pos[0] - bod[0], pos[1] - bod[1], pos[2] - bod[2]];
|
||||
if (dr[0]**2 + dr[1]**2 + dr[2]**2 < soi**2) {
|
||||
bodies.push(child);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return body!;
|
||||
}
|
||||
|
||||
export function computeOrbit(player: any, body: Body, time: number) {
|
||||
const {cross, diff, norm, dot, scale} = linalg;
|
||||
const rvec = diff(player.position, body.position);
|
||||
const r = norm(rvec);
|
||||
|
||||
if (norm(player.velocity) < 1e-6) {
|
||||
// cheating
|
||||
console.log('cheating');
|
||||
player.velocity = scale(cross([1, 1, 1], rvec), 0.01/(r**2));
|
||||
}
|
||||
const vvec = diff(player.velocity, body.velocity);
|
||||
const v = norm(vvec);
|
||||
const Hvec = cross(rvec, vvec);
|
||||
const H = norm(Hvec);
|
||||
|
||||
const mu = body.mass;
|
||||
const p = H**2 / mu;
|
||||
const resinnu = Math.sqrt(p/mu) * dot(vvec, rvec)
|
||||
const recosnu = p - r;
|
||||
|
||||
const e = Math.sqrt(resinnu**2 + recosnu**2) / r;
|
||||
|
||||
// should also work for hyperbolic orbits
|
||||
const a = p/(1-e**2);
|
||||
|
||||
const x = scale(rvec, 1/r);
|
||||
const yy = cross(Hvec, rvec);
|
||||
const y = scale(yy, 1/norm(yy));
|
||||
const z = scale(Hvec, 1/H);
|
||||
|
||||
// Om i and w can be skipped when we just give tf...
|
||||
let Om = Math.atan2(Hvec[0], -Hvec[1]);
|
||||
if (Hvec[0] === 0 && Hvec[1] === 0) {
|
||||
Om = 0;
|
||||
}
|
||||
|
||||
let i = Math.atan2(Math.sqrt(Hvec[0]**2 + Hvec[1]**2), Hvec[2]);
|
||||
if (i * Math.sign((Hvec[0] || 1) * Math.sin(Om)) < 0) {
|
||||
i *= -1;
|
||||
}
|
||||
|
||||
const nu = Math.atan2(resinnu, recosnu);
|
||||
|
||||
let w = Math.atan2(rvec[2] / r / Math.sin(i), y[2] / Math.sin(i)) || 0 - nu;
|
||||
|
||||
let t0;
|
||||
let E;
|
||||
|
||||
if (a < 0) {
|
||||
E = 2 * Math.atanh(Math.sqrt((e-1)/(e+1)) * Math.tan(nu/2));
|
||||
const n = Math.sqrt(-mu / (a**3));
|
||||
t0 = time - (e*Math.sinh(E) - E) / n;
|
||||
|
||||
t0 %= 2 * Math.PI / n;
|
||||
} else {
|
||||
E = 2 * Math.atan(Math.sqrt((1-e)/(1+e)) * Math.tan(nu/2));
|
||||
const n = Math.sqrt(mu / (a**3));
|
||||
t0 = time - (1/n)*(E - e*Math.sin(E));
|
||||
|
||||
t0 %= 2 * Math.PI / n;
|
||||
}
|
||||
|
||||
// column-major... see se3.js
|
||||
const tf = se3.product([
|
||||
x[0], x[1], x[2], 0,
|
||||
y[0], y[1], y[2], 0,
|
||||
z[0], z[1], z[2], 0,
|
||||
0, 0, 0, 1,
|
||||
], se3.rotz(-nu));
|
||||
|
||||
const orbit = {
|
||||
excentricity: e,
|
||||
semimajor_axis: a,
|
||||
inclination: i,
|
||||
ascending_node_longitude: Om,
|
||||
periapsis_argument: w,
|
||||
t0,
|
||||
tf,
|
||||
lastE: E,
|
||||
};
|
||||
|
||||
return orbit;
|
||||
}
|
||||
|
||||
/** Let's be honest I should clean this up.
|
||||
*
|
||||
* This is the part that solves Kepler's equation using Newton's method.
|
||||
* For circular-ish orbits, one or two iterations are usually enough.
|
||||
* More excentric orbits can take more (6 or 7?).
|
||||
*
|
||||
* For near-parabolic orbits (and some others?) it often fails to converge...
|
||||
*/
|
||||
export function getCartesianState(orbit: Orbit, mu: number, time: number) {
|
||||
const {
|
||||
excentricity: e,
|
||||
semimajor_axis: a,
|
||||
inclination: i,
|
||||
ascending_node_longitude: Om,
|
||||
periapsis_argument: w,
|
||||
t0,
|
||||
} = orbit;
|
||||
let n = Math.sqrt(mu/(a**3));
|
||||
if (a < 0) {
|
||||
n = Math.sqrt(mu/-(a**3)); // mean motion
|
||||
}
|
||||
const M = (n * (time - t0)) % (2 * Math.PI); // mean anomaly
|
||||
|
||||
// Newton's method
|
||||
var E2 = 0;
|
||||
var E = M;
|
||||
let iterations = 0;
|
||||
// a clever guess? https://link.springer.com/article/10.1023/A:1008200607490
|
||||
// doesn't work at all.
|
||||
|
||||
while (Math.abs(E - E2) > 1e-10) {
|
||||
if (e < 0.001) {
|
||||
break;
|
||||
}
|
||||
E = E2;
|
||||
if (e < 1) {
|
||||
E2 = E - (E - e * Math.sin(E) - M) / (1 - e * Math.cos(E));
|
||||
} else if (e > 1) {
|
||||
E2 = E - (-E + e * Math.sinh(E) - M) / (e * Math.cosh(E) - 1);
|
||||
} else {
|
||||
E2 = E - (E + E*E*E/3 - M) / (1 + E*E);
|
||||
}
|
||||
|
||||
iterations++;
|
||||
if (iterations > 100) {
|
||||
console.log('numerical instability');
|
||||
return {};
|
||||
}
|
||||
}
|
||||
orbit.lastE = E;
|
||||
let nu;
|
||||
if (e > 1) {
|
||||
nu = 2 * Math.atan(Math.sqrt((e+1) / (e-1)) * Math.tanh(E/2));
|
||||
} else {
|
||||
nu = 2 * Math.atan(Math.sqrt((1+e) / (1-e)) * Math.tan(E/2));
|
||||
}
|
||||
const p = a * (1 - e**2);
|
||||
const r = p / (1 + e * Math.cos(nu));// * ((a < 0) ? -1 : 1);
|
||||
const rd = e * Math.sqrt(mu / p) * Math.sin(nu);
|
||||
|
||||
if (orbit.tf === undefined) {
|
||||
// FIXME: this is actually borken. :/
|
||||
orbit.tf = [se3.rotz(Om), se3.rotx(i), se3.rotz(w)].reduce(se3.product);
|
||||
}
|
||||
|
||||
const tf = se3.product(orbit.tf, se3.rotz(nu));
|
||||
const pos = se3.apply(tf, [r, 0, 0, 1]);
|
||||
const vel = se3.apply(tf, [rd, Math.sqrt(p * mu) / r, 0, 1]);
|
||||
|
||||
return {
|
||||
position: pos.slice(0, 3),
|
||||
velocity: vel.slice(0, 3),
|
||||
};
|
||||
}
|
||||
|
||||
function getOrientation(body: Body, time: number) {
|
||||
return se3.rotxyz(
|
||||
body.spin[0] * time,
|
||||
body.spin[1] * time,
|
||||
body.spin[2] * time,
|
||||
);
|
||||
}
|
||||
|
||||
export function makeOrbitObject(gl: WebGLRenderingContext, glContext: any, orbit: Orbit, parentPosition: number[]) {
|
||||
const position = parentPosition;
|
||||
|
||||
// FIXME: currently borken.
|
||||
// const orientation = [
|
||||
// se3.rotz(orbit.ascendingNodeLongitude),
|
||||
// se3.rotx(orbit.inclination),
|
||||
// se3.rotz(orbit.periapsisArgument),
|
||||
// ].reduce(se3.product);
|
||||
const orientation = orbit.tf;
|
||||
|
||||
const buffer = gl.createBuffer();
|
||||
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
|
||||
|
||||
const a = orbit.semimajor_axis;
|
||||
const b = a * Math.sqrt(1 - orbit.excentricity**2);
|
||||
|
||||
const x = - orbit.semimajor_axis * orbit.excentricity;
|
||||
|
||||
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
|
||||
x-a, -b, 0, -1, -1,
|
||||
x-a, +b, 0, -1, +1,
|
||||
x+a, -b, 0, +1, -1,
|
||||
x+a, +b, 0, +1, +1,
|
||||
]), gl.STATIC_DRAW);
|
||||
|
||||
const geometry = {
|
||||
glBuffer: buffer,
|
||||
numVertices: 4,
|
||||
delete: () => gl.deleteBuffer(buffer),
|
||||
};
|
||||
|
||||
return {
|
||||
geometry,
|
||||
orientation,
|
||||
position,
|
||||
glContext,
|
||||
};
|
||||
}
|
@@ -1,14 +1,14 @@
|
||||
{
|
||||
"name": "skycraft",
|
||||
"version": "1.0.0",
|
||||
"main": "index.js",
|
||||
"main": "index.ts",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"esbuild": "^0.14.2"
|
||||
},
|
||||
"scripts": {
|
||||
"watch": "esbuild --outfile=app.js index.js --bundle --sourcemap=inline --watch",
|
||||
"serve": "esbuild --outfile=app.js index.js --bundle --sourcemap=inline --servedir=.",
|
||||
"build": "esbuild --outfile=app.js index.js --bundle --minify"
|
||||
"watch": "esbuild --outfile=app.js index.ts --bundle --sourcemap=inline --watch",
|
||||
"serve": "esbuild --outfile=app.js index.ts --bundle --sourcemap=inline --servedir=.",
|
||||
"build": "esbuild --outfile=app.js index.ts --bundle --minify"
|
||||
}
|
||||
}
|
||||
|
124
skycraft/quat.ts
Normal file
124
skycraft/quat.ts
Normal file
@@ -0,0 +1,124 @@
|
||||
import {Mat4} from './linalg';
|
||||
import * as se3 from '../se3';
|
||||
|
||||
export interface Quat {
|
||||
x: number,
|
||||
y: number,
|
||||
z: number,
|
||||
w: number,
|
||||
}
|
||||
|
||||
export function mat2Quat(m: Mat4) : Quat {
|
||||
const q : Quat = {};
|
||||
|
||||
if (m[0 * 4 + 0] + m[1 * 4 + 1] + m[2 * 4 + 2] > 0.0) {
|
||||
const t = + m[0 * 4 + 0] + m[1 * 4 + 1] + m[2 * 4 + 2] + 1.0;
|
||||
const s = 0.5 / Math.sqrt(t);
|
||||
q.w = s * t;
|
||||
q.z = (m[1 * 4 + 0] - m[0 * 4 + 1]) * s;
|
||||
q.y = (m[0 * 4 + 2] - m[2 * 4 + 0]) * s;
|
||||
q.x = (m[2 * 4 + 1] - m[1 * 4 + 2]) * s;
|
||||
} else if (m[0 * 4 + 0] > m[1 * 4 + 1] && m[0 * 4 + 0] > m[2 * 4 + 2]) {
|
||||
const t = + m[0 * 4 + 0] - m[1 * 4 + 1] - m[2 * 4 + 2] + 1.0;
|
||||
const s = 0.5 / Math.sqrt(t);
|
||||
q.x = s * t;
|
||||
q.y = (m[1 * 4 + 0] + m[0 * 4 + 1]) * s;
|
||||
q.z = (m[0 * 4 + 2] + m[2 * 4 + 0]) * s;
|
||||
q.w = (m[2 * 4 + 1] - m[1 * 4 + 2]) * s;
|
||||
} else if (m[1 * 4 + 1] > m[2 * 4 + 2]) {
|
||||
const t = - m[0 * 4 + 0] + m[1 * 4 + 1] - m[2 * 4 + 2] + 1.0;
|
||||
const s = 0.5 / Math.sqrt(t);
|
||||
q.y = s * t;
|
||||
q.x = (m[1 * 4 + 0] + m[0 * 4 + 1]) * s;
|
||||
q.w = (m[0 * 4 + 2] - m[2 * 4 + 0]) * s;
|
||||
q.z = (m[2 * 4 + 1] + m[1 * 4 + 2]) * s;
|
||||
} else {
|
||||
const t = - m[0 * 4 + 0] - m[1 * 4 + 1] + m[2 * 4 + 2] + 1.0;
|
||||
const s = 0.5 / Math.sqrt(t);
|
||||
q.z = s * t;
|
||||
q.w = (m[1 * 4 + 0] - m[0 * 4 + 1]) * s;
|
||||
q.x = (m[0 * 4 + 2] + m[2 * 4 + 0]) * s;
|
||||
q.y = (m[2 * 4 + 1] + m[1 * 4 + 2]) * s;
|
||||
}
|
||||
|
||||
return q;
|
||||
}
|
||||
|
||||
export function quat2Mat(q: Quat): Mat4 {
|
||||
const m: Mat4 = se3.identity();
|
||||
|
||||
const x2 = q.x + q.x;
|
||||
const y2 = q.y + q.y;
|
||||
const z2 = q.z + q.z;
|
||||
{
|
||||
const xx2 = q.x * x2;
|
||||
const yy2 = q.y * y2;
|
||||
const zz2 = q.z * z2;
|
||||
m[0 * 4 + 0] = 1.0 - yy2 - zz2;
|
||||
m[1 * 4 + 1] = 1.0 - xx2 - zz2;
|
||||
m[2 * 4 + 2] = 1.0 - xx2 - yy2;
|
||||
}
|
||||
{
|
||||
const yz2 = q.y * z2;
|
||||
const wx2 = q.w * x2;
|
||||
m[1 * 4 + 2] = yz2 - wx2;
|
||||
m[2 * 4 + 1] = yz2 + wx2;
|
||||
}
|
||||
{
|
||||
const xy2 = q.x * y2;
|
||||
const wz2 = q.w * z2;
|
||||
m[0 * 4 + 1] = xy2 - wz2;
|
||||
m[1 * 4 + 0] = xy2 + wz2;
|
||||
}
|
||||
{
|
||||
const xz2 = q.x * z2;
|
||||
const wy2 = q.w * y2;
|
||||
m[2 * 4 + 0] = xz2 - wy2;
|
||||
m[0 * 4 + 2] = xz2 + wy2;
|
||||
}
|
||||
|
||||
return m;
|
||||
}
|
||||
|
||||
export function normalize(q: Quat) : Quat {
|
||||
const n = norm(q);
|
||||
if (n < 1e-10) {
|
||||
return {x: 0, y: 0, z: 0, w: 1};
|
||||
}
|
||||
return {
|
||||
x: q.x / n,
|
||||
y: q.y / n,
|
||||
z: q.z / n,
|
||||
w: q.w / n,
|
||||
};
|
||||
}
|
||||
|
||||
export function diff(q0: Quat, q1: Quat) {
|
||||
return {
|
||||
x: q0.x - q1.x,
|
||||
y: q0.y - q1.y,
|
||||
z: q0.z - q1.z,
|
||||
w: q0.w - q1.w,
|
||||
};
|
||||
}
|
||||
export function norm(q: Quat) {
|
||||
return Math.sqrt(q.x**2 + q.y**2 + q.z**2 + q.w**2);
|
||||
}
|
||||
|
||||
export function add(q0: Quat, q1: Quat) {
|
||||
return {
|
||||
x: q0.x + q1.x,
|
||||
y: q0.y + q1.y,
|
||||
z: q0.z + q1.z,
|
||||
w: q0.w + q1.w,
|
||||
};
|
||||
}
|
||||
|
||||
export function scale(q: Quat, a: number): Quat {
|
||||
return {
|
||||
x: a * q.x,
|
||||
y: a * q.y,
|
||||
z: a * q.z,
|
||||
w: a * q.w,
|
||||
};
|
||||
}
|
2
skycraft/server/.cargo/config.toml
Normal file
2
skycraft/server/.cargo/config.toml
Normal file
@@ -0,0 +1,2 @@
|
||||
[build]
|
||||
rustflags = ["-C", "link-arg=-fuse-ld=lld"]
|
1
skycraft/server/.gitignore
vendored
Normal file
1
skycraft/server/.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
||||
/target
|
1864
skycraft/server/Cargo.lock
generated
Normal file
1864
skycraft/server/Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
12
skycraft/server/Cargo.toml
Normal file
12
skycraft/server/Cargo.toml
Normal file
@@ -0,0 +1,12 @@
|
||||
[package]
|
||||
name = "skycraft-server"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
tide = "0.14.0"
|
||||
async-std = { version = "1.6.0", features = ["attributes"] }
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
14
skycraft/server/Dockerfile
Normal file
14
skycraft/server/Dockerfile
Normal file
@@ -0,0 +1,14 @@
|
||||
FROM rust:1.80.1 AS build
|
||||
|
||||
RUN apt-get update && apt-get install -y lld
|
||||
|
||||
WORKDIR /workspace
|
||||
|
||||
COPY src /workspace/src
|
||||
COPY Cargo.toml /workspace/
|
||||
COPY Cargo.lock /workspace/
|
||||
|
||||
RUN cargo build
|
||||
|
||||
|
||||
FROM build AS dev
|
19
skycraft/server/Makefile
Normal file
19
skycraft/server/Makefile
Normal file
@@ -0,0 +1,19 @@
|
||||
dev-image:
|
||||
docker build -t cargo-server-dev --target dev .
|
||||
|
||||
.PHONY: dev
|
||||
dev: dev-image ## Start a dev container
|
||||
docker run -it --rm \
|
||||
-v $(CURDIR)/src:/workspace/src \
|
||||
-v $(CURDIR)/Cargo.toml:/workspace/Cargo.toml \
|
||||
-v $(CURDIR)/Cargo.lock:/workspace/Cargo.lock \
|
||||
-p 127.0.0.1:8080:8080 \
|
||||
cargo-server-dev \
|
||||
bash
|
||||
|
||||
|
||||
.PHONY: help
|
||||
help: ## Show this help
|
||||
@echo Noteworthy targets:
|
||||
@egrep '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-20s\033[0m %s\n", $$1, $$2}'
|
||||
.DEFAULT_GOAL := help
|
262
skycraft/server/src/main.rs
Normal file
262
skycraft/server/src/main.rs
Normal file
@@ -0,0 +1,262 @@
|
||||
use tide::Request;
|
||||
use tide::Response;
|
||||
use tide::prelude::*;
|
||||
//use serde_json::json;
|
||||
use std::f64::consts::PI;
|
||||
|
||||
#[derive(Default, Serialize)]
|
||||
struct SystemBody {
|
||||
name: String,
|
||||
mass: f32,
|
||||
seed: u32,
|
||||
spin: [f32; 3],
|
||||
// geometry: ,
|
||||
glow_color: [f32; 3],
|
||||
orbit: KeplerOrbit,
|
||||
children: Vec<SystemBody>,
|
||||
}
|
||||
|
||||
#[derive(Default, Serialize)]
|
||||
struct KeplerOrbit {
|
||||
excentricity: f32,
|
||||
semimajor_axis: f32,
|
||||
inclination: f32,
|
||||
ascending_node_longitude: f32,
|
||||
periapsis_argument: f32,
|
||||
t0: f32,
|
||||
}
|
||||
|
||||
const CHUNKSIZE: usize = 32;
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct Chunk {
|
||||
position: [f32; 3],
|
||||
layout: [i32; 3],
|
||||
#[serde(serialize_with = "<[_]>::serialize")]
|
||||
blocks: [u32; CHUNKSIZE.pow(3)],
|
||||
seed: u32,
|
||||
underground: bool,
|
||||
}
|
||||
|
||||
impl PartialEq for Chunk {
|
||||
fn eq(&self, other: &Chunk) -> bool {
|
||||
self.seed == other.seed && self.position == other.position
|
||||
}
|
||||
}
|
||||
|
||||
#[async_std::main]
|
||||
async fn main() -> tide::Result<()> {
|
||||
let mut app = tide::new();
|
||||
app.at("/api/system/:seed").get(get_system);
|
||||
app.at("/api/body/:seed").get(get_body);
|
||||
app.listen("0.0.0.0:8080").await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_sun_chunk(seed: u32, pos: [i32; 3]) -> Chunk {
|
||||
let cs = CHUNKSIZE as i32;
|
||||
Chunk {
|
||||
position: pos.map(|x| ((x * cs - cs / 2) as f32)),
|
||||
layout: pos,
|
||||
blocks: [8; CHUNKSIZE.pow(3)],
|
||||
seed: seed,
|
||||
underground: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn get_dirt_chunk(seed: u32, pos: [i32; 3]) -> Chunk {
|
||||
let cs = CHUNKSIZE as i32;
|
||||
Chunk {
|
||||
position: pos.map(|x| ((x * cs - cs / 2) as f32)),
|
||||
layout: pos,
|
||||
blocks: [2; CHUNKSIZE.pow(3)],
|
||||
seed: seed,
|
||||
underground: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn get_chunk(seed: u32, pos: [i32; 3]) -> Option<Chunk>{
|
||||
match seed {
|
||||
0 => match pos {
|
||||
[0, 0, 0] => Some(get_sun_chunk(seed, pos)),
|
||||
_ => None,
|
||||
},
|
||||
_ => match pos {
|
||||
[0, 0, 0] => Some(get_dirt_chunk(seed, pos)),
|
||||
_ => None,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn get_body_chunks(seed: u32) -> Vec<Chunk> {
|
||||
let mut chunks = vec![];
|
||||
let mut tocheck = vec![[0, 0, 0]];
|
||||
|
||||
while tocheck.len() > 0 {
|
||||
let pos = tocheck.pop().unwrap();
|
||||
let thischunk = get_chunk(seed, pos);
|
||||
if thischunk.is_none() || chunks.contains(thischunk.as_ref().unwrap()) {
|
||||
continue;
|
||||
}
|
||||
chunks.push(thischunk.unwrap());
|
||||
println!("Adding chunk for seed {seed} at position {:?}", pos);
|
||||
|
||||
let [ci, cj, ck] = pos;
|
||||
tocheck.push([ci - 1, cj, ck]);
|
||||
tocheck.push([ci + 1, cj, ck]);
|
||||
tocheck.push([ci, cj - 1, ck]);
|
||||
tocheck.push([ci, cj + 1, ck]);
|
||||
tocheck.push([ci, cj, ck - 1]);
|
||||
tocheck.push([ci, cj, ck + 1]);
|
||||
}
|
||||
|
||||
chunks
|
||||
}
|
||||
|
||||
async fn get_body(req: Request<()>) -> tide::Result {
|
||||
let seed: u32 = req.param("seed")?.parse()?;
|
||||
let chunks = get_body_chunks(seed);
|
||||
let response = Response::builder(200)
|
||||
.body(serde_json::to_string(&chunks)?)
|
||||
.content_type("application/json")
|
||||
.header("access-control-allow-origin", "*")
|
||||
.build();
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
// TODO
|
||||
// ----
|
||||
// [ ] serve chunks
|
||||
// [ ] universe simulation?
|
||||
// [ ] websocket with client updates
|
||||
|
||||
async fn get_system(_req: Request<()>) -> tide::Result {
|
||||
// let seed: i32 = req.param("seed")?.parse()?;
|
||||
let response = Response::builder(200)
|
||||
.content_type("application/json")
|
||||
.header("access-control-allow-origin", "*")
|
||||
.body(serde_json::to_string(&SystemBody
|
||||
{
|
||||
name: "Tat".to_string(),
|
||||
seed: 0,
|
||||
|
||||
mass: 1000.0,
|
||||
spin: [0.0, 0.0, 0.2],
|
||||
|
||||
// geometry: getBodyGeometry(0),
|
||||
glow_color: [0.5, 0.5, 0.46],
|
||||
|
||||
children: Vec::from([
|
||||
SystemBody {
|
||||
name: "Quicksilver".to_string(),
|
||||
seed: 1336,
|
||||
|
||||
mass: 0.1,
|
||||
spin: [0.0, 0.0, 0.05],
|
||||
|
||||
// geometry: makeCube([0, 4]),
|
||||
|
||||
orbit: KeplerOrbit {
|
||||
excentricity: 0.0,
|
||||
semimajor_axis: 200.0,
|
||||
inclination: 0.8,
|
||||
ascending_node_longitude: 0.0,
|
||||
periapsis_argument: 0.0,
|
||||
t0: 0.0,
|
||||
},
|
||||
|
||||
..Default::default()
|
||||
},
|
||||
SystemBody {
|
||||
name: "Satourne".to_string(),
|
||||
seed: 1338,
|
||||
|
||||
mass: 0.1,
|
||||
spin: [0.0, 0.5, 0.0],
|
||||
|
||||
// geometry: makeCube([0, 5]),
|
||||
|
||||
orbit: KeplerOrbit {
|
||||
excentricity: 0.0,
|
||||
semimajor_axis: 900.0,
|
||||
inclination: 0.0,
|
||||
ascending_node_longitude: 0.0,
|
||||
periapsis_argument: 0.0,
|
||||
t0: 0.0,
|
||||
},
|
||||
|
||||
children: Vec::from([
|
||||
SystemBody {
|
||||
name: "Kyoujin".to_string(),
|
||||
seed: 13381,
|
||||
|
||||
mass: 0.01,
|
||||
spin: [0.0, 0.0, 0.05],
|
||||
|
||||
// geometry: makeCube([0, 6]),
|
||||
|
||||
orbit: KeplerOrbit {
|
||||
excentricity: 0.0,
|
||||
semimajor_axis: 20.0,
|
||||
inclination: (PI / 2.0) as f32,
|
||||
ascending_node_longitude: 0.0,
|
||||
periapsis_argument: 0.0,
|
||||
t0: 0.0,
|
||||
},
|
||||
|
||||
..Default::default()
|
||||
},
|
||||
]),
|
||||
|
||||
..Default::default()
|
||||
},
|
||||
SystemBody {
|
||||
name: "Tataooine".to_string(),
|
||||
seed: 1337,
|
||||
|
||||
mass: 50.0,
|
||||
spin: [0.0, 0.0, 0.05],
|
||||
|
||||
// geometry: getBodyGeometry(1337),
|
||||
|
||||
orbit: KeplerOrbit {
|
||||
excentricity: 0.3,
|
||||
semimajor_axis: 500.0,
|
||||
inclination: 0.0,
|
||||
ascending_node_longitude: 0.0,
|
||||
periapsis_argument: 0.0,
|
||||
t0: 0.0,
|
||||
},
|
||||
|
||||
children: Vec::from([
|
||||
SystemBody {
|
||||
name: "Mun".to_string(),
|
||||
seed: 13371,
|
||||
|
||||
mass: 0.01,
|
||||
spin: [0.0, 0.0, 0.05],
|
||||
|
||||
// geometry: makeCube([0, 7]),
|
||||
|
||||
orbit: KeplerOrbit {
|
||||
excentricity: 0.0,
|
||||
semimajor_axis: 50.0,
|
||||
inclination: (PI / 2.0) as f32,
|
||||
ascending_node_longitude: 0.0,
|
||||
periapsis_argument: 0.0,
|
||||
t0: 0.0,
|
||||
},
|
||||
|
||||
..Default::default()
|
||||
},
|
||||
]),
|
||||
|
||||
..Default::default()
|
||||
},
|
||||
]),
|
||||
|
||||
..Default::default()
|
||||
})?)
|
||||
.build();
|
||||
Ok(response)
|
||||
}
|
3743
skycraft/spaceship.obj
Normal file
3743
skycraft/spaceship.obj
Normal file
File diff suppressed because it is too large
Load Diff
BIN
skycraft/spaceship.stl
Normal file
BIN
skycraft/spaceship.stl
Normal file
Binary file not shown.
76
skycraft/stl.ts
Normal file
76
skycraft/stl.ts
Normal file
@@ -0,0 +1,76 @@
|
||||
import * as linalg from './linalg';
|
||||
|
||||
function parseTriangle(triangleData) {
|
||||
const dv = new DataView(triangleData.buffer);
|
||||
function data(idx) {
|
||||
const offset = 4 * idx;
|
||||
return dv.getFloat32(offset, /*littleEndian=*/true);
|
||||
}
|
||||
|
||||
const attributeByteCount = dv.getUint16(48, /*littleEndian=*/true);
|
||||
console.assert(attributeByteCount === 0);
|
||||
|
||||
const x = [data(3), data(4), data(5)];
|
||||
const y = [data(6), data(7), data(8)];
|
||||
const z = [data(9), data(10), data(11)];
|
||||
const n = linalg.cross(linalg.diff(y, x), linalg.diff(z, y));
|
||||
|
||||
return {
|
||||
vertices: [x, y, z],
|
||||
normals: new Array(3).fill(linalg.scale(n, 1 / linalg.norm(n))),
|
||||
textures: new Array(3).fill([0, 0]),
|
||||
}; // no normals, default texture
|
||||
}
|
||||
|
||||
export async function loadStlModel(url) {
|
||||
const stlDataStream = (await fetch(url)).body;
|
||||
const triangles = [];
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
let bytesReceived = 0;
|
||||
let gotHeader = false;
|
||||
const partial = new Uint8Array(50); // each triangle is 50 bytes
|
||||
let partialOffset = 0;
|
||||
const reader = stlDataStream.getReader();
|
||||
|
||||
function pump() {
|
||||
reader.read().then(({ done, value }) => {
|
||||
if (done) {
|
||||
return resolve(triangles);
|
||||
}
|
||||
|
||||
const skipped = bytesReceived;
|
||||
bytesReceived += value.length;
|
||||
let inputOffset = 0;
|
||||
|
||||
if (!gotHeader) {
|
||||
if (bytesReceived < 84) { // header + triangle count
|
||||
return pump();
|
||||
} else {
|
||||
gotHeader = true;
|
||||
inputOffset = 84 - skipped;
|
||||
}
|
||||
}
|
||||
|
||||
// parse triangle data
|
||||
while (true) {
|
||||
const spaceLeft = 50 - partialOffset;
|
||||
console.assert(spaceLeft > 0);
|
||||
|
||||
const leftToCopy = value.length - inputOffset;
|
||||
const toCopy = value.subarray(inputOffset, inputOffset + Math.min(leftToCopy, spaceLeft));
|
||||
partial.set(toCopy, partialOffset);
|
||||
if (leftToCopy < spaceLeft) {
|
||||
break;
|
||||
}
|
||||
// parse a triangle!
|
||||
triangles.push(parseTriangle(partial));
|
||||
partialOffset = 0;
|
||||
inputOffset += toCopy.length;
|
||||
}
|
||||
pump();
|
||||
});
|
||||
}
|
||||
pump();
|
||||
});
|
||||
}
|
15
skycraft/tsconfig.json
Normal file
15
skycraft/tsconfig.json
Normal file
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "es6",
|
||||
"module": "commonjs",
|
||||
"lib": ["es2022", "dom"],
|
||||
"declaration": true,
|
||||
"outDir": "dist",
|
||||
"strict": true,
|
||||
"esModuleInterop": true
|
||||
},
|
||||
"exclude": [
|
||||
"node_modules",
|
||||
"dist"
|
||||
]
|
||||
}
|
Reference in New Issue
Block a user