From 4b3c8f94497c6a5d5e5e5e73e128326736cefd1d Mon Sep 17 00:00:00 2001 From: ari melody Date: Fri, 14 Mar 2025 20:42:44 +0000 Subject: [PATCH] lol cursor is multiplayer now --- cursor/cursor.go | 189 ++++++++++++++++++++++++++++++ go.mod | 1 + go.sum | 2 + log/log.go | 1 + main.go | 16 ++- public/script/cursor.js | 253 ++++++++++++++++++++++++---------------- public/style/cursor.css | 7 +- 7 files changed, 362 insertions(+), 107 deletions(-) create mode 100644 cursor/cursor.go diff --git a/cursor/cursor.go b/cursor/cursor.go new file mode 100644 index 0000000..a74c998 --- /dev/null +++ b/cursor/cursor.go @@ -0,0 +1,189 @@ +package cursor + +import ( + "arimelody-web/model" + "fmt" + "math/rand" + "net/http" + "strconv" + "strings" + "sync" + "time" + + "github.com/gorilla/websocket" +) + +type CursorClient struct { + ID int32 + Conn *websocket.Conn + Route string + X int16 + Y int16 + Disconnected bool +} + +type CursorMessage struct { + Data []byte + Route string + Exclude []*CursorClient +} + +func (client *CursorClient) Send(data []byte) { + err := client.Conn.WriteMessage(websocket.TextMessage, data) + if err != nil { + client.Disconnect() + } +} + +func (client *CursorClient) Disconnect() { + client.Disconnected = true + broadcast <- CursorMessage{ + []byte(fmt.Sprintf("leave:%d", client.ID)), + client.Route, + []*CursorClient{}, + } +} + +var clients = make(map[int32]*CursorClient) +var broadcast = make(chan CursorMessage) +var mutex = &sync.Mutex{} + +func StartCursor(app *model.AppState) { + var includes = func (clients []*CursorClient, client *CursorClient) bool { + for _, c := range clients { + if c.ID == client.ID { return true } + } + return false + } + + log("Cursor message handler ready!") + + for { + message := <-broadcast + mutex.Lock() + for _, client := range clients { + if client.Route != message.Route { continue } + if includes(message.Exclude, client) { continue } + client.Send(message.Data) + } + mutex.Unlock() + } +} + +func handleClient(client *CursorClient) { + msgType, message, err := client.Conn.ReadMessage() + if err != nil { + client.Disconnect() + return + } + if msgType != websocket.TextMessage { return } + + args := strings.Split(string(message), ":") + if len(args) == 0 { return } + switch args[0] { + case "loc": + if len(args) < 2 { return } + + client.Route = args[1] + + mutex.Lock() + for _, otherClient := range clients { + if otherClient.ID == client.ID { continue } + if otherClient.Route != client.Route { continue } + client.Send([]byte(fmt.Sprintf("join:%d", otherClient.ID))) + client.Send([]byte(fmt.Sprintf("pos:%d:%d:%d", otherClient.ID, otherClient.X, otherClient.Y))) + } + mutex.Unlock() + broadcast <- CursorMessage{ + []byte(fmt.Sprintf("join:%d", client.ID)), + client.Route, + []*CursorClient{ client }, + } + case "char": + if len(args) < 2 { return } + // haha, turns out using ':' as a separator means you can't type ':'s + // i should really be writing byte packets, not this nonsense + msg := byte(':') + if len(args[1]) > 0 { + msg = args[1][0] + } + broadcast <- CursorMessage{ + []byte(fmt.Sprintf("char:%d:%c", client.ID, msg)), + client.Route, + []*CursorClient{ client }, + } + case "nochar": + broadcast <- CursorMessage{ + []byte(fmt.Sprintf("nochar:%d", client.ID)), + client.Route, + []*CursorClient{ client }, + } + case "pos": + if len(args) < 3 { return } + x, err := strconv.ParseInt(args[1], 10, 32) + y, err := strconv.ParseInt(args[2], 10, 32) + if err != nil { return } + client.X = int16(x) + client.Y = int16(y) + broadcast <- CursorMessage{ + []byte(fmt.Sprintf("pos:%d:%d:%d", client.ID, client.X, client.Y)), + client.Route, + []*CursorClient{ client }, + } + } +} + +func Handler(app *model.AppState) http.HandlerFunc { + var upgrader = websocket.Upgrader{ + CheckOrigin: func (r *http.Request) bool { + origin := r.Header.Get("Origin") + return origin == app.Config.BaseUrl + }, + } + + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + conn, err := upgrader.Upgrade(w, r, nil) + if err != nil { + log("Failed to upgrade to WebSocket connection: %v\n", err) + http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) + return + } + defer conn.Close() + + client := CursorClient{ + ID: rand.Int31(), + Conn: conn, + X: 0.0, + Y: 0.0, + Disconnected: false, + } + + err = client.Conn.WriteMessage(websocket.TextMessage, []byte(fmt.Sprintf("id:%d", client.ID))) + if err != nil { + client.Conn.Close() + return + } + + mutex.Lock() + clients[client.ID] = &client + mutex.Unlock() + + // log("Client connected: %s (%s)", fmt.Sprintf("0x%08x", client.ID), client.Conn.RemoteAddr().String()) + + for { + if client.Disconnected { + mutex.Lock() + delete(clients, client.ID) + client.Conn.Close() + mutex.Unlock() + return + } + handleClient(&client) + } + }) +} + +func log(format string, args ...any) { + logString := fmt.Sprintf(format, args...) + fmt.Printf("[%s] [CURSOR] %s\n", time.Now().Format(time.UnixDate), logString) +} diff --git a/go.mod b/go.mod index f8717a2..a1c6c76 100644 --- a/go.mod +++ b/go.mod @@ -10,6 +10,7 @@ require ( require golang.org/x/crypto v0.27.0 // indirect require ( + github.com/gorilla/websocket v1.5.3 // indirect github.com/pelletier/go-toml/v2 v2.2.3 // indirect github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e // indirect ) diff --git a/go.sum b/go.sum index 15259a1..f2ec7e7 100644 --- a/go.sum +++ b/go.sum @@ -2,6 +2,8 @@ filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y= github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg= +github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= +github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/jmoiron/sqlx v1.4.0 h1:1PLqN7S1UYp5t4SrVVnt4nUVNemrDAtxlulVe+Qgm3o= github.com/jmoiron/sqlx v1.4.0/go.mod h1:ZrZ7UsYB/weZdl2Bxg6jCRO9c3YHl8r3ahlKmRT4JLY= github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw= diff --git a/log/log.go b/log/log.go index 3d023ab..2d1c0c2 100644 --- a/log/log.go +++ b/log/log.go @@ -30,6 +30,7 @@ const ( TYPE_ARTWORK string = "artwork" TYPE_FILES string = "files" TYPE_MISC string = "misc" + TYPE_CURSOR string = "cursor" ) type LogLevel int diff --git a/main.go b/main.go index 03e9d77..2252622 100644 --- a/main.go +++ b/main.go @@ -1,11 +1,13 @@ package main import ( + "bufio" "errors" "fmt" stdLog "log" "math" "math/rand" + "net" "net/http" "os" "path/filepath" @@ -17,9 +19,10 @@ import ( "arimelody-web/api" "arimelody-web/colour" "arimelody-web/controller" + "arimelody-web/cursor" + "arimelody-web/log" "arimelody-web/model" "arimelody-web/templates" - "arimelody-web/log" "arimelody-web/view" "github.com/jmoiron/sqlx" @@ -428,6 +431,8 @@ func main() { os.Exit(1) } + go cursor.StartCursor(&app) + // start the web server! mux := createServeMux(&app) fmt.Printf("Now serving at http://%s:%d\n", app.Config.Host, app.Config.Port) @@ -444,6 +449,7 @@ func createServeMux(app *model.AppState) *http.ServeMux { mux.Handle("/api/", http.StripPrefix("/api", api.Handler(app))) mux.Handle("/music/", http.StripPrefix("/music", view.MusicHandler(app))) mux.Handle("/uploads/", http.StripPrefix("/uploads", staticHandler(filepath.Join(app.Config.DataDirectory, "uploads")))) + mux.Handle("/cursor-ws", cursor.Handler(app)) mux.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method == http.MethodHead { w.WriteHeader(http.StatusOK) @@ -536,6 +542,14 @@ type LoggingResponseWriter struct { Status int } +func (lrw *LoggingResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { + hijack, ok := lrw.ResponseWriter.(http.Hijacker) + if !ok { + return nil, nil, errors.New("Server does not support hijacking\n") + } + return hijack.Hijack() +} + func (lrw *LoggingResponseWriter) WriteHeader(status int) { lrw.Status = status lrw.ResponseWriter.WriteHeader(status) diff --git a/public/script/cursor.js b/public/script/cursor.js index a1df6bb..059a2bd 100644 --- a/public/script/cursor.js +++ b/public/script/cursor.js @@ -2,8 +2,9 @@ import config from './config.js'; const CURSOR_TICK_RATE = 1000/30; const CURSOR_LERP_RATE = 1/100; +const CURSOR_FUNCHAR_RATE = 20; const CURSOR_CHAR_MAX_LIFE = 5000; -const CURSOR_MAX_CHARS = 50; +const CURSOR_MAX_CHARS = 64; /** @type HTMLElement */ let cursorContainer; @@ -11,61 +12,57 @@ let cursorContainer; let myCursor; /** @type Map */ let cursors = new Map(); -/** @type Array */ -let chars = new Array(); + +/** @type WebSocket */ +let ws; let running = false; -let lastCursorUpdateTime = 0; -let lastCharUpdateTime = 0; +let lastUpdate = 0; class Cursor { - /** @type number */ id; - - // real coordinates (canonical) - /** @type number */ x; - /** @type number */ y; - - // update coordinates (interpolated) - /** @type number */ rx; - /** @type number */ ry; - /** @type HTMLElement */ #element; /** @type HTMLElement */ - #char; + #charElement; + #funCharCooldown = CURSOR_FUNCHAR_RATE; /** - * @param {number} id + * @param {string} id * @param {number} x * @param {number} y */ constructor(id, x, y) { - this.id = id; + // real coordinates (canonical) this.x = x; this.y = y; + // render coordinates (interpolated) this.rx = x; this.ry = y; + this.msg = ''; + this.funChars = new Array(); const element = document.createElement('i'); element.classList.add('cursor'); - element.id = 'cursor' + id; const colour = randomColour(); element.style.borderColor = colour; element.style.color = colour; - element.innerText = '0x' + navigator.userAgent.hashCode(); - - const char = document.createElement('p'); - char.className = 'char'; - element.appendChild(char); - + cursorContainer.appendChild(element); this.#element = element; - this.#char = char; - cursorContainer.appendChild(this.#element); + + const char = document.createElement('i'); + char.className = 'char'; + cursorContainer.appendChild(char); + this.#charElement = char; + + this.setID(id); } destroy() { this.#element.remove(); - this.#char.remove(); + this.#charElement.remove(); + this.funChars.forEach(char => { + char.destroy(); + }); } /** @@ -85,14 +82,52 @@ class Cursor { this.ry += (this.y - this.ry) * CURSOR_LERP_RATE * deltaTime; this.#element.style.left = this.rx + 'px'; this.#element.style.top = this.ry + 'px'; + this.#charElement.style.left = this.rx + 'px'; + this.#charElement.style.top = (this.ry - 24) + 'px'; + + if (this.#funCharCooldown > 0) + this.#funCharCooldown -= deltaTime; + + if (this.msg.length > 0) { + if (config.cursorFunMode === true) { + if (this.#funCharCooldown <= 0) { + this.#funCharCooldown = CURSOR_FUNCHAR_RATE; + if (this.funChars.length >= CURSOR_MAX_CHARS) { + const char = this.funChars.shift(); + char.destroy(); + } + const yOffset = -20; + const accelMultiplier = 0.002; + this.funChars.push(new FunChar( + this.x + window.scrollX, this.y + window.scrollY + yOffset, + (this.x - this.rx) * accelMultiplier, (this.y - this.ry) * accelMultiplier, + this.msg)); + } + } else { + this.#charElement.innerText = this.msg; + } + } else { + this.#charElement.innerText = ''; + } + + this.funChars.forEach(char => { + if (char.life > CURSOR_CHAR_MAX_LIFE || + char.y > document.body.clientHeight || + char.x < 0 || + char.x > document.body.clientWidth + ) { + this.funChars = this.funChars.filter(c => c !== this); + char.destroy(); + return; + } + char.update(deltaTime); + }); } - /** - * @param {string} text - */ - print(text) { - if (text.length > 1) return; - this.#char.innerText = text; + setID(id) { + this.id = id; + this.#element.id = 'cursor' + id; + this.#element.innerText = '0x' + id.toString(16).slice(0, 8).padStart(8, '0'); } /** @@ -107,12 +142,6 @@ class Cursor { } class FunChar { - /** @type number */ x; y; - /** @type number */ xa; ya; - /** @type number */ r; ra; - /** @type HTMLElement */ element; - /** @type number */ life; - /** * @param {number} x * @param {number} y @@ -144,14 +173,6 @@ class FunChar { */ update(deltaTime) { this.life += deltaTime; - if (this.life > CURSOR_CHAR_MAX_LIFE || - this.y > document.body.clientHeight || - this.x < 0 || - this.x > document.body.clientWidth - ) { - this.destroy(); - return; - } this.x += this.xa * deltaTime; this.y += this.ya * deltaTime; @@ -164,22 +185,10 @@ class FunChar { } destroy() { - chars = chars.filter(char => char !== this); this.element.remove(); } } -String.prototype.hashCode = function() { - var hash = 0; - if (this.length === 0) return hash; - for (let i = 0; i < this.length; i++) { - const chr = this.charCodeAt(i); - hash = ((hash << 5) - hash) + chr; - hash |= 0; // convert to 32-bit integer - } - return Math.round(Math.abs(hash)).toString(16).slice(0, 8).padStart(8, '0'); -}; - /** * @returns string */ @@ -198,6 +207,8 @@ function randomColour() { */ function handleMouseMove(event) { if (!myCursor) return; + if (ws && ws.readyState == WebSocket.OPEN) + ws.send(`pos:${event.x}:${event.y}`); myCursor.move(event.x, event.y); } @@ -211,26 +222,19 @@ function handleMouseUp() { /** * @param {KeyboardEvent} event */ -function handleKeyDown(event) { +function handleKeyPress(event) { if (event.key.length > 1) return; if (event.metaKey || event.ctrlKey) return; - if (config.cursorFunMode === true) { - const yOffset = -20; - const accelMultiplier = 0.002; - if (chars.length < CURSOR_MAX_CHARS) - chars.push(new FunChar( - myCursor.x + window.scrollX, myCursor.y + window.scrollY + yOffset, - (myCursor.x - myCursor.rx) * accelMultiplier, (myCursor.y - myCursor.ry) * accelMultiplier, - event.key)); - } else { - myCursor.print(event.key); - } + if (myCursor.msg === event.key) return; + if (ws && ws.readyState == WebSocket.OPEN) + ws.send(`char:${event.key}`); + myCursor.msg = event.key; } function handleKeyUp() { - if (!config.cursorFunMode) { - myCursor.print(''); - } + if (ws && ws.readyState == WebSocket.OPEN) + ws.send(`nochar`); + myCursor.msg = ''; } /** @@ -239,32 +243,16 @@ function handleKeyUp() { function updateCursors(time) { if (!running) return; - const deltaTime = time - lastCursorUpdateTime; + const deltaTime = time - lastUpdate; cursors.forEach(cursor => { cursor.update(deltaTime); }); - lastCursorUpdateTime = time; + lastUpdate = time; requestAnimationFrame(updateCursors); } -/** - * @param {number} time - */ -function updateChars(time) { - if (!running) return; - - const deltaTime = time - lastCharUpdateTime; - - chars.forEach(char => { - char.update(deltaTime); - }); - - lastCharUpdateTime = time; - requestAnimationFrame(updateChars); -} - function cursorSetup() { if (running) throw new Error('Only one instance of Cursor can run at a time.'); running = true; @@ -273,19 +261,82 @@ function cursorSetup() { cursorContainer.id = 'cursors'; document.body.appendChild(cursorContainer); - myCursor = new Cursor(0, window.innerWidth / 2, window.innerHeight / 2); + myCursor = new Cursor("You!", window.innerWidth / 2, window.innerHeight / 2); cursors.set(0, myCursor); document.addEventListener('mousemove', handleMouseMove); document.addEventListener('mousedown', handleMouseDown); document.addEventListener('mouseup', handleMouseUp); - document.addEventListener('keydown', handleKeyDown); + document.addEventListener('keypress', handleKeyPress); document.addEventListener('keyup', handleKeyUp); requestAnimationFrame(updateCursors); - requestAnimationFrame(updateChars); - console.debug(`Cursor tracking @ ${window.location.pathname}`); + ws = new WebSocket("/cursor-ws"); + + ws.addEventListener("open", () => { + console.log("Cursor connected to server successfully."); + + ws.send(`loc:${window.location.pathname}`); + }); + ws.addEventListener("error", error => { + console.error("Cursor WebSocket error:", error); + }); + ws.addEventListener("close", () => { + console.log("Cursor connection closed."); + }); + + ws.addEventListener("message", event => { + const args = String(event.data).split(":"); + if (args.length == 0) return; + + let id = 0; + /** @type Cursor */ + let cursor; + if (args.length > 1) { + id = Number(args[1]); + cursor = cursors.get(id); + } + + switch (args[0]) { + case 'id': { + myCursor.setID(Number(args[1])); + break; + } + case 'join': { + if (id === myCursor.id) break; + cursors.set(id, new Cursor(id, 0, 0)); + break; + } + case 'leave': { + if (!cursor || cursor === myCursor) break; + cursors.get(id).destroy(); + cursors.delete(id); + break; + } + case 'char': { + if (!cursor || cursor === myCursor) break; + cursor.msg = args[2]; + break; + } + case 'nochar': { + if (!cursor || cursor === myCursor) break; + cursor.msg = ''; + break; + } + case 'pos': { + if (!cursor || cursor === myCursor) break; + cursor.move(Number(args[2]), Number(args[3])); + break; + } + default: { + console.warn("Cursor: Unknown command received from server:", args[0]); + break; + } + } + }); + + console.log(`Cursor tracking @ ${window.location.pathname}`); } function cursorDestroy() { @@ -294,13 +345,9 @@ function cursorDestroy() { document.removeEventListener('mousemove', handleMouseMove); document.removeEventListener('mousedown', handleMouseDown); document.removeEventListener('mouseup', handleMouseUp); - document.removeEventListener('keydown', handleKeyDown); + document.removeEventListener('keypress', handleKeyPress); document.removeEventListener('keyup', handleKeyUp); - chars.forEach(char => { - char.destroy(); - }); - chars = new Array(); cursors.forEach(cursor => { cursor.destroy(); }); @@ -309,7 +356,7 @@ function cursorDestroy() { cursorContainer.remove(); - console.debug(`Cursor no longer tracking.`); + console.log(`Cursor no longer tracking.`); running = false; } diff --git a/public/style/cursor.css b/public/style/cursor.css index e53cee5..8561716 100644 --- a/public/style/cursor.css +++ b/public/style/cursor.css @@ -20,15 +20,16 @@ border-color: var(--on-background) !important; } -#cursors i.cursor .char { +#cursors i.char { position: absolute; - transform: translateY(-44px); margin: 0; + font-style: normal; font-size: 20px; + font-weight: bold; color: var(--on-background); } -#cursors .funchar { +#cursors i.funchar { position: absolute; margin: 0;