Пример #1
5
func main() {
	// Initialize GLFW for window management
	glfw.SetErrorCallback(glfwErrorCallback)
	if !glfw.Init() {
		panic("failed to initialize glfw")
	}
	defer glfw.Terminate()

	glfw.WindowHint(glfw.Resizable, glfw.False)
	glfw.WindowHint(glfw.ContextVersionMajor, 3)
	glfw.WindowHint(glfw.ContextVersionMinor, 3)
	glfw.WindowHint(glfw.OpenglForwardCompatible, glfw.True)    // Necessary for OS X
	glfw.WindowHint(glfw.OpenglProfile, glfw.OpenglCoreProfile) // Necessary for OS X
	glfw.WindowHint(glfw.OpenglDebugContext, glfw.True)
	window, err := glfw.CreateWindow(WindowWidth, WindowHeight, "Cube", nil, nil)
	if err != nil {
		panic(err)
	}
	window.MakeContextCurrent()

	// Initialize Glow
	if err := gl.Init(); err != nil {
		panic(err)
	}

	// Note that it is possible to use GL functions spanning multiple versions
	if err := gl4.Init(); err != nil {
		fmt.Printf("Could not initialize GL 4.4 (non-fatal)")
	}

	if gl.ARB_debug_output {
		gl.Enable(gl.DEBUG_OUTPUT_SYNCHRONOUS_ARB)
		gl.DebugMessageCallbackARB(gl.DebugProc(glDebugCallback), gl.Ptr(nil))
		// Trigger an error to demonstrate debug output
		gl.Enable(gl.CONTEXT_FLAGS)
	}

	version := gl.GoStr(gl.GetString(gl.VERSION))
	fmt.Println("OpenGL version", version)

	// Configure the vertex and fragment shaders
	program, err := newProgram(vertexShader, fragmentShader)
	if err != nil {
		panic(err)
	}
	gl.UseProgram(program)

	projection := mgl32.Perspective(70.0, float32(WindowWidth)/WindowHeight, 0.1, 10.0)
	projectionUniform := gl.GetUniformLocation(program, gl.Str("projection\x00"))
	gl.UniformMatrix4fv(projectionUniform, 1, false, &projection[0])

	camera := mgl32.LookAtV(mgl32.Vec3{3, 3, 3}, mgl32.Vec3{0, 0, 0}, mgl32.Vec3{0, 1, 0})
	cameraUniform := gl.GetUniformLocation(program, gl.Str("camera\x00"))
	gl.UniformMatrix4fv(cameraUniform, 1, false, &camera[0])

	model := mgl32.Ident4()
	modelUniform := gl.GetUniformLocation(program, gl.Str("model\x00"))
	gl.UniformMatrix4fv(modelUniform, 1, false, &model[0])

	textureUniform := gl.GetUniformLocation(program, gl.Str("tex\x00"))
	gl.Uniform1i(textureUniform, 0)

	gl.BindFragDataLocation(program, 0, gl.Str("outputColor\x00"))

	// Load the texture
	texture, err := newTexture("square.png")
	if err != nil {
		panic(err)
	}

	// Configure the vertex data
	var vao uint32
	gl.GenVertexArrays(1, &vao)
	gl.BindVertexArray(vao)

	var vbo uint32
	gl.GenBuffers(1, &vbo)
	gl.BindBuffer(gl.ARRAY_BUFFER, vbo)
	gl.BufferData(gl.ARRAY_BUFFER, len(cubeVertices)*4, gl.Ptr(cubeVertices), gl.STATIC_DRAW)

	vertAttrib := uint32(gl.GetAttribLocation(program, gl.Str("vert\x00")))
	gl.EnableVertexAttribArray(vertAttrib)
	gl.VertexAttribPointer(vertAttrib, 3, gl.FLOAT, false, 5*4, gl.PtrOffset(0))

	texCoordAttrib := uint32(gl.GetAttribLocation(program, gl.Str("vertTexCoord\x00")))
	gl.EnableVertexAttribArray(texCoordAttrib)
	gl.VertexAttribPointer(texCoordAttrib, 2, gl.FLOAT, false, 5*4, gl.PtrOffset(3*4))

	// Configure global settings
	gl.Enable(gl.DEPTH_TEST)
	gl.DepthFunc(gl.LESS)
	gl.ClearColor(1.0, 1.0, 1.0, 1.0)

	angle := 0.0
	previousTime := glfw.GetTime()

	for !window.ShouldClose() {
		gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)

		// Update
		time := glfw.GetTime()
		elapsed := time - previousTime
		previousTime = time

		angle += elapsed
		model = mgl32.HomogRotate3D(float32(angle), mgl32.Vec3{0, 1, 0})

		// Render
		gl.UseProgram(program)
		gl.UniformMatrix4fv(modelUniform, 1, false, &model[0])

		gl.BindVertexArray(vao)

		gl.ActiveTexture(gl.TEXTURE0)
		gl.BindTexture(gl.TEXTURE_2D, texture)

		gl.DrawArrays(gl.TRIANGLES, 0, 6*2*3)

		// Maintenance
		window.SwapBuffers()
		glfw.PollEvents()
	}
}
Пример #2
0
func main() {
	runtime.LockOSThread()

	if !glfw.Init() {
		fmt.Fprintf(os.Stderr, "Can't open GLFW")
		return
	}
	defer glfw.Terminate()

	glfw.WindowHint(glfw.Samples, 4)
	glfw.WindowHint(glfw.ContextVersionMajor, 3)
	glfw.WindowHint(glfw.ContextVersionMinor, 3)
	glfw.WindowHint(glfw.OpenglProfile, glfw.OpenglCoreProfile)
	glfw.WindowHint(glfw.OpenglForwardCompatible, glfw.True) // needed for macs

	window, err := glfw.CreateWindow(1024, 768, "Tutorial 1", nil, nil)
	if err != nil {
		fmt.Fprintf(os.Stderr, "%v\n", err)
		return
	}

	window.MakeContextCurrent()

	gl.Init()
	gl.GetError() // Ignore error
	window.SetInputMode(glfw.StickyKeys, 1)

	gl.ClearColor(0., 0., 0.4, 0.)
	// Equivalent to a do... while
	for ok := true; ok; ok = (window.GetKey(glfw.KeyEscape) != glfw.Press && !window.ShouldClose()) {
		window.SwapBuffers()
		glfw.PollEvents()
	}

}
Пример #3
0
// Initialize creates new window
func (e *E) Initialize(title string, params Params, state State) error {
	if !glfw3.Init() {
		return fmt.Errorf("unable to initialize glfw")
	}
	if e.window != nil {
		return fmt.Errorf("Initialize error: window is not nil")
	}

	glfw3.SetErrorCallback(OnError)

	glfw3.WindowHint(glfw3.Resizable, glfw3.True)
	glfw3.WindowHint(glfw3.ContextVersionMajor, params.Version[0])
	glfw3.WindowHint(glfw3.ContextVersionMinor, params.Version[1])
	glfw3.WindowHint(glfw3.OpenglProfile, glfw3.OpenglCoreProfile)
	glfw3.WindowHint(glfw3.OpenglDebugContext, glfw3.True)

	size := params.Size
	window, err := glfw3.CreateWindow(size[0], size[1], title, nil, nil)
	if err != nil {
		return err
	}

	window.MakeContextCurrent()
	window.SetKeyCallback(e.OnKey)
	window.SetFramebufferSizeCallback(e.OnFramebufferResize)

	e.window = window
	e.state = state

	return nil
}
Пример #4
0
func main() {
	glfw.SetErrorCallback(glfwErrorCallback)
	if !glfw.Init() {
		panic("failed to initialize glfw")
	}
	defer glfw.Terminate()

	glfw.WindowHint(glfw.Resizable, glfw.False)
	glfw.WindowHint(glfw.ContextVersionMajor, 2)
	glfw.WindowHint(glfw.ContextVersionMinor, 1)
	window, err := glfw.CreateWindow(800, 600, "Cube", nil, nil)
	if err != nil {
		panic(err)
	}
	window.MakeContextCurrent()

	if err := gl.Init(); err != nil {
		panic(err)
	}

	texture = newTexture("square.png")
	defer gl.DeleteTextures(1, &texture)

	setupScene()
	for !window.ShouldClose() {
		drawScene()
		window.SwapBuffers()
		glfw.PollEvents()
	}
}
Пример #5
0
func RunIn3DContext(example func()) {
	if !glfw.Init() {
		log.Panic("glfw Error")
	}
	defer glfw.Terminate()

	glfw.WindowHint(glfw.ContextVersionMajor, 3)
	glfw.WindowHint(glfw.ContextVersionMinor, 3)
	glfw.WindowHint(glfw.OpenglForwardCompatible, glfw.True)
	glfw.WindowHint(glfw.OpenglProfile, glfw.OpenglCoreProfile)

	w, h := 100, 100
	window, err := glfw.CreateWindow(w, h, "Test", nil, nil)
	if err != nil {
		log.Panic(err)
	}
	window.MakeContextCurrent()

	if gl.Init() != 0 {
		log.Panic("gl error")
	}
	gl.GetError()

	vertexArray := gl.GenVertexArray()
	vertexArray.Bind()

	example()
}
Пример #6
0
func main() {
	runtime.LockOSThread()
	defer runtime.UnlockOSThread()
	defer glfw.Terminate()

	gorgasm.Verbose = true

	if !glfw.Init() {
		panic("Can't init glfw!")
	}

	// Enable OpenGL ES 2.0.
	glfw.WindowHint(glfw.ClientApi, glfw.OpenglEsApi)
	glfw.WindowHint(glfw.ContextVersionMajor, 2)
	window, err := glfw.CreateWindow(testlib.Width, testlib.Height, "Gorgasm Test", nil, nil)
	if err != nil {
		panic(err)
	}

	gorgasm.Init(window)

	go prettytest.Run(new(testing.T), testlib.NewTestSuite())

	for !window.ShouldClose() {
		glfw.WaitEvents()
	}
}
Пример #7
0
func main() {
	runtime.LockOSThread()
	defer runtime.UnlockOSThread()
	defer glfw.Terminate()

	mandala.Verbose = true

	if !glfw.Init() {
		panic("Can't init glfw!")
	}

	// Enable OpenGL ES 2.0.
	glfw.WindowHint(glfw.ClientApi, glfw.OpenglEsApi)
	glfw.WindowHint(glfw.ContextVersionMajor, 2)
	window, err := glfw.CreateWindow(Width, Height, "gltext black-box testing", nil, nil)
	if err != nil {
		panic(err)
	}

	glfw.SwapInterval(0)
	mandala.Init(window)

	go prettytest.Run(new(testing.T), testlib.NewTestSuite(outputPath))

	for !window.ShouldClose() {
		glfw.WaitEvents()
	}
}
Пример #8
0
Файл: run.go Проект: james4k/exp
func setupGlfw() {
	glfw.SetErrorCallback(onGlfwError)

	glfw.WindowHint(glfw.Resizable, 1)
	glfw.WindowHint(glfw.Visible, 1)
	glfw.WindowHint(glfw.Decorated, 1)
	glfw.WindowHint(glfw.ClientApi, glfw.OpenglApi)

	glfw.WindowHint(glfw.OpenglForwardCompatible, 1)
	glfw.WindowHint(glfw.ContextVersionMajor, 3)
	glfw.WindowHint(glfw.ContextVersionMinor, 2)
	glfw.WindowHint(glfw.OpenglProfile, glfw.OpenglCoreProfile)
	glfw.WindowHint(glfw.OpenglDebugContext, 1)
}
Пример #9
0
func initWindow() (window *glfw.Window, err error) {
	monitor, err := glfw.GetPrimaryMonitor()
	if err != nil {
		return nil, err
	}
	videomode, err := monitor.GetVideoMode()
	if err != nil {
		return nil, err
	}
	if videomode.Height < 480 || videomode.Width < 640 {
		return nil, errors.New("unsupported resolution!")
	}

	ratio := float64(videomode.Width) / float64(videomode.Height)

	if fullscreen {
		glfw.WindowHint(glfw.Decorated, 0)
		window, err = glfw.CreateWindow(videomode.Width, videomode.Height, "Golang Asteroids!", nil, nil)
		if err != nil {
			return nil, err
		}
		window.SetPosition(0, 0)
	} else {
		glfw.WindowHint(glfw.Decorated, 1)
		window, err = glfw.CreateWindow(int(ratio*480), 480, "Golang Asteroids!", nil, nil)
		if err != nil {
			return nil, err
		}
		window.SetPosition(videomode.Width/2-320, videomode.Height/2-240)
	}

	window.SetKeyCallback(keyCallback)
	window.SetFramebufferSizeCallback(reshapeWindow)
	window.MakeContextCurrent()

	gl.Init()
	gl.ClearColor(gl.GLclampf(Colorize(0)), gl.GLclampf(Colorize(0)), gl.GLclampf(Colorize(0)), 0.0)
	gl.Clear(gl.COLOR_BUFFER_BIT)

	width, height := window.GetFramebufferSize()
	reshapeWindow(window, width, height)

	return window, nil
}
Пример #10
0
func main() {
	flag.Parse()
	glfw.SetErrorCallback(errorCallback)
	if !glfw.Init() {
		println("glfw init failure")
	}
	defer glfw.Terminate()
	glfw.WindowHint(glfw.ClientApi, glfw.OpenglEsApi)
	glfw.WindowHint(glfw.ContextVersionMajor, 2)
	glfw.WindowHint(glfw.ContextVersionMinor, 0)
	window, err := glfw.CreateWindow(Width, Height, Title, nil, nil)
	if err != nil {
		panic(err)
	}
	defer window.Destroy()
	window.MakeContextCurrent()
	glfw.SwapInterval(1)
	window.SetSizeCallback(reshape)
	window.SetKeyCallback(keyEvent)
	gl.Viewport(0, 0, Width, Height)
	initScene()

	if *debug {
		go func() {
			tick := time.Tick(1 * time.Second)
			for {
				<-tick
				fmt.Printf("FPS:%v\tGOROUTINE:%v\r", atomic.LoadUint64(fps), runtime.NumGoroutine())
				atomic.StoreUint64(fps, 0)
			}
		}()
	}
	for !window.ShouldClose() {
		drawScene()
		window.SwapBuffers()
		glfw.PollEvents()
		atomic.AddUint64(fps, 1)
	}
}
Пример #11
0
func (self *OpenGLWindow) Open() {
	var err error
	if !glfw.Init() {
		panic(errors.New("Unable to initialize GLFW"))
	}

	glfw.SetErrorCallback(func(code glfw.ErrorCode, desc string) {
		log.Printf("[GLFW Error] (%d) %s", code, desc)
	})

	var monitor *glfw.Monitor
	if self.config.Fullscreen {
		monitor, err = glfw.GetPrimaryMonitor()

		if err != nil {
			panic(err)
		}
	}

	glfw.WindowHint(glfw.ContextVersionMajor, 4)
	glfw.WindowHint(glfw.ContextVersionMinor, 1)
	glfw.WindowHint(glfw.OpenglProfile, glfw.OpenglCoreProfile)
	glfw.WindowHint(glfw.OpenglForwardCompatible, glfw.True)

	// Default buffer sizes
	glfw.WindowHint(glfw.DepthBits, 32)
	glfw.WindowHint(glfw.StencilBits, 0)

	// Toggle VSync. Turning VSync off aparently doesn't work via glfw through
	// some ATI cards and drivers
	if self.config.VSync {
		glfw.SwapInterval(1)
	} else {
		glfw.SwapInterval(0)
	}

	self.window, err = glfw.CreateWindow(
		int(self.config.Width), int(self.config.Height),
		"Project Slartibartfast",
		monitor,
		nil)

	if err != nil {
		panic(err)
	}

	self.window.MakeContextCurrent()

	if glewError := gl.Init(); glewError != 0 {
		panic(errors.New("Unable to initialize OpenGL"))
	}
}
Пример #12
0
func (a *Application) init() {
	glfw.SetErrorCallback(a.glfwError)
	if !glfw.Init() {
		os.Exit(1)
	}

	a.Width = 1280
	a.Height = 720
	a.Title = filepath.Base(os.Args[0])

	// For now, force a fixed size window. bgfx currently breaks glfw
	// events on OS X because it overrides the NSWindow's content view.
	glfw.WindowHint(glfw.Resizable, 0)
	var err error
	a.window, err = glfw.CreateWindow(a.Width, a.Height, a.Title, nil, nil)
	if err != nil {
		log.Fatalln(err)
	}
	bgfx_glfw.SetWindow(a.window)
}
Пример #13
0
func main() {
	if !glfw.Init() {
		panic("Failed to initialize GLFW")
	}

	defer glfw.Terminate()

	glfw.WindowHint(glfw.DepthBits, 16)

	window, err := glfw.CreateWindow(300, 300, "Gears", nil, nil)
	if err != nil {
		panic(err)
	}

	// Set callback functions
	window.SetFramebufferSizeCallback(reshape)
	window.SetKeyCallback(key)

	window.MakeContextCurrent()
	glfw.SwapInterval(1)

	width, height := window.GetFramebufferSize()
	reshape(window, width, height)

	// Parse command-line options
	Init()

	// Main loop
	for !window.ShouldClose() {
		// Draw gears
		draw()

		// Update animation
		animate()

		// Swap buffers
		window.SwapBuffers()
		glfw.PollEvents()
	}
}
Пример #14
0
Файл: 09.go Проект: nzlov/gogl
func main() {
	glfw.SetErrorCallback(errorCallback)

	if !glfw.Init() {
		panic("Can't init glfw!")
	}
	defer glfw.Terminate()

	glfw.WindowHint(glfw.DepthBits, 16)

	window, err := glfw.CreateWindow(Width, Height, Title, nil, nil)
	if err != nil {
		panic(err)
	}

	window.SetFramebufferSizeCallback(reshape)
	window.SetKeyCallback(key)

	window.MakeContextCurrent()

	glfw.SwapInterval(1000 / 60)

	width, height := window.GetFramebufferSize()
	reshape(window, width, height)

	if err := initGL(); err != nil {
		fmt.Fprintf(os.Stderr, "init: %s\n", err)
		return
	}
	defer destroyGL()

	for !window.ShouldClose() {
		drawScene()
		window.SwapBuffers()
		glfw.PollEvents()
	}
}
Пример #15
0
func CreateWindow(width, height int, name string, fullscreen bool, delegate WindowDelegate, legacy bool) error {
	if !glfw.Init() {
		return errors.New("Failed to initialize GLFW")
	}
	defer glfw.Terminate()

	glfw.WindowHint(glfw.DepthBits, 16)
	if !legacy {
		glfw.WindowHint(glfw.ContextVersionMajor, 3)
		glfw.WindowHint(glfw.ContextVersionMinor, 2)
		glfw.WindowHint(glfw.OpenglProfile, glfw.OpenglCoreProfile)
		glfw.WindowHint(glfw.OpenglForwardCompatible, 1)
	}

	var monitor *glfw.Monitor = nil
	var err error = nil
	if fullscreen {
		monitor, err = glfw.GetPrimaryMonitor()
		if err != nil {
			return err
		}

		vidModes, _ := monitor.GetVideoModes()
		maxResolution := vidModes[len(vidModes)-1]
		width = maxResolution.Width
		height = maxResolution.Height
	}
	window, err := glfw.CreateWindow(width, height, name, monitor, nil)
	if err != nil {
		return err
	}

	if fullscreen {
		window.SetInputMode(glfw.Cursor, glfw.CursorDisabled)
	}

	start := time.Now()
	last := start
	doSimulation := func() {
		now := time.Now()
		gameTime := GameTime{
			now,
			now.Sub(start),
			now.Sub(last),
		}
		delegate.Simulate(gameTime)
		last = now
	}

	bindEvents(window, &IdleSimulatorWindowDelegator{
		WindowDelegator{delegate},
		doSimulation,
	})
	window.MakeContextCurrent()
	glfw.SwapInterval(1)
	delegate.Init(window)
	frameWidth, frameHeight := window.GetFramebufferSize()
	delegate.Reshape(window, frameWidth, frameHeight)
	for !window.ShouldClose() {
		doSimulation()
		if delegate.NeedsRender() {
			delegate.Draw(window)
		}
		window.SwapBuffers()
		if delegate.IsIdle() {
			glfw.WaitEvents()
		} else {
			glfw.PollEvents()
		}
	}
	return nil
}
Пример #16
0
func main() {
	runtime.LockOSThread()

	if !glfw.Init() {
		fmt.Fprintf(os.Stderr, "Can't open GLFW")
		return
	}
	defer glfw.Terminate()

	glfw.WindowHint(glfw.Samples, 4)
	glfw.WindowHint(glfw.ContextVersionMajor, 3)
	glfw.WindowHint(glfw.ContextVersionMinor, 3)
	glfw.WindowHint(glfw.OpenglProfile, glfw.OpenglCoreProfile)
	glfw.WindowHint(glfw.OpenglForwardCompatible, glfw.True) // needed for macs

	window, err := glfw.CreateWindow(1024, 768, "Tutorial 8", nil, nil)
	if err != nil {
		fmt.Fprintf(os.Stderr, "%v\n", err)
		return
	}

	window.MakeContextCurrent()

	gl.Init()
	gl.GetError() // Ignore error
	window.SetInputMode(glfw.StickyKeys, 1)
	window.SetCursorPosition(1024/2, 768/2)
	window.SetInputMode(glfw.Cursor, glfw.CursorHidden)

	gl.ClearColor(0., 0., 0.4, 0.)

	gl.Enable(gl.DEPTH_TEST)
	gl.DepthFunc(gl.LESS)

	gl.Enable(gl.CULL_FACE)

	camera := input.NewCamera(window)

	vertexArray := gl.GenVertexArray()
	defer vertexArray.Delete()
	vertexArray.Bind()

	prog := helper.MakeProgram("StandardShading.vertexshader", "StandardShading.fragmentshader")
	defer prog.Delete()

	matrixID := prog.GetUniformLocation("MVP")
	viewMatrixID := prog.GetUniformLocation("V")
	modelMatrixID := prog.GetUniformLocation("M")

	texture, err := helper.TextureFromDDS("uvmap.DDS")
	if err != nil {
		fmt.Printf("Could not load texture: %v\n", err)
	}
	defer texture.Delete()
	texSampler := prog.GetUniformLocation("myTextureSampler")

	meshObj := objloader.LoadObject("suzanne.obj", true)

	indices, indexedVertices, indexedUVs, indexedNormals := indexer.IndexVBOSlow(meshObj.Vertices, meshObj.UVs, meshObj.Normals)

	vertexBuffer := gl.GenBuffer()
	defer vertexBuffer.Delete()
	vertexBuffer.Bind(gl.ARRAY_BUFFER)
	gl.BufferData(gl.ARRAY_BUFFER, len(indexedVertices)*3*4, indexedVertices, gl.STATIC_DRAW)

	uvBuffer := gl.GenBuffer()
	defer uvBuffer.Delete()
	uvBuffer.Bind(gl.ARRAY_BUFFER)
	// And yet, the weird length stuff doesn't seem to matter for UV or normal
	gl.BufferData(gl.ARRAY_BUFFER, len(indexedUVs)*2*4, indexedUVs, gl.STATIC_DRAW)

	normBuffer := gl.GenBuffer()
	defer normBuffer.Delete()
	normBuffer.Bind(gl.ARRAY_BUFFER)
	gl.BufferData(gl.ARRAY_BUFFER, len(indexedNormals)*3*4, indexedNormals, gl.STATIC_DRAW)

	elementBuffer := gl.GenBuffer()
	defer elementBuffer.Delete()
	elementBuffer.Bind(gl.ELEMENT_ARRAY_BUFFER)
	gl.BufferData(gl.ELEMENT_ARRAY_BUFFER, len(indices)*2, indices, gl.STATIC_DRAW) // NOTE: a GL_UNSIGNED_SHORT is 16-bits

	lightID := prog.GetUniformLocation("LightPosition_worldspace")
	lastTime := glfw.GetTime()
	nbFrames := 0
	// Equivalent to a do... while
	for ok := true; ok; ok = (window.GetKey(glfw.KeyEscape) != glfw.Press && !window.ShouldClose()) {

		currTime := glfw.GetTime()
		nbFrames++
		if currTime-lastTime >= 1.0 {
			fmt.Printf("%f ms/frame\n", 1000.0/float64(nbFrames))
			nbFrames = 0
			lastTime += 1.0
		}

		func() {
			gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)

			prog.Use()
			defer gl.ProgramUnuse()

			view, proj := camera.ComputeViewPerspective()
			model := mgl32.Ident4()

			MVP := proj.Mul4(view).Mul4(model)
			//mvpArray := mvp.AsCMOArray(mathgl.FLOAT32).([16]float32)
			//vArray := view.AsCMOArray(mathgl.FLOAT32).([16]float32)
			//mArray := model.AsCMOArray(mathgl.FLOAT32).([16]float32)

			matrixID.UniformMatrix4fv(false, MVP)
			viewMatrixID.UniformMatrix4fv(false, view)
			modelMatrixID.UniformMatrix4fv(false, model)

			lightID.Uniform3f(4., 4., 4.)

			gl.ActiveTexture(gl.TEXTURE0)
			texture.Bind(gl.TEXTURE_2D)
			defer texture.Unbind(gl.TEXTURE_2D)
			texSampler.Uniform1i(0)

			vertexAttrib := gl.AttribLocation(0)
			vertexAttrib.EnableArray()
			defer vertexAttrib.DisableArray()
			vertexBuffer.Bind(gl.ARRAY_BUFFER)
			defer vertexBuffer.Unbind(gl.ARRAY_BUFFER)
			vertexAttrib.AttribPointer(3, gl.FLOAT, false, 0, nil)

			uvAttrib := gl.AttribLocation(1)
			uvAttrib.EnableArray()
			defer uvAttrib.DisableArray()
			uvBuffer.Bind(gl.ARRAY_BUFFER)
			defer uvBuffer.Unbind(gl.ARRAY_BUFFER)
			uvAttrib.AttribPointer(2, gl.FLOAT, false, 0, nil)

			normAttrib := gl.AttribLocation(2)
			normAttrib.EnableArray()
			defer normAttrib.DisableArray()
			normBuffer.Bind(gl.ARRAY_BUFFER)
			defer normBuffer.Unbind(gl.ARRAY_BUFFER)
			normAttrib.AttribPointer(3, gl.FLOAT, false, 0, nil)

			elementBuffer.Bind(gl.ELEMENT_ARRAY_BUFFER)
			defer elementBuffer.Unbind(gl.ELEMENT_ARRAY_BUFFER)

			gl.DrawElements(gl.TRIANGLES, len(indices), gl.UNSIGNED_SHORT, nil)

			window.SwapBuffers()
			glfw.PollEvents()
		}() // Defers unbinds and disables to here, end of the loop
	}

}
Пример #17
0
func main() {
	var programState programState
	var err error
	glfw.SetErrorCallback(errorCallback)

	if !glfw.Init() {
		panic("GLFW initialization failed.")
	}
	defer glfw.Terminate()

	glfw.WindowHint(glfw.ContextVersionMajor, 3)
	glfw.WindowHint(glfw.ContextVersionMinor, 3)
	glfw.WindowHint(glfw.SrgbCapable, glfw.True)
	glfw.WindowHint(glfw.Resizable, glfw.False)
	programState.Gl.Window, err = glfw.CreateWindow(640, 480, "Daggor", nil, nil)
	if err != nil {
		panic(err)
	}
	defer programState.Gl.Window.Destroy()

	programState.Gl.glfwKeyEventList = makeGlfwKeyEventList()
	programState.Gl.Window.SetKeyCallback(programState.Gl.glfwKeyEventList.Callback)

	programState.Gl.Window.MakeContextCurrent()
	if ec := gl.Init(); ec != 0 {
		panic(fmt.Sprintf("OpenGL initialization failed with code %v.", ec))
	}
	// For some reason, here, the OpenGL error flag for me contains "Invalid enum".
	// This is weird since I have not done anything yet.  I imagine that something
	// goes wrong in gl.Init.  Reading the error flag clears it, so I do it.
	// Here's the reason:
	//     https://github.com/go-gl/glfw3/issues/50
	// Maybe I should not even ask for a core profile anyway.
	// What are the advantages are asking for a core profile?
	if err := glw.CheckGlError(); err != nil {
		err.Description = "OpenGL has this error right after init for some reason."
		//fmt.Println(err)
	}
	{
		// Assert OpenGL >= 3.3.
		major := programState.Gl.Window.GetAttribute(glfw.ContextVersionMajor)
		minor := programState.Gl.Window.GetAttribute(glfw.ContextVersionMinor)
		fmt.Printf("OpenGL version %v.%v.\n", major, minor)
		if (major < 3) || (major == 3 && minor < 3) {
			panic("OpenGL version 3.3 required, your video card/driver does not seem to support it.")
		}
	}

	programState.Gl.context = glw.NewGlContext()

	programState.Gl.Shapes[floorID] = sculpt.FloorInstNorm(programState.Gl.context.Programs)
	programState.Gl.Shapes[ceilingID] = sculpt.CeilingInstNorm(programState.Gl.context.Programs)
	programState.Gl.Shapes[wallID] = sculpt.WallInstNorm(programState.Gl.context.Programs)

	{
		// I do not like the default reference frame of OpenGl.
		// By default, we look in the direction -z, and y points up.
		// I want z to point up, and I want to look in the direction +x
		// by default.  That way, I move on an xy plane where z is the
		// altitude, instead of having the altitude stuffed between
		// the two things I use the most.  And my reason for pointing
		// toward +x is that I use the convention for trigonometry:
		// an angle of 0 points to the right (east) of the trigonometric
		// circle.  Bonus point: this matches Blender's reference frame.
		myFrame := glm.ZUP.Mult(glm.RotZ(90))
		eye_to_clip := glm.PerspectiveProj(110, 640./480., .1, 100).Mult(myFrame)
		programState.Gl.context.SetEyeToClp(eye_to_clip)
	}
	gl.Enable(gl.FRAMEBUFFER_SRGB)
	gl.Enable(gl.DEPTH_TEST)
	gl.Enable(gl.CULL_FACE)
	gl.CullFace(gl.BACK)
	gl.FrontFace(gl.CCW)
	gl.Enable(gl.TEXTURE_CUBE_MAP_SEAMLESS)

	// This needs a texture server attached to the context, like for programs.
	glw.LoadSkybox()

	programState.World = world.MakeWorld()
	mainLoop(programState)
}
Пример #18
0
func (me *context) Window(winf *ngctx.WinProfile, bufSize *ngctx.BufferBits, ctxProf *ngctx.CtxProfile) (window ngctx.Window, err error) {
	glfw.WindowHint(glfw.Samples, winf.MultiSampling)
	glfw.WindowHint(glfw.RedBits, bufSize.Color.R)
	glfw.WindowHint(glfw.GreenBits, bufSize.Color.G)
	glfw.WindowHint(glfw.BlueBits, bufSize.Color.B)
	glfw.WindowHint(glfw.AlphaBits, bufSize.Color.A)
	glfw.WindowHint(glfw.DepthBits, bufSize.Depth)
	glfw.WindowHint(glfw.StencilBits, bufSize.Stencil)
	glfw.WindowHint(glfw.ContextVersionMajor, ctxProf.Version.Major)
	glfw.WindowHint(glfw.ContextVersionMinor, ctxProf.Version.Minor)
	glfw.WindowHint(glfw.OpenglProfile, glfw.OpenglCoreProfile)
	if ctxProf.ForwardCompat {
		glfw.WindowHint(glfw.OpenglForwardCompatible, 1)
	}
	var mon *glfw.Monitor
	if winf.FullScreen {
		mon, err = glfw.GetPrimaryMonitor()
	}
	if err == nil {
		var win *glfw.Window
		if win, err = glfw.CreateWindow(winf.Width, winf.Height, winf.Title, mon, nil); win != nil {
			window = newWindow(win)
			if winf.FullScreen {
				win.SetInputMode(glfw.Cursor, glfw.CursorHidden)
			}
		}
	}
	return
}
Пример #19
0
func (me *context) Hint(flag, value int) {
	glfw.WindowHint(glfw.Hint(flag), value)
}
Пример #20
0
func main() {
	runtime.LockOSThread()

	if !glfw.Init() {
		fmt.Fprintf(os.Stderr, "Can't open GLFW")
		return
	}
	defer glfw.Terminate()

	glfw.WindowHint(glfw.Samples, 4)
	glfw.WindowHint(glfw.ContextVersionMajor, 3)
	glfw.WindowHint(glfw.ContextVersionMinor, 3)
	glfw.WindowHint(glfw.OpenglProfile, glfw.OpenglCoreProfile)
	glfw.WindowHint(glfw.OpenglForwardCompatible, glfw.True) // needed for macs

	window, err := glfw.CreateWindow(1024, 768, "Tutorial 7", nil, nil)
	if err != nil {
		fmt.Fprintf(os.Stderr, "%v\n", err)
		return
	}

	window.MakeContextCurrent()

	gl.Init()
	gl.GetError() // Ignore error
	window.SetInputMode(glfw.StickyKeys, 1)
	window.SetCursorPosition(1024/2, 768/2)
	window.SetInputMode(glfw.Cursor, glfw.CursorHidden)

	gl.ClearColor(0., 0., 0.4, 0.)

	gl.Enable(gl.DEPTH_TEST)
	gl.DepthFunc(gl.LESS)

	gl.Enable(gl.CULL_FACE)

	camera := input.NewCamera(window)

	vertexArray := gl.GenVertexArray()
	defer vertexArray.Delete()
	vertexArray.Bind()

	prog := helper.MakeProgram("TransformVertexShader.vertexshader", "TextureFragmentShader.fragmentshader")
	defer prog.Delete()

	matrixID := prog.GetUniformLocation("MVP")

	texture, err := helper.TextureFromDDS("uvmap.DDS")
	if err != nil {
		fmt.Println("Couldn't load texture")
		return
	}
	defer texture.Delete()
	texSampler := prog.GetUniformLocation("myTextureSampler")

	meshObj := objloader.LoadObject("cube.obj", true)
	vertices, uvs := meshObj.Vertices, meshObj.UVs

	vertexBuffer := gl.GenBuffer()
	defer vertexBuffer.Delete()
	vertexBuffer.Bind(gl.ARRAY_BUFFER)
	gl.BufferData(gl.ARRAY_BUFFER, len(vertices)*3*4, vertices, gl.STATIC_DRAW)

	uvBuffer := gl.GenBuffer()
	defer uvBuffer.Delete()
	uvBuffer.Bind(gl.ARRAY_BUFFER)

	// UV doesn't seem to care
	gl.BufferData(gl.ARRAY_BUFFER, len(uvs)*2*4, uvs, gl.STATIC_DRAW)

	// Equivalent to a do... while
	for ok := true; ok; ok = (window.GetKey(glfw.KeyEscape) != glfw.Press && !window.ShouldClose()) {
		func() {
			gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)

			prog.Use()
			defer gl.ProgramUnuse()

			view, proj := camera.ComputeViewPerspective()
			model := mgl32.Ident4()

			MVP := proj.Mul4(view).Mul4(model)

			matrixID.UniformMatrix4fv(false, MVP)

			gl.ActiveTexture(gl.TEXTURE0)
			texture.Bind(gl.TEXTURE_2D)
			defer texture.Unbind(gl.TEXTURE_2D)
			texSampler.Uniform1i(0)

			vertexAttrib := gl.AttribLocation(0)
			vertexAttrib.EnableArray()
			defer vertexAttrib.DisableArray()
			vertexBuffer.Bind(gl.ARRAY_BUFFER)
			defer vertexBuffer.Unbind(gl.ARRAY_BUFFER)
			vertexAttrib.AttribPointer(3, gl.FLOAT, false, 0, nil)

			uvAttrib := gl.AttribLocation(1)
			uvAttrib.EnableArray()
			defer uvAttrib.DisableArray()
			uvBuffer.Bind(gl.ARRAY_BUFFER)
			defer uvBuffer.Unbind(gl.ARRAY_BUFFER)
			uvAttrib.AttribPointer(2, gl.FLOAT, false, 0, nil)

			gl.DrawArrays(gl.TRIANGLES, 0, len(vertices))

			window.SwapBuffers()
			glfw.PollEvents()
		}() // Defers unbinds and disables to here, end of the loop
	}

}
Пример #21
0
func main() {
	runtime.LockOSThread()
	var looping = true
	defer fmt.Println("EXIT")
	// if err = glfw.Init(); err != nil {
	// 	panic(err)
	// }
	if !glfw.Init() {
		panic("glfw.Init() failed!")
	}
	defer glfw.Terminate()
	// glfw.OpenWindowHint(glfw.FsaaSamples, 0)
	glfw.WindowHint(glfw.Samples, 0)
	if useStrictCoreProfile {
		// glfw.OpenWindowHint(glfw.OpenGLVersionMajor, 3)
		// glfw.OpenWindowHint(glfw.OpenGLVersionMinor, 2)
		// glfw.OpenWindowHint(glfw.OpenGLProfile, glfw.OpenGLCoreProfile)
		glfw.WindowHint(glfw.ContextVersionMajor, 3)
		glfw.WindowHint(glfw.ContextVersionMinor, 2)
		glfw.WindowHint(glfw.OpenglProfile, glfw.OpenglCoreProfile)
	}
	// if err = glfw.OpenWindow(1280, 720, 8, 8, 8, 0, 24, 8, glfw.Windowed); err != nil {
	// 	panic(err)
	// }
	// defer glfw.CloseWindow()
	glfw.WindowHint(glfw.RedBits, 8)
	glfw.WindowHint(glfw.BlueBits, 8)
	glfw.WindowHint(glfw.GreenBits, 8)
	glfw.WindowHint(glfw.AlphaBits, 0)
	glfw.WindowHint(glfw.DepthBits, 24)
	glfw.WindowHint(glfw.StencilBits, 8)
	win, err := glfw.CreateWindow(1280, 720, "Test", nil, nil)
	if err != nil {
		panic(err)
	}
	defer win.Destroy()
	win.MakeContextCurrent()

	// glfw.Enable(glfw.StickyKeys)
	win.SetInputMode(glfw.StickyKeys, glfw.True)
	if !gl.Util.Init() {
		panic("Failed to initialize at least OpenGL 3.2 or higher.")
	}
	defer logLastGlError("(post loop)")
	gl.ClearColor(0.3, 0.1, 0.0, 1.0)
	gl.Enable(gl.DEPTH_TEST)
	gl.FrontFace(gl.CCW)
	gl.CullFace(gl.BACK)
	gl.Disable(gl.CULL_FACE)
	if err = compileShaders(); err != nil {
		panic(err)
	}
	setupGeometry()
	defer deleteGeometry()
	logLastGlError("(pre loop)")

	for looping {
		gl.UseProgram(shaderProg)
		if isFirstLoop {
			logLastGlError("gl.UseProgram")
		}

		gl.Viewport(0, 0, 1280, 720)
		if isFirstLoop {
			logLastGlError("gl.ViewPort")
		}

		gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
		if isFirstLoop {
			logLastGlError("gl.Clear")
		}

		renderGeometry(faceTri)
		if isFirstLoop {
			logLastGlError("renderGeometry(faceTri)")
		}

		renderGeometry(faceQuad)
		if isFirstLoop {
			logLastGlError("renderGeometry(faceQuad)")
		}

		// if (glfw.WindowParam(glfw.Opened) != 1) || (glfw.Key(glfw.KeyEsc) == glfw.KeyPress) {
		if win.ShouldClose() || win.GetKey(glfw.KeyEscape) == glfw.Press {
			looping = false
		} else {
			// glfw.SwapBuffers()
			win.SwapBuffers()
			glfw.PollEvents()
		}
		isFirstLoop = false
	}
	logLastGlError("post-loop")
}
Пример #22
0
func main() {
	runtime.LockOSThread()

	if !glfw.Init() {
		fmt.Fprintf(os.Stderr, "Can't open GLFW")
		return
	}
	defer glfw.Terminate()

	glfw.WindowHint(glfw.Samples, 4)
	glfw.WindowHint(glfw.ContextVersionMajor, 3)
	glfw.WindowHint(glfw.ContextVersionMinor, 3)
	glfw.WindowHint(glfw.OpenglProfile, glfw.OpenglCoreProfile)
	glfw.WindowHint(glfw.OpenglForwardCompatible, glfw.True) // needed for macs

	window, err := glfw.CreateWindow(1024, 768, "Tutorial 4", nil, nil)
	if err != nil {
		fmt.Fprintf(os.Stderr, "%v\n", err)
		return
	}

	window.MakeContextCurrent()

	gl.Init()
	gl.GetError() // Ignore error
	window.SetInputMode(glfw.StickyKeys, 1)

	gl.ClearColor(0., 0., 0.4, 0.)

	gl.Enable(gl.DEPTH_TEST)
	gl.DepthFunc(gl.LESS)

	vertexArray := gl.GenVertexArray()
	defer vertexArray.Delete()
	vertexArray.Bind()

	prog := helper.MakeProgram("TransformVertexShader.vertexshader", "ColorFragmentShader.fragmentshader")
	defer prog.Delete()

	matrixID := prog.GetUniformLocation("MVP")

	Projection := mgl32.Perspective(45.0, 4.0/3.0, 0.1, 100.0)

	View := mgl32.LookAt(4.0, 3.0, -3.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0)

	Model := mgl32.Ident4()

	MVP := Projection.Mul4(View).Mul4(Model) // Remember, transform multiplication order is "backwards"

	vBufferData := [...]float32{
		-1.0, -1.0, -1.0,
		-1.0, -1.0, 1.0,
		-1.0, 1.0, 1.0,
		1.0, 1.0, -1.0,
		-1.0, -1.0, -1.0,
		-1.0, 1.0, -1.0,
		1.0, -1.0, 1.0,
		-1.0, -1.0, -1.0,
		1.0, -1.0, -1.0,
		1.0, 1.0, -1.0,
		1.0, -1.0, -1.0,
		-1.0, -1.0, -1.0,
		-1.0, -1.0, -1.0,
		-1.0, 1.0, 1.0,
		-1.0, 1.0, -1.0,
		1.0, -1.0, 1.0,
		-1.0, -1.0, 1.0,
		-1.0, -1.0, -1.0,
		-1.0, 1.0, 1.0,
		-1.0, -1.0, 1.0,
		1.0, -1.0, 1.0,
		1.0, 1.0, 1.0,
		1.0, -1.0, -1.0,
		1.0, 1.0, -1.0,
		1.0, -1.0, -1.0,
		1.0, 1.0, 1.0,
		1.0, -1.0, 1.0,
		1.0, 1.0, 1.0,
		1.0, 1.0, -1.0,
		-1.0, 1.0, -1.0,
		1.0, 1.0, 1.0,
		-1.0, 1.0, -1.0,
		-1.0, 1.0, 1.0,
		1.0, 1.0, 1.0,
		-1.0, 1.0, 1.0,
		1.0, -1.0, 1.0}

	colorBufferData := [...]float32{
		0.583, 0.771, 0.014,
		0.609, 0.115, 0.436,
		0.327, 0.483, 0.844,
		0.822, 0.569, 0.201,
		0.435, 0.602, 0.223,
		0.310, 0.747, 0.185,
		0.597, 0.770, 0.761,
		0.559, 0.436, 0.730,
		0.359, 0.583, 0.152,
		0.483, 0.596, 0.789,
		0.559, 0.861, 0.639,
		0.195, 0.548, 0.859,
		0.014, 0.184, 0.576,
		0.771, 0.328, 0.970,
		0.406, 0.615, 0.116,
		0.676, 0.977, 0.133,
		0.971, 0.572, 0.833,
		0.140, 0.616, 0.489,
		0.997, 0.513, 0.064,
		0.945, 0.719, 0.592,
		0.543, 0.021, 0.978,
		0.279, 0.317, 0.505,
		0.167, 0.620, 0.077,
		0.347, 0.857, 0.137,
		0.055, 0.953, 0.042,
		0.714, 0.505, 0.345,
		0.783, 0.290, 0.734,
		0.722, 0.645, 0.174,
		0.302, 0.455, 0.848,
		0.225, 0.587, 0.040,
		0.517, 0.713, 0.338,
		0.053, 0.959, 0.120,
		0.393, 0.621, 0.362,
		0.673, 0.211, 0.457,
		0.820, 0.883, 0.371,
		0.982, 0.099, 0.879}

	//elBufferData := [...]uint8{0, 1, 2} // Not sure why this is here

	vertexBuffer := gl.GenBuffer()
	defer vertexBuffer.Delete()
	vertexBuffer.Bind(gl.ARRAY_BUFFER)
	gl.BufferData(gl.ARRAY_BUFFER, len(vBufferData)*4, &vBufferData, gl.STATIC_DRAW)

	colorBuffer := gl.GenBuffer()
	defer colorBuffer.Delete()
	colorBuffer.Bind(gl.ARRAY_BUFFER)
	gl.BufferData(gl.ARRAY_BUFFER, len(colorBufferData)*4, &colorBufferData, gl.STATIC_DRAW)

	// Equivalent to a do... while
	for ok := true; ok; ok = (window.GetKey(glfw.KeyEscape) != glfw.Press && !window.ShouldClose()) {
		gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)

		prog.Use()

		matrixID.UniformMatrix4fv(false, MVP)

		vertexAttrib := gl.AttribLocation(0)
		vertexAttrib.EnableArray()
		vertexBuffer.Bind(gl.ARRAY_BUFFER)
		vertexAttrib.AttribPointer(3, gl.FLOAT, false, 0, nil)

		colorAttrib := gl.AttribLocation(1)
		colorAttrib.EnableArray()
		colorBuffer.Bind(gl.ARRAY_BUFFER)
		colorAttrib.AttribPointer(3, gl.FLOAT, false, 0, nil)

		gl.DrawArrays(gl.TRIANGLES, 0, 12*3)

		vertexAttrib.DisableArray()
		colorAttrib.DisableArray()

		window.SwapBuffers()
		glfw.PollEvents()
	}

}
Пример #23
0
// NewWindow creates a new window for the given dimensions and title.
// The window is created via GLFW.
func NewWindow(settings WindowSettings) (*Window, error) {
	// Error callback
	glfw.SetErrorCallback(errorCallback)

	// Init glfw
	logger.Debug("Initializing GLFW")
	if !glfw.Init() {
		return nil, errors.New("Could not initialise GLFW.")
	}

	glfw.WindowHint(glfw.Samples, 4)
	glfw.WindowHint(glfw.ContextVersionMajor, 3)
	glfw.WindowHint(glfw.ContextVersionMinor, 3)
	glfw.WindowHint(glfw.OpenglForwardCompatible, glfw.True)
	glfw.WindowHint(glfw.OpenglProfile, glfw.OpenglCoreProfile)
	glfw.WindowHint(glfw.OpenglDebugContext, 1)

	var monitor *glfw.Monitor
	var err error
	if settings.Fullscreen {
		logger.Debug("Get primary monitor to create fullscreen window.")
		monitor, err = glfw.GetPrimaryMonitor()
		if err != nil {
			return nil, err
		}

		logger.Debug("Checking available video modes:")
		videoModes, err := monitor.GetVideoModes()
		if err != nil {
			return nil, err
		}

		for _, videoMode := range videoModes {
			logger.Debug(fmt.Sprintf("-- %+v", videoMode))
		}

		idealVideoMode := videoModes[len(videoModes)-1]

		settings.Width = idealVideoMode.Width
		settings.Height = idealVideoMode.Height
	}

	// Create window
	logger.Info("Creating new window")
	window, err := glfw.CreateWindow(settings.Width, settings.Height, settings.Title, monitor, nil)
	if err != nil {
		return nil, err
	}
	window.SetKeyCallback(keyCallback)
	window.MakeContextCurrent()
	window.SetInputMode(glfw.StickyKeys, 1)

	// Use vsync
	glfw.SwapInterval(1)

	w := &Window{
		window:   window,
		Settings: settings,
	}

	currentWindow = w

	return w, nil
}
Пример #24
0
func main() {
	runtime.LockOSThread()

	if !glfw.Init() {
		fmt.Fprintf(os.Stderr, "Can't open GLFW")
		return
	}
	defer glfw.Terminate()

	glfw.WindowHint(glfw.Samples, 4)
	glfw.WindowHint(glfw.ContextVersionMajor, 3)
	glfw.WindowHint(glfw.ContextVersionMinor, 3)
	glfw.WindowHint(glfw.OpenglProfile, glfw.OpenglCoreProfile)
	glfw.WindowHint(glfw.OpenglForwardCompatible, glfw.True) // needed for macs

	window, err := glfw.CreateWindow(1024, 768, "Tutorial 3", nil, nil)
	if err != nil {
		fmt.Fprintf(os.Stderr, "%v\n", err)
		return
	}

	window.MakeContextCurrent()

	gl.Init()
	gl.GetError() // Ignore error
	window.SetInputMode(glfw.StickyKeys, 1)

	gl.ClearColor(0., 0., 0.4, 0.)

	vertexArray := gl.GenVertexArray()
	defer vertexArray.Delete()
	vertexArray.Bind()

	prog := helper.MakeProgram("SimpleTransform.vertexshader", "SingleColor.fragmentshader")
	defer prog.Delete()

	matrixID := prog.GetUniformLocation("MVP")

	Projection := mgl32.Perspective(45.0, 4.0/3.0, 0.1, 100.0)
	//Projection := mathgl.Identity(4,mathgl.FLOAT64)
	//Projection := mathgl.Ortho2D(-5,5,-5,5)
	View := mgl32.LookAt(4.0, 3.0, 3.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0)
	//View := mathgl.Identity(4,mathgl.FLOAT64)

	Model := mgl32.Ident4()
	//Model := mathgl.Scale3D(2.,2.,2.).Mul(mathgl.HomogRotate3DX(25.0)).Mul(mathgl.Translate3D(.5,.2,-.7))
	MVP := Projection.Mul4(View).Mul4(Model) // Remember, transform multiplication order is "backwards"

	vBufferData := [...]float32{
		-1., -1., 0.,
		1., -1., 0.,
		0., 1., 0.}
	//elBufferData := [...]uint8{0, 1, 2} // Not sure why this is here

	buffer := gl.GenBuffer()
	defer buffer.Delete()
	buffer.Bind(gl.ARRAY_BUFFER)
	gl.BufferData(gl.ARRAY_BUFFER, len(vBufferData)*4, &vBufferData, gl.STATIC_DRAW)

	// Equivalent to a do... while
	for ok := true; ok; ok = (window.GetKey(glfw.KeyEscape) != glfw.Press && !window.ShouldClose()) {
		gl.Clear(gl.COLOR_BUFFER_BIT)

		prog.Use()

		matrixID.UniformMatrix4fv(false, MVP)

		attribLoc := gl.AttribLocation(0)
		attribLoc.EnableArray()
		buffer.Bind(gl.ARRAY_BUFFER)
		attribLoc.AttribPointer(3, gl.FLOAT, false, 0, nil)

		gl.DrawArrays(gl.TRIANGLES, 0, 3)

		attribLoc.DisableArray()

		window.SwapBuffers()
		glfw.PollEvents()
	}

}
Пример #25
0
func main() {

	runtime.LockOSThread()

	verbose := flag.Bool("verbose", false, "produce verbose output")
	debug := flag.Bool("debug", false, "produce debug output")
	size := flag.String("size", "320x480", "set the size of the window")

	flag.Parse()

	if *verbose {
		mandala.Verbose = true
	}

	if *debug {
		mandala.Debug = true
	}

	dims := strings.Split(strings.ToLower(*size), "x")
	width, err := strconv.Atoi(dims[0])
	if err != nil {
		panic(err)
	}
	height, err := strconv.Atoi(dims[1])
	if err != nil {
		panic(err)
	}

	if !glfw.Init() {
		panic("Can't init glfw!")
	}
	defer glfw.Terminate()

	// Enable OpenGL ES 2.0.
	glfw.WindowHint(glfw.ClientApi, glfw.OpenglEsApi)
	glfw.WindowHint(glfw.ContextVersionMajor, 2)
	window, err := glfw.CreateWindow(width, height, "{{.AppName}}", nil, nil)
	if err != nil {
		panic(err)
	}

	mandala.Init(window)

	// Create a rendering loop control struct containing a set of
	// channels that control rendering.
	renderLoopControl := newRenderLoopControl()

	// Start the rendering loop
	loop.GoRecoverable(
		renderLoopFunc(renderLoopControl),
		func(rs loop.Recoverings) (loop.Recoverings, error) {
			for _, r := range rs {
				log.Printf("%s\n%s", r.Reason, mandala.Stacktrace())
			}
			return rs, fmt.Errorf("Unrecoverable loop\n")
		},
	)
	// Start the event loop
	loop.GoRecoverable(
		eventLoopFunc(renderLoopControl),
		func(rs loop.Recoverings) (loop.Recoverings, error) {
			for _, r := range rs {
				log.Printf("%s\n%s", r.Reason, mandala.Stacktrace())
			}
			return rs, fmt.Errorf("Unrecoverable loop\n")
		},
	)

	for !window.ShouldClose() {
		glfw.WaitEvents()
	}

}
Пример #26
0
// Starts a game loop.
// If error == nil everything went well, otherwise a fatal error occured
func Gameloop(g Game, width, height, tickrate int, glfwHints map[glfw.Hint]int) (err error) {
	// Disable GC
	debug.SetGCPercent(-1)

	// Make sure this function/goroutine keeps running on the current OS thread
	runtime.LockOSThread()

	// Calculate tick delay
	nanosPerTick := int64(NANOS_PER_SECOND / tickrate)

	// Variables for statistics
	ticks := 0
	frames := 0

	// Initialize game
	g.Init()
	defer g.Cleanup()

	// Setup window
	glfw.SetErrorCallback(g.HandleGlfwError)
	if !glfw.Init() {
		err = errors.New("gogame: glfw failed to initialize")
		return
	}
	defer glfw.Terminate()

	for target, hint := range glfwHints {
		glfw.WindowHint(target, hint)
	}

	window, err := glfw.CreateWindow(width, height, "GoGame", nil, nil)
	if err != nil {
		// Just to be verbose
		err = err
		return
	}

	// Set callbacks
	window.SetFramebufferSizeCallback(g.HandleReshape)
	window.SetKeyCallback(g.HandleKey)

	window.MakeContextCurrent()
	// TODO: Investigate double buffering/vsync
	glfw.SwapInterval(1)

	if gl.Init() != 0 { // GLEW_OK
		err = errors.New("gogame: error initializing opengl/glew")
		return
	}

	// Manually reshape window
	width, height = window.GetFramebufferSize()
	g.HandleReshape(window, width, height)

	// Let the game initialize its graphics
	g.InitGL()
	defer g.CleanupGL()

	last_out := time.Now().UnixNano()
	previous := time.Now().UnixNano()
	unprocessed := int64(0)
	for !window.ShouldClose() {
		current := time.Now().UnixNano()
		elapsed := current - previous
		previous = current

		unprocessed += elapsed

		for unprocessed >= nanosPerTick {
			if g.OnUpdate() {
				window.SetShouldClose(true)
			}

			ticks++
			unprocessed -= nanosPerTick
		}

		if true {
			substep := float32(unprocessed) / float32(nanosPerTick)
			g.OnRender(substep)

			frames++
		}

		if current-last_out >= NANOS_PER_SECOND {
			// TODO: Pass tps and fps to game instead of logging here
			log.Printf("%d TPS, %d FPS", ticks, frames)

			ticks = 0
			frames = 0
			last_out += NANOS_PER_SECOND
		}

		// Manually call GC
		runtime.GC()

		// Swap buffers
		window.SwapBuffers()
		glfw.PollEvents()

		// TODO: Look into handling sleeping between frames
		/*elapsed_time := time.Duration(time.Now().UnixNano()) - previous
		sleep_time := NANOS_PER_FRAME - elapsed_time // TODO: Decrease sleep time?

		if sleep_time >= SLEEP_THRESHOLD {
			time.Sleep(sleep_time)
		}*/
	}

	err = nil
	return
}
Пример #27
0
func main() {
	f, err := os.Create("Go.pprof") // Create file for profiling
	if err != nil {
		panic(err)
	}

	glfw.SetErrorCallback(errorCallback)
	if !glfw.Init() {
		panic("Can't init glfw!")
	}
	defer glfw.Terminate()
	glfw.WindowHint(glfw.Samples, 2)
	glfw.WindowHint(glfw.ContextVersionMajor, 2)
	glfw.WindowHint(glfw.ContextVersionMinor, 1)
	window, err := glfw.CreateWindow(Width, Height, Title, nil, nil)
	if err != nil {
		panic(err)
	}
	window.MakeContextCurrent()

	glfw.SwapInterval(0) // No limit on FPS
	gl.Init()
	initScene()
	loadCubeToGPU()
	for !window.ShouldClose() {
		frameInitT = time.Now()
		movPts(frameDur)
		doWind()
		if spwnTmr >= SpawnInterval {
			spwnPts(SpawnInterval)
			spwnTmr -= SpawnInterval
		}
		if cleanupTmr >= float64(MaxLife)/1000 {
			cleanupPtPool()
			cleanupTmr = 0
		}
		checkColls()
		gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)

		gpuInitT = time.Now()
		renderPts()
		window.SwapBuffers()
		gpuEndT = time.Now()
		glfw.PollEvents()

		frameEndT = time.Now()
		frameDur = frameEndT.Sub(frameInitT).Seconds() // Calculate the length of the previous frame
		spwnTmr += frameDur
		cleanupTmr += frameDur
		runTmr += frameDur
		if runTmr > MaxLife/1000 { // Start collecting framerate data and profiling after a full MaxLife worth of particles have been spawned
			frames[curFrame] = frameDur
			gpuTimes[curFrame] = gpuEndT.Sub(gpuInitT).Seconds()
			curFrame += 1
			pprof.StartCPUProfile(f)
		}
		if runTmr >= RunningTime { // Animation complete; calculate framerate mean and standard deviation
			pprof.StopCPUProfile()
			var sum float64
			var i uint64
			for i = 0; i < curFrame; i++ {
				sum += frames[i]
			}
			frameTimeMean := sum / float64(curFrame)
			fmt.Println("Average framerate was:", 1/frameTimeMean, "frames per second.")

			sum = 0
			for i = 0; i < curFrame; i++ {
				sum += gpuTimes[i]
			}
			gpuTimeMean := sum / float64(curFrame)
			fmt.Println("Average cpu time was-", frameTimeMean-gpuTimeMean, "seconds per frame.")

			sumDiffs := 0.0
			for i = 0; i < curFrame; i++ {
				sumDiffs += math.Pow(1/frames[i]-1/frameTimeMean, 2)
			}
			variance := sumDiffs / float64(curFrame)
			sd := math.Sqrt(variance)
			fmt.Println("The standard deviation was:", sd, "frames per second.")
			if PrintFrames == true {
				fmt.Print("--:")
				for i = 0; i < curFrame; i++ {
					fmt.Print(1 / frames[i])
					fmt.Print(",")
				}
				fmt.Print(".--")
			}
			break
		}

	}
	gl.DisableClientState(gl.NORMAL_ARRAY)
	gl.DisableClientState(gl.VERTEX_ARRAY)
}
Пример #28
0
func main() {
	runtime.LockOSThread()

	if !glfw.Init() {
		fmt.Fprintf(os.Stderr, "Can't open GLFW")
		return
	}
	defer glfw.Terminate()

	glfw.WindowHint(glfw.Samples, 4)
	glfw.WindowHint(glfw.ContextVersionMajor, 3)
	glfw.WindowHint(glfw.ContextVersionMinor, 3)
	glfw.WindowHint(glfw.OpenglProfile, glfw.OpenglCoreProfile)
	glfw.WindowHint(glfw.OpenglForwardCompatible, glfw.True) // needed for macs

	window, err := glfw.CreateWindow(1024, 768, "Tutorial 2", nil, nil)
	if err != nil {
		fmt.Fprintf(os.Stderr, "%v\n", err)
		return
	}

	window.MakeContextCurrent()

	gl.Init()
	gl.GetError() // Ignore error
	window.SetInputMode(glfw.StickyKeys, 1)

	gl.ClearColor(0., 0., 0.4, 0.)

	vBufferData := [...]float32{
		-1., -1., 0.,
		1., -1., 0.,
		0., 1., 0.}

	vertexArray := gl.GenVertexArray()
	vertexArray.Bind()

	prog := helper.MakeProgram("SimpleVertexShader.vertexshader", "SimpleFragmentShader.fragmentshader")

	buffer := gl.GenBuffer()
	buffer.Bind(gl.ARRAY_BUFFER)
	gl.BufferData(gl.ARRAY_BUFFER, len(vBufferData)*4, &vBufferData[0], gl.STATIC_DRAW)

	// Equivalent to a do... while
	for ok := true; ok; ok = (window.GetKey(glfw.KeyEscape) != glfw.Press && !window.ShouldClose()) {
		gl.Clear(gl.COLOR_BUFFER_BIT)

		prog.Use()

		attribLoc := gl.AttribLocation(0)
		attribLoc.EnableArray()
		buffer.Bind(gl.ARRAY_BUFFER)
		attribLoc.AttribPointer(3, gl.FLOAT, false, 0, nil)

		gl.DrawArrays(gl.TRIANGLES, 0, 3)

		attribLoc.DisableArray()

		window.SwapBuffers()
		glfw.PollEvents()
	}

}
Пример #29
0
func main() {
	runtime.LockOSThread()

	if !glfw.Init() {
		fmt.Fprintf(os.Stderr, "Can't open GLFW")
		return
	}
	defer glfw.Terminate()

	glfw.WindowHint(glfw.Samples, 4)
	glfw.WindowHint(glfw.ContextVersionMajor, 3)
	glfw.WindowHint(glfw.ContextVersionMinor, 3)
	glfw.WindowHint(glfw.OpenglProfile, glfw.OpenglCoreProfile)
	glfw.WindowHint(glfw.OpenglForwardCompatible, glfw.True) // needed for macs

	window, err := glfw.CreateWindow(1024, 768, "Tutorial 6", nil, nil)
	if err != nil {
		fmt.Fprintf(os.Stderr, "%v\n", err)
		return
	}

	window.MakeContextCurrent()

	gl.Init()
	gl.GetError() // Ignore error
	window.SetInputMode(glfw.StickyKeys, 1)
	window.SetCursorPosition(1024/2, 768/2)
	window.SetInputMode(glfw.Cursor, glfw.CursorHidden)

	gl.ClearColor(0., 0., 0.4, 0.)

	gl.Enable(gl.DEPTH_TEST)
	gl.DepthFunc(gl.LESS)

	gl.Enable(gl.CULL_FACE)

	camera := input.NewCamera(window)

	vertexArray := gl.GenVertexArray()
	defer vertexArray.Delete()
	vertexArray.Bind()

	prog := helper.MakeProgram("TransformVertexShader.vertexshader", "TextureFragmentShader.fragmentshader")
	defer prog.Delete()

	matrixID := prog.GetUniformLocation("MVP")

	texture, err := helper.TextureFromDDS("uvtemplate.DDS")
	if err != nil {
		fmt.Printf("Couldn't make texture: %v\n", err)
		return
	}
	defer texture.Delete()
	texSampler := prog.GetUniformLocation("myTextureSampler")

	vBufferData := [...]float32{
		-1.0, -1.0, -1.0,
		-1.0, -1.0, 1.0,
		-1.0, 1.0, 1.0,
		1.0, 1.0, -1.0,
		-1.0, -1.0, -1.0,
		-1.0, 1.0, -1.0,
		1.0, -1.0, 1.0,
		-1.0, -1.0, -1.0,
		1.0, -1.0, -1.0,
		1.0, 1.0, -1.0,
		1.0, -1.0, -1.0,
		-1.0, -1.0, -1.0,
		-1.0, -1.0, -1.0,
		-1.0, 1.0, 1.0,
		-1.0, 1.0, -1.0,
		1.0, -1.0, 1.0,
		-1.0, -1.0, 1.0,
		-1.0, -1.0, -1.0,
		-1.0, 1.0, 1.0,
		-1.0, -1.0, 1.0,
		1.0, -1.0, 1.0,
		1.0, 1.0, 1.0,
		1.0, -1.0, -1.0,
		1.0, 1.0, -1.0,
		1.0, -1.0, -1.0,
		1.0, 1.0, 1.0,
		1.0, -1.0, 1.0,
		1.0, 1.0, 1.0,
		1.0, 1.0, -1.0,
		-1.0, 1.0, -1.0,
		1.0, 1.0, 1.0,
		-1.0, 1.0, -1.0,
		-1.0, 1.0, 1.0,
		1.0, 1.0, 1.0,
		-1.0, 1.0, 1.0,
		1.0, -1.0, 1.0,
	}

	uvBufferData := [...]float32{
		0.000059, 1.0 - 0.000004,
		0.000103, 1.0 - 0.336048,
		0.335973, 1.0 - 0.335903,
		1.000023, 1.0 - 0.000013,
		0.667979, 1.0 - 0.335851,
		0.999958, 1.0 - 0.336064,
		0.667979, 1.0 - 0.335851,
		0.336024, 1.0 - 0.671877,
		0.667969, 1.0 - 0.671889,
		1.000023, 1.0 - 0.000013,
		0.668104, 1.0 - 0.000013,
		0.667979, 1.0 - 0.335851,
		0.000059, 1.0 - 0.000004,
		0.335973, 1.0 - 0.335903,
		0.336098, 1.0 - 0.000071,
		0.667979, 1.0 - 0.335851,
		0.335973, 1.0 - 0.335903,
		0.336024, 1.0 - 0.671877,
		1.000004, 1.0 - 0.671847,
		0.999958, 1.0 - 0.336064,
		0.667979, 1.0 - 0.335851,
		0.668104, 1.0 - 0.000013,
		0.335973, 1.0 - 0.335903,
		0.667979, 1.0 - 0.335851,
		0.335973, 1.0 - 0.335903,
		0.668104, 1.0 - 0.000013,
		0.336098, 1.0 - 0.000071,
		0.000103, 1.0 - 0.336048,
		0.000004, 1.0 - 0.671870,
		0.336024, 1.0 - 0.671877,
		0.000103, 1.0 - 0.336048,
		0.336024, 1.0 - 0.671877,
		0.335973, 1.0 - 0.335903,
		0.667969, 1.0 - 0.671889,
		1.000004, 1.0 - 0.671847,
		0.667979, 1.0 - 0.335851,
	}

	// Invert V because we're using a compressed texture
	for i := 1; i < len(uvBufferData); i += 2 {
		uvBufferData[i] = 1.0 - uvBufferData[i]
	}

	vertexBuffer := gl.GenBuffer()
	defer vertexBuffer.Delete()
	vertexBuffer.Bind(gl.ARRAY_BUFFER)
	gl.BufferData(gl.ARRAY_BUFFER, len(vBufferData)*4, &vBufferData, gl.STATIC_DRAW)

	uvBuffer := gl.GenBuffer()
	defer uvBuffer.Delete()
	uvBuffer.Bind(gl.ARRAY_BUFFER)
	gl.BufferData(gl.ARRAY_BUFFER, len(uvBufferData)*4, &uvBufferData, gl.STATIC_DRAW)

	// Equivalent to a do... while
	for ok := true; ok; ok = (window.GetKey(glfw.KeyEscape) != glfw.Press && !window.ShouldClose()) {
		func() {
			gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)

			prog.Use()
			defer gl.ProgramUnuse()

			view, proj := camera.ComputeViewPerspective()
			model := mgl32.Ident4()

			MVP := proj.Mul4(view).Mul4(model)
			//mvpArray := mvp.AsCMOArray(mathgl.FLOAT32).([16]float32)

			matrixID.UniformMatrix4fv(false, MVP)

			gl.ActiveTexture(gl.TEXTURE0)
			texture.Bind(gl.TEXTURE_2D)
			defer texture.Unbind(gl.TEXTURE_2D)
			texSampler.Uniform1i(0)

			vertexAttrib := gl.AttribLocation(0)
			vertexAttrib.EnableArray()
			defer vertexAttrib.DisableArray()
			vertexBuffer.Bind(gl.ARRAY_BUFFER)
			defer vertexBuffer.Unbind(gl.ARRAY_BUFFER)
			vertexAttrib.AttribPointer(3, gl.FLOAT, false, 0, nil)

			uvAttrib := gl.AttribLocation(1)
			uvAttrib.EnableArray()
			defer uvAttrib.DisableArray()
			uvBuffer.Bind(gl.ARRAY_BUFFER)
			defer uvBuffer.Unbind(gl.ARRAY_BUFFER)
			uvAttrib.AttribPointer(2, gl.FLOAT, false, 0, nil)

			gl.DrawArrays(gl.TRIANGLES, 0, 12*3)

			window.SwapBuffers()
			glfw.PollEvents()
		}() // Defers unbinds and disables to here, end of the loop
	}

}
Пример #30
0
func main() {
	runtime.LockOSThread()
	defer runtime.UnlockOSThread()

	fmt.Println("OpenTibia Map Editor")

	conf := &Configuration{}
	conf.Load("config.json")

	var sprLoader client.SpriteLoader
	var datLoader client.DatLoader
	var itemLoader ot.ItemLoader
	//var otbLoader ot.OtbLoader
	//var otMap ot.Map

	var group sync.WaitGroup
	group.Add(3)

	go func() {
		if err := sprLoader.Load(conf.SprFile); err != nil {
			log.Fatal(err)
		}
		group.Done()
	}()
	go func() {
		if err := datLoader.Load(conf.DatFile); err != nil {
			log.Fatal(err)
		}
		group.Done()
	}()
	go func() {
		if err := itemLoader.LoadXML("items.xml"); err != nil {
			log.Fatal(err)
		}
		group.Done()
	}()
	/*
		go func() {
			if err := otbLoader.Load("items.otb"); err != nil {
				log.Fatal(err)
			}

			otMap.Initialize()
			if err := otMap.ReadOTBM("forgotten.otbm", &otbLoader); err != nil {
				log.Fatal(err)
			}

			group.Done()
		}()
	*/
	group.Wait()

	if !glfw.Init() {
		panic("Failed to initialize GLFW")
	}
	defer glfw.Terminate()

	glfw.WindowHint(glfw.ContextVersionMajor, 3)
	glfw.WindowHint(glfw.ContextVersionMinor, 2)
	glfw.WindowHint(glfw.OpenglForwardCompatible, glfw.True)
	glfw.WindowHint(glfw.OpenglProfile, glfw.OpenglCoreProfile)

	window, err := glfw.CreateWindow(640, 480, "Map Editor", nil, nil)
	if err != nil {
		panic(err)
	}

	window.SetKeyCallback(keyHandler)

	window.MakeContextCurrent()

	if err := gl.Init(); err != 0 {
		log.Fatal("Could not init gl")
	}

	log.Printf("OpenGL Version: %s", gl.GetString(gl.VERSION))
	log.Printf("GLSL Version: %s", gl.GetString(gl.SHADING_LANGUAGE_VERSION))
	log.Printf("Vendor: %s", gl.GetString(gl.VENDOR))
	log.Printf("Renderer: %s", gl.GetString(gl.RENDERER))

	r := renderer.Renderer{}

	r.Initialize()
	r.SetViewport(0, 0, 800, 600)

	for !window.ShouldClose() {
		r.Render()

		window.SwapBuffers()
		glfw.PollEvents()
	}

	/*
		ids := datLoader.GetSpriteIDs(420)
		sprite := sprLoader.GetSprite(ids[0])

		img := image.NewNRGBA(image.Rect(0, 0, 32, 32))
		img.Pix = sprite

		out, _ := os.Create("test.png")
		defer out.Close()

		if err := png.Encode(out, img); err != nil {
			log.Fatal(err)
		}*/
}