forked from lunar-hill/renderer
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
469 lines (387 loc) · 11.5 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
package main
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"image"
"image/draw"
"image/png"
"io"
"net/http"
"os"
"github.com/gofrs/uuid"
fauxgl "github.com/hawl1/brickgl"
"github.com/nfnt/resize"
"github.com/spf13/pflag"
)
const (
scale = 3
fovy = 50
near = 0.1
far = 1000
)
var (
eye = fauxgl.V(0.75, 0.85, 2)
center = fauxgl.V(0, 0.06, 0)
up = fauxgl.V(0, 1, 0)
light = fauxgl.V(0, 6, 4).Normalize()
// Default values for host, port, and access key
defaultHost = "0.0.0.0"
defaultPort = 7231
defaultAccessKey = "change-it-or-die"
)
// RenderEvent input data structure
type RenderEvent struct {
AvatarJSON string `json:"avatarJSON"`
Size int `json:"size"`
}
// Avatar structure for avatar data
type Avatar struct {
UserID int `json:"user_id"`
Items map[string]interface{} `json:"items"`
Colors map[string]string `json:"colors"`
}
// ImageResponse structure for response data
type ImageResponse struct {
UUID string `json:"uuid"`
Image string `json:"image"`
}
func main() {
// Parse command-line flags
host := pflag.StringP("host", "H", defaultHost, "Host IP address to listen on")
port := pflag.IntP("port", "p", defaultPort, "Port to listen on")
accessKey := pflag.String("accesskey", defaultAccessKey, "Access key for authentication")
pflag.Parse()
http.HandleFunc("/render", func(w http.ResponseWriter, r *http.Request) {
HandleRenderEvent(w, r, *accessKey)
})
addr := fmt.Sprintf("%s:%d", *host, *port)
fmt.Printf("Server is listening on %s...\n", addr)
err := http.ListenAndServe(addr, nil)
if err != nil {
panic(err)
}
}
// LoadMeshFromURL loads mesh from url
func LoadMeshFromURL(url string) *fauxgl.Mesh {
resp, err := http.Get(url)
if err != nil {
panic(err)
}
mesh, _ := fauxgl.LoadOBJFromReader(resp.Body)
return mesh
}
func LoadMeshFromFile(filepath string) *fauxgl.Mesh {
file, err := os.Open(filepath)
if err != nil {
panic(err)
}
defer file.Close()
mesh, err := fauxgl.LoadOBJFromReader(file)
if err != nil {
panic(err)
}
return mesh
}
// LoadTexture loads texture from URL
func LoadTexture(url string) fauxgl.Texture {
resp, err := http.Get(url)
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
panic(err)
}
return fauxgl.TexFromBytes(body)
}
func LoadTextureFromFile(filepath string) fauxgl.Texture {
file, err := os.Open(filepath)
if err != nil {
panic(err)
}
defer file.Close()
body, err := io.ReadAll(file)
if err != nil {
panic(err)
}
return fauxgl.TexFromBytes(body)
}
// LoadItem loads item from url
func LoadItem(item int, scene *fauxgl.Scene) {
if item != 0 {
resp, err := http.Get(fmt.Sprintf("https://api.brick-hill.com/v1/assets/getPoly/1/%d", item))
if err != nil {
panic(err)
}
defer resp.Body.Close()
var data []map[string]string
err = json.NewDecoder(resp.Body).Decode(&data)
if err != nil {
panic(err)
}
mesh := data[0]["mesh"]
mesh = mesh[len("asset://"):]
texture := data[0]["texture"]
texture = texture[len("asset://"):]
scene.AddObject(&fauxgl.Object{
Mesh: LoadMeshFromURL("https://api.brick-hill.com/v1/assets/get/" + mesh),
Texture: LoadTexture("https://api.brick-hill.com/v1/assets/get/" + texture),
})
}
}
// HandleRenderEvent handles the rendering HTTP request
func HandleRenderEvent(w http.ResponseWriter, r *http.Request, accessKey string) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// Validate access key
if accessKey != "" {
rAccessKey := r.Header.Get("X-Access-Key")
if rAccessKey != accessKey {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
}
var e RenderEvent
err := json.NewDecoder(r.Body).Decode(&e)
if err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
var avatarJSON string
if e.AvatarJSON == "" {
// Use the default JSON string if AvatarJSON is empty
avatarJSON = "{\"user_id\":13,\"items\":{\"face\":0,\"hats\":[20121,0,0,0,0],\"head\":0,\"tool\":6929,\"pants\":0,\"shirt\":368750,\"figure\":0,\"tshirt\":187683},\"colors\":{\"head\":\"f3b700\",\"torso\":\"929292\",\"left_arm\":\"f3b700\",\"left_leg\":\"e6e6e6\",\"right_arm\":\"f3b700\",\"right_leg\":\"e6e6e6\"}}"
} else {
avatarJSON = e.AvatarJSON
}
avatar := Avatar{}
err = json.Unmarshal([]byte(avatarJSON), &avatar)
if err != nil {
http.Error(w, "Invalid avatar JSON", http.StatusBadRequest)
return
}
aspect := float64(e.Size) / float64(e.Size)
matrix := fauxgl.LookAt(eye, center, up).Perspective(fovy, aspect, near, far)
shader := fauxgl.NewPhongShader(matrix, light, eye)
context := fauxgl.NewContext(e.Size, e.Size, scale, shader)
scene := fauxgl.NewScene(context)
shirt := image.NewRGBA(image.Rect(0, 0, 1, 1))
if shirtValue, ok := avatar.Items["shirt"].(float64); ok && shirtValue != 0 {
resp, err := http.Get(fmt.Sprintf("https://api.brick-hill.com/v1/assets/getPoly/1/%d", int(shirtValue)))
if err != nil {
panic(err)
}
defer resp.Body.Close()
var data []map[string]string
err = json.NewDecoder(resp.Body).Decode(&data)
if err != nil {
panic(err)
}
if len(data) == 0 {
panic("API response does not contain expected data")
}
texture := data[0]["texture"]
texture = texture[len("asset://"):]
resp, err = http.Get("https://api.brick-hill.com/v1/assets/get/" + texture)
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
panic(err)
}
img, _, err := image.Decode(bytes.NewReader(body))
if err != nil {
panic(err)
}
rgba := image.NewRGBA(img.Bounds())
draw.Draw(rgba, rgba.Bounds(), img, image.Point{0, 0}, draw.Src)
shirt = rgba
}
tshirt := image.NewRGBA(image.Rect(0, 0, 836, 836))
if tshirtValue, ok := avatar.Items["tshirt"].(float64); ok && tshirtValue != 0 {
resp, err := http.Get(fmt.Sprintf("https://api.brick-hill.com/v1/assets/getPoly/1/%d", int(tshirtValue)))
if err != nil {
panic(err)
}
defer resp.Body.Close()
var data []map[string]string
err = json.NewDecoder(resp.Body).Decode(&data)
if err != nil {
panic(err)
}
texture := data[0]["texture"]
texture = texture[len("asset://"):]
resp, err = http.Get("https://api.brick-hill.com/v1/assets/get/" + texture)
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
panic(err)
}
img, _, err := image.Decode(bytes.NewReader(body))
if err != nil {
panic(err)
}
rgba := image.NewRGBA(img.Bounds())
draw.Draw(rgba, rgba.Bounds(), img, image.Point{0, 0}, draw.Src)
tshirt = rgba
resizedTshirt := resize.Resize(126, 126, tshirt, resize.Lanczos3)
blankTemplate := image.NewRGBA(image.Rect(0, 0, 836, 836))
draw.Draw(blankTemplate, image.Rect(183, 87, 309, 213), resizedTshirt, image.Point{}, draw.Src)
tshirt = blankTemplate
}
combinedWidth := shirt.Bounds().Max.X
combinedHeight := shirt.Bounds().Max.Y
combined := image.NewRGBA(image.Rect(0, 0, combinedWidth, combinedHeight))
draw.Draw(combined, shirt.Bounds(), shirt, image.Point{}, draw.Over)
draw.Draw(combined, tshirt.Bounds(), tshirt, image.Point{}, draw.Over)
var tshirtBuf bytes.Buffer
if err := png.Encode(&tshirtBuf, combined); err != nil {
panic(err)
}
combinedShirt := fauxgl.NewImageTexture(combined)
pants := fauxgl.NewImageTexture(image.NewRGBA(image.Rect(0, 0, 1, 1)))
if pantsValue, ok := avatar.Items["pants"].(float64); ok && pantsValue != 0 {
resp, err := http.Get(fmt.Sprintf("https://api.brick-hill.com/v1/assets/getPoly/1/%d", int(pantsValue)))
if err != nil {
panic(err)
}
defer resp.Body.Close()
var data []map[string]string
err = json.NewDecoder(resp.Body).Decode(&data)
if err != nil {
panic(err)
}
texture := data[0]["texture"]
texture = texture[len("asset://"):]
pants = LoadTexture("https://api.brick-hill.com/v1/assets/get/" + texture)
}
mesh := LoadMeshFromFile("asset/Torso.obj")
scene.AddObject(&fauxgl.Object{
Mesh: mesh,
Color: fauxgl.HexColor(avatar.Colors["torso"]),
Texture: combinedShirt,
})
if headValue, ok := avatar.Items["head"].(float64); ok && headValue != 0 {
resp, err := http.Get(fmt.Sprintf("https://api.brick-hill.com/v1/assets/getPoly/1/%d", int(headValue)))
if err != nil {
panic(err)
}
defer resp.Body.Close()
var data []map[string]string
err = json.NewDecoder(resp.Body).Decode(&data)
if err != nil {
panic(err)
}
if len(data) > 0 {
meshdat := data[0]["mesh"]
meshdat = meshdat[len("asset://"):]
mesh = LoadMeshFromURL("https://api.brick-hill.com/v1/assets/get/" + meshdat)
}
} else {
mesh = LoadMeshFromFile("asset/Head.obj")
}
if faceValue, ok := avatar.Items["face"].(float64); ok && faceValue != 0 {
resp, err := http.Get(fmt.Sprintf("https://api.brick-hill.com/v1/assets/getPoly/1/%d", int(faceValue)))
if err != nil {
panic(err)
}
defer resp.Body.Close()
var data []map[string]string
err = json.NewDecoder(resp.Body).Decode(&data)
if err != nil {
panic(err)
}
if len(data) > 0 {
texture := data[0]["texture"]
texture = texture[len("asset://"):]
scene.AddObject(&fauxgl.Object{
Mesh: mesh,
Color: fauxgl.HexColor(avatar.Colors["head"]),
Texture: LoadTexture("https://api.brick-hill.com/v1/assets/get/" + texture),
})
}
} else {
// Load the default face texture
scene.AddObject(&fauxgl.Object{
Mesh: mesh,
Color: fauxgl.HexColor(avatar.Colors["head"]),
Texture: LoadTextureFromFile("asset/DefaultFace.png"),
})
}
scene.AddObject(&fauxgl.Object{
Mesh: LoadMeshFromFile("asset/LeftArm.obj"),
Color: fauxgl.HexColor(avatar.Colors["left_arm"]),
Texture: combinedShirt,
})
scene.AddObject(&fauxgl.Object{
Mesh: LoadMeshFromFile("asset/LeftLeg.obj"),
Color: fauxgl.HexColor(avatar.Colors["left_leg"]),
Texture: pants,
})
if toolValue, ok := avatar.Items["tool"].(float64); ok && toolValue != 0 {
mesh = LoadMeshFromFile("asset/ArmHold.obj")
scene.AddObject(&fauxgl.Object{
Mesh: mesh,
Color: fauxgl.HexColor(avatar.Colors["right_arm"]),
Texture: combinedShirt,
})
LoadItem(int(toolValue), scene)
} else {
mesh = LoadMeshFromFile("asset/RightArm.obj")
scene.AddObject(&fauxgl.Object{
Mesh: mesh,
Color: fauxgl.HexColor(avatar.Colors["right_arm"]),
Texture: combinedShirt,
})
}
mesh = LoadMeshFromFile("asset/RightLeg.obj")
scene.AddObject(&fauxgl.Object{
Mesh: mesh,
Color: fauxgl.HexColor(avatar.Colors["right_leg"]),
Texture: pants,
})
hats, ok := avatar.Items["hats"].([]interface{})
if ok {
for _, hatValue := range hats {
if hat, ok := hatValue.(float64); ok && hat != 0 {
LoadItem(int(hat), scene)
}
}
}
shader.AmbientColor = fauxgl.HexColor("AAA")
shader.DiffuseColor = fauxgl.HexColor("777")
shader.SpecularPower = 0
newMatrix := scene.FitObjectsToScene(eye, center, up, fovy, aspect, near, far)
shader.Matrix = newMatrix
scene.Draw()
outImg := context.Image()
buf := new(bytes.Buffer)
if err := png.Encode(buf, outImg); err != nil {
// Handle error
fmt.Println("Error encoding image to PNG:", err)
return
}
// Encode PNG bytes to base64
encodedImage := base64.StdEncoding.EncodeToString(buf.Bytes())
// Generate UUID
namespaceUUID := uuid.Must(uuid.FromString("6ba7b810-9dad-11d1-80b4-00c04fd430c8"))
uuid := uuid.NewV5(namespaceUUID, "lunar-hill")
// Create the response object
resp := ImageResponse{
Image: encodedImage,
UUID: uuid.String(),
}
// Return JSON response
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(resp)
}