Merge pull request 'merge to main' (#9) from malouze-cooking into main

Reviewed-on: https://codeberg.org/adrien-lsh/ft_transcendence/pulls/9
This commit is contained in:
kbz_8 2024-02-21 15:44:06 +00:00
commit f2910f0620
12 changed files with 457 additions and 17 deletions

View File

@ -0,0 +1,69 @@
function initBuffers(gl)
{
const vertexBuffer = initVertexBuffer(gl);
const indexBuffer = initIndexBuffer(gl);
const normalBuffer = initNormalBuffer(gl);
return { vertex: vertexBuffer, index : indexBuffer, normal: normalBuffer };
}
function initVertexBuffer(gl)
{
const positionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
const positions = [
// Front face
-1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0, 1.0,
// Back face
-1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0, -1.0,
// Top face
-1.0, 1.0, -1.0, -1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, -1.0,
// Bottom face
-1.0, -1.0, -1.0, 1.0, -1.0, -1.0, 1.0, -1.0, 1.0, -1.0, -1.0, 1.0,
// Right face
1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0,
// Left face
-1.0, -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0
];
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);
return positionBuffer;
}
function initNormalBuffer(gl)
{
const normalBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, normalBuffer);
const vertexNormals = [
// Front
0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0,
// Back
0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0,
// Top
0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0,
// Bottom
0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0,
// Right
1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0,
// Left
-1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0,
];
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertexNormals), gl.STATIC_DRAW);
return normalBuffer;
}
function initIndexBuffer(gl)
{
const indexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
const indices = [
0, 1, 2, 0, 2, 3, // front
4, 5, 6, 4, 6, 7, // back
8, 9, 10, 8, 10, 11, // top
12, 13, 14, 12, 14, 15, // bottom
16, 17, 18, 16, 18, 19, // right
20, 21, 22, 20, 22, 23, // left
];
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);
return indexBuffer;
}
export { initBuffers };

View File

@ -0,0 +1,36 @@
import { shaderInfos } from "../3D/shaders.js"
function renderCube(ctx, x, y, z, angle = 0, sx = 1, sy = 1, sz = 1)
{
const modelMatrix = mat4.create();
mat4.translate(
modelMatrix,
modelMatrix,
[x, y, z]
);
mat4.rotate(
modelMatrix,
modelMatrix,
angle,
[0, 1, 1],
);
mat4.scale(
modelMatrix,
modelMatrix,
[sx, sy, sz]
);
const normalMatrix = mat4.create();
mat4.invert(normalMatrix, modelMatrix);
mat4.transpose(normalMatrix, normalMatrix);
ctx.uniformMatrix4fv(shaderInfos.uniformLocations.modelMatrix, false, modelMatrix);
ctx.uniformMatrix4fv(shaderInfos.uniformLocations.normalMatrix, false, normalMatrix);
ctx.drawElements(ctx.TRIANGLES, 36, ctx.UNSIGNED_SHORT, 0);
}
export { renderCube };

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,87 @@
const vertex_shader_source = `
attribute vec4 aPos;
attribute vec3 aNormal;
uniform mat4 uMod;
uniform mat4 uView;
uniform mat4 uProj;
uniform mat4 uNormalMat;
varying highp vec3 vLighting;
void main()
{
gl_Position = uProj * uView * uMod * aPos;
highp vec3 ambientLight = vec3(0.3, 0.3, 0.3);
highp vec3 directionalLightColor = vec3(1, 1, 1);
highp vec3 directionalVector = normalize(vec3(1, 15, -1.75));
highp vec4 transformedNormal = uNormalMat * vec4(aNormal, 1.0);
highp float directional = max(dot(transformedNormal.xyz, directionalVector), 0.0);
vLighting = ambientLight + (directionalLightColor * directional);
}
`;
const fragment_shader_source = `
varying highp vec3 vLighting;
void main()
{
highp vec3 color = vec3(1.0, 1.0, 1.0);
gl_FragColor = vec4(color * vLighting, 1.0);
}
`;
export function initShaderProgram(gl)
{
const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vertex_shader_source);
const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fragment_shader_source);
const prog = gl.createProgram();
gl.attachShader(prog, vertexShader);
gl.attachShader(prog, fragmentShader);
gl.linkProgram(prog);
shaderInfos = {
program: prog,
attribLocations: {
vertexPosition: gl.getAttribLocation(prog, "aPos"),
vertexNormal: gl.getAttribLocation(prog, "aNormal"),
},
uniformLocations: {
projectionMatrix: gl.getUniformLocation(prog, "uProj"),
modelMatrix: gl.getUniformLocation(prog, "uMod"),
viewMatrix: gl.getUniformLocation(prog, "uView"),
normalMatrix: gl.getUniformLocation(prog, "uNormalMat"),
},
};
if(!gl.getProgramParameter(prog, gl.LINK_STATUS))
{
alert(`Unable to initialize the shader program: ${gl.getProgramInfoLog(prog)}`);
return null;
}
return prog;
}
function loadShader(gl, type, source)
{
const shader = gl.createShader(type);
gl.shaderSource(shader, source);
gl.compileShader(shader);
if(!gl.getShaderParameter(shader, gl.COMPILE_STATUS))
{
alert(`An error occurred while compiling the shaders: ${gl.getShaderInfoLog(shader)}`);
gl.deleteShader(shader);
return null;
}
return shader;
}
export let shaderInfos;

