Golix for developers
Host Golix rooms from Node with golix.js, script what happens in them, join rooms as a bot and write your own stadiums.
Getting started
golix.js needs Node 22 or later.
npm install golix.js
A room registers with the public lobby, and players connect straight to your process over WebRTC, or through the lobby when a direct connection fails.
const golix = require('golix.js');
golix().then((HBInit) => {
const room = HBInit({
roomName: 'My room',
maxPlayers: 12,
noPlayer: true,
lobby: 'wss://golix.cosmosfutsal.com',
// 22 characters of A-Z, a-z, 0-9, - and _: keeps the room link across restarts.
roomSecret: process.env.ROOM_SECRET,
// Only the first time this roomSecret opens a room: from https://golix.cosmosfutsal.com/headlesstoken
token: process.env.ROOM_TOKEN,
});
room.onRoomLink = (link) => console.log(link);
room.onPlayerJoin = (player) => room.sendAnnouncement(`Welcome ${player.name}`, player.id);
});
With ES modules: import golix from 'golix.js'; const HBInit = await golix();
Callbacks run inside the room's tick, 60 times a second. Methods called from them take effect on the next tick, and an exception thrown by a callback is logged without stopping the room.
Room config
| Field | Meaning |
|---|---|
roomName | Up to 40 characters. |
playerName | Name of the host player; leave out with noPlayer: true. |
password | Up to 30 characters. |
maxPlayers | 2 to 30, default 12. |
public | Whether the room is listed. Default true. |
geo | { code, lat, lon } shown in the room list. |
noPlayer | Run the room without a host player. |
lobby | ws:// or wss:// lobby to register with. |
roomSecret | With lobby: the secret the room id is derived from, so the link survives restarts. |
token | With lobby: a room token from /headlesstoken, needed the first time a roomSecret opens a room. It works once, for ten minutes; the same roomSecret reopens the room later without one. |
server | Without lobby: serve the room from your own lobby, given as a running server or its options (default port 8787). |
clientUrl | Origin used in the room link. |
webrtc | { bindAddress, portRange: [first, last], iceServers } for the WebRTC connections players open to your process. |
Room methods
Players and chat
| Method | Notes |
|---|---|
sendChat(message, targetId?) | As the host player; up to 140 characters. |
sendAnnouncement(msg, targetId?, color?, style?, sound?) | Style normal, bold, italic, small, small-bold or small-italic; sound 0, 1 or 2; up to 1000 characters. |
setPlayerAdmin(id, admin) | |
setPlayerTeam(id, team) | 0 spectators, 1 red, 2 blue. |
kickPlayer(id, reason, ban) | A ban matches the player's auth and conn. |
clearBan(id), clearBans() | |
getPlayer(id), getPlayerList() | |
reorderPlayers(ids, moveToTop) | |
setPlayerAvatar(id, avatar) | Null gives back the avatar the player chose. |
Game
| Method | Notes |
|---|---|
startGame(), stopGame(), pauseGame(paused) | |
setScoreLimit(n), setTimeLimit(minutes) | 0 to 99; only between games. |
setTeamsLock(locked) | |
setTeamColors(team, angle, textColor, colors) | Up to five stripes. |
setKickRateLimit(min, rate, burst) | |
getScores(), getBallPosition() | scores.timeLimit is in seconds. |
setCustomStadium(text) | Takes a stadium file; throws when the text is not a valid one. |
setDefaultStadium(name) | Built-ins: Standard, Wide Goals, Compact, Stadium, Oval, Rink, Big Rink, Stadium Wide Goals, Big Oval, Colossal. Classic, Easy, Small, Big, Rounded, Hockey, Big Hockey, Big Easy, Big Rounded and Huge name the same ones in that order. |
startRecording(), stopRecording() | Returns a .glx replay as a Uint8Array. |
setPassword(pass) | Null or empty removes it. |
Discs
| Method | Notes |
|---|---|
getDiscCount() | Stadium discs, with the ball at 0, then player discs. |
getDiscProperties(index), setDiscProperties(index, props) | Fields x y xspeed yspeed xgravity ygravity radius bCoeff invMass damping color cMask cGroup; floats are stored as 32-bit. |
getPlayerDiscProperties(id), setPlayerDiscProperties(id, props) | Players get fresh discs at every kickoff, so changes last until then. For lasting changes use setPlayerPhysics. |
Protection
| Method | Notes |
|---|---|
setRequireRecaptcha(on) | Asks every joiner for a captcha. See room protection. |
setRaidProtection({ joins, seconds, minutes }) | Tunes the automatic raid guard; null turns it off. |
setMaxPlayersPerConn(n) | How many players one network address may have in the room; null for no limit (the default). |
Room events
Assign a function to the property.
| Event | Notes |
|---|---|
onPlayerJoin(player), onPlayerLeave(player) | |
onPlayerChat(player, message) | Return false to keep the message from the others. |
onPlayerKicked(player, reason, ban, byPlayer) | |
onPlayerAdminChange(player, byPlayer), onPlayerTeamChange(player, byPlayer) | |
onPlayerActivity(player) | The player sent input, which happens when their keys change. |
onPlayerInput(player, prevInput) | The player's keys changed; player.input holds the new ones. |
onPlayerAction(player, actionId, isPressed) | An action key 1 to 6 went down or up, in rooms with setActionKeys(true). |
onPlayerBallKick(player) | |
onTeamGoal(team), onTeamVictory(scores) | |
onGameStart(byPlayer), onGameStop(byPlayer) | |
onGamePause(byPlayer), onGameUnpause(byPlayer) | |
onGameTick() | Every tick of a running, unpaused game. |
onPositionsReset() | After a goal, before the next kickoff. |
onStadiumChange(name, byPlayer) | |
onKickRateLimitSet(min, rate, burst, byPlayer), onTeamsLockChange(locked, byPlayer) | |
onCollisionDiscVsDisc(disc1, disc2) | Two discs bounced off each other; disc indexes as in getDiscProperties. |
onCollisionDiscVsPlane(disc, planeIndex), onCollisionDiscVsSegment(disc, segmentIndex), onCollisionDiscVsVertex(disc, vertexIndex) | A disc bounced off the stadium's plane, segment or vertex at that index. |
onRoomLink(url) | The room's link, once it is registered. |
onLobbyDisconnect(retryInMs) | The lobby is out of reach. Players on WebRTC keep playing; new ones cannot join until it is back. |
onLobbyReconnect() | Registered again under the same room link. |
A post hit is the ball, disc 0, against a post's disc index; a touch is the ball against a player's disc.
Player objects
| Field | Meaning |
|---|---|
id, name, team, admin | |
position | { x, y }, or null without a disc. |
input | The keys held, as input flags. |
auth | The player's identity: an 87-character base64url P-256 public key that stays with their browser. Only set in onPlayerJoin. |
conn | The hex of the player's network address. Only set in onPlayerJoin. |
Customizing the game
Physics for one player
room.setPlayerPhysics(player.id, { kickStrength: 7, acceleration: 0.12, radius: 17 });
room.getPlayerPhysics(player.id); // { kickStrength: 7, acceleration: 0.12, radius: 17 }
room.setPlayerPhysics(player.id, null); // back to the stadium's
Any of radius bCoef invMass damping acceleration kickingAcceleration kickingDamping kickStrength kickback; the fields you leave out keep the stadium's playerPhysics. The change lasts across kickoffs until you clear it.
Text on the game screen
room.setHudItem('score', { text: 'Round 2 of 3', x: 0.5, y: 0.12, align: 'center', color: 0xffd34d, size: 22 });
room.clearHudItem('score');
x and y place the item as a fraction of the screen from the top left. Calling setHudItem with the same id replaces the item. Up to 16 items of 100 characters, sizes 8 to 64. Players who join later see them too.
Camera
room.setCamera({ playerId: scorer.id }, 1.6); // follow a player, zoomed in
room.setCamera({ discIndex: 0 }); // the ball
room.setCamera({ x: 0, y: 0 }, 0.8); // a fixed point
room.setCamera(null); // back to normal
The zoom, 0.25 to 4, multiplies each player's own view setting.
Kits
setPlayerColors(id, angle, textColor, colors) dresses one player in their own kit instead of the team's, with up to five stripes; clearPlayerColors(id) takes it off.
Action keys
setActionKeys(true) lets players send six extra keys, Q, E, R, F, C and V by default. Each press and release arrives as onPlayerAction(player, actionId, isPressed); the keys do nothing by themselves.
Room hosts who play in the browser get most of this without code, from the Mods button in their room.
Flags
room.InputFlags // up 1, down 2, left 4, right 8, kick 16
room.CollisionFlags // ball 1, red 2, blue 4, redKO 8, blueKO 16, wall 32, all 63,
// kick 64, score 128, c0 1<<28, c1 1<<29, c2 1<<30, c3 1<<31
With action keys on, player.input also carries them as bits 32, 64, 128, 256, 512 and 1024 for actions 1 to 6.
Joining as a player
const { session, auth, key } = await golix.joinRoom({
room: 'https://golix.cosmosfutsal.com/play?c=<id>',
name: 'bot',
});
session.send({ type: 'chat', text: 'hi' });
session.onEvent((event) => console.log(event));
Store key and pass it back as key to join again with the same auth. A refused join rejects with a golix.JoinError whose reason is password, full, banned, invalid, rateLimited, captcha, connLimit, version (the room runs another Golix version) or closed. Joining again with a key that is already in the room replaces the older connection.
Replays
golix.decodeReplay(bytes), golix.encodeReplay(replay) and golix.trimReplay(replay, fromFrame, toFrame) read, write and cut .glx replays. The game runs at 60 frames per second, so a 10 second clip ending at frame f is trimReplay(replay, f - 600, f). Replays open in the game from the room list.
Stadium files
A stadium is a JSON5 text file (.hbs) holding one object. Every field but name, width and height has a default; null counts as leaving a field out.
| Field | Meaning |
|---|---|
name | Shown in the room. |
width, height | Half-size of the area the camera stays in. |
maxViewWidth | Zooms in when a screen would show more than this width; 0 (default) for no limit. |
cameraFollow | "ball" (default) follows the ball and the player, "player" only the player. |
spawnDistance | How far from the centre teams line up at kickoff when there are no spawn points. Default 200. |
redSpawnPoints, blueSpawnPoints | [[x, y], ...] kickoff positions, taken in player order; a player who joins a team mid-game takes the last one. |
kickOffReset | "partial" (default) resets the ball and the players at kickoff, "full" every disc. |
canBeStored | Whether players may keep the stadium. Default true. |
bg | { type, width, height, kickOffRadius, cornerRadius, goalLine, color }; type is "grass", "hockey" or "none" (default), color default "718C5A". |
traits | Named sets of default fields; an object with "trait": "name" takes the fields it leaves out from that set. |
vertexes | { x, y, bCoef, cMask, cGroup }: points that discs bounce off. |
segments | { v0, v1, curve, curveF, bias, bCoef, cMask, cGroup, vis, color }: lines between two vertexes. curve bends it by that many degrees; bias makes it one-sided and that thick. |
planes | { normal: [x, y], dist, bCoef, cMask, cGroup }: endless walls, usually the outer bounds. |
goals | { p0: [x, y], p1: [x, y], team }: a line that scores for the other team when a score disc crosses it. |
discs | { pos, speed, gravity, radius, invMass, damping, bCoef, color, cMask, cGroup }: posts, extra balls and anything else round. invMass: 0 does not move. |
joints | { d0, d1, length, strength, color }: links two discs. length null keeps their starting distance, a number fixes it, [min, max] allows a range; strength "rigid" (default) or a number for a spring. |
playerPhysics | { radius, bCoef, invMass, damping, acceleration, kickingAcceleration, kickingDamping, kickStrength, kickback, gravity, cGroup }. |
ballPhysics | A disc for the ball, which always scores and can be kicked, or "disc0" to use the first disc as the ball. |
- Colors are
"RRGGBB",[r, g, b]or"transparent". A transparent disc still shows its outline; a transparent segment is drawn white unlessvisis false. - Collision flags are lists of names:
["ball", "red", "c0"]. Two objects collide when each one'scGroupshares a flag with the other'scMask. - Defaults: vertexes, segments and planes have
bCoef1,cGroupwall andcMaskall; discs radius 10,invMass1, damping 0.99,bCoef0.5, color white,cGroupandcMaskall. - Limits: 255 vertexes, segments, planes, goals and joints each, 255 discs counting the ball, and one million characters per file. A field of the wrong type, like a number written as text, fails the file.
- The ball and stadium discs are drawn over the players.
Room protection
Every room gets these without any code:
- One address can hold 30 connections to the lobby and open 30 within 10 seconds.
- One address gets 5 join attempts a minute per room.
- A connection that sends more than 300 messages a second is disconnected and kept out for a minute.
- Chat is rate limited per player.
- Raid guard. When 6 players with new keys join within 10 seconds, the room asks every new joiner for a captcha for 5 minutes and announces it. The first 2 minutes of a room and keys that joined before are not counted, so a restarted room fills up again without tripping it.
- A player who solves a captcha once gets a proof tied to their browser's key and skips captchas in every room for 30 days. Raiders who make a new key for each join solve one every time.
- Opening a room needs a captcha once: from the Create Room button, or for a script through a token from /headlesstoken. A room that comes back with its
roomSecretneeds none. - Golix's operators can ban an identity from every room at once; it is turned away at the join and removed from rooms it is in. Bans from
kickPlayerstay with the room.
The captcha is Cloudflare Turnstile. setRequireRecaptcha(true) turns it on for good; on a lobby without Turnstile keys it and the raid guard allow one join attempt per address every 30 seconds instead.