Exemple #1
0
func (self *Application) run() error {
	if err := glfw.Init(); err != nil {
		return err
	}
	defer glfw.Terminate()

	glfw.WindowHint(glfw.Resizable, glfw.False)
	glfw.WindowHint(glfw.ContextVersionMajor, 4)
	glfw.WindowHint(glfw.ContextVersionMinor, 1)
	glfw.WindowHint(glfw.OpenGLProfile, glfw.OpenGLCoreProfile)
	glfw.WindowHint(glfw.OpenGLForwardCompatible, glfw.True)

	window, err := glfw.CreateWindow(512, 512, "GL", nil, nil)
	if err != nil {
		return err
	}

	window.MakeContextCurrent()

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

	if err := self.setup(); err != nil {
		return err
	}

	for !window.ShouldClose() {
		self.display()
		window.SwapBuffers()
		glfw.PollEvents()
	}

	return nil
}
Exemple #2
0
func CreateContext(width int, height int) (*Context, error) {
	if err := glfw.Init(); err != nil {
		fmt.Println("failed to initialize glfw:", err)
	}

	glfw.WindowHint(glfw.Resizable, glfw.False)
	glfw.WindowHint(glfw.ContextVersionMajor, 4)
	glfw.WindowHint(glfw.ContextVersionMinor, 1)
	glfw.WindowHint(glfw.OpenGLProfile, glfw.OpenGLCoreProfile)
	glfw.WindowHint(glfw.OpenGLForwardCompatible, glfw.True)
	window, err := glfw.CreateWindow(width, height, "flamingo", nil, nil)

	if err != nil {
		glfw.Terminate()
		return nil, err
	}

	window.MakeContextCurrent()

	// Initialize Glow
	if err = gl.Init(); err != nil {
		glfw.Terminate()
		return nil, err
	}

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

	return &Context{window}, nil
}
func main() {
	if err := glfw.Init(); err != nil {
		log.Fatalln("failed to inifitialize glfw:", err)
	}
	defer glfw.Terminate()

	glfw.WindowHint(glfw.Resizable, glfw.False)
	glfw.WindowHint(glfw.ContextVersionMajor, 4)
	glfw.WindowHint(glfw.ContextVersionMinor, 1)
	glfw.WindowHint(glfw.OpenGLProfile, glfw.OpenGLCoreProfile)
	glfw.WindowHint(glfw.OpenGLForwardCompatible, glfw.True)
	window, err := glfw.CreateWindow(windowWidth, windowHeight, "basic shaders", nil, nil)
	if err != nil {
		panic(err)
	}
	window.MakeContextCurrent()

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

	window.SetKeyCallback(keyCallback)

	err = programLoop(window)
	if err != nil {
		log.Fatal(err)
	}
}
Exemple #4
0
func (me *Core) Init() {
	if err := glfw.Init(); err != nil {
		panic(err)
	}
	if err := gl.Init(); err != nil {
		panic(err)
	}
}
func Run() {
	if err := glfw.Init(); err != nil {
		glog.Fatalln("failed to initialize glfw", err)
	}
	defer glfw.Terminate()

	setupWindowOptions()
	window, err := glfw.CreateWindow(WindowWidth, WindowHeight, "Game", nil, nil)
	if err != nil {
		panic(err)
	}
	window.MakeContextCurrent()

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

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

	shaderSource, err := ReadShaders("colorShader")
	if err != nil {
		panic(err)
	}
	program, err := NewProgram(shaderSource)
	if err != nil {
		panic(err)
	}
	program.Use()

	sprite := &SpriteComponent{-.5, -.5, 1, 1}
	sprite.ReloadGraphics()

	vertAttrib := uint32(gl.GetAttribLocation(program.program, CStr("vertPosition")))
	gl.EnableVertexAttribArray(vertAttrib)
	gl.VertexAttribPointer(vertAttrib, 3, gl.FLOAT, false, 0, gl.PtrOffset(0))

	gl.Enable(gl.DEPTH_TEST)
	gl.DepthFunc(gl.LESS)
	gl.ClearColor(1.0, 1.0, 1.0, 1.0)

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

		program.Use()

		gl.BindVertexArray(sprite.vaoID)
		gl.DrawArrays(gl.TRIANGLES, 0, 2*3)

		window.SwapBuffers()
		glfw.PollEvents()
	}
}
Exemple #6
0
// New returns a newly created Screen
func New(width int, height int, fullscreen bool, FSAA int, name string) *Screen {
	window := &Screen{}

	C.SDL_Init(C.SDL_INIT_VIDEO)
	C.setGlContextAttributes()

	C.SDL_GL_SetAttribute(C.SDL_GL_DOUBLEBUFFER, 1)

	// Force hardware accel
	C.SDL_GL_SetAttribute(C.SDL_GL_ACCELERATED_VISUAL, 1)

	if FSAA > 0 {
		// FSAA (Fullscreen antialiasing)
		C.SDL_GL_SetAttribute(C.SDL_GL_MULTISAMPLEBUFFERS, 1)
		C.SDL_GL_SetAttribute(C.SDL_GL_MULTISAMPLESAMPLES, C.int(FSAA)) // 2, 4, 8
	}

	flags := C.SDL_WINDOW_OPENGL | C.SDL_RENDERER_ACCELERATED
	if fullscreen {
		flags = flags | C.SDL_WINDOW_FULLSCREEN
	}

	C.SDL_CreateWindowAndRenderer(C.int(width), C.int(height), C.Uint32(flags), &window.sdlWindow, &window.renderer)
	C.SDL_SetWindowTitle(window.sdlWindow, C.CString(name))
	C.SDL_GL_CreateContext(window.sdlWindow)

	if err := gl.Init(); err != nil {
		panic(err)
	}
	version := gl.GoStr(gl.GetString(gl.VERSION))
	fmt.Println("OpenGL version", version)

	// Configure global settings
	gl.Enable(gl.BLEND)
	gl.BlendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA)

	gl.ClearColor(0.0, 0.0, 0.0, 1.0)
	gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)

	window.Width = width
	window.Height = height
	window.name = name
	window.shouldClose = false
	C.SDL_GL_SwapWindow(window.sdlWindow)

	window.startTime = time.Now()
	window.frameTime = time.Now()
	C.SDL_GL_SetSwapInterval(1)
	window.vsync = true

	return window
}
Exemple #7
0
func makeWindow() *glfw.Window {
	win, err := glfw.CreateWindow(windowWidth, windowHeight, "Tutorial #1", nil, nil)

	if err != nil {
		panic(err)
	}

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

	win.MakeContextCurrent()
	gl.ClearColor(1.0, 1.0, 1.0, 1.0)

	return win
}
Exemple #8
0
func initGL() string {
	// Initialize Glow
	if err := gl.Init(); err != nil {
		panic(err)
	}

	version := gl.GoStr(gl.GetString(gl.VERSION))
	fmt.Println("OpenGL version", version)
	fmt.Println("OpenGl shading version", gl.GoStr(gl.GetString(gl.SHADING_LANGUAGE_VERSION)))
	fmt.Println("OpenGl renderer", gl.GoStr(gl.GetString(gl.RENDERER)))

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

	return version
}
Exemple #9
0
func (screen *Screen) Init(title string, onCloseHandler func(), chip *chip8.Chip8) {
	var err error

	screen.chip = chip

	err = glfw.Init()

	if err != nil {
		panic(err)
	}

	window, err := glfw.CreateWindow(SCREEN_WIDTH, SCREEN_HEIGHT, title, nil, nil)
	if err != nil {
		panic(err)
	}

	window.MakeContextCurrent()

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

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

	gl.ClearColor(255.0, 0.0, 0.0, 0.0)                          //Set the cleared screen colour to black
	gl.Viewport(0, 0, int32(SCREEN_WIDTH), int32(SCREEN_HEIGHT)) //This sets up the viewport so that the coordinates (0, 0) are at the top left of the window

	for !window.ShouldClose() {
		// Do OpenGL stuff
		gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
		window.SwapBuffers()
		glfw.PollEvents()
	}

	onCloseHandler()

}
Exemple #10
0
func CreateWindow(title string, width int, height int) *Window {
	if err := glfw.Init(); err != nil {
		log.Fatalln("Failed to initialize glfw:", err)
	}

	/* GLFW Window settings */
	glfw.WindowHint(glfw.ContextVersionMajor, 4)
	glfw.WindowHint(glfw.ContextVersionMinor, 1)
	glfw.WindowHint(glfw.OpenGLProfile, glfw.OpenGLCoreProfile)
	glfw.WindowHint(glfw.OpenGLForwardCompatible, glfw.True)

	window, err := glfw.CreateWindow(width, height, title, nil, nil)
	if err != nil {
		panic(err)
	}
	window.MakeContextCurrent()
	glfw.SwapInterval(2)

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

	window.SetInputMode(glfw.CursorMode, glfw.CursorDisabled)
	window.SetKeyCallback(KeyCallback)
	window.SetCursorPosCallback(MouseMoveCallback)
	window.SetMouseButtonCallback(MouseButtonCallback)

	w := &Window{
		Width:         width,
		Height:        height,
		Wnd:           window,
		maxFrameTime:  0.0,
		lastFrameTime: glfw.GetTime(),
	}
	w.SetMaxFps(60)
	return w
}
func main() {
	if err := glfw.Init(); err != nil {
		log.Fatalln("failed to inifitialize glfw:", err)
	}
	defer glfw.Terminate()

	glfw.WindowHint(glfw.Resizable, glfw.False)
	glfw.WindowHint(glfw.ContextVersionMajor, 4)
	glfw.WindowHint(glfw.ContextVersionMinor, 1)
	glfw.WindowHint(glfw.OpenGLProfile, glfw.OpenGLCoreProfile)
	glfw.WindowHint(glfw.OpenGLForwardCompatible, glfw.True)
	window, err := glfw.CreateWindow(windowWidth, windowHeight, "Hello!", nil, nil)
	if err != nil {
		panic(err)
	}
	window.MakeContextCurrent()

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

	window.SetKeyCallback(keyCallback)

	// program loop
	for !window.ShouldClose() {
		// poll events and call their registered callbacks
		glfw.PollEvents()

		// perform rendering
		gl.ClearColor(0.2, 0.5, 0.5, 1.0)
		gl.Clear(gl.COLOR_BUFFER_BIT)

		// swap in the rendered buffer
		window.SwapBuffers()
	}
}
Exemple #12
0
func main() {
	if err := glfw.Init(); err != nil {
		log.Fatalln("failed to inifitialize glfw:", err)
	}
	defer glfw.Terminate()

	glfw.WindowHint(glfw.Resizable, glfw.False)
	glfw.WindowHint(glfw.ContextVersionMajor, 4)
	glfw.WindowHint(glfw.ContextVersionMinor, 1)
	glfw.WindowHint(glfw.OpenGLProfile, glfw.OpenGLCoreProfile)
	glfw.WindowHint(glfw.OpenGLForwardCompatible, glfw.True)

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

	window := win.NewWindow(1280, 720, "Lighting maps")

	err := programLoop(window)
	if err != nil {
		log.Fatalln(err)
	}
}
/* *****************  MAIN FUNCTION  ************************ */
func main() {

	/* ****************    OVR INIT CODE  ***************** */

	if err := glfw.Init(); err != nil {
		log.Fatalln("failed to initialize glfw")
	}

	defer glfw.Terminate()
	C.ovr_Initialize(nil)

	//create an HMD for reference.
	var hmd C.ovrHmd = nil

	// find number of headsets
	hmdCount := (int)(C.ovrHmd_Detect())
	// print headset count
	fmt.Println(hmdCount)
	fmt.Printf("Found %d connected Rift device(s)\n\n", hmdCount)

	// grab the first headset
	if hmdCount > 0 {
		for i := 0; i < 1; i++ {
			hmd = C.ovrHmd_Create((C.int)(i))
			//Print headset name
			fmt.Println(C.GoString(hmd.ProductName))
		}
	}

	//if there is no headset connected, create a new debug.
	if hmd == nil {

		fmt.Println("Unable to open rift device\n Creating debug device.\n")
		hmd = C.ovrHmd_CreateDebug(C.ovrHmd_DK2)
	}

	//Starts the sensor device
	if C.ovrHmd_ConfigureTracking(hmd, C.ovrTrackingCap_Orientation|C.ovrTrackingCap_Position, 0) == 0 {
		fmt.Println("Unable to start Rift head tracker\n")

	}

	//extendedMode := C.ovrHmdCap_ExtendDesktop & hmd.HmdCaps

	//positioning of window and size of window
	var outposition mgl32.Vec2
	outposition[0] = (float32)(hmd.WindowsPos.x)
	outposition[1] = (float32)(hmd.WindowsPos.y)

	//TODO: Change this to output at chosen resolution, not necessarily native pg. 76 Oculus Rift in action
	var outsize mgl32.Vec2
	outsize[0] = (float32)(hmd.Resolution.w)
	outsize[1] = (float32)(hmd.Resolution.h)

	//print position and sizes to console
	fmt.Printf("Rift position:\t\t %f \t %f \nRift Size:\t\t %f \t %f \n\n", outposition.X(), outposition.Y(), outsize.X(), outsize.Y())

	monitors := glfw.GetMonitors()
	var riftIndex int
	//loop over the monitors
	for index, element := range monitors {
		//print the monitor positions
		posX, posY := element.GetPos()
		fmt.Printf("Monitor Position:\t\t %d \t %d\n", posX, posY)

		if float32(posX) == outposition.X() && float32(posY) == outposition.Y() {

			riftIndex = index
		}
	}

	//Get video mode of monitor
	mode := monitors[riftIndex].GetVideoMode()
	outsize[0] = float32(mode.Width)
	outsize[1] = float32(mode.Height)

	/* ***************************************************** */

	// *************  OPENGL / GLFW INIT CODE  ************** */

	glfw.WindowHint(glfw.Decorated, 0)
	glfw.WindowHint(glfw.Resizable, glfw.False)
	glfw.WindowHint(glfw.ContextVersionMajor, 4)
	glfw.WindowHint(glfw.ContextVersionMinor, 1)
	glfw.WindowHint(glfw.OpenGLProfile, glfw.OpenGLCoreProfile)
	glfw.WindowHint(glfw.OpenGLForwardCompatible, glfw.True)

	window, err := glfw.CreateWindow(int(outsize.X()), int(outsize.Y()), "LinuxVR", nil, nil)
	window.SetPos(int(outposition.X()), int(outposition.Y()))

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

	window.MakeContextCurrent()

	//Print OpenGL Version to console
	version := gl.GoStr(gl.GetString(gl.VERSION))
	fmt.Println("OpenGL Version", version, "\n\n")

	//keyboard input callback
	window.SetKeyCallback(onKey)

	/* **************************************************** */

	previousTime := glfw.GetTime()
	totalTime := 0.0000

	/* *******************   MAIN LOOP  ******************** */

	for !window.ShouldClose() {

		glfw.PollEvents()

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

		//get current head state
		state := C.ovrHmd_GetTrackingState(hmd, 0)
		orientation := state.HeadPose.ThePose.Orientation

		//convert to go type float32
		var q mgl32.Quat
		q.W = (float32)(orientation.w)
		q.V[0] = (float32)(orientation.x)
		q.V[1] = (float32)(orientation.y)
		q.V[2] = (float32)(orientation.z)

		//publish tracking information once a second
		if totalTime >= 1 {
			fmt.Printf("w: %f X: %f Y: %f Z: %f\n", q.W, q.X(), q.Y(), q.Z())
			totalTime = 0
		}

		//basic opengl things

		draw(window)

		//Swap buffers
		window.SwapBuffers()

		//Poll for events (keyboard, resize, etc)

	}

	/* *****************  OVR SHUTDOWN  ******************** */
	C.ovrHmd_Destroy(hmd)
	C.ovr_Shutdown()

}
func (renderer *Renderer) Loop() {

	defer glog.Flush()

	if err := glfw.Init(); err != nil {
		glog.Fatalln("GLFW failed to initialize:", err)
		glog.Info("GLFW failed to init")
	}

	glfw.WindowHint(glfw.ContextVersionMajor, 3)
	glfw.WindowHint(glfw.ContextVersionMinor, 2)
	glfw.WindowHint(glfw.OpenGLForwardCompatible, glfw.True)
	glfw.WindowHint(glfw.Resizable, glfw.False)

	window, windowError := glfw.CreateWindow(800, 600, "OpenGL", nil, nil)

	if windowError != nil {
		glog.Info("oops")
		panic(windowError)
	}
	glog.Info("Buffer")
	defer func() {
		window.Destroy()
		glfw.Terminate()
		glog.Info("ending")
		renderer.ended = true
		//system_end <- true
	}()

	window.MakeContextCurrent()

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

	renderer.keyCallback = func(window *glfw.Window, key glfw.Key, scancode int, action glfw.Action, mods glfw.ModifierKey) {
		glog.Infof("key: %v, scancode: %v, action: %v, mods: %v", key, scancode, action, mods)
	}

	window.SetKeyCallback(renderer.keyCallback)

	//<-system_start
	renderer.started = true
	//system_started <- true
	gl.ClearDepth(1.0)

	var vboID uint32
	gl.GenBuffers(1, &vboID)
	var vertexData = []float32{
		1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1,
	}
	gl.BindBuffer(gl.ARRAY_BUFFER, vboID)
	gl.BufferData(gl.ARRAY_BUFFER, len(vertexData)*4, gl.Ptr(vertexData), gl.STATIC_DRAW)
	gl.BindBuffer(gl.ARRAY_BUFFER, 0)

	//get shaders
	vertexShader, fragmentShader := getShaders()
	program, err := newProgram(vertexShader, fragmentShader)
	program.UseProgram()

	if err != nil {
		panic(err)
	}

	//bind attributes

	//	L:
	for !window.ShouldClose() {

		//renderer.drawGame(program)
		gl.EnableVertexAttribArray(0)
		gl.BindBuffer(gl.ARRAY_BUFFER, vboID)
		gl.VertexAttribPointer(
			0,
			3,
			gl.FLOAT,
			false,
			0,
			gl.PtrOffset(0))
		gl.DrawArrays(gl.TRIANGLES, 0, 3)
		gl.DisableVertexAttribArray(0)
		window.SwapBuffers()
		glfw.PollEvents()
	}

	if vboID != 0 {
		gl.DeleteBuffers(1, &vboID)
	}

}
Exemple #15
0
func main() {
	var parser = flags.NewParser(&gOpts, flags.Default)

	var err error
	var args []string
	if args, err = parser.Parse(); err != nil {
		os.Exit(1)
	}

	if len(args) < 1 || len(args) > 2 {
		panic(fmt.Errorf("Too many or not enough arguments"))
	}

	gDiffFlag = len(args) == 2

	// make sure that we display any errors that are encountered
	//glfw.SetErrorCallback(errorCallback)

	// the GLFW library has to be initialized before any of the methods
	// can be invoked
	if err = glfw.Init(); err != nil {
		panic(err)
	}

	// to be tidy, make sure glfw.Terminate() is called at the end of
	// the program to clean things up by using `defer`
	defer glfw.Terminate()

	// hints are the way you configure the features requested for the
	// window and are required to be set before calling glfw.CreateWindow().

	// desired number of samples to use for mulitsampling
	//glfw.WindowHint(glfw.Samples, 4)

	// request a OpenGL 4.1 core context
	if runtime.GOOS == "darwin" {
		glfw.WindowHint(glfw.ContextVersionMajor, 3)
		glfw.WindowHint(glfw.ContextVersionMinor, 3)
	} else {
		glfw.WindowHint(glfw.ContextVersionMajor, 4)
		glfw.WindowHint(glfw.ContextVersionMinor, 1)
	}
	glfw.WindowHint(glfw.OpenGLForwardCompatible, glfw.True)
	glfw.WindowHint(glfw.OpenGLProfile, glfw.OpenGLCoreProfile)

	// do the actual window creation
	var window *glfw.Window
	window, err = glfw.CreateWindow(1024, 768, "goicmpgl", nil, nil)
	if err != nil {
		// we legitimately cannot recover from a failure to create
		// the window in this sample, so just bail out
		panic(err)
	}

	// set the callback function to get all of the key input from the user
	window.SetKeyCallback(keyCallback)
	window.SetMouseButtonCallback(mouseDownCallback)
	window.SetScrollCallback(mouseWheelCallback)
	window.SetCursorPosCallback(mouseMoveCallback)

	// GLFW3 can work with more than one window, so make sure we set our
	// new window as the current context to operate on
	window.MakeContextCurrent()

	// disable v-sync for max FPS if the driver allows it
	//glfw.SwapInterval(0)

	// make sure that GLEW initializes all of the GL functions
	if err = gl.Init(); err != nil {
		panic(err)
	}

	var attribs []string = []string{
		"position",
		"uvs",
	}

	// compile our shaders
	var progTex0 *Program
	if progTex0, err = LoadShaderProgram(vertShader, fragShaderTex0, attribs); err != nil {
		panic(err)
	}
	defer progTex0.DeleteProgram()

	var progGrid *Program
	if progGrid, err = LoadShaderProgram(vertShader, S_FragmentShader_Grid, attribs); err != nil {
		panic(err)
	}
	defer progGrid.DeleteProgram()

	var diffProg2 *Program
	if diffProg2, err = LoadShaderProgram(vertShader, sProgram2Src, attribs); err != nil {
		panic(err)
	}
	defer diffProg2.DeleteProgram()

	var diffProg3 *Program
	if diffProg3, err = LoadShaderProgram(vertShader, sProgram3Src, attribs); err != nil {
		panic(err)
	}
	defer diffProg3.DeleteProgram()

	var diffProg4 *Program
	if diffProg4, err = LoadShaderProgram(vertShader, sProgram4Src, attribs); err != nil {
		panic(err)
	}
	defer diffProg4.DeleteProgram()

	var diffProg5 *Program
	if diffProg5, err = LoadShaderProgram(vertShader, sProgram5Src, attribs); err != nil {
		panic(err)
	}
	defer diffProg5.DeleteProgram()

	var image1_path string = args[0]
	if strings.HasPrefix(image1_path, "http") {
		if err, image1_path = downloadImage(image1_path); err != nil {
			panic(err)
		}
	}

	var texture *Texture
	if err, texture, gImage1 = NewTexture(image1_path, false); err != nil {
		panic(err)
	}
	defer texture.DeleteTexture()

	var texture2 *Texture
	if gDiffFlag {
		var image2_path string = args[1]
		if strings.HasPrefix(image2_path, "http") {
			if err, image2_path = downloadImage(image2_path); err != nil {
				panic(err)
			}
		}

		if err, texture2, gImage2 = NewTexture(image2_path, false); err != nil {
			panic(err)
		}
		defer texture2.DeleteTexture()

		if texture.Size.X != texture2.Size.X || texture.Size.Y != texture2.Size.Y {
			fmt.Println("WARNING: image dimensions differ!")
		} else {
			fmt.Printf("image dimensions: %dx%d\n", texture.Size.X, texture.Size.Y)
		}
	} else {
		fmt.Printf("image dimensions: %dx%d\n", texture.Size.X, texture.Size.Y)
	}

	var font *Font
	if err, font = NewFont("Font.png", 16); err != nil {
		panic(err)
	}
	defer font.DeleteFont()

	var help1 *String = font.NewString("1: show only A")
	defer help1.DeleteString()
	var help2 *String = font.NewString("2: show only B")
	defer help2.DeleteString()
	var help3 *String = font.NewString("3: show diff A&B")
	defer help3.DeleteString()
	var helph *String = font.NewString("h: toggle this help")
	defer helph.DeleteString()
	var helparrows *String = font.NewString("<up>,<down>: go from A to B")
	defer helparrows.DeleteString()
	var helpzoom *String = font.NewString("[]: zoom in/out (also mouse wheel)")
	defer helpzoom.DeleteString()
	var helpclear *String = font.NewString("Z: reset zoom/view")
	defer helpclear.DeleteString()
	var helpescape *String = font.NewString("ESC: quit")
	defer helpescape.DeleteString()

	var vbo *VBO
	if vbo, err = NewVBOQuad(0, 0, float32(texture.Size.X), float32(texture.Size.Y)); err != nil {
		panic(err)
	}
	defer vbo.DeleteVBO()

	var cnt float32 = 0

	// while there's no request to close the window
	for !window.ShouldClose() {
		cnt += 1

		// get the texture of the window because it may have changed since creation
		width, height := window.GetFramebufferSize()
		wwidth, _ := window.GetSize()
		gRetinaScale = float32(width) / float32(wwidth)

		//fmt.Printf("x=%d y=%d wx=%d wy=%d\n", width, height, wwidth, wheight)

		if cnt >= float32(width) {
			cnt = 0
		}

		var matrix Matrix2x3 = IdentityMatrix2x3()
		matrix = matrix.Translate(-1.0, 1.0)
		matrix = matrix.Scale(2.0/float32(width), -2.0/float32(height))

		// clear it all out
		gl.Viewport(0, 0, int32(width), int32(height))
		gl.ClearColor(0.0, 0.0, 0.0, 1.0)
		gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)

		gl.Enable(gl.BLEND)
		gl.BlendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA)
		gl.BlendEquation(gl.FUNC_ADD)

		var matrix3 Matrix2x3 = matrix.Scale(gZoom, gZoom)
		matrix3 = matrix3.Translate(gOffX, gOffY)

		// draw the grid
		if true {
			vbo.Bind()
			progGrid.UseProgram()

			color1 := [4]float32{.4, .4, .4, 1}
			color2 := [4]float32{.9, .9, .9, 1}
			grid := [3]float32{float32(texture.Size.X), float32(texture.Size.Y), 8 / gZoom}
			//fmt.Printf("%.2f %.2f %.2f %.2f\n", grid[0], grid[1], grid[2], grid[3])
			progGrid.ProgramUniformMatrix4fv("ModelviewMatrix", matrix3.Array())
			progGrid.ProgramUniform4fv("color1", color1)
			progGrid.ProgramUniform4fv("color2", color2)
			progGrid.ProgramUniform3fv("grid", grid)

			if err = progGrid.ValidateProgram(); err != nil {
				panic(err)
			}

			vbo.Draw()

			vbo.Unbind()
			progGrid.UnuseProgram()
		}

		// draw the texture
		if !gDiffFlag {
			vbo.Bind()
			progTex0.UseProgram()
			texture.BindTexture(0)

			progTex0.ProgramUniformMatrix4fv("ModelviewMatrix", matrix3.Array())
			progTex0.ProgramUniform1i("tex1", 0)
			progTex0.ProgramUniform1f("blend", gBlend)

			if err = progTex0.ValidateProgram(); err != nil {
				panic(err)
			}

			vbo.Draw()

			vbo.Unbind()
			progTex0.UnuseProgram()
			texture.UnbindTexture(0)
		} else {
			var diffBlend float32 = gBlend

			var diffProg *Program

			if diffBlend < 0.25 {
				diffBlend *= 4
				diffProg = diffProg2
			} else if diffBlend < 0.5 { // 0.25 -> 0.5
				diffBlend = 4*diffBlend - 1
				diffProg = diffProg4
			} else if diffBlend < 0.75 { // 0.5 -> 0.75
				diffBlend = 4*diffBlend - 2
				diffProg = diffProg5
			} else { // 0.75 -> 1.0=
				diffBlend = 4*diffBlend - 3
				diffProg = diffProg3
			}

			vbo.Bind()
			diffProg.UseProgram()
			texture.BindTexture(0)
			texture2.BindTexture(1)

			diffProg.ProgramUniformMatrix4fv("ModelviewMatrix", matrix3.Array())
			diffProg.ProgramUniform1i("decalA", 0)
			diffProg.ProgramUniform1i("decalB", 1)
			diffProg.ProgramUniform1f("diffBlend", diffBlend)

			if err = diffProg.ValidateProgram(); err != nil {
				panic(err)
			}

			vbo.Draw()

			vbo.Unbind()
			diffProg.UnuseProgram()
			texture.UnbindTexture(0)
			texture2.UnbindTexture(1)
		}

		// font
		if gHelp {
			color := [...]float32{0, 0, 1, 1}
			bg := [...]float32{0.5, 0.5, 0.5, 0.5}
			var line float32 = 0
			if err = helph.Draw(font, color, bg, matrix, 0.5, 20, 100+line*128); err != nil {
				panic(err)
			}
			line += 1
			help1.Draw(font, color, bg, matrix, 0.5, 20, 100+line*128)
			line += 1
			help2.Draw(font, color, bg, matrix, 0.5, 20, 100+line*128)
			line += 1
			help3.Draw(font, color, bg, matrix, 0.5, 20, 100+line*128)
			line += 1
			helparrows.Draw(font, color, bg, matrix, 0.5, 20, 100+line*128)
			line += 1
			helpzoom.Draw(font, color, bg, matrix, 0.5, 20, 100+line*128)
			line += 1
			helpclear.Draw(font, color, bg, matrix, 0.5, 20, 100+line*128)
			line += 1
			helpescape.Draw(font, color, bg, matrix, 0.5, 20, 100+line*128)
			line += 1
		}

		// swapping OpenGL buffers and polling events has been decoupled
		// in GLFW3, so make sure to invoke both here
		window.SwapBuffers()
		glfw.PollEvents()
	}
}
Exemple #16
0
func main() {
	if err := glfw.Init(); err != nil {
		log.Fatalln("failed to initialize glfw:", err)
	}
	defer glfw.Terminate()

	glfw.WindowHint(glfw.Resizable, glfw.False)
	glfw.WindowHint(glfw.ContextVersionMajor, 4)
	glfw.WindowHint(glfw.ContextVersionMinor, 1)
	glfw.WindowHint(glfw.OpenGLProfile, glfw.OpenGLCoreProfile)
	glfw.WindowHint(glfw.OpenGLForwardCompatible, 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)
	}

	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(mgl32.DegToRad(45.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()
	}
}
Exemple #17
0
//Start -
func (glRenderer *OpenglRenderer) Start() {
	if err := glfw.Init(); err != nil {
		log.Fatalln("failed to initialize glfw:", err)
	}
	defer glfw.Terminate()

	glfw.WindowHint(glfw.Resizable, glfw.False)
	glfw.WindowHint(glfw.ContextVersionMajor, 4)
	glfw.WindowHint(glfw.ContextVersionMinor, 1)
	glfw.WindowHint(glfw.OpenGLProfile, glfw.OpenGLCoreProfile)
	glfw.WindowHint(glfw.OpenGLForwardCompatible, glfw.True)

	if glRenderer.FullScreen {
		glRenderer.WindowWidth = glfw.GetPrimaryMonitor().GetVideoMode().Width
	} else if glRenderer.WindowWidth == 0 {
		glRenderer.WindowWidth = glfw.GetPrimaryMonitor().GetVideoMode().Width * 95 / 100
	}
	if glRenderer.FullScreen {
		glRenderer.WindowHeight = glfw.GetPrimaryMonitor().GetVideoMode().Height
	} else if glRenderer.WindowHeight == 0 {
		glRenderer.WindowHeight = glfw.GetPrimaryMonitor().GetVideoMode().Height * 95 / 100
	}

	var monitor *glfw.Monitor
	if glRenderer.FullScreen {
		monitor = glfw.GetPrimaryMonitor()
	}
	window, err := glfw.CreateWindow(glRenderer.WindowWidth, glRenderer.WindowHeight, glRenderer.WindowTitle, monitor, nil)
	if err != nil {
		panic(err)
	}
	window.MakeContextCurrent()
	glRenderer.Window = window

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

	var vao uint32
	gl.GenVertexArrays(1, &vao)
	gl.BindVertexArray(vao)

	gl.Enable(gl.TEXTURE_CUBE_MAP_SEAMLESS)
	gl.Enable(gl.BLEND)
	gl.DepthFunc(gl.LEQUAL)
	gl.CullFace(gl.BACK)

	glRenderer.initPostEffects()

	glRenderer.onInit()

	window.SetRefreshCallback(func(w *glfw.Window) {
		glRenderer.mainLoop()
		window.SwapBuffers()
	})

	//Main loop
	for !window.ShouldClose() {
		glRenderer.mainLoop()
		window.SwapBuffers()
		glfw.PollEvents()
	}
}
Exemple #18
0
func Main() {
	err := glfw.Init()
	if err != nil {
		panic(err)
	}
	defer glfw.Terminate()

	glfw.WindowHint(glfw.Resizable, glfw.False)
	glfw.WindowHint(glfw.ContextVersionMajor, 3)
	glfw.WindowHint(glfw.ContextVersionMinor, 2)
	glfw.WindowHint(glfw.OpenGLProfile, glfw.OpenGLCoreProfile)
	glfw.WindowHint(glfw.OpenGLForwardCompatible, glfw.True)
	window, err := glfw.CreateWindow(WindowWidth, WindowHeight, "Cube", nil, nil)
	Window = window
	if err != nil {
		panic(err)
	}
	window.MakeContextCurrent()

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

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

	// Configure the vertex and fragment shaders
	program, err := newProgram("SimpleVertexShader.vertexshader", "SimpleFragmentShader.fragmentshader")
	if err != nil {
		panic(err)
	}
	gl.UseProgram(program)

	projection := mgl32.Perspective(mgl32.DegToRad(45.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"))
	// 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()

	width, height := window.GetSize()
	window.SetCursorPos(float64(width/2), float64(height/2))
	window.SetKeyCallback(input.OnKey)
	window.SetCursorPosCallback(input.OnCursor)
	window.SetMouseButtonCallback(input.OnMouse)

	meshes.LoadColladaCube("cube.dae")

	for !player.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])
		player.MainPlayer.Draw(program)
		for _, element := range game.Universe {
			(element).Draw(program)
		}

		// Maintenance
		window.SwapBuffers()
		glfw.PollEvents()
	}
}