View File

@ -1,6 +1,6 @@
import { Game } from "./Game.js";
import { Point } from "./Point.js";
import { renderCube } from "../../3D/cube.js"
class Ball
{
@ -45,9 +45,21 @@ class Ball
* @param {CanvasRenderingContext2D} ctx
*/
draw(ctx)
{
if(ctx instanceof CanvasRenderingContext2D)
{
ctx.rect(this.position.x - this.size / 2, this.position.y - this.size / 2, this.size, this.size);
}
else if(ctx instanceof WebGLRenderingContext)
{
console.log((this.position.x - this.size / 2) / 10, 0, (this.position.y - this.size / 2) / 10)
renderCube(ctx, (this.position.x - this.size / 2) / 10, 0, (this.position.y - this.size / 2) / 10, 0, this.size * 10, this.size * 10, this.size * 10);
}
else
{
alert('Unknown rendering context type');
}
}
/**
*

View File

@ -113,8 +113,11 @@ class Game
* @param {CanvasRenderingContext2D} ctx
*/
render(ctx)
{
if(ctx instanceof CanvasRenderingContext2D)
{
ctx.clearRect(0, 0, this.config.size_x, this.config.size_y);
}
this.draw_sides(ctx);
this.ball.render(ctx);

View File

@ -1,6 +1,7 @@
import { Game } from "./Game.js";
import { Point } from "./Point.js";
import { Segment } from "./Segment.js";
import { renderCube } from "../../3D/cube.js"
class Player
{
@ -66,9 +67,12 @@ class Player
draw(ctx)
{
if (this.is_connected === false)
{
if(ctx instanceof CanvasRenderingContext2D)
{
ctx.moveTo(this.rail.start.x, this.rail.start.y);
ctx.lineTo(this.rail.stop.x, this.rail.stop.y);
}
return;
}

View File

@ -1,4 +1,9 @@
<<<<<<< HEAD
import { Point } from "./Point.js";
=======
import { Point } from "./Point.js"
import { renderCube } from "../../3D/cube.js"
>>>>>>> de2488589cf0a579b849e706b40901c355ff35f8
class Segment
{
@ -40,10 +45,21 @@ class Segment
* @param {CanvasRenderingContext2D} ctx
*/
draw(ctx)
{
if(ctx instanceof CanvasRenderingContext2D)
{
ctx.moveTo(this.start.x, this.start.y);
ctx.lineTo(this.stop.x, this.stop.y);
}
else if(ctx instanceof WebGLRenderingContext)
{
renderCube(ctx, this.start.x, -3, this.start.y, 0, 0.5, 0.5, 0.5);
}
else
{
alert('Unknown rendering context type');
}
}
from_json(data)
{
@ -54,4 +70,4 @@ class Segment
}
}
export { Segment };
export { Segment }

View File

@ -5,7 +5,8 @@ import Search from "./views/Search.js";
import HomeView from "./views/HomeView.js";
import LogoutView from "./views/accounts/LogoutView.js";
import GameOfflineView from "./views/GameOfflineView.js";
import GameView from "./views/GameView.js";
import GameView2D from "./views/GameView.js";
import GameView3D from "./views/GameView3D.js";
import PageNotFoundView from './views/PageNotFoundView.js' ;
@ -88,8 +89,9 @@ const router = async(uri) => {
{ path: "/settings", view: SettingsView },
{ path: "/matchmaking", view: MatchMakingView },
{ path: "/games/offline", view: GameOfflineView },
{ path: "/games/:id", view: GameView },
{ path: "/tictactoe", view: TicTacToeView },
{ path: "/games/0/:id", view: GameView2D },
{ path: "/games/1/:id", view: GameView3D },
];
// Test each route for potential match

View File

@ -0,0 +1,166 @@
import { client } from "../index.js";
import { Game } from "../api/game/Game.js";
import AbstractView from "./abstracts/AbstractView.js";
import { initShaderProgram, shaderInfos } from "../3D/shaders.js"
import { initBuffers } from "../3D/buffers.js"
import "../3D/maths/gl-matrix-min.js"
import { renderCube } from "../3D/cube.js"
export default class extends AbstractView
{
constructor(params)
{
super(params, "Game");
this.game = new Game(client, params.id);
this.keys_pressed = [];
this.my_player = undefined;
this.gl = null;
this.shader_prog = null;
this.buffers = null;
this.cam_pos = [0, 500, 0];
this.cam_target = [0, 0, 35];
}
initGL()
{
const canvas = document.getElementById('glcanva');
this.gl = canvas.getContext("webgl");
if(this.gl === null)
{
alert("Unable to initialize WebGL. Your browser or machine may not support it. You may also be a bozo");
return;
}
this.shader_prog = initShaderProgram(this.gl);
this.buffers = initBuffers(this.gl);
this.gl.enable(this.gl.CULL_FACE);
this.gl.cullFace(this.gl.BACK);
}
async join_game()
{
await this.game.join()
let canvas = document.createElement("canvas");
canvas.height = this.game.config.size_x;
canvas.width = this.game.config.size_y;
canvas.id = "glcanva";
document.getElementById("app").appendChild(canvas);
this.initGL();
this.render_game();
}
draw()
{
const canvas = document.getElementById('glcanva');
if(canvas === null)
return 1;
this.gl.clearColor(0.1, 0.1, 0.1, 1.0);
this.gl.clearDepth(1.0);
this.gl.enable(this.gl.DEPTH_TEST);
this.gl.depthFunc(this.gl.LEQUAL);
this.gl.clear(this.gl.COLOR_BUFFER_BIT | this.gl.DEPTH_BUFFER_BIT);
const projectionMatrix = mat4.create();
const viewMatrix = mat4.create();
mat4.perspective(projectionMatrix, (90 * Math.PI) / 180, this.gl.canvas.clientWidth / this.gl.canvas.clientHeight, 0.1, 10000000.0);
mat4.lookAt(viewMatrix, this.cam_pos, this.cam_target, [0, 1, 0]);
this.setPositionAttribute();
this.setNormalAttribute();
this.gl.useProgram(shaderInfos.program);
this.gl.uniformMatrix4fv(shaderInfos.uniformLocations.projectionMatrix, false, projectionMatrix);
this.gl.uniformMatrix4fv(shaderInfos.uniformLocations.viewMatrix, false, viewMatrix);
this.game.render(this.gl);
}
setNormalAttribute()
{
const numComponents = 3;
const type = this.gl.FLOAT;
const normalize = false;
const stride = 0;
const offset = 0;
this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.buffers.normal);
this.gl.vertexAttribPointer(
shaderInfos.attribLocations.vertexNormal,
numComponents,
type,
normalize,
stride,
offset,
);
this.gl.enableVertexAttribArray(shaderInfos.attribLocations.vertexNormal);
}
setPositionAttribute()
{
const numComponents = 3;
const type = this.gl.FLOAT;
const normalize = false;
const stride = 0;
const offset = 0;
this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.buffers.vertex);
this.gl.bindBuffer(this.gl.ELEMENT_ARRAY_BUFFER, this.buffers.index);
this.gl.vertexAttribPointer(
shaderInfos.attribLocations.vertexPosition,
numComponents,
type,
normalize,
stride,
offset
);
this.gl.enableVertexAttribArray(shaderInfos.attribLocations.vertexPosition);
}
render_game()
{
let loop_id = setInterval(() => {
if (this.game === undefined)
clearInterval(loop_id);
if (this.my_player)
this.my_player.update_paddle(this.keys_pressed);
this.draw();
this.game?.time.new_frame();
}, 1000 / 60);
}
async update_game_state()
{
document.getElementById("game-state").innerText = this.game.state;
if (this.game.finished === false)
await this.join_game();
}
async postInit()
{
let error_code = await this.game.init();
if (error_code)
return error_code;
await this.update_game_state();
}
async getHtml()
{
return /* HTML */ `
<link rel="stylesheet" href="/static/css/game.css">
<h2 id="game-state"></h2>
<div id="player_list"></div>
`;
}
}

View File

@ -7,6 +7,7 @@ export default class extends AbstractAuthenticatedView {
constructor(params)
{
super(params, "Matchmaking");
this.game_mode = 0; // 0 -> 2D; 1 -> 3D
}
async press_button()
@ -27,6 +28,20 @@ export default class extends AbstractAuthenticatedView {
}
}
async press_button_game_mode()
{
if(this.game_mode === 0)
{
document.getElementById("game-mode").value = "3D";
this.game_mode = 1;
}
else
{
document.getElementById("game-mode").value = "2D";
this.game_mode = 0;
}
}
ondisconnect(event)
{
document.getElementById("button").value = "Find a game";
@ -36,7 +51,7 @@ export default class extends AbstractAuthenticatedView {
{
if (data.detail === "game_found")
{
navigateTo(`/games/${data.game_id}`);
navigateTo(`/games/${this.game_mode}/${data.game_id}`);
return;
}
this.display_data(data);
@ -80,6 +95,7 @@ export default class extends AbstractAuthenticatedView {
["change", "oninput"].forEach((event_name) => {
input.addEventListener(event_name, update);
});
document.getElementById("game-mode").onclick = this.press_button_game_mode.bind(this)
}
async getHtml() {
@ -87,6 +103,7 @@ export default class extends AbstractAuthenticatedView {
<h1>Select mode</h1>
<input type="number" value="2" min="1" id="nb_players-input">
<input type="button" value="Find a game" id="button">
<input type="button" value="2D" id="game-mode">
<span id="detail"></span>
`;
}