-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
381 lines (312 loc) · 9.81 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
// Hover is a work-in-progress [source port] of Hover, a game [originally created] by Eric Undersander in 2000.
//
// The goal of the port is to run on multiple platforms (macOS, Linux, Windows, browser,
// iOS, Android) and improve technical aspects (e.g., support for higher resolutions),
// while preserving the original gameplay.
//
// [source port]: https://en.wikipedia.org/wiki/Source_port
// [originally created]: https://www.flipcode.com/archives/11-21-2000.shtml
package main
import (
"flag"
"fmt"
"image"
_ "image/png"
"log"
"math"
"os"
"runtime"
"runtime/pprof"
"time"
"github.com/go-gl/mathgl/mgl32"
"github.com/go-gl/mathgl/mgl64"
"github.com/goxjs/gl"
"github.com/goxjs/glfw"
)
var stateFileFlag = flag.String("state-file", "Hover.state", "File to save/load state.")
var cpuprofileFlag = flag.String("cpuprofile", "", "Write cpu profile to file.")
var startedProcess = time.Now()
var windowSize [2]int
var wireframe bool
func init() {
runtime.LockOSThread()
}
func main() {
flag.Parse()
if *cpuprofileFlag != "" {
f, err := os.Create(*cpuprofileFlag)
if err != nil {
log.Fatal(err)
}
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
}
if *stateFileFlag != "" {
err := loadState(*stateFileFlag)
fmt.Println("loadState:", err)
}
err := glfw.Init(gl.ContextWatcher)
if err != nil {
log.Fatalln("glfw.Init:", err)
}
defer glfw.Terminate()
//glfw.WindowHint(glfw.Samples, 8) // Anti-aliasing.
window, err := glfw.CreateWindow(1024, 800, "Hover", nil, nil)
if err != nil {
log.Fatalln(err)
}
window.MakeContextCurrent()
fmt.Printf("OpenGL: %s %s %s; %v samples.\n", gl.GetString(gl.VENDOR), gl.GetString(gl.RENDERER), gl.GetString(gl.VERSION), gl.GetInteger(gl.SAMPLES))
fmt.Printf("GLSL: %s.\n", gl.GetString(gl.SHADING_LANGUAGE_VERSION))
glfw.SwapInterval(1) // Vsync.
framebufferSizeCallback := func(w *glfw.Window, framebufferSize0, framebufferSize1 int) {
gl.Viewport(0, 0, framebufferSize0, framebufferSize1)
windowSize[0], windowSize[1] = w.GetSize()
}
{
var framebufferSize [2]int
framebufferSize[0], framebufferSize[1] = window.GetFramebufferSize()
framebufferSizeCallback(window, framebufferSize[0], framebufferSize[1])
}
window.SetFramebufferSizeCallback(framebufferSizeCallback)
mouseMovement := func(_ *glfw.Window, xpos, ypos, xdelta, ydelta float64) {
sliders := []float64{xdelta, ydelta}
{
isButtonPressed := [2]bool{
window.GetMouseButton(glfw.MouseButton1) != glfw.Release,
window.GetMouseButton(glfw.MouseButton2) != glfw.Release,
}
var moveSpeed = 1.0
const rotateSpeed = 0.3
if window.GetKey(glfw.KeyLeftShift) != glfw.Release || window.GetKey(glfw.KeyRightShift) != glfw.Release {
moveSpeed *= 0.01
}
if isButtonPressed[0] && !isButtonPressed[1] {
camera.RH += rotateSpeed * sliders[0]
} else if isButtonPressed[0] && isButtonPressed[1] {
camera.X += moveSpeed * sliders[0] * math.Cos(mgl64.DegToRad(camera.RH))
camera.Y += -moveSpeed * sliders[0] * math.Sin(mgl64.DegToRad(camera.RH))
} else if !isButtonPressed[0] && isButtonPressed[1] {
camera.RH += rotateSpeed * sliders[0]
}
if isButtonPressed[0] && !isButtonPressed[1] {
camera.X -= moveSpeed * sliders[1] * math.Sin(mgl64.DegToRad(camera.RH))
camera.Y -= moveSpeed * sliders[1] * math.Cos(mgl64.DegToRad(camera.RH))
} else if isButtonPressed[0] && isButtonPressed[1] {
camera.Z -= moveSpeed * sliders[1]
} else if !isButtonPressed[0] && isButtonPressed[1] {
camera.RV -= rotateSpeed * sliders[1]
}
for camera.RH < 0 {
camera.RH += 360
}
for camera.RH >= 360 {
camera.RH -= 360
}
if camera.RV > 90 {
camera.RV = 90
}
if camera.RV < -90 {
camera.RV = -90
}
}
}
window.SetMouseMovementCallback(mouseMovement)
window.SetMouseButtonCallback(func(_ *glfw.Window, button glfw.MouseButton, action glfw.Action, mods glfw.ModifierKey) {
isButtonPressed := [2]bool{
window.GetMouseButton(glfw.MouseButton1) != glfw.Release,
window.GetMouseButton(glfw.MouseButton2) != glfw.Release,
}
if isButtonPressed[0] || isButtonPressed[1] {
window.SetInputMode(glfw.CursorMode, glfw.CursorDisabled)
} else {
window.SetInputMode(glfw.CursorMode, glfw.CursorNormal)
}
})
window.SetKeyCallback(func(w *glfw.Window, key glfw.Key, scancode int, action glfw.Action, mods glfw.ModifierKey) {
if action == glfw.Press {
switch key {
case glfw.Key1, glfw.Key2, glfw.Key3, glfw.Key4, glfw.Key5, glfw.Key6, glfw.Key7, glfw.Key8:
player.X = float64(track.Header.RacerStartPositions[key-glfw.Key1][0])
player.Y = float64(track.Header.RacerStartPositions[key-glfw.Key1][2])
player.Z = float64(track.Header.RacerStartPositions[key-glfw.Key1][1])
player.Vel = mgl64.Vec3{}
player.Pitch = 0
player.Roll = 0
player.R = 0
case glfw.KeyEscape:
window.SetShouldClose(true)
case glfw.KeyF1:
wireframe = !wireframe
case glfw.KeyF2:
cameraIndex = (cameraIndex + 1) % len(cameras)
switch cameraIndex {
case 0:
window.SetInputMode(glfw.CursorMode, glfw.CursorNormal)
case 1:
window.SetInputMode(glfw.CursorMode, glfw.CursorHidden)
}
case glfw.KeyF5: // Quick-save.
if *stateFileFlag != "" {
err := saveState(*stateFileFlag)
fmt.Println("saveState:", err)
}
case glfw.KeyF9: // Quick-load.
if *stateFileFlag != "" {
err := loadState(*stateFileFlag)
fmt.Println("loadState:", err)
}
}
}
})
fpsWidget := NewFpsWidget(mgl64.Vec2{0, 60})
track, err = loadTrack("track1.dat")
if err != nil {
log.Fatalln(err)
}
err = loadModel()
if err != nil {
log.Fatalln(err)
}
err = loadDebugShape()
if err != nil {
log.Fatalln(err)
}
gl.ClearColor(0.85, 0.85, 0.85, 1)
gl.Clear(gl.COLOR_BUFFER_BIT)
//gl.Enable(gl.CULL_FACE)
gl.Enable(gl.DEPTH_TEST)
gl.Enable(0x8642) // gl.VERTEX_PROGRAM_POINT_SIZE
gl.Enable(0x0B10) // gl.POINT_SMOOTH
fmt.Printf("Loaded in %v ms.\n", time.Since(startedProcess).Seconds()*1000)
// ---
firstFrame := true
for !window.ShouldClose() {
frameStartTime := time.Now()
glfw.PollEvents()
// Input
cameras[cameraIndex].Input(window)
player.Input(window)
player.Physics()
gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
pMatrix = Set3DProjection()
mvMatrix = cameras[cameraIndex].Apply()
track.Render()
player.Render()
//Set2DProjection()
//fpsWidget.Render()
fpsWidget.PushTimeToRender(time.Since(frameStartTime).Seconds() * 1000)
window.SwapBuffers()
runtime.Gosched()
fpsWidget.PushTimeTotal(time.Since(frameStartTime).Seconds() * 1000)
if firstFrame {
fmt.Printf("First frame in %v ms.\n", time.Since(startedProcess).Seconds()*1000)
firstFrame = false
}
}
}
// ---
/*func Set2DProjection() mgl32.Mat4 {
// Update the projection matrix
gl.MatrixMode(gl.PROJECTION)
gl.LoadIdentity()
gl.Ortho(0, float64(windowSize[0]), float64(windowSize[1]), 0, -1, 1)
gl.MatrixMode(gl.MODELVIEW)
gl.LoadIdentity()
}*/
func Set3DProjection() mgl32.Mat4 {
return mgl32.Perspective(mgl32.DegToRad(45), float32(windowSize[0])/float32(windowSize[1]), 0.1, 1000)
}
// ---
func loadTexture(path string) (gl.Texture, error) {
fmt.Printf("Trying to load texture %q: ", path)
started := time.Now()
defer func() {
fmt.Println("taken:", time.Since(started))
}()
// Open the file
file, err := glfw.Open(path)
if err != nil {
return gl.Texture{}, err
}
defer file.Close()
// Decode the image
img, _, err := image.Decode(file)
if err != nil {
return gl.Texture{}, err
}
bounds := img.Bounds()
fmt.Printf("loaded %vx%v texture.\n", bounds.Dx(), bounds.Dy())
var pix []byte
switch img := img.(type) {
case *image.RGBA:
pix = img.Pix
case *image.NRGBA:
pix = img.Pix
default:
panic("Unsupported image type.")
}
texture := gl.CreateTexture()
gl.BindTexture(gl.TEXTURE_2D, texture)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
gl.TexImage2D(gl.TEXTURE_2D, 0, bounds.Dx(), bounds.Dy(), gl.RGBA, gl.UNSIGNED_BYTE, pix)
gl.GenerateMipmap(gl.TEXTURE_2D)
if glError := gl.GetError(); glError != 0 {
return gl.Texture{}, fmt.Errorf("gl.GetError: %v", glError)
}
return texture, nil
}
// ---
// TODO: Import the stuff below instead of copy-pasting it.
// ---
/*func DrawBorderlessBox(pos, size mgl64.Vec2, backgroundColor mgl64.Vec3) {
gl.Color3dv((*float64)(&backgroundColor[0]))
gl.Rectd(float64(pos[0]), float64(pos[1]), float64(pos.Add(size)[0]), float64(pos.Add(size)[1]))
}*/
// ---
type Widget struct {
pos mgl64.Vec2
size mgl64.Vec2
}
func NewWidget(pos, size mgl64.Vec2) Widget {
return Widget{pos: pos, size: size}
}
// ---
type fpsSample struct{ Render, Total float64 }
type FpsWidget struct {
Widget
samples []fpsSample
}
func NewFpsWidget(pos mgl64.Vec2) *FpsWidget {
return &FpsWidget{Widget: NewWidget(pos, mgl64.Vec2{})}
}
func (w *FpsWidget) Render() {
/*gl.PushMatrix()
defer gl.PopMatrix()
gl.Translated(float64(w.pos[0]), float64(w.pos[1]), 0)
gl.Begin(gl.LINES)
gl.Color3d(1, 0, 0)
gl.Vertex2d(float64(0), float64(-1000.0/60))
gl.Vertex2d(float64(30), float64(-1000.0/60))
gl.End()
for index, sample := range w.samples {
var color mgl64.Vec3
if sample.Render <= 1000.0/60*1.25 {
color = mgl64.Vec3{0, 0, 0}
} else {
color = mgl64.Vec3{1, 0, 0}
}
DrawBorderlessBox(mgl64.Vec2{float64(30 - len(w.samples) + index), -sample.Render}, mgl64.Vec2{1, sample.Render}, color)
DrawBorderlessBox(mgl64.Vec2{float64(30 - len(w.samples) + index), -sample.Total}, mgl64.Vec2{1, sample.Total - sample.Render}, mgl64.Vec3{0.65, 0.65, 0.65})
}*/
}
func (w *FpsWidget) PushTimeToRender(sample float64) {
w.samples = append(w.samples, fpsSample{Render: sample})
if len(w.samples) > 30 {
w.samples = w.samples[len(w.samples)-30:]
}
}
func (w *FpsWidget) PushTimeTotal(sample float64) {
w.samples[len(w.samples)-1].Total = sample
}