r_place/go/util.go

82 lines
2.2 KiB
Go
Raw Normal View History

2022-05-26 12:14:36 +00:00
package main
import (
2022-05-27 14:12:27 +00:00
"fmt"
"sync"
2022-05-26 12:14:36 +00:00
)
2022-05-27 14:12:27 +00:00
type Message struct {
X uint32 `json:"x"`
Y uint32 `json:"y"`
2022-05-26 12:14:36 +00:00
Color uint8 `json:"color"`
2022-05-26 13:01:09 +00:00
Timestamp int64 `json:"timestamp"`
2022-05-26 12:14:36 +00:00
UserID uint64 `json:"userid"`
}
2022-05-27 14:12:27 +00:00
type pixel struct {
Color uint8 `json:"c"`
Timestamp int64 `json:"ts"`
UserID uint64 `json:"uid"`
2022-05-27 14:12:27 +00:00
}
type pixelContainer struct {
Pixel pixel `json:"p"`
mutex sync.Mutex
2022-05-27 16:00:19 +00:00
}
type image struct {
Width uint32 `json:"Width"`
Height uint32 `json:"Height"`
Pixels []pixelContainer `json:"Pixels"`
2022-05-27 16:00:19 +00:00
}
func GetImage(w uint32, h uint32) image {
Pixels := make([]pixelContainer, w*h)
2022-05-27 14:12:27 +00:00
for i := 0; i < int(w*h); i++ {
Pixels[i] = pixelContainer{Pixel: pixel{Color: 0, Timestamp: 0, UserID: 0}, mutex: sync.Mutex{}}
2022-05-27 14:12:27 +00:00
}
return image{Width: w, Height: h, Pixels: Pixels}
2022-05-27 14:12:27 +00:00
}
func (p *pixelContainer) setColor(color uint8, timestamp int64, userid uint64) {
p.mutex.Lock()
defer p.mutex.Unlock()
if timestamp > p.Pixel.Timestamp {
p.Pixel.Color = color
p.Pixel.Timestamp = timestamp
p.Pixel.UserID = userid
2022-05-27 14:12:27 +00:00
}
}
2022-05-31 14:15:09 +00:00
func (img *image) SetPixel(message Message) int {
if message.X >= img.Width || message.Y >= img.Height || message.X < 0 || message.Y < 0 {
2022-05-27 14:12:27 +00:00
fmt.Printf("User %d tried accessing out of bounds \n", message.UserID)
2022-05-31 14:15:09 +00:00
return 1
2022-05-27 14:12:27 +00:00
}
2022-06-05 13:44:28 +00:00
if message.Color > 255 || message.Color < 0 {
fmt.Printf("User %d tried setting non existent color %d \n", message.UserID, message.Color)
2022-05-31 14:15:09 +00:00
return 1
2022-05-27 14:12:27 +00:00
}
pos := uint32(message.X)*uint32(img.Width) + uint32(message.Y)
img.Pixels[pos].setColor(message.Color, message.Timestamp, message.UserID)
2022-05-31 14:15:09 +00:00
return 0
2022-05-26 12:14:36 +00:00
}
2022-05-27 16:00:19 +00:00
func comparePixels(pixel1 *pixelContainer, pixel2 *pixelContainer) bool {
return pixel1.Pixel.Color == pixel2.Pixel.Color &&
pixel1.Pixel.Timestamp == pixel2.Pixel.Timestamp &&
pixel1.Pixel.UserID == pixel2.Pixel.UserID
2022-05-27 16:00:19 +00:00
}
func (img *image) GetDiff(img2 *image) image {
diff := GetImage(img.Width, img.Height)
for i := 0; i < int(img.Width*img.Height); i++ {
if !comparePixels(&img.Pixels[i], &img2.Pixels[i]) {
diff.Pixels[i].Pixel.Color = img2.Pixels[i].Pixel.Color
diff.Pixels[i].Pixel.UserID = img2.Pixels[i].Pixel.UserID
diff.Pixels[i].Pixel.Timestamp = img2.Pixels[i].Pixel.Timestamp
2022-05-27 16:00:19 +00:00
}
}
return diff
}