예제 #1
5
파일: cube.go 프로젝트: jasonrpowers/glow
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
파일: main.go 프로젝트: rakyll/GCSolutions
func onStart(glctx gl.Context, sz size.Event) {
	log.Printf("creating GL program")
	var err error
	keystate = map[touch.Sequence]int{}
	program, err = glutil.CreateProgram(glctx, vertexShader, fragmentShader)
	if err != nil {
		log.Printf("error creating GL program: %v", err)
		return
	}

	glctx.Enable(gl.DEPTH_TEST)

	position = glctx.GetAttribLocation(program, "position")
	texCordIn = glctx.GetAttribLocation(program, "texCordIn")
	color = glctx.GetUniformLocation(program, "color")
	drawi = glctx.GetUniformLocation(program, "drawi")
	projection = glctx.GetUniformLocation(program, "projection")
	camera = glctx.GetUniformLocation(program, "camera")

	loadTexture(glctx)
	glctx.UseProgram(program)

	projectionMat := mgl32.Perspective(mgl32.DegToRad(75.0), float32(1), 0.5, 40.0)
	glctx.UniformMatrix4fv(projection, projectionMat[:])

	cameraMat := mgl32.LookAtV(mgl32.Vec3{0.5, 0, 1.5}, mgl32.Vec3{0, 0, 0}, mgl32.Vec3{0, 1, 0})
	glctx.UniformMatrix4fv(camera, cameraMat[:])

	board = NewBoard(glctx, float32(0.05), 10)

	numKeys := len(board.bigKeys) + len(board.smallKeys)

	InitializeSound(numKeys)
}
예제 #3
0
//
// Draw Loop Function
// This function gets called on every update.
//
func drawLoop(glw *wrapper.Glw) {
	// Sets the Clear Color (Background Color)
	gl.ClearColor(0.0, 0.0, 0.0, 1.0)

	// Clears the Window
	gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)

	// Enables Depth
	gl.Enable(gl.DEPTH_TEST)

	// Sets the Shader program to Use
	gl.UseProgram(shaderProgram)

	// Define the model transformations for the cube
	cube.ResetModel()
	cube.Translate(x+0.5, y, z)
	cube.Scale(scale, scale, scale)            //scale equally in all axis
	cube.Rotate(-angle_x, mgl32.Vec3{1, 0, 0}) //rotating in clockwise direction around x-axis
	cube.Rotate(-angle_y, mgl32.Vec3{0, 1, 0}) //rotating in clockwise direction around y-axis
	cube.Rotate(-angle_z, mgl32.Vec3{0, 0, 1}) //rotating in clockwise direction around z-axis

	// Define the model transformations for our sphere
	sphere.ResetModel()
	sphere.Translate(-x-0.5, 0, 0)
	sphere.Scale(scale/3.0, scale/3.0, scale/3.0) //scale equally in all axis
	sphere.Rotate(-angle_x, mgl32.Vec3{1, 0, 0})  //rotating in clockwise direction around x-axis
	sphere.Rotate(-angle_y, mgl32.Vec3{0, 1, 0})  //rotating in clockwise direction around y-axis
	sphere.Rotate(-angle_z, mgl32.Vec3{0, 0, 1})  //rotating in clockwise direction around z-axis

	// Projection matrix : 45° Field of View, 4:3 ratio, display range : 0.1 unit <-> 100 units
	var Projection mgl32.Mat4 = mgl32.Perspective(30.0, aspect_ratio, 0.1, 100.0)

	// Camera matrix
	var View mgl32.Mat4 = mgl32.LookAtV(
		mgl32.Vec3{0, 0, 4}, // Camera is at (0,0,4), in World Space
		mgl32.Vec3{0, 0, 0}, // and looks at the origin
		mgl32.Vec3{0, 1, 0}, // Head is up (set to 0,-1,0 to look upside-down)
	)

	// Send our uniforms variables to the currently bound shader,
	gl.Uniform1ui(colourmodeUniform, uint32(colourmode))
	gl.UniformMatrix4fv(viewUniform, 1, false, &View[0])
	gl.UniformMatrix4fv(projectionUniform, 1, false, &Projection[0])

	// Draws the Cube
	gl.UniformMatrix4fv(modelUniform, 1, false, &cube.Model[0])
	cube.Draw()

	// Draw our sphere
	gl.UniformMatrix4fv(modelUniform, 1, false, &sphere.Model[0])
	sphere.DrawSphere()

	gl.DisableVertexAttribArray(0)
	gl.UseProgram(0)

	/* Modify our animation variables */
	angle_x += angle_inc_x
	angle_y += angle_inc_y
	angle_z += angle_inc_z
}
예제 #4
0
파일: camera.go 프로젝트: jcecil/go-avatar
func (c *Camera) Draw(program uint32) {
	//c.UpdateCamera()

	camera := mgl32.LookAtV(c.position, c.position.Add(c.direction), c.up)
	cameraUniform := gl.GetUniformLocation(program, gl.Str("camera\x00"))
	gl.UniformMatrix4fv(cameraUniform, 1, false, &camera[0])

}
예제 #5
0
파일: hlgl.go 프로젝트: hialin/hialin
func Start(windowName string) error {
	err := llgl.InitDisplay(windowName)
	if err != nil {
		return err
	}
	err = llgl.InitGL()
	if err != nil {
		return err
	}

	glstate.program, err = loadShaders("cube.vert", "cube.frag")
	if err != nil {
		return err
	}
	glstate.program.Use()

	glstate.projectionUL = glstate.program.Uniform("projection")
	glstate.cameraUL = glstate.program.Uniform("camera")
	glstate.modelUL = glstate.program.Uniform("model")
	glstate.texUL = glstate.program.Uniform("tex")

	state.camera = mgl.LookAtV(mgl.Vec3{3, 3, 3}, mgl.Vec3{0, 0, 0}, mgl.Vec3{0, 1, 0})
	state.model = mgl.Ident4()

	glstate.cameraUL.SetMat4(state.camera)
	glstate.modelUL.SetMat4(state.model)
	glstate.texUL.SetTextureSlot(0)

	glstate.program.BindFragDataLocation(0, "outputColor")

	texturePath, err := assets.Locate("code.png")
	if err != nil {
		return err
	}
	texture, err := llgl.MakeTexture(0, texturePath)
	if err != nil {
		return err
	}
	texture.Bind(0)

	// Configure the vertex data
	vao := llgl.NewVertexArray()
	vao.Bind()

	glstate.vbo = llgl.NewVertexBuffer()
	glstate.vbo.Bind()

	val := glstate.program.VertexAttrib("vert")
	val.Enable()
	val.PointerFloat32(3, 5, 0)

	valTC := glstate.program.VertexAttrib("vertTexCoord")
	valTC.Enable()
	valTC.PointerFloat32(2, 5, 3)

	fpsCounter = NewFpsCounter()
	return nil
}
예제 #6
0
// Load loads and sets up the model
func (m *Model) Load(fileName string) {

	m.loadFile(fileName)

	shader := sm.Shader{VertSrcFile: m.data.VertShaderFile, FragSrcFile: m.data.FragShaderFile, Name: fmt.Sprintf("%s:%s", m.data.VertShaderFile, m.data.FragShaderFile)}
	program, err := m.shaders.LoadProgram(shader, false)
	if err != nil {
		return
	}
	m.currentProgram = program

	gl.UseProgram(m.currentProgram)

	m.projection = mgl32.Perspective(mgl32.DegToRad(45.0), float32(windowWidth)/windowHeight, 0.1, 10.0)
	m.projectionUniform = gl.GetUniformLocation(m.currentProgram, gl.Str("projection\x00"))
	gl.UniformMatrix4fv(m.projectionUniform, 1, false, &m.projection[0])

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

	m.modelUniform = gl.GetUniformLocation(m.currentProgram, gl.Str("model\x00"))
	gl.UniformMatrix4fv(m.modelUniform, 1, false, &m.model[0])

	m.textureUniform = gl.GetUniformLocation(m.currentProgram, gl.Str("tex\x00"))
	gl.Uniform1i(m.textureUniform, 0)

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

	// Load the texture
	m.textures.LoadTexture(m.data.TextureFile, m.data.TextureFile)

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

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

	vertAttrib := uint32(gl.GetAttribLocation(m.currentProgram, gl.Str("vert\x00")))
	gl.EnableVertexAttribArray(vertAttrib)
	gl.VertexAttribPointer(vertAttrib, 3, gl.FLOAT, false, m.data.VertSize*4, gl.PtrOffset(0)) // 4:number of bytes in a float32

	texCoordAttrib := uint32(gl.GetAttribLocation(m.currentProgram, gl.Str("vertTexCoord\x00")))
	gl.EnableVertexAttribArray(texCoordAttrib)
	gl.VertexAttribPointer(texCoordAttrib, 2, gl.FLOAT, true, m.data.VertSize*4, gl.PtrOffset(3*4)) // 4:number of bytes in a float32

	if m.data.Indexed {
		var indices uint32
		gl.GenBuffers(1, &indices)
		gl.BindBuffer(gl.ELEMENT_ARRAY_BUFFER, indices)
		gl.BufferData(gl.ELEMENT_ARRAY_BUFFER, len(m.data.Indices)*4, gl.Ptr(m.data.Indices), gl.STATIC_DRAW)
	}

	gl.BindVertexArray(0)
}
예제 #7
0
// LookAt changes the transformation of the 3D object
// to face the target's position. The model matrix
// will be updated accordingly.
//
// Note: This transformation makes use of the up vector.
func (t *Transform) LookAt(x, y, z float32) {
	target := mgl32.Vec3{x, y, z}

	t.matrix = mgl32.LookAtV(
		t.position,
		target,
		t.Up,
	).Inv()
}
예제 #8
0
func (e *Engine) Draw(c size.Event) {

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

	gl.ClearColor(0.2, 0.2, 0.2, 1)
	gl.Clear(gl.COLOR_BUFFER_BIT)
	gl.Clear(gl.DEPTH_BUFFER_BIT)

	gl.UseProgram(e.shader.program)

	m := mgl32.Perspective(0.785, float32(c.WidthPt/c.HeightPt), 0.1, 10.0)
	gl.UniformMatrix4fv(e.shader.projection, m[:])

	eye := mgl32.Vec3{0, 0, 8}
	center := mgl32.Vec3{0, 0, 0}
	up := mgl32.Vec3{0, 1, 0}

	m = mgl32.LookAtV(eye, center, up)
	gl.UniformMatrix4fv(e.shader.view, m[:])

	m = mgl32.HomogRotate3D(float32(e.touchLoc.X/c.WidthPt-0.5)*3.14*2, mgl32.Vec3{0, 1, 0})
	gl.UniformMatrix4fv(e.shader.modelx, m[:])

	m = mgl32.HomogRotate3D(float32(e.touchLoc.Y/c.HeightPt-0.5)*3.14, mgl32.Vec3{1, 0, 0})
	gl.UniformMatrix4fv(e.shader.modely, m[:])

	coordsPerVertex := 3
	for _, obj := range e.shape.Objs {
		gl.BindBuffer(gl.ARRAY_BUFFER, obj.coord)
		gl.EnableVertexAttribArray(e.shader.vertCoord)

		gl.VertexAttribPointer(e.shader.vertCoord, coordsPerVertex, gl.FLOAT, false, 12, 0)

		if obj.useuv == true {
			gl.Uniform1i(e.shader.useuv, 1)
			texCoordsPerVertex := 2
			gl.BindBuffer(gl.ARRAY_BUFFER, obj.uvcoord)
			gl.EnableVertexAttribArray(e.shader.vertTexCoord)
			gl.VertexAttribPointer(e.shader.vertTexCoord, texCoordsPerVertex, gl.FLOAT, false, 8, 0)

			gl.BindTexture(gl.TEXTURE_2D, obj.tex)
		} else {
			gl.Uniform1i(e.shader.useuv, 0)
			gl.Uniform4f(e.shader.color, obj.color[0], obj.color[1], obj.color[2], obj.color[3])
		}
		gl.DrawArrays(gl.TRIANGLES, 0, obj.vcount)
		if obj.useuv {
			gl.DisableVertexAttribArray(e.shader.vertTexCoord)
		}
		gl.DisableVertexAttribArray(e.shader.vertCoord)
	}

	debug.DrawFPS(c)
}
예제 #9
0
func (e *Engine) Draw(c size.Event) {

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

	gl.ClearColor(0.5, 0.8, 0.8, 1)
	gl.Clear(gl.COLOR_BUFFER_BIT)
	gl.Clear(gl.DEPTH_BUFFER_BIT)

	gl.UseProgram(e.shader.program)

	gl.Uniform3fv(e.shader.lightdir, []float32{0.5, 0.6, 0.7})

	m := mgl32.Perspective(1.3, float32(c.WidthPt/c.HeightPt), 0.1, 10.0)
	gl.UniformMatrix4fv(e.shader.projectionmatrix, m[:])

	eye := mgl32.Vec3{0, 0, 0.2}
	center := mgl32.Vec3{0, 0, 0}
	up := mgl32.Vec3{0, 1, 0}

	m = mgl32.LookAtV(eye, center, up)
	gl.UniformMatrix4fv(e.shader.viewmatrix, m[:])

	m = mgl32.HomogRotate3D((e.touchx/float32(c.WidthPt)-0.5)*6.28, mgl32.Vec3{0, 1, 0})
	gl.UniformMatrix4fv(e.shader.modelmatrix, m[:])

	m = mgl32.HomogRotate3D((e.touchx/float32(c.WidthPt)-0.5)*6.28, mgl32.Vec3{0, -1, 0})
	gl.UniformMatrix4fv(e.shader.lightmatrix, m[:])

	coordsPerVertex := 3
	for _, obj := range e.shape.Objs {
		gl.BindBuffer(gl.ARRAY_BUFFER, obj.coord)
		gl.EnableVertexAttribArray(e.shader.vertCoord)
		gl.VertexAttribPointer(e.shader.vertCoord, coordsPerVertex, gl.FLOAT, false, 12, 0)

		texCoordsPerVertex := 2
		gl.BindBuffer(gl.ARRAY_BUFFER, obj.uvcoord)
		gl.EnableVertexAttribArray(e.shader.texcoord)
		gl.VertexAttribPointer(e.shader.texcoord, texCoordsPerVertex, gl.FLOAT, false, 8, 0)

		gl.BindBuffer(gl.ARRAY_BUFFER, obj.normal)
		gl.EnableVertexAttribArray(e.shader.normal)
		gl.VertexAttribPointer(e.shader.normal, 3, gl.FLOAT, false, 12, 0)

		gl.BindTexture(gl.TEXTURE_2D, obj.tex)

		gl.DrawArrays(gl.TRIANGLES, 0, obj.vcount)

		gl.DisableVertexAttribArray(e.shader.texcoord)
		gl.DisableVertexAttribArray(e.shader.normal)
		gl.DisableVertexAttribArray(e.shader.vertCoord)
	}

	debug.DrawFPS(c)
}
예제 #10
0
파일: test.go 프로젝트: Nekony/go-gl-test
func (me *test) Display(c *Core) {
	me.o1.Draw(c)
	me.o2.Draw(c)

	projection := mgl32.Perspective(mgl32.DegToRad(Fov), float32(WindowWidth)/WindowHeight, Near, Far)
	view := mgl32.LookAtV(mgl32.Vec3{3, 3, 3}, mgl32.Vec3{0, 0, 0}, mgl32.Vec3{0, 1, 0})
	model := mgl32.Ident4()
	MVP := projection.Mul4(view).Mul4(model)

	gl.UniformMatrix4fv(mvpLoc, 1, false, &MVP[0])
	gl.Uniform1i(TexLoc, 0)

}
예제 #11
0
파일: camera.go 프로젝트: walesey/go-engine
func (c *Camera) GetMouseVector(windowSize mgl32.Vec2, mouse mgl32.Vec2) mgl32.Vec3 {
	v, err := mgl32.UnProject(
		mgl32.Vec3{mouse.X(), windowSize.Y() - mouse.Y(), 0.5},
		mgl32.LookAtV(c.Translation, c.Lookat, c.Up),
		mgl32.Perspective(mgl32.DegToRad(c.Angle), windowSize.X()/windowSize.Y(), c.Near, c.Far),
		0, 0, int(windowSize.X()), int(windowSize.Y()),
	)
	if err == nil {
		return v.Sub(c.Translation).Normalize()
	} else {
		log.Println("Error converting camera vector: ", err)
	}
	return c.Lookat
}
예제 #12
0
func (e *Engine) Draw(c size.Event) {
	since := time.Now().Sub(e.started)
	//gl.Enable()

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

	gl.ClearColor(0, 0, 0, 1)
	gl.Clear(gl.COLOR_BUFFER_BIT)
	gl.Clear(gl.DEPTH_BUFFER_BIT)

	gl.UseProgram(e.shader.program)

	m := mgl32.Perspective(0.785, float32(c.WidthPt/c.HeightPt), 0.1, 10.0)
	gl.UniformMatrix4fv(e.shader.projection, m[:])

	eye := mgl32.Vec3{3, 3, 3}
	center := mgl32.Vec3{0, 0, 0}
	up := mgl32.Vec3{0, 1, 0}

	m = mgl32.LookAtV(eye, center, up)
	gl.UniformMatrix4fv(e.shader.view, m[:])

	m = mgl32.HomogRotate3D(float32(since.Seconds()), mgl32.Vec3{0, 1, 0})
	gl.UniformMatrix4fv(e.shader.model, m[:])

	gl.BindBuffer(gl.ARRAY_BUFFER, e.shape.buf)

	coordsPerVertex := 3
	texCoordsPerVertex := 2
	vertexCount := len(cubeData) / (coordsPerVertex + texCoordsPerVertex)

	gl.EnableVertexAttribArray(e.shader.vertCoord)
	gl.VertexAttribPointer(e.shader.vertCoord, coordsPerVertex, gl.FLOAT, false, 20, 0) // 4 bytes in float, 5 values per vertex

	gl.EnableVertexAttribArray(e.shader.vertTexCoord)
	gl.VertexAttribPointer(e.shader.vertTexCoord, texCoordsPerVertex, gl.FLOAT, false, 20, 12)

	gl.BindTexture(gl.TEXTURE_2D, e.shape.texture)

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

	gl.DisableVertexAttribArray(e.shader.vertCoord)

	debug.DrawFPS(c)
}
예제 #13
0
func (e *Engine) Draw(c event.Config) {
	since := time.Now().Sub(e.started)

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

	gl.ClearColor(0, 0, 0, 1)
	gl.Clear(gl.COLOR_BUFFER_BIT)
	gl.Clear(gl.DEPTH_BUFFER_BIT)

	gl.UseProgram(e.shader.program)

	// Setup MVP
	var m mgl.Mat4
	m = mgl.Perspective(0.785, float32(c.Width/c.Height), 0.1, 10.0)
	gl.UniformMatrix4fv(e.shader.projection, m[:])

	m = mgl.LookAtV(
		mgl.Vec3{3, 3, 3}, // eye
		mgl.Vec3{0, 0, 0}, // center
		mgl.Vec3{0, 1, 0}, // up
	)
	gl.UniformMatrix4fv(e.shader.view, m[:])

	m = mgl.HomogRotate3D(float32(since.Seconds()), mgl.Vec3{0, 1, 0})
	gl.UniformMatrix4fv(e.shader.model, m[:])

	// Draw our shape
	gl.BindBuffer(gl.ARRAY_BUFFER, e.shape.buf)

	gl.EnableVertexAttribArray(e.shader.vertCoord)
	gl.VertexAttribPointer(e.shader.vertCoord, e.shape.coordsPerVertex, gl.FLOAT, false, 20, 0) // 4 bytes in float, 5 values per vertex

	gl.EnableVertexAttribArray(e.shader.vertTexCoord)
	gl.VertexAttribPointer(e.shader.vertTexCoord, e.shape.texCoordsPerVertex, gl.FLOAT, false, 20, 12)

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

	gl.DrawArrays(gl.TRIANGLES, 0, e.shape.vertexCount)

	gl.DisableVertexAttribArray(e.shader.vertCoord)

	//debug.DrawFPS(c)
}
예제 #14
0
func (e *Engine) Draw(c size.Event) {

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

	gl.ClearColor(0, 0, 0, 1)
	gl.Clear(gl.COLOR_BUFFER_BIT)
	gl.Clear(gl.DEPTH_BUFFER_BIT)

	gl.UseProgram(e.shader.program)

	m := mgl32.Perspective(0.785, float32(c.WidthPt/c.HeightPt), 0.1, 10.0)
	gl.UniformMatrix4fv(e.shader.projection, m[:])

	eye := mgl32.Vec3{0, 3, 3}
	center := mgl32.Vec3{0, 0, 0}
	up := mgl32.Vec3{0, 1, 0}

	m = mgl32.LookAtV(eye, center, up)
	gl.UniformMatrix4fv(e.shader.view, m[:])

	m = mgl32.HomogRotate3D(float32(e.touchLocX*5/c.WidthPt), mgl32.Vec3{0, 1, 0})
	gl.UniformMatrix4fv(e.shader.modelx, m[:])

	m = mgl32.HomogRotate3D(float32(e.touchLocY*5/c.HeightPt), mgl32.Vec3{1, 0, 0})
	gl.UniformMatrix4fv(e.shader.modely, m[:])

	gl.BindBuffer(gl.ARRAY_BUFFER, e.shape.buf)
	gl.EnableVertexAttribArray(e.shader.vertCoord)
	gl.VertexAttribPointer(e.shader.vertCoord, coordsPerVertex, gl.FLOAT, false, 0, 0)

	gl.BindBuffer(gl.ARRAY_BUFFER, e.shape.colorbuf)
	gl.EnableVertexAttribArray(e.shader.color)
	gl.VertexAttribPointer(e.shader.color, colorsPerVertex, gl.FLOAT, false, 0, 0) //更新color值

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

	gl.DisableVertexAttribArray(e.shader.vertCoord)
	gl.DisableVertexAttribArray(e.shader.color)

	debug.DrawFPS(c)
}
예제 #15
0
func (e *Engine) Draw(c size.Event) {

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

	gl.ClearColor(0.2, 0.2, 0.2, 1)
	gl.Clear(gl.COLOR_BUFFER_BIT)
	gl.Clear(gl.DEPTH_BUFFER_BIT)

	gl.UseProgram(e.shader.program)

	m := mgl32.Perspective(0.785, float32(c.WidthPt/c.HeightPt), 0.1, 10.0)
	gl.UniformMatrix4fv(e.shader.projection, m[:])

	eye := mgl32.Vec3{0, 0, 5}
	center := mgl32.Vec3{0, 0, 0}
	up := mgl32.Vec3{0, 1, 0}

	m = mgl32.LookAtV(eye, center, up)
	gl.UniformMatrix4fv(e.shader.view, m[:])

	m = mgl32.HomogRotate3D(float32(e.touchLoc.X*10/c.WidthPt), mgl32.Vec3{0, 1, 0})
	gl.UniformMatrix4fv(e.shader.modelx, m[:])

	m = mgl32.HomogRotate3D(float32(e.touchLoc.Y*10/c.HeightPt), mgl32.Vec3{1, 0, 0})
	gl.UniformMatrix4fv(e.shader.modely, m[:])

	coordsPerVertex := 3
	for _, buf := range e.shape.bufs {
		gl.BindBuffer(gl.ARRAY_BUFFER, buf.coord)
		gl.EnableVertexAttribArray(e.shader.vertCoord)
		gl.VertexAttribPointer(e.shader.vertCoord, coordsPerVertex, gl.FLOAT, false, 0, 0)
		gl.Uniform4f(e.shader.color, buf.color[0], buf.color[1], buf.color[2], buf.color[3])
		gl.DrawArrays(gl.TRIANGLES, 0, buf.vcount)

		gl.DisableVertexAttribArray(e.shader.vertCoord)
	}

	debug.DrawFPS(c)
}
예제 #16
0
func main() {
	// init glfw
	if err := glfw.Init(); err != nil {
		panic(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)

	// make an application window
	window, err := glfw.CreateWindow(windowWidth, windowHeight, "Transform", nil, nil)
	if err != nil {
		panic(err)
	}
	window.MakeContextCurrent()

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

	// create vertex & fragment shader
	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])

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

	points := []float32{
		-0.9, -0.9, -0.9,
		0.9, -0.9, -0.9,
		0.9, -0.9, 0.9,
		-0.9, -0.9, 0.9,
		-0.9, 0.9, -0.9,
		0.9, 0.9, -0.9,
		0.9, 0.9, 0.9,
		-0.9, 0.9, 0.9,
	}

	vertices := []uint32{
		0, 1,
		1, 2,
		2, 3,
		3, 0,
		0, 4,
		1, 5,
		2, 6,
		3, 7,
		4, 5,
		5, 6,
		6, 7,
		7, 4,
	}

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

	defer gl.BindVertexArray(0)

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

	var ibo uint32
	gl.GenBuffers(1, &ibo)
	gl.BindBuffer(gl.ELEMENT_ARRAY_BUFFER, ibo)
	gl.BufferData(gl.ELEMENT_ARRAY_BUFFER, len(vertices)*4, gl.Ptr(vertices), gl.STATIC_DRAW)

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

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

	angleX := 0.0
	angleY := 0.0
	angleZ := 0.0
	previousTime := glfw.GetTime()

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

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

		angleX += math.Sin((elapsed / period) * math.Pi * 2.0)
		angleY += math.Sin((elapsed / period) / 6.0 * math.Pi * 2.0)
		angleZ += math.Sin((elapsed / period) / 3.0 * math.Pi * 2.0)
		model = mgl32.HomogRotate3DY(float32(angleY)).Mul4(mgl32.HomogRotate3DX(float32(angleX))).Mul4(mgl32.HomogRotate3DZ(float32(angleZ)))
		gl.UseProgram(program)
		gl.UniformMatrix4fv(modelUniform, 1, false, &model[0])

		gl.BindVertexArray(vao)

		gl.DrawElements(gl.LINES, int32(len(vertices)), gl.UNSIGNED_INT, gl.PtrOffset(0))

		window.SwapBuffers()
		glfw.PollEvents()
	}
}
예제 #17
0
func (glRenderer *OpenglRenderer) DrawGeometry(geometry *renderer.Geometry, transform mgl32.Mat4) {
	glRenderer.enableShader()
	glRenderer.enableMaterial()
	glRenderer.enableCubeMap()

	if glRenderer.activeShader == nil {
		panic("ERROR: No shader is configured.")
	}

	shader := glRenderer.activeShader
	program := shader.Program
	params := glRenderer.rendererParams

	glRenderer.enableDepthTest(params.DepthTest)
	glRenderer.enableDepthMask(params.DepthMask)
	glRenderer.enableCullFace(params.CullBackface)
	glRenderer.enableUnlit(params.Unlit)
	glRenderer.setTransparency(params.Transparency)

	// set buffers
	gl.BindBuffer(gl.ARRAY_BUFFER, geometry.VboId)
	gl.BindBuffer(gl.ELEMENT_ARRAY_BUFFER, geometry.IboId)

	// update buffers
	if geometry.VboDirty && len(geometry.Verticies) > 0 && len(geometry.Indicies) > 0 {
		gl.BufferData(gl.ARRAY_BUFFER, len(geometry.Verticies)*4, gl.Ptr(geometry.Verticies), gl.DYNAMIC_DRAW)
		gl.BufferData(gl.ELEMENT_ARRAY_BUFFER, len(geometry.Indicies)*4, gl.Ptr(geometry.Indicies), gl.DYNAMIC_DRAW)
		geometry.VboDirty = false
	}

	// set uniforms
	modelNormal := transform.Inv().Transpose()
	shader.Uniforms["model"] = transform
	shader.Uniforms["modelNormal"] = modelNormal

	// set camera uniforms
	cam := glRenderer.camera
	win := glRenderer.WindowDimensions()
	shader.Uniforms["cameraTranslation"] = cam.Translation
	if cam.Ortho {
		shader.Uniforms["projection"] = mgl32.Ortho2D(0, win.X(), win.Y(), 0)
		shader.Uniforms["camera"] = mgl32.Ident4()
	} else {
		shader.Uniforms["projection"] = mgl32.Perspective(mgl32.DegToRad(cam.Angle), win.X()/win.Y(), cam.Near, cam.Far)
		shader.Uniforms["camera"] = mgl32.LookAtV(cam.Translation, cam.Lookat, cam.Up)
	}

	shader.Uniforms["unlit"] = glRenderer.unlit
	shader.Uniforms["useTextures"] = glRenderer.useTextures

	shader.Uniforms["ambientLightValue"] = glRenderer.ambientLightValue

	shader.Uniforms["nbPointLights"] = glRenderer.nbPointLights
	shader.Uniforms["pointLightValues"] = glRenderer.pointLightValues
	shader.Uniforms["pointLightPositions"] = glRenderer.pointLightPositions

	shader.Uniforms["nbDirectionalLights"] = glRenderer.nbDirectionalLights
	shader.Uniforms["directionalLightValues"] = glRenderer.directionalLightValues
	shader.Uniforms["directionalLightVectors"] = glRenderer.directionalLightVectors

	// set custom uniforms
	setupUniforms(shader)

	// set verticies attribute
	vertAttrib := uint32(gl.GetAttribLocation(program, gl.Str("vert\x00")))
	gl.EnableVertexAttribArray(vertAttrib)
	gl.VertexAttribPointer(vertAttrib, 3, gl.FLOAT, false, renderer.VertexStride*4, gl.PtrOffset(0))
	// set normals attribute
	normAttrib := uint32(gl.GetAttribLocation(program, gl.Str("normal\x00")))
	gl.EnableVertexAttribArray(normAttrib)
	gl.VertexAttribPointer(normAttrib, 3, gl.FLOAT, false, renderer.VertexStride*4, gl.PtrOffset(3*4))
	// set texture coord attribute
	texCoordAttrib := uint32(gl.GetAttribLocation(program, gl.Str("texCoord\x00")))
	gl.EnableVertexAttribArray(texCoordAttrib)
	gl.VertexAttribPointer(texCoordAttrib, 2, gl.FLOAT, false, renderer.VertexStride*4, gl.PtrOffset(6*4))
	// vertex color attribute
	colorAttrib := uint32(gl.GetAttribLocation(program, gl.Str("color\x00")))
	gl.EnableVertexAttribArray(colorAttrib)
	gl.VertexAttribPointer(colorAttrib, 4, gl.FLOAT, false, renderer.VertexStride*4, gl.PtrOffset(8*4))

	gl.DrawElements(gl.TRIANGLES, (int32)(len(geometry.Indicies)), gl.UNSIGNED_INT, gl.PtrOffset(0))
}
예제 #18
0
파일: godraw.go 프로젝트: esenti/godraw
func CreateContext(width, height int) Context {
	vertexShader := `
#version 330
uniform mat4 projection;
uniform mat4 camera;
uniform mat4 model;
in vec3 vert;
void main() {
    gl_Position = projection * camera * model * vec4(vert, 1);
}
` + "\x00"

	fragmentShader := `
#version 330
uniform vec4 color;
out vec4 outputColor;
void main() {
    outputColor = color;
}
` + "\x00"

	vertices := []float32{
		0.0, 0.0, 0.0,
		1.0, 0.0, 0.0,
		1.0, 1.0, 0.0,
		1.0, 1.0, 0.0,
		0.0, 1.0, 0.0,
		0.0, 0.0, 0.0,
	}

	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, 3)
	glfw.WindowHint(glfw.ContextVersionMinor, 3)
	glfw.WindowHint(glfw.OpenGLProfile, glfw.OpenGLCoreProfile)
	glfw.WindowHint(glfw.OpenGLForwardCompatible, glfw.True)
	window, err := glfw.CreateWindow(width, height, "OpenGL", nil, nil)
	if err != nil {
		panic(err)
	}
	window.MakeContextCurrent()

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

	program, err := newProgram(vertexShader, fragmentShader)
	if err != nil {
		panic(err)
	}

	gl.UseProgram(program)

	projection := mgl32.Ortho2D(0, 800, 0, 600)
	projectionUniform := gl.GetUniformLocation(program, gl.Str("projection\x00"))
	gl.UniformMatrix4fv(projectionUniform, 1, false, &projection[0])

	camera := mgl32.LookAtV(mgl32.Vec3{0, 0, 0.5}, 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])

	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(vertices)*4, gl.Ptr(vertices), gl.STATIC_DRAW)

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

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

	return Context{Window: window, program: program}
}
예제 #19
0
func (c *Camera) Update(dt float32) {
	/* Handle keyboard input */
	move := false
	dir := mgl.Vec3{}
	if KeyDown(KeyW) && !KeyDown(KeyS) {
		dir[2] += 1
		move = true
	}
	if KeyDown(KeyS) && !KeyDown(KeyW) {
		dir[2] -= 1
		move = true
	}
	if KeyDown(KeyA) && !KeyDown(KeyD) {
		dir[0] -= 1
		move = true
	}
	if KeyDown(KeyD) && !KeyDown(KeyA) {
		dir[0] += 1
		move = true
	}
	if KeyDown(KeyE) && !KeyDown(KeyQ) {
		dir[1] += 1
		move = true
	}
	if KeyDown(KeyQ) && !KeyDown(KeyE) {
		dir[1] -= 1
		move = true
	}

	if move {
		/* Calculate normalized movement vector */
		dv := 5.0 * dt /* magic number: movement speed */
		dir = dir.Normalize().Mul(dv)

		right := c.Transform.Right.Mul(dir[0])
		up := mgl.Vec3{0, dir[1], 0}
		forward := c.Transform.Forward.Mul(dir[2])

		/* Translate camera */
		c.Transform.Translate(right.Add(up.Add(forward)))
	}

	/* Mouse look */
	if MouseDown(MouseButton1) {
		rx := c.Transform.Rotation[0] - Mouse.DY*0.08
		ry := c.Transform.Rotation[1] - Mouse.DX*0.09

		/* Camera angle limits */
		/* -90 < rx < 90 */
		rx = float32(math.Max(-90.0, math.Min(90.0, float64(rx))))

		/* -180 < ry < 180 */
		if ry > 180.0 {
			ry -= 360.0
		}
		if ry < -180.0 {
			ry += 360.0
		}
		c.Transform.Rotation[0] = rx
		c.Transform.Rotation[1] = ry
	}

	/* Update transform with new position & rotation */
	c.Transform.Update(dt)

	/* Calculate new view matrix based on forward vector */
	lookAt := c.Transform.Position.Add(c.Transform.Forward)
	c.View = mgl.LookAtV(c.Transform.Position, lookAt, mgl.Vec3{0, 1, 0})
}
예제 #20
0
파일: cube.go 프로젝트: depy/examples
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()
	}
}
예제 #21
0
func (p *LightPass) DrawPass(scene *Scene) {
	/* use light pass shader */
	p.Material.Use()
	shader := p.Material.Shader

	/* compute camera view projection inverse */
	vp := scene.Camera.Projection.Mul4(scene.Camera.View)
	vp_inv := vp.Inv()
	shader.Matrix4f("cameraInverse", &vp_inv[0])

	/* clear */
	gl.ClearColor(0.9, 0.9, 0.9, 1.0)
	gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)

	/* set blending mode to additive */

	gl.DepthMask(false)

	/* draw lights */
	lights := scene.FindLights()
	last := len(lights) - 1

	for i, light := range lights {
		if i == 1 {
			/* first light pass we want the shader to restore the depth buffer
			 * then, disable depth masking so that multiple lights can be drawn */
			gl.BlendFunc(gl.ONE, gl.ONE)
		}
		if i == last {
			gl.DepthMask(true)
		}

		/* draw shadow pass for this light into shadow map */
		p.Shadows.DrawPass(scene, &light)

		/* use light pass shader */
		p.Material.Use()

		/* compute world to lightspace (light view projection) matrix */
		lp := light.Projection
		lv := mgl.LookAtV(light.Position, mgl.Vec3{}, mgl.Vec3{0, 1, 0}) // only for directional light
		lvp := lp.Mul4(lv)
		shader.Matrix4f("light_vp", &lvp[0])

		/* set light uniform attributes */
		shader.Vec3("light.Position", &light.Position)
		shader.Vec3("light.Color", &light.Color)
		shader.Int32("light.Type", int32(light.Type))
		shader.Float("light.Range", light.Range)
		shader.Float("light.attenuation.Constant", light.Attenuation.Constant)
		shader.Float("light.attenuation.Linear", light.Attenuation.Linear)
		shader.Float("light.attenuation.Quadratic", light.Attenuation.Quadratic)

		/* render light */
		gl.Viewport(0, 0, int32(scene.Camera.Width), int32(scene.Camera.Height))
		p.quad.Draw()
	}

	/* reset GL state */
	gl.BlendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA)
}
예제 #22
0
파일: camera.go 프로젝트: anthonyrego/gosmf
// SetPosition2D will adjust the camera for ortho viewing to specified location
func (cam *Camera) SetPosition2D(x float32, y float32) {
	cam.Position = mgl32.Vec3{x, y, cam.zDepth}
	cam.loc = mgl32.LookAtV(mgl32.Vec3{x, y, cam.zDepth}, mgl32.Vec3{x, y, 0}, mgl32.Vec3{0, 1, 0})
	cam.update()
}
예제 #23
0
파일: main.go 프로젝트: jcecil/go-avatar
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()
	}
}
예제 #24
0
파일: input.go 프로젝트: krux02/mathgl
// Since go has multiple return values, I just went ahead and made it return the view and perspective matrices (in that order) rather than messing with getter methods
func (c *Camera) ComputeViewPerspective() (mgl32.Mat4, mgl32.Mat4) {
	if mgl64.FloatEqual(-1.0, c.time) {
		c.time = glfw.GetTime()
	}

	currTime := glfw.GetTime()
	deltaT := currTime - c.time

	xPos, yPos := c.window.GetCursorPosition()
	c.window.SetCursorPosition(width/2.0, height/2.0)

	c.hAngle += mouseSpeed * ((width / 2.0) - float64(xPos))
	c.vAngle += mouseSpeed * ((height / 2.0) - float64(yPos))

	dir := mgl32.Vec3{
		float32(math.Cos(c.vAngle) * math.Sin(c.hAngle)),
		float32(math.Sin(c.vAngle)),
		float32(math.Cos(c.vAngle) * math.Cos(c.hAngle))}

	right := mgl32.Vec3{
		float32(math.Sin(c.hAngle - math.Pi/2.0)),
		0.0,
		float32(math.Cos(c.hAngle - math.Pi/2.0))}

	up := right.Cross(dir)

	if c.window.GetKey(glfw.KeyUp) == glfw.Press || c.window.GetKey('W') == glfw.Press {
		c.pos = c.pos.Add(dir.Mul(float32(deltaT * speed)))
	}

	if c.window.GetKey(glfw.KeyDown) == glfw.Press || c.window.GetKey('S') == glfw.Press {
		c.pos = c.pos.Sub(dir.Mul(float32(deltaT * speed)))
	}

	if c.window.GetKey(glfw.KeyRight) == glfw.Press || c.window.GetKey('D') == glfw.Press {
		c.pos = c.pos.Add(right.Mul(float32(deltaT * speed)))
	}

	if c.window.GetKey(glfw.KeyLeft) == glfw.Press || c.window.GetKey('A') == glfw.Press {
		c.pos = c.pos.Sub(right.Mul(float32(deltaT * speed)))
	}

	// Adding to the original tutorial, Space goes up
	if c.window.GetKey(glfw.KeySpace) == glfw.Press {
		c.pos = c.pos.Add(up.Mul(float32(deltaT * speed)))
	}

	// Adding to the original tutorial, left control goes down
	if c.window.GetKey(glfw.KeyLeftControl) == glfw.Press {
		c.pos = c.pos.Sub(up.Mul(float32(deltaT * speed)))
	}

	fov := initialFOV //- 5.0*float64(glfw.MouseWheel())

	proj := mgl32.Perspective(float32(fov), 4.0/3.0, 0.1, 100.0)
	view := mgl32.LookAtV(c.pos, c.pos.Add(dir), up)

	c.time = currTime

	return view, proj
}
예제 #25
0
// View returns the transform matrix from world space into camera space
func (c *QuatCamera) View() mgl.Mat4 {
	// FIXME: Is there a way to get this matrix from the quat+position directly?
	return mgl.LookAtV(c.position, c.position.Add(c.Center()), c.Up())
}
예제 #26
0
파일: render.go 프로젝트: num5/steven
// Draw draws a single frame
func Draw(width, height int, delta float64) {
	tickAnimatedTextures(delta)
	frameID++
sync:
	for {
		select {
		case f := <-syncChan:
			f()
		default:
			break sync
		}
	}

	// Only update the viewport if the window was resized
	if lastHeight != height || lastWidth != width || lastFOV != FOV.Value() {
		lastWidth = width
		lastHeight = height
		lastFOV = FOV.Value()

		perspectiveMatrix = mgl32.Perspective(
			(math.Pi/180)*float32(lastFOV),
			float32(width)/float32(height),
			0.1,
			500.0,
		)
		gl.Viewport(0, 0, width, height)
		frustum.SetPerspective(
			(math.Pi/180)*float32(lastFOV),
			float32(width)/float32(height),
			0.1,
			500.0,
		)
		initTrans()
	}

	mainFramebuffer.Bind()
	gl.Enable(gl.Multisample)

	gl.ActiveTexture(0)
	glTexture.Bind(gl.Texture2DArray)

	gl.ClearColor(ClearColour.R, ClearColour.G, ClearColour.B, 1.0)
	gl.Clear(gl.ColorBufferBit | gl.DepthBufferBit)

	chunkProgram.Use()

	viewVector = mgl32.Vec3{
		float32(math.Cos(Camera.Yaw-math.Pi/2) * -math.Cos(Camera.Pitch)),
		float32(-math.Sin(Camera.Pitch)),
		float32(-math.Sin(Camera.Yaw-math.Pi/2) * -math.Cos(Camera.Pitch)),
	}
	cam := mgl32.Vec3{-float32(Camera.X), -float32(Camera.Y), float32(Camera.Z)}
	cameraMatrix = mgl32.LookAtV(
		cam,
		cam.Add(mgl32.Vec3{-viewVector.X(), -viewVector.Y(), viewVector.Z()}),
		mgl32.Vec3{0, -1, 0},
	)
	cameraMatrix = cameraMatrix.Mul4(mgl32.Scale3D(-1.0, 1.0, 1.0))

	frustum.SetCamera(
		cam,
		cam.Add(mgl32.Vec3{-viewVector.X(), -viewVector.Y(), viewVector.Z()}),
		mgl32.Vec3{0, -1, 0},
	)

	shaderChunk.PerspectiveMatrix.Matrix4(&perspectiveMatrix)
	shaderChunk.CameraMatrix.Matrix4(&cameraMatrix)
	shaderChunk.Texture.Int(0)
	shaderChunk.LightLevel.Float(LightLevel)
	shaderChunk.SkyOffset.Float(SkyOffset)

	chunkPos := position{
		X: int(Camera.X) >> 4,
		Y: int(Camera.Y) >> 4,
		Z: int(Camera.Z) >> 4,
	}
	nearestBuffer = buffers[chunkPos]

	for _, dir := range direction.Values {
		validDirs[dir] = viewVector.Dot(dir.AsVec()) > -0.8
	}

	renderOrder = renderOrder[:0]
	renderBuffer(nearestBuffer, chunkPos, direction.Invalid, delta)

	drawLines()
	drawModels()
	clouds.tick(delta)

	chunkProgramT.Use()
	shaderChunkT.PerspectiveMatrix.Matrix4(&perspectiveMatrix)
	shaderChunkT.CameraMatrix.Matrix4(&cameraMatrix)
	shaderChunkT.Texture.Int(0)
	shaderChunkT.LightLevel.Float(LightLevel)
	shaderChunkT.SkyOffset.Float(SkyOffset)

	// Copy the depth buffer
	mainFramebuffer.BindRead()
	transFramebuffer.BindDraw()
	gl.BlitFramebuffer(
		0, 0, lastWidth, lastHeight,
		0, 0, lastWidth, lastHeight,
		gl.DepthBufferBit, gl.Nearest,
	)

	gl.Enable(gl.Blend)
	gl.DepthMask(false)
	transFramebuffer.Bind()
	gl.ClearColor(0, 0, 0, 1)
	gl.Clear(gl.ColorBufferBit)
	gl.ClearBuffer(gl.Color, 0, []float32{0, 0, 0, 1})
	gl.ClearBuffer(gl.Color, 1, []float32{0, 0, 0, 0})
	gl.BlendFuncSeparate(gl.OneFactor, gl.OneFactor, gl.ZeroFactor, gl.OneMinusSrcAlpha)
	for _, chunk := range renderOrder {
		if chunk.countT > 0 && chunk.bufferT.IsValid() {
			shaderChunkT.Offset.Int3(chunk.X, chunk.Y*4096-chunk.Y*int(4096*(1-chunk.progress)), chunk.Z)

			chunk.arrayT.Bind()
			gl.DrawElements(gl.Triangles, chunk.countT, elementBufferType, 0)
		}
	}

	gl.UnbindFramebuffer()
	gl.Disable(gl.DepthTest)
	gl.Clear(gl.ColorBufferBit)
	gl.Disable(gl.Blend)

	transDraw()

	gl.Enable(gl.DepthTest)
	gl.DepthMask(true)
	gl.BlendFunc(gl.SrcAlpha, gl.OneMinusSrcAlpha)
	gl.Disable(gl.Multisample)

	drawUI()

	if debugFramebuffers.Value() {
		gl.Enable(gl.Multisample)
		blitBuffers()
		gl.Disable(gl.Multisample)
	}
}
예제 #27
0
// View returns the transform matrix from world space into camera space
func (c *EulerCamera) View() mgl.Mat4 {
	return mgl.LookAtV(c.eye, c.eye.Add(c.center), c.up)
}