public void dibuja_arbol(GL gl) { IntPtr qobj = gl.gluNewQuadric(); gl.gluQuadricDrawStyle(qobj, GL.GLU_FILL); //Material tronco float[] sombra_tronco = { 0.588f, 0.2275f, 0.004f, 1.0f }; float[] luz_tronco = { 0.643f, 0.353f, 0.016f, 1.0f }; float[] reflejo = { 1.0f, 1.0f, 1.0f, 1.0f };//Blaco float[] brillo = { 0.0f, 0.0f, 0.0f, 1.0f };//Negro float intensidadbrillo = 40.0f;//0 - 128 gl.glMaterialfv(GL.GL_FRONT, GL.GL_AMBIENT, sombra_tronco); //color a la sombra gl.glMaterialfv(GL.GL_FRONT, GL.GL_DIFFUSE, luz_tronco); //color a la luz gl.glMaterialfv(GL.GL_FRONT, GL.GL_SPECULAR, reflejo); //color del reflejo gl.glMaterialf(GL.GL_FRONT, GL.GL_SHININESS, intensidadbrillo); //intensidad del reflejo gl.glMaterialfv(GL.GL_FRONT, GL.GL_EMISSION, brillo); //Tronco gl.gluCylinder(qobj, 0.5, 0.5, 0.25, 10, 10); //Capa uno del arbol float[] sombra_arbol = { 0.118f, 0.353f, 0.003f }; float[] luz_arbol = { 0.169f, 0.518f, 0.008f }; gl.glMaterialfv(GL.GL_FRONT, GL.GL_AMBIENT, sombra_arbol); //color a la sombra gl.glMaterialfv(GL.GL_FRONT, GL.GL_DIFFUSE, luz_arbol); //color a la luz gl.glTranslatef(0.0f, 0.0f, 0.25f); gl.gluCylinder(qobj, 1.2 , 0.9, 0.6, 10, 10); gl.glTranslatef(0.0f, 0.0f, 0.6f); gl.gluCylinder(qobj, 1.2, 0.6, 0.6, 10, 10); gl.glTranslatef(0.0f, 0.0f, 0.6f); gl.gluCylinder(qobj, 0.9, 0.3, 0.6, 10, 10); gl.glTranslatef(0.0f, 0.0f, 0.6f); gl.gluCylinder(qobj, 0.6, 0.0, 0.5, 10, 10); }
public void dibuja_plano(GL gl, int num_quads, float size_quad) { for (int j = 0; j < num_quads; j++) { planoX = 0; for (int i = 0; i < num_quads; i++) { gl.glBegin(GL.GL_QUADS); gl.glVertex3f(planoX, planoY, 0.0f); gl.glVertex3f(planoX, planoY - size_quad, 0.0f); gl.glVertex3f(planoX + size_quad, planoY - size_quad, 0.0f); gl.glVertex3f(planoX + size_quad, planoY, 0.0f); gl.glEnd(); planoX += size_quad; } planoY += size_quad; } }
public Cubelet(GL gl) { this.gl = gl; _sideLength = 0.8f; _roundWidth = 0.1f; _roundSteps = 2; _sideMaterial[0] = _sideMaterial[1] = _sideMaterial[2] = 0.15f; _sideMaterial[3] = 1.0f; _shininess[0] = 2; // The sides have small highlights. _bevelDiffuse[0] = _bevelDiffuse[1] = _bevelDiffuse[2] = 0.25f; _bevelDiffuse[3] = 1.0f; _bevelMaterial[0] = _bevelMaterial[1] = _bevelMaterial[2] = 1.0f; _bevelMaterial[3] = 1.0f; _bevelShininess[0] = 115f; _sides[0] = RED; _sides[1] = YELLOW; _sides[2] = BLUE; _sides[3] = GREEN; _sides[4] = WHITE; _sides[5] = ORANGE; }
void IMustInit.Init(GL gl) { Bitmap Bmp = Bitmap.FromFile(FileName) as Bitmap; fixed(uint* Tex = &T) gl.GenTextures(1,Tex); Bmp.RotateFlip(RotateFlipType.RotateNoneFlipY); Bound = new Rectangle(0,0,Bmp.Width,Bmp.Height); BitmapData BData = Bmp.LockBits(Bound,ImageLockMode.ReadOnly,Bmp.PixelFormat); if(BData.PixelFormat == System.Drawing.Imaging.PixelFormat.Format24bppRgb) { gl.BindTexture(TEXTURE_2D,T); gl.TexImage2D(TEXTURE_2D,0,RGB,Bmp.Width,Bmp.Height ,0,BGR,UNSIGNED_BYTE,(byte*)BData.Scan0); gl.TexParameteri(TEXTURE_2D,TEXTURE_MIN_FILTER,(int)NEAREST); } Bmp.UnlockBits(BData); }
public Cube3D(GL gl) { this.gl = gl; _cubeX = _cubeY = _cubeZ = 0; for (int i = 0; i < 3; i++) { _rotateX[i] = _rotateY[i] = _rotateZ[i] = 0; } for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { for (int k = 0; k < 3; k++) { _cubelets[i, j, k] = new Cubelet(gl); _savedCubes[i, j, k] = new Cubelet(gl); } } } Reset(); }
protected override void OnResize(EventArgs e) { GL.Viewport(0, 0, this.Width, this.Height); }
public void Render(Material graphMaterial) { if (CurrentRange == 0.0f || DataPairs.Count <= 1.0f) { return; } StartRender(graphMaterial, IsWorldSpace); // This is so that we can see the graph scrolling from right to left float screenOffset = DataPairs.Count != MaxNumPoints ? (1.0f - (float)DataPairs.Count / (float)MaxNumPoints) : 0.0f; for (int i = 1; i < DataPairs.Count; ++i) { // Set the color of the specific data pair GL.Color(DataPairs[i].Color); // Calculate positions Vector3 pPos = new Vector3(GetX(i - 1, screenOffset), GetY(i - 1), 0.0f); Vector3 cPos = new Vector3(GetX(i - 0, screenOffset), GetY(i - 0), 0.0f); if (IsWorldSpace) { pPos.x -= 0.5f; cPos.x -= 0.5f; pPos.y -= 0.5f; cPos.y -= 0.5f; pPos = TRS.TRS.MultiplyPoint(pPos); cPos = TRS.TRS.MultiplyPoint(cPos); } else { //Clamp to 1.0f, 1.0f cPos = Vector3.Min(Vector3.one, cPos); pPos = Vector3.Min(Vector3.one, pPos); // convert into rectangle space thats provided by user pPos.x *= Rectangle.z; pPos.y *= Rectangle.w; pPos.x += Rectangle.x; pPos.y = ((1.0f - Rectangle.y) - Rectangle.w) + pPos.y; cPos.x *= Rectangle.z; cPos.y *= Rectangle.w; cPos.x += Rectangle.x; cPos.y = ((1.0f - Rectangle.y) - Rectangle.w) + cPos.y; } // Draw the line pair DrawLine(pPos, cPos, false); } // coordinates here are 0,0 at the bottom, so we need to invert so the square is in the right place if (IsWorldSpace) { Vector4 shiftedRectangle = Rectangle; shiftedRectangle.x -= 0.5f; shiftedRectangle.y -= 0.5f; DrawRectangle(shiftedRectangle, IsWorldSpace, TRS.TRS, true); } else { DrawRectangle(Rectangle, IsWorldSpace, TRS.TRS, true); } //// Draw the grid for the corresponding graph //{ // float deltaX = Rectangle.z / 20.0f; // for (float startX = Rectangle.x; startX <= Rectangle.x + Rectangle.z; startX += deltaX) // { // Vector3 t = new Vector3(startX, Rectangle.y, 0.0f); // Vector3 b = new Vector3(startX, Rectangle.y + Rectangle.w, 0.0f); // DrawLine(t, b, true); // } //} EndRender(); UpdateText(); }
void RenderReflectionAndRefraction() { Camera renderCamera = Camera.mainCamera; Matrix4x4 originalWorldToCam = renderCamera.worldToCameraMatrix; int cullingMask = ~(1 << 4) & renderLayers.value; ; //Reflection pass Matrix4x4 reflection = Matrix4x4.zero; //TODO: Use local plane here, not global! float d = -transform.position.y; offscreenCam.backgroundColor = RenderSettings.fogColor; CameraHelper.CalculateReflectionMatrix(ref reflection, new Vector4(0f, 1f, 0f, d)); offscreenCam.transform.position = reflection.MultiplyPoint(renderCamera.transform.position); offscreenCam.transform.rotation = renderCamera.transform.rotation; offscreenCam.worldToCameraMatrix = originalWorldToCam * reflection; offscreenCam.cullingMask = cullingMask; offscreenCam.targetTexture = reflectionTexture; //Need to reverse face culling for reflection pass, since the camera //is now flipped upside/down. GL.SetRevertBackfacing(true); Vector4 cameraSpaceClipPlane = CameraHelper.CameraSpacePlane(offscreenCam, new Vector3(0.0f, transform.position.y, 0.0f), Vector3.up, 1.0f); Matrix4x4 projection = renderCamera.projectionMatrix; Matrix4x4 obliqueProjection = projection; offscreenCam.fieldOfView = renderCamera.fieldOfView; offscreenCam.aspect = renderCamera.aspect; CameraHelper.CalculateObliqueMatrix(ref obliqueProjection, cameraSpaceClipPlane); //Do the actual render, with the near plane set as the clipping plane. See the //pro water source for details. offscreenCam.projectionMatrix = obliqueProjection; if (!renderReflection) { offscreenCam.cullingMask = 0; } offscreenCam.Render(); GL.SetRevertBackfacing(false); //Refractionpass //TODO: If we want to use this as a refraction seen from under the seaplane, // the cameraclear should be skybox. offscreenCam.cullingMask = cullingMask; offscreenCam.targetTexture = refractionTexture; obliqueProjection = projection; offscreenCam.transform.position = renderCamera.transform.position; offscreenCam.transform.rotation = renderCamera.transform.rotation; offscreenCam.worldToCameraMatrix = originalWorldToCam; cameraSpaceClipPlane = CameraHelper.CameraSpacePlane(offscreenCam, Vector3.zero, Vector3.up, -1.0f); CameraHelper.CalculateObliqueMatrix(ref obliqueProjection, cameraSpaceClipPlane); offscreenCam.projectionMatrix = obliqueProjection; //if (!renderRefraction) //offscreenCam.cullingMask = 0; offscreenCam.Render(); offscreenCam.projectionMatrix = projection; offscreenCam.targetTexture = null; }
void DrawSense(GL gl) { gl.glTranslatef(0, 0, -_zoomZ); gl.glRotatef(RotateX_Angle, 1, 0, 0); gl.glRotatef(RotateY_Angle, 0, 1, 0); _cube3D.Render(); }
void IMustInit.Init(GL gl) { S = gl.CreateShader(T); fixed(byte* pB = Encoding.UTF8.GetBytes(Src + '\0')) { sbyte* ppB = (sbyte*)pB; gl.ShaderSource(S,1,&ppB,null); } gl.CompileShader(S); }
void InitGL(GL gl) { gl.glClearColor(0.8f, 0.8f, 0.8f, 0.5f); gl.glClearDepth(1.0); gl.glEnable(GL.GL_DEPTH_TEST); gl.glDepthFunc(GL.GL_LEQUAL); gl.glHint(GL.GL_PERSPECTIVE_CORRECTION_HINT, GL.GL_NICEST); float[] light_ambient = { 0.3f, 0.3f, 0.3f, 1.0f }; float[] light_diffuse = { 1.0f, 1.0f, 1.0f, 1.0f }; float[] light_specular = { 0.35f, 0.35f, 0.35f, 1.0f }; float[] light_position = { 0, 10.0f, 20.0f, 1.0f }; gl.glShadeModel(GL.GL_SMOOTH); gl.glLightfv(GL.GL_LIGHT0, GL.GL_POSITION, light_position); gl.glLightfv(GL.GL_LIGHT0,GL.GL_AMBIENT, light_ambient); gl.glLightfv(GL.GL_LIGHT0, GL.GL_DIFFUSE, light_diffuse); gl.glLightfv(GL.GL_LIGHT0, GL.GL_SPECULAR, light_specular); gl.glLightModelf(GL.GL_LIGHT_MODEL_LOCAL_VIEWER, GL.GL_TRUE); gl.glEnable(GL.GL_LIGHT0); gl.glEnable(GL.GL_LIGHTING); }
void IMustInit.Init(GL gl) { if(B == 0) { fixed(uint* pB = &B) gl.GenBuffers(1,pB); if(B == 0) throw new Exception("GLObject Gen fails"); } gl.BindBuffer((uint)BType,B); switch(T) { case DataType.SByte : fixed(sbyte* pD = Data as sbyte[]) gl.BufferData((uint)BType,sizeof(sbyte) * Data.Length,pD,(uint)U); break; case DataType.Byte: fixed(byte* pD = Data as byte[]) gl.BufferData((uint)BType,sizeof(byte) * Data.Length,pD,(uint)U); break; case DataType.Short: fixed(short* pD = Data as short[]) gl.BufferData((uint)BType,sizeof(short) * Data.Length,pD,(uint)U); break; case DataType.UShort: fixed(ushort* pD = Data as ushort[]) gl.BufferData((uint)BType,sizeof(ushort) * Data.Length,pD,(uint)U); break; case DataType.Int: fixed(int* pD = Data as int[]) gl.BufferData((uint)BType,sizeof(int) * Data.Length,pD,(uint)U); break; case DataType.UInt: fixed(uint* pD = Data as uint[]) gl.BufferData((uint)BType,sizeof(uint) * Data.Length,pD,(uint)U); break; case DataType.Float: fixed(float* pD = Data as float[]) gl.BufferData((uint)BType,sizeof(float) * Data.Length,pD,(uint)U); break; case DataType.Double: fixed(double* pD = Data as double[]) gl.BufferData((uint)BType,sizeof(double) * Data.Length,pD,(uint)U); break; } // Data = null; }
// This just sets up some matrices in the material; for really // old cards to make water texture scroll. void Update() { if (!GetComponent <Renderer>()) { return; } Material mat = GetComponent <Renderer>().sharedMaterial; if (!mat) { return; } Vector4 waveSpeed = mat.GetVector("WaveSpeed"); float waveScale = mat.GetFloat("_WaveScale"); Vector4 waveScale4 = new Vector4(waveScale, waveScale, waveScale * 0.4f, waveScale * 0.45f); // Time since level load, and do intermediate calculations with doubles double t = Time.timeSinceLevelLoad / 20.0; Vector4 offsetClamped = new Vector4( (float)System.Math.IEEERemainder(waveSpeed.x * waveScale4.x * t, 1.0), (float)System.Math.IEEERemainder(waveSpeed.y * waveScale4.y * t, 1.0), (float)System.Math.IEEERemainder(waveSpeed.z * waveScale4.z * t, 1.0), (float)System.Math.IEEERemainder(waveSpeed.w * waveScale4.w * t, 1.0) ); mat.SetVector("_WaveOffset", offsetClamped); mat.SetVector("_WaveScale4", waveScale4); Vector3 waterSize = GetComponent <Renderer>().bounds.size; Vector3 scale = new Vector3(waterSize.x * waveScale4.x, waterSize.z * waveScale4.y, 1); Matrix4x4 scrollMatrix = Matrix4x4.TRS(new Vector3(offsetClamped.x, offsetClamped.y, 0), Quaternion.identity, scale); mat.SetMatrix("_WaveMatrix", scrollMatrix); scale = new Vector3(waterSize.x * waveScale4.z, waterSize.z * waveScale4.w, 1); scrollMatrix = Matrix4x4.TRS(new Vector3(offsetClamped.z, offsetClamped.w, 0), Quaternion.identity, scale); mat.SetMatrix("_WaveMatrix2", scrollMatrix); if (!enabled || !GetComponent <Renderer>() || !GetComponent <Renderer>().sharedMaterial || !GetComponent <Renderer>().enabled) { return; } Camera cam = Camera.main; if (!cam) { return; } // Safeguard from recursive water reflections. if (s_InsideWater) { return; } s_InsideWater = true; // Actual water rendering mode depends on both the current setting AND // the hardware support. There's no point in rendering refraction textures // if they won't be visible in the end. m_HardwareWaterSupport = FindHardwareWaterSupport(); WaterMode mode = GetWaterMode(); Camera reflectionCamera, refractionCamera; CreateWaterObjects(cam, out reflectionCamera, out refractionCamera); // find out the reflection plane: position and normal in world space Vector3 pos = transform.position; Vector3 normal = transform.up; // Optionally disable pixel lights for reflection/refraction int oldPixelLightCount = QualitySettings.pixelLightCount; if (m_DisablePixelLights) { QualitySettings.pixelLightCount = 0; } UpdateCameraModes(cam, reflectionCamera); UpdateCameraModes(cam, refractionCamera); // Render reflection if needed if (mode >= WaterMode.Reflective) { // Reflect camera around reflection plane float d = -Vector3.Dot(normal, pos) - m_ClipPlaneOffset; Vector4 reflectionPlane = new Vector4(normal.x, normal.y, normal.z, d); Matrix4x4 reflection = Matrix4x4.zero; CalculateReflectionMatrix(ref reflection, reflectionPlane); Vector3 oldpos = cam.transform.position; Vector3 newpos = reflection.MultiplyPoint(oldpos); reflectionCamera.worldToCameraMatrix = cam.worldToCameraMatrix * reflection; // Setup oblique projection matrix so that near plane is our reflection // plane. This way we clip everything below/above it for free. Vector4 clipPlane = CameraSpacePlane(reflectionCamera, pos, normal, 1.0f); reflectionCamera.projectionMatrix = cam.CalculateObliqueMatrix(clipPlane); reflectionCamera.cullingMask = ~(1 << 4) & m_ReflectLayers.value; // never render water layer reflectionCamera.targetTexture = m_ReflectionTexture; GL.SetRevertBackfacing(true); reflectionCamera.transform.position = newpos; Vector3 euler = cam.transform.eulerAngles; reflectionCamera.transform.eulerAngles = new Vector3(-euler.x, euler.y, euler.z); reflectionCamera.Render(); reflectionCamera.transform.position = oldpos; GL.SetRevertBackfacing(false); GetComponent <Renderer>().sharedMaterial.SetTexture("_ReflectionTex", m_ReflectionTexture); } // Render refraction if (mode >= WaterMode.Refractive) { refractionCamera.worldToCameraMatrix = cam.worldToCameraMatrix; // Setup oblique projection matrix so that near plane is our reflection // plane. This way we clip everything below/above it for free. Vector4 clipPlane = CameraSpacePlane(refractionCamera, pos, normal, -1.0f); refractionCamera.projectionMatrix = cam.CalculateObliqueMatrix(clipPlane); refractionCamera.cullingMask = ~(1 << 4) & m_RefractLayers.value; // never render water layer refractionCamera.targetTexture = m_RefractionTexture; refractionCamera.transform.position = cam.transform.position; refractionCamera.transform.rotation = cam.transform.rotation; refractionCamera.Render(); GetComponent <Renderer>().sharedMaterial.SetTexture("_RefractionTex", m_RefractionTexture); } // Restore pixel light count if (m_DisablePixelLights) { QualitySettings.pixelLightCount = oldPixelLightCount; } // Setup shader keywords based on water mode switch (mode) { case WaterMode.Simple: Shader.EnableKeyword("WATER_SIMPLE"); Shader.DisableKeyword("WATER_REFLECTIVE"); Shader.DisableKeyword("WATER_REFRACTIVE"); break; case WaterMode.Reflective: Shader.DisableKeyword("WATER_SIMPLE"); Shader.EnableKeyword("WATER_REFLECTIVE"); Shader.DisableKeyword("WATER_REFRACTIVE"); break; case WaterMode.Refractive: Shader.DisableKeyword("WATER_SIMPLE"); Shader.DisableKeyword("WATER_REFLECTIVE"); Shader.EnableKeyword("WATER_REFRACTIVE"); break; } s_InsideWater = false; }
internal void draw() { if (!visible || disposed || fbo == 0 || texture == 0) { return; } if (sprites.Count <= 0) { GL.BindTexture(TextureTarget.Texture2D, texture); GL.BindFramebuffer(FramebufferTarget.Framebuffer, fbo); GL.ClearColor(0, 0, 0, 0f); GL.Clear(ClearBufferMask.ColorBufferBit); return; } //re-render the render-to-texture here from all sprites/planes GL.BindTexture(TextureTarget.Texture2D, texture); GL.BindFramebuffer(FramebufferTarget.Framebuffer, fbo); GL.ClearColor(0, 0, 0, 0f); GL.Clear(ClearBufferMask.ColorBufferBit); GL.Viewport(0, 0, width, height); GL.MatrixMode(MatrixMode.Projection); GL.LoadIdentity(); GL.Ortho(0, width, 0, height, -1f, 1f); if (ox != 0 || oy != 0) { //Console.WriteLine("Transforming viewport: " + ox + ":" + oy); GL.Translate(0 - ox, 0 - oy, 0); //untested } sort(); foreach (Drawable s in sprites) { //Console.WriteLine("drawing sprite: " + s.z); s.draw(); } GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0); GL.Viewport(0, 0, Graphics.width, Graphics.height); GL.MatrixMode(MatrixMode.Projection); GL.LoadIdentity(); GL.Ortho(0, Graphics.width, Graphics.height, 0, -1, 1); GL.Enable(EnableCap.Texture2D); GL.BindTexture(TextureTarget.Texture2D, texture); GL.Color3(1.0f, 1.0f, 1.0f); GL.Begin(BeginMode.Quads); GL.TexCoord2(0f, 0f); GL.Vertex3(x, y, 0.5f); GL.TexCoord2(1f, 0f); GL.Vertex3(x + width, y, 0.5f); GL.TexCoord2(1f, 1f); GL.Vertex3(x + width, y + height, 0.5f); GL.TexCoord2(0f, 1f); GL.Vertex3(x, y + height, 0.5f); GL.End(); //GL.Disable(EnableCap.Texture2D); }
void OnRenderImage (RenderTexture source, RenderTexture destination) { if (CheckResources()==false) { Graphics.Blit (source, destination); return; } // we actually need to check this every frame if (useDepthTexture) GetComponent<Camera>().depthTextureMode |= DepthTextureMode.Depth; int divider = 4; if (resolution == SunShaftsResolution.Normal) divider = 2; else if (resolution == SunShaftsResolution.High) divider = 1; Vector3 v = Vector3.one * 0.5f; if (sunTransform) v = GetComponent<Camera>().WorldToViewportPoint (sunTransform.position); else v = new Vector3(0.5f, 0.5f, 0.0f); int rtW = source.width / divider; int rtH = source.height / divider; RenderTexture lrColorB; RenderTexture lrDepthBuffer = RenderTexture.GetTemporary (rtW, rtH, 0); // mask out everything except the skybox // we have 2 methods, one of which requires depth buffer support, the other one is just comparing images sunShaftsMaterial.SetVector ("_BlurRadius4", new Vector4 (1.0f, 1.0f, 0.0f, 0.0f) * sunShaftBlurRadius ); sunShaftsMaterial.SetVector ("_SunPosition", new Vector4 (v.x, v.y, v.z, maxRadius)); sunShaftsMaterial.SetVector ("_SunThreshold", sunThreshold); if (!useDepthTexture) { var format= GetComponent<Camera>().hdr ? RenderTextureFormat.DefaultHDR: RenderTextureFormat.Default; RenderTexture tmpBuffer = RenderTexture.GetTemporary (source.width, source.height, 0, format); RenderTexture.active = tmpBuffer; GL.ClearWithSkybox (false, GetComponent<Camera>()); sunShaftsMaterial.SetTexture ("_Skybox", tmpBuffer); Graphics.Blit (source, lrDepthBuffer, sunShaftsMaterial, 3); RenderTexture.ReleaseTemporary (tmpBuffer); } else { Graphics.Blit (source, lrDepthBuffer, sunShaftsMaterial, 2); } // paint a small black small border to get rid of clamping problems DrawBorder (lrDepthBuffer, simpleClearMaterial); // radial blur: radialBlurIterations = Mathf.Clamp (radialBlurIterations, 1, 4); float ofs = sunShaftBlurRadius * (1.0f / 768.0f); sunShaftsMaterial.SetVector ("_BlurRadius4", new Vector4 (ofs, ofs, 0.0f, 0.0f)); sunShaftsMaterial.SetVector ("_SunPosition", new Vector4 (v.x, v.y, v.z, maxRadius)); for (int it2 = 0; it2 < radialBlurIterations; it2++ ) { // each iteration takes 2 * 6 samples // we update _BlurRadius each time to cheaply get a very smooth look lrColorB = RenderTexture.GetTemporary (rtW, rtH, 0); Graphics.Blit (lrDepthBuffer, lrColorB, sunShaftsMaterial, 1); RenderTexture.ReleaseTemporary (lrDepthBuffer); ofs = sunShaftBlurRadius * (((it2 * 2.0f + 1.0f) * 6.0f)) / 768.0f; sunShaftsMaterial.SetVector ("_BlurRadius4", new Vector4 (ofs, ofs, 0.0f, 0.0f) ); lrDepthBuffer = RenderTexture.GetTemporary (rtW, rtH, 0); Graphics.Blit (lrColorB, lrDepthBuffer, sunShaftsMaterial, 1); RenderTexture.ReleaseTemporary (lrColorB); ofs = sunShaftBlurRadius * (((it2 * 2.0f + 2.0f) * 6.0f)) / 768.0f; sunShaftsMaterial.SetVector ("_BlurRadius4", new Vector4 (ofs, ofs, 0.0f, 0.0f) ); } // put together: if (v.z >= 0.0f) sunShaftsMaterial.SetVector ("_SunColor", new Vector4 (sunColor.r, sunColor.g, sunColor.b, sunColor.a) * sunShaftIntensity); else sunShaftsMaterial.SetVector ("_SunColor", Vector4.zero); // no backprojection ! sunShaftsMaterial.SetTexture ("_ColorBuffer", lrDepthBuffer); Graphics.Blit (source, destination, sunShaftsMaterial, (screenBlendMode == ShaftsScreenBlendMode.Screen) ? 0 : 4); RenderTexture.ReleaseTemporary (lrDepthBuffer); }
void Loaded(object o, EventArgs e) { GL.ClearColor(0.0f, 0.0f, 0.0f, 0.0f); }
private void Page_Loaded( object sender, RoutedEventArgs e ) { #if ALPHA this.Surface.ColorMode = ColorMode.RGBA; #else this.Surface.ColorMode = ColorMode.RGB; #endif _isScaling = true; this.EnableScaling(); _camera = new Camera(); gl = new GL( this.Surface.RasterBuffer ); gl.glClearColor( 0.0f, 0.0f, 0.0f, 0.0f ); this.MakeTexture(); CompositionTarget.Rendering += new EventHandler( CompositionTarget_Rendering ); }
public override void Update() { GL.Viewport(0, 0, max, max); demoContext.Render(); }
public void Unbind() { GL.BindBuffer(BufferTarget, 0); }
public static Shader CreateShader(string shaderFilepath,ShaderType type) { var shaderId = GL.CreateShader(type); var shaderSourceCode = LoadShaderCode(shaderFilepath); return CreateShader(shaderId, shaderSourceCode, type); }
public void Vagon(GL gl) { float[] sombra = { 0.0f, 0.0f, 0.2f, 1.0f }; float[] luz = { 0.0f, 0.0f, 1.0f, 1.0f }; float[] reflejo = { 1.0f, 1.0f, 1.0f, 1.0f }; float[] brillo = { 0.0f, 0.0f, 0.0f, 1.0f }; float intensidadbrillo = 40.0f;//0 - 128 gl.glMaterialfv(GL.GL_FRONT, GL.GL_AMBIENT, sombra); //color a la sombra gl.glMaterialfv(GL.GL_FRONT, GL.GL_DIFFUSE, luz); //color a la luz gl.glMaterialfv(GL.GL_FRONT, GL.GL_SPECULAR, reflejo); //color del reflejo gl.glMaterialf(GL.GL_FRONT, GL.GL_SHININESS, intensidadbrillo); //intensidad del reflejo gl.glMaterialfv(GL.GL_FRONT, GL.GL_EMISSION, brillo); //color de luz emitida GLUTShapes obj = new GLUTShapes(gl); gl.glScalef(2.0f, 0.0f, 0.0f); obj.glutSolidCube(1.0); }
public static Shader CreateShader(Stream stream,ShaderType type) { var shaderId = GL.CreateShader(type); var shaderSourceCode = new StreamReader(stream).ReadToEnd(); return CreateShader(shaderId, shaderSourceCode, type); }
void IMustExit.Exit(GL gl) { fixed(uint* Tex = &T) gl.DeleteTextures(1,Tex); }
protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) { if (this.DesignMode) return; if (area.LocationMiddle.Lat == 0 && area.LocationMiddle.Lng == 0) return; try { base.OnPaint(e); } catch { return; } double heightscale = (step/90.0)*1; float yawradians = (float) (Math.PI*(rpy.Z*1)/180.0f); //radians = 0; float mouseY = (float) step/10f; cameraX = center.Lng; // -Math.Sin(yawradians) * mouseY; // multiplying by mouseY makes the cameraY = center.Lat; // -Math.Cos(yawradians) * mouseY; // camera get closer/farther away with mouseY cameraZ = (center.Alt < srtm.getAltitude(center.Lat, center.Lng).alt) ? (srtm.getAltitude(center.Lat, center.Lng).alt + 1)*heightscale : center.Alt*heightscale; // (srtm.getAltitude(lookZ, lookX, 20) + 100) * heighscale; lookX = center.Lng + Math.Sin(yawradians)*mouseY; lookY = center.Lat + Math.Cos(yawradians)*mouseY; lookZ = cameraZ; // cameraZ += 0.04; GMapProvider type = GMap.NET.MapProviders.GoogleSatelliteMapProvider.Instance; PureProjection prj = type.Projection; int size = (int) (cameraZ*150000); // in front PointLatLngAlt leftf = center.newpos(rpy.Z, size); // behind PointLatLngAlt rightf = center.newpos(rpy.Z, 50); // left : 90 allows for 180 degree viewing angle PointLatLngAlt left = center.newpos(rpy.Z - 90, size); // right PointLatLngAlt right = center.newpos(rpy.Z + 90, size); double maxlat = Math.Max(left.Lat, Math.Max(right.Lat, Math.Max(leftf.Lat, rightf.Lat))); double minlat = Math.Min(left.Lat, Math.Min(right.Lat, Math.Min(leftf.Lat, rightf.Lat))); double maxlng = Math.Max(left.Lng, Math.Max(right.Lng, Math.Max(leftf.Lng, rightf.Lng))); double minlng = Math.Min(left.Lng, Math.Min(right.Lng, Math.Min(leftf.Lng, rightf.Lng))); // if (Math.Abs(area.Lat - maxlat) < 0.001) { } // else { area = RectLatLng.FromLTRB(minlng, maxlat, maxlng, minlat); } GPoint topLeftPx = prj.FromLatLngToPixel(area.LocationTopLeft, zoom); GPoint rightButtomPx = prj.FromLatLngToPixel(area.Bottom, area.Right, zoom); GPoint pxDelta = new GPoint(rightButtomPx.X - topLeftPx.X, rightButtomPx.Y - topLeftPx.Y); zoom = 21; pxDelta.X = 9999; int otherzoomlevel = 12; // zoom based on pixel density while (pxDelta.X > this.Width) { zoom--; // current area topLeftPx = prj.FromLatLngToPixel(area.LocationTopLeft, zoom); rightButtomPx = prj.FromLatLngToPixel(area.Bottom, area.Right, zoom); pxDelta = new GPoint(rightButtomPx.X - topLeftPx.X, rightButtomPx.Y - topLeftPx.Y); } otherzoomlevel = zoom - 4; //Console.WriteLine("zoom {0}", zoom); // update once per seconds - we only read from disk, so need to let cahce settle if (lastrefresh.AddSeconds(0.5) < DateTime.Now) { // get tiles - bg core.Provider = type; core.Position = LocationCenter; // get zoom 10 core.Zoom = otherzoomlevel; core.OnMapSizeChanged(this.Width, this.Height); // get actual current zoom core.Zoom = zoom; core.OnMapSizeChanged(this.Width, this.Height); lastrefresh = DateTime.Now; } else { //return; } float screenscale = this.Width/(float) this.Height; if(!Context.IsCurrent) MakeCurrent(); GL.MatrixMode(MatrixMode.Projection); OpenTK.Matrix4 projection = OpenTK.Matrix4.CreatePerspectiveFieldOfView((float)(120*MathHelper.deg2rad), screenscale, 0.00001f, (float) step*20000); GL.LoadMatrix(ref projection); Matrix4 modelview = Matrix4.LookAt((float) cameraX, (float) cameraY, (float) cameraZ, (float) lookX, (float) lookY, (float) lookZ, 0, 0, 1); GL.MatrixMode(MatrixMode.Modelview); // roll modelview = Matrix4.Mult(modelview, Matrix4.CreateRotationZ((float)(rpy.X*MathHelper.deg2rad))); // pitch modelview = Matrix4.Mult(modelview, Matrix4.CreateRotationX((float)((rpy.Y - 15)*-MathHelper.deg2rad))); GL.LoadMatrix(ref modelview); GL.ClearColor(Color.CornflowerBlue); GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit | ClearBufferMask.AccumBufferBit); GL.LightModel(LightModelParameter.LightModelAmbient, new float[] {1f, 1f, 1f, 1f}); // GL.Disable(EnableCap.Fog); GL.Enable(EnableCap.Fog); //GL.Enable(EnableCap.Lighting); //GL.Enable(EnableCap.Light0); GL.Fog(FogParameter.FogColor, new float[] {100/255.0f, 149/255.0f, 237/255.0f, 1f}); //GL.Fog(FogParameter.FogDensity,0.1f); GL.Fog(FogParameter.FogMode, (int) FogMode.Linear); GL.Fog(FogParameter.FogStart, (float) step*40); GL.Fog(FogParameter.FogEnd, (float) (step*50)); // GL.Enable(EnableCap.DepthTest); GL.DepthFunc(DepthFunction.Always); /* GL.Begin(BeginMode.LineStrip); GL.Color3(Color.White); GL.Vertex3(0, 0, 0); //GL.Color3(Color.Red); GL.Vertex3(area.Bottom, 0, area.Left); //GL.Color3(Color.Yellow); GL.Vertex3(lookX, lookY, lookZ); //GL.Color3(Color.Green); GL.Vertex3(cameraX, cameraY, cameraZ); GL.End(); */ /* GL.PointSize(10); GL.Color4(Color.Yellow); GL.LineWidth(5); GL.Begin(PrimitiveType.LineStrip); //GL.Vertex3(new Vector3((float)center.Lng,(float)center.Lat,(float)(center.Alt * heightscale))); //GL.Vertex3(new Vector3(0, 0, 0)); //GL.Vertex3(new Vector3((float)cameraX, (float)cameraY, (float)cameraZ)); //GL.Color3(Color.Green); //GL.Vertex3(new Vector3((float)lookX, (float)lookY, (float)lookZ)); GL.Vertex3(area.LocationTopLeft.Lng, area.LocationTopLeft.Lat, (float)cameraZ); GL.Vertex3(area.LocationTopLeft.Lng, area.LocationRightBottom.Lat, (float)cameraZ); GL.Vertex3(area.LocationRightBottom.Lng, area.LocationRightBottom.Lat, (float)cameraZ); GL.Vertex3(area.LocationRightBottom.Lng, area.LocationTopLeft.Lat, (float)cameraZ); GL.Vertex3(area.LocationTopLeft.Lng, area.LocationTopLeft.Lat, (float)cameraZ); GL.End(); */ GL.Finish(); GL.PointSize((float) (step*1)); GL.Color3(Color.Blue); GL.Begin(PrimitiveType.Points); GL.Vertex3(new Vector3((float) center.Lng, (float) center.Lat, (float) cameraZ)); GL.End(); //GL.ClampColor(ClampColorTarget.ClampReadColor, ClampColorMode.True); /* GL.Enable(EnableCap.Blend); GL.DepthMask(false); GL.BlendFunc(BlendingFactorSrc.Zero, BlendingFactorDest.Src1Color); GL.DepthMask(true); GL.Disable(EnableCap.Blend); */ // textureid.Clear(); // get level 10 tiles List<GPoint> tileArea1 = prj.GetAreaTileList(area, otherzoomlevel, 1); // get type list at new zoom level List<GPoint> tileArea2 = prj.GetAreaTileList(area, zoom, 2); List<GPoint> tileArea = new List<GPoint>(); tileArea.AddRange(tileArea1); tileArea.AddRange(tileArea2); // get tiles & combine into one foreach (var p in tileArea) { int localzoom = zoom; core.tileDrawingListLock.AcquireReaderLock(); core.Matrix.EnterReadLock(); try { if (tileArea1.Contains(p)) localzoom = otherzoomlevel; topLeftPx = prj.FromLatLngToPixel(area.LocationTopLeft, localzoom); GMap.NET.Internals.Tile t = core.Matrix.GetTileWithNoLock(localzoom, p); if (t.NotEmpty) { foreach (GMapImage img in t.Overlays) { if (!textureid.ContainsKey(p)) { generateTexture(p, (Bitmap) img.Img); } } } else { } } finally { core.Matrix.LeaveReadLock(); core.tileDrawingListLock.ReleaseReaderLock(); } //GMapImage tile = ((PureImageCache)Maps.MyImageCache.Instance).GetImageFromCache(type.DbId, p, zoom) as GMapImage; //if (tile != null && !textureid.ContainsKey(p)) { // generateTexture(p, (Bitmap)tile.Img); } if (textureid.ContainsKey(p)) { int texture = textureid[p]; GL.Enable(EnableCap.Texture2D); GL.BindTexture(TextureTarget.Texture2D, texture); } else { //Console.WriteLine("Missing tile"); continue; } long x = p.X*prj.TileSize.Width - topLeftPx.X; long y = p.Y*prj.TileSize.Width - topLeftPx.Y; long xr = p.X*prj.TileSize.Width; long yr = p.Y*prj.TileSize.Width; long x2 = (p.X + 1)*prj.TileSize.Width; long y2 = (p.Y + 1)*prj.TileSize.Width; GL.LineWidth(0); GL.Color3(Color.White); // generate terrain GL.Begin(PrimitiveType.TriangleStrip); var latlng = prj.FromPixelToLatLng(xr, yr, localzoom); double heightl = srtm.getAltitude(latlng.Lat, latlng.Lng).alt; if (localzoom == 10) heightl = 0; //xr - topLeftPx.X, yr - topLeftPx.Y GL.TexCoord2(0, 0); GL.Vertex3(latlng.Lng, latlng.Lat, heightl*heightscale); // next down latlng = prj.FromPixelToLatLng(xr, y2, localzoom); heightl = srtm.getAltitude(latlng.Lat, latlng.Lng).alt; if (localzoom == 10) heightl = 0; GL.TexCoord2(0, 1); GL.Vertex3(latlng.Lng, latlng.Lat, heightl*heightscale); // next right latlng = prj.FromPixelToLatLng(x2, yr, localzoom); heightl = srtm.getAltitude(latlng.Lat, latlng.Lng).alt; if (localzoom == 10) heightl = 0; GL.TexCoord2(1, 0); GL.Vertex3(latlng.Lng, latlng.Lat, heightl*heightscale); // next right down latlng = prj.FromPixelToLatLng(x2, y2, localzoom); heightl = srtm.getAltitude(latlng.Lat, latlng.Lng).alt; if (localzoom == 10) heightl = 0; GL.TexCoord2(1, 1); GL.Vertex3(latlng.Lng, latlng.Lat, heightl*heightscale); GL.End(); } GL.Flush(); try { this.SwapBuffers(); //Context.MakeCurrent(null); } catch { } //this.Invalidate(); return; }
public Ambiente(GL gl) { this.gl = gl; shapes1 = new GLUTShapes(gl); }
protected override void OnLoad(EventArgs e) { GL.LineWidth(LineWidth); base.OnLoad(e); }
private void PreviewTexture(Rect r, Texture t, GUIStyle background, Event e) { bool isVolume = IsVolume(t); // Render target must be created before we can display it (case 491797) RenderTexture rt = t as RenderTexture; if (rt != null) { if (!SystemInfo.SupportsRenderTextureFormat(rt.format)) { return; // can't do this RT format } if (!isVolume) { rt.Create(); } } if (IsCubemap()) { //TODO perhaps support custom cubemap settings. Not currently! defaultEditor.OnPreviewGUI(r, background); return; } if (isVolume) { if (rt != null && rt.depth != 0) { float h = r.height / 2f; h -= 15; float y = r.y + h; h = 30; EditorGUI.HelpBox(new Rect(r.x, y, r.width, h), noSupportFor3DWithDepth, MessageType.Error); return; } editor3D.OnPreviewGUI(r, background); return; } if (r.width == 32 && r.height == 32 || r.width == 1 && r.height == 1) { //There seems to be some unhelpful layout and repaint steps that provide rect scales that are unhelpful... return; } bool isNormalMap = IsNormalMap(t); // target can report zero sizes in some cases just after a parameter change; // guard against that. int texWidth = Mathf.Max(t.width, 1); int texHeight = Mathf.Max(t.height, 1); float mipLevel = GetMipLevelForRendering(); float GetMipLevelForRendering() { if (target == null) { return(0.0f); } if (IsCubemap()) { throw new NotImplementedException(); //This should never be called yet by this class, and is handled by the default editor. //TODO support cubemap rendering here too //return m_CubemapPreview.GetMipLevelForRendering(target as Texture); } return(Mathf.Min(m_MipLevel, GetMipmapCount(target as Texture) - 1)); } zoomLevel = Mathf.Min(Mathf.Min(r.width / texWidth, r.height / texHeight), 1); Rect wantedRect = new Rect(r.x, r.y, texWidth * zoomLevel * zoomMultiplier, texHeight * zoomLevel * zoomMultiplier); if (e.type == EventType.MouseDown) { hasDragged = false; } if (isNormalMap) { if (e.button == 1) { switch (e.type) { case EventType.MouseDown: normalsMaterial.EnableKeyword("PREVIEW_DIFFUSE"); normalsMaterial.DisableKeyword("PREVIEW_NORMAL"); Cursor.SetCursor(LightCursor, new Vector2(16, 16), CursorMode.Auto); continuousRepaint = true; break; case EventType.MouseUp: normalsMaterial.DisableKeyword("PREVIEW_DIFFUSE"); normalsMaterial.EnableKeyword("PREVIEW_NORMAL"); continuousRepaint = false; break; } if (e.type != EventType.Repaint && e.type != EventType.Layout) { e.Use(); } } if (continuousRepaint) { Vector2 pos = Event.current.mousePosition - r.position; pos -= r.size / 2f; pos += m_Pos; pos += new Vector2(texWidth * zoomLevel * zoomMultiplier, texHeight * zoomLevel * zoomMultiplier) / 2f; normalsMaterial.SetFloat(LightX, pos.x / wantedRect.size.x); normalsMaterial.SetFloat(LightY, 1 - pos.y / wantedRect.size.y); EditorGUIUtility.AddCursorRect(r, MouseCursor.CustomCursor); } } else { if (e.button == 1) { switch (e.type) { case EventType.MouseDown: samplingColour = true; Cursor.SetCursor(PickerCursor, new Vector2(15, 15), CursorMode.Auto); break; case EventType.MouseUp: samplingColour = false; break; } if (e.type != EventType.Repaint && e.type != EventType.Layout && !(e.control || e.command || e.alt)) { e.Use(); } } } if (e.type == EventType.MouseDrag) { //Don't allow dragging for zoomMultiplier 1 if (Math.Abs(zoomMultiplier - 1) < 0.001f) { e.Use(); return; } hasDragged = true; m_Pos -= e.delta; m_Pos = ClampPos(m_Pos, r, texWidth, texHeight, zoomLevel); e.Use(); Repaint(); } if (!hasDragged && e.type == EventType.MouseUp && e.button == 2) { //Middle mouse button click re-centering animatedPos.value = m_Pos; Vector2 tgt = ClampPos(m_Pos + ConvertPositionToLocalTextureRect(r, e.mousePosition), r, texWidth, texHeight, zoomLevel); animatedPos.target = tgt; e.Use(); } if (e.type == EventType.ScrollWheel) { if (continuousRepaint) { lightZ = Mathf.Clamp(lightZ + e.delta.y * 0.01f, 0.01f, 1f); normalsMaterial.SetFloat(LightZ, lightZ); } else { float zoomMultiplierLast = zoomMultiplier; zoomMultiplier = Mathf.Max(1, zoomMultiplier - e.delta.y * zoomMultiplier * 0.1f); //Maximum 2x texture zoom zoomMultiplier = Mathf.Clamp(zoomMultiplier, 1, maxZoomNormalized / zoomLevel); //if zoom has changed if (Math.Abs(zoomMultiplierLast - zoomMultiplier) > 0.001f) { //Focuses Center Vector2 posNormalized = new Vector2(m_Pos.x / wantedRect.width, m_Pos.y / wantedRect.height); Vector2 newPos = new Vector2(posNormalized.x * (texWidth * zoomLevel * zoomMultiplier), posNormalized.y * (texHeight * zoomLevel * zoomMultiplier)); m_Pos = newPos; m_Pos = ClampPos(m_Pos, r, texWidth, texHeight, zoomLevel); } } e.Use(); Repaint(); } Texture2D t2d = t as Texture2D; { //SCROLL VIEW ----------------------------------------------------------------------------- PreviewGUIUtility.BeginScrollView(r, m_Pos, wantedRect, "PreHorizontalScrollbar", "PreHorizontalScrollbarThumb"); // FilterMode oldFilter = t.filterMode; // SetFilterModeNoDirty(t, FilterMode.Point); if (m_ShowAlpha) { #if UNITY_2018_1_OR_NEWER EditorGUI.DrawTextureAlpha(wantedRect, t, ScaleMode.StretchToFill, 0, mipLevel); #else EditorGUI.DrawTextureAlpha(wantedRect, t, ScaleMode.StretchToFill, 0); #endif } else if (t2d != null && t2d.alphaIsTransparency) { float imageAspect = t.width / (float)t.height; DrawTransparencyCheckerTexture(wantedRect, ScaleMode.StretchToFill, imageAspect); #if UNITY_2018_1_OR_NEWER EditorGUI.DrawPreviewTexture(wantedRect, t, rGBATransparentMaterial, ScaleMode.StretchToFill, imageAspect, mipLevel); #else EditorGUI.DrawPreviewTexture(wantedRect, t, rGBATransparentMaterial, ScaleMode.StretchToFill, imageAspect); #endif } else { Material matToUse = isNormalMap ? normalsMaterial : rGBAMaterial; #if UNITY_2018_1_OR_NEWER EditorGUI.DrawPreviewTexture(wantedRect, t, matToUse, ScaleMode.StretchToFill, 0, mipLevel); #else EditorGUI.DrawPreviewTexture(wantedRect, t, matToUse, ScaleMode.StretchToFill, 0); #endif } // TODO: Less hacky way to prevent sprite rects to not appear in smaller previews like icons. if (wantedRect.width > 32 && wantedRect.height > 32) { string path = AssetDatabase.GetAssetPath(t); TextureImporter textureImporter = AssetImporter.GetAtPath(path) as TextureImporter; SpriteMetaData[] spritesheet = textureImporter != null ? textureImporter.spritesheet : null; if (spritesheet != null && textureImporter.spriteImportMode == SpriteImportMode.Multiple) { Rect screenRect = new Rect(); Rect sourceRect = new Rect(); GUICalculateScaledTextureRects(wantedRect, ScaleMode.StretchToFill, t.width / (float)t.height, ref screenRect, ref sourceRect); int origWidth = t.width; int origHeight = t.height; TextureImporterGetWidthAndHeight(textureImporter, ref origWidth, ref origHeight); float definitionScale = t.width / (float)origWidth; ApplyWireMaterial(); GL.PushMatrix(); GL.MultMatrix(Handles.matrix); GL.Begin(GL.LINES); GL.Color(new Color(1f, 1f, 1f, 0.5f)); foreach (SpriteMetaData sprite in spritesheet) { Rect spriteRect = sprite.rect; Rect spriteScreenRect = new Rect { xMin = screenRect.xMin + screenRect.width * (spriteRect.xMin / t.width * definitionScale), xMax = screenRect.xMin + screenRect.width * (spriteRect.xMax / t.width * definitionScale), yMin = screenRect.yMin + screenRect.height * (1f - spriteRect.yMin / t.height * definitionScale), yMax = screenRect.yMin + screenRect.height * (1f - spriteRect.yMax / t.height * definitionScale) }; DrawRect(spriteScreenRect); } GL.End(); GL.PopMatrix(); } } //SetFilterModeNoDirty(t, oldFilter); m_Pos = PreviewGUIUtility.EndScrollView(); } //----------------------------------------------------------------------------------------- if (samplingColour && (t2d != null || rt != null)) { EditorGUIUtility.AddCursorRect(r, MouseCursor.CustomCursor); Vector2 mousePosition = Event.current.mousePosition; Color pixel = t2d != null? GetColorFromMousePosition(mousePosition, r, wantedRect, texWidth, texHeight, t2d) : GetColorFromMousePosition(mousePosition, r, wantedRect, texWidth, texHeight, rt); //Copy shortcuts if ((e.button == 0 || e.control || e.command || e.alt) && e.type == EventType.MouseDown) { if (e.clickCount == 1) { EditorGUIUtility.systemCopyBuffer = ColorUtility.ToHtmlStringRGBA(pixel); ShowNotification(copiedHexContent, 1); } else { EditorGUIUtility.systemCopyBuffer = $"new Color({pixel.r}f, {pixel.g}f, {pixel.b}f, {pixel.a}f);"; ShowNotification(copiedCodeContent, 1); } if (e.type != EventType.Repaint && e.type != EventType.Layout) { e.Use(); } } else if ((e.control || e.command) && e.keyCode == KeyCode.C) { if (!e.shift) { EditorGUIUtility.systemCopyBuffer = ColorUtility.ToHtmlStringRGBA(pixel); ShowNotification(copiedHexContent, 1); } else { EditorGUIUtility.systemCopyBuffer = $"new Color({pixel.r}f, {pixel.g}f, {pixel.b}f, {pixel.a}f);"; ShowNotification(copiedCodeContent, 1); } if (e.type != EventType.Repaint && e.type != EventType.Layout) { e.Use(); } } //----------- //Picker label string label = $"({pixel.r:F3}, {pixel.g:F3}, {pixel.b:F3}, {pixel.a:F3})"; Vector2 labelSize = PickerLabelStyle.CalcSize(new GUIContent(label)); Rect labelRect; if (mousePosition.x > r.width - labelSize.x) { labelRect = new Rect(mousePosition.x - labelSize.x - 5, mousePosition.y + 5, labelSize.x, 16); PickerLabelStyle.alignment = TextAnchor.MiddleRight; } else { labelRect = new Rect(mousePosition.x + 5, mousePosition.y + 5, labelSize.x, 16); PickerLabelStyle.alignment = TextAnchor.MiddleLeft; } EditorGUI.DrawRect(labelRect, new Color(0f, 0f, 0f, 0.2f)); EditorGUI.LabelField(labelRect, label, PickerLabelStyle); //Picker swatch pixel.a = 1; EditorGUI.DrawRect(new Rect(mousePosition.x - 57, mousePosition.y - 57, 52, 52), Color.black); EditorGUI.DrawRect(new Rect(mousePosition.x - 56, mousePosition.y - 56, 50, 50), pixel); } // ReSharper disable once CompareOfFloatsByEqualityOperator if (mipLevel != 0) { EditorGUI.DropShadowLabel(new Rect(r.x, r.y, r.width, 20), "Mip " + mipLevel); } DrawNotification(r); //This approach is much smoother than using RequiresConstantRepaint if (continuousRepaint || continuousRepaintOverride || notificationRepaint || samplingColour) { Repaint(); } }
public AbstractShaderProgram(string vertexProgramName, string fragmentProgramName) { VertexShaderId = LoadShader(vertexProgramName, ShaderType.VertexShader); FragmentShaderId = LoadShader(fragmentProgramName, ShaderType.FragmentShader); ProgramId = GL.CreateProgram(); }
private static void EndRender() { GL.End(); }
public void Start() { GL.UseProgram(ProgramId); }
public void LoadTexture(int[] mTexture_ID, int mTextureIndex, ShaderUtility mShader) { string filepath; if (mTextureIndex == 0) { filepath = @"ACW/texture.jpg"; if (System.IO.File.Exists(filepath)) { Bitmap TextureBitmap = new Bitmap(filepath); TextureBitmap.RotateFlip(RotateFlipType.RotateNoneFlipY); BitmapData TextureData = TextureBitmap.LockBits(new System.Drawing.Rectangle(0, 0, TextureBitmap.Width, TextureBitmap.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb); GL.ActiveTexture(TextureUnit.Texture0); GL.GenTextures(1, out mTexture_ID[mTextureIndex]); GL.BindTexture(TextureTarget.Texture2D, mTexture_ID[mTextureIndex]); GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, TextureData.Width, TextureData.Height, 0, OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, TextureData.Scan0); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear); TextureBitmap.UnlockBits(TextureData); int uTextureSamplerLocation = GL.GetUniformLocation(mShader.ShaderProgramID, "uTextureSampler[0]"); GL.Uniform1(uTextureSamplerLocation, 0); } else { throw new Exception("Could not find file " + filepath); } } if (mTextureIndex == 1) { filepath = @"ACW/texture2.jpg"; if (System.IO.File.Exists(filepath)) { Bitmap TextureBitmap = new Bitmap(filepath); TextureBitmap.RotateFlip(RotateFlipType.RotateNoneFlipY); BitmapData TextureData = TextureBitmap.LockBits(new System.Drawing.Rectangle(0, 0, TextureBitmap.Width, TextureBitmap.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb); GL.ActiveTexture(TextureUnit.Texture1); GL.GenTextures(1, out mTexture_ID[1]); GL.BindTexture(TextureTarget.Texture2D, mTexture_ID[1]); GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, TextureData.Width, TextureData.Height, 0, OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, TextureData.Scan0); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear); TextureBitmap.UnlockBits(TextureData); int uTextureSamplerLocation = GL.GetUniformLocation(mShader.ShaderProgramID, "uTextureSampler[1]"); GL.Uniform1(uTextureSamplerLocation, 1); } else { throw new Exception("Could not find file " + filepath); } } if (mTextureIndex == 2) { filepath = @"ACW/texture3.jpg"; if (System.IO.File.Exists(filepath)) { Bitmap TextureBitmap = new Bitmap(filepath); TextureBitmap.RotateFlip(RotateFlipType.RotateNoneFlipY); BitmapData TextureData = TextureBitmap.LockBits(new System.Drawing.Rectangle(0, 0, TextureBitmap.Width, TextureBitmap.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb); GL.ActiveTexture(TextureUnit.Texture2); GL.GenTextures(1, out mTexture_ID[2]); GL.BindTexture(TextureTarget.Texture2D, mTexture_ID[2]); GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, TextureData.Width, TextureData.Height, 0, OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, TextureData.Scan0); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear); TextureBitmap.UnlockBits(TextureData); int uTextureSamplerLocation = GL.GetUniformLocation(mShader.ShaderProgramID, "uTextureSampler[2]"); GL.Uniform1(uTextureSamplerLocation, 2); } else { throw new Exception("Could not find file " + filepath); } } if (mTextureIndex == 3) { filepath = @"ACW/texture4.jpg"; if (System.IO.File.Exists(filepath)) { Bitmap TextureBitmap = new Bitmap(filepath); TextureBitmap.RotateFlip(RotateFlipType.RotateNoneFlipY); BitmapData TextureData = TextureBitmap.LockBits(new System.Drawing.Rectangle(0, 0, TextureBitmap.Width, TextureBitmap.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb); GL.ActiveTexture(TextureUnit.Texture3); GL.GenTextures(1, out mTexture_ID[3]); GL.BindTexture(TextureTarget.Texture2D, mTexture_ID[3]); GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, TextureData.Width, TextureData.Height, 0, OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, TextureData.Scan0); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear); TextureBitmap.UnlockBits(TextureData); int uTextureSamplerLocation = GL.GetUniformLocation(mShader.ShaderProgramID, "uTextureSampler[3]"); GL.Uniform1(uTextureSamplerLocation, 3); } else { throw new Exception("Could not find file " + filepath); } } }
public void Stop() { GL.UseProgram(0); }
public void BindVao() { GL.BindVertexArray(Vao); }
protected void BindAttribute(int attribute, string name) { GL.BindAttribLocation(ProgramId, attribute, name); }
public void Bind() { GL.Enable(ArrayType); GL.BindBuffer(BufferTarget, Handle); }
private void updateFire() { // If texture does not exist, create it createTexture(ref velocityTex, size, 4); createTexture(ref velocityTexRes, size, 4); createTexture(ref pressureTex, size, 1); createTexture(ref pressureTexRes, size, 1); createTexture(ref densityTex, size, 1); createTexture(ref densityTexRes, size, 1); createTexture(ref temperatureTex, size, 1); createTexture(ref temperatureTexRes, size, 1); createTexture(ref vorticityTex, size, 4); createTexture(ref divergenceTex, size, 1); createTexture(ref fuelTex, size, 1); createTexture(ref fuelTexRes, size, 1); createTexture(ref emberTex, size, 4); createTexture(ref emberTexRes, size, 4); createTexture(ref debugTex, size, 1); // Find kernel int initHandle = fireComputeShader.FindKernel("InitFire"); int advectionHandle = fireComputeShader.FindKernel("Advection"); int divergenceHandle = fireComputeShader.FindKernel("Divergence"); int jacobiHandle = fireComputeShader.FindKernel("Jacobi"); int projectionHandle = fireComputeShader.FindKernel("Projection"); int buoyancyHandle = fireComputeShader.FindKernel("ApplyBuoyancy"); int vorticityHandle = fireComputeShader.FindKernel("Vorticity"); int vorticityApplyHandle = fireComputeShader.FindKernel("ApplyVorticity"); int clearEmberHandle = fireComputeShader.FindKernel("ClearEmberTarget"); // static Input foreach (int handle in new int[] { advectionHandle, divergenceHandle, jacobiHandle, projectionHandle }) { fireComputeShader.SetTexture(handle, "divergenceTex", divergenceTex); } fireComputeShader.SetInt("size", size); // Clear Ember Target before filling new values fireComputeShader.SetTexture(clearEmberHandle, "emberTexRes", emberTexRes); fireComputeShader.Dispatch(clearEmberHandle, size / 8, size / 8, size / 8); GL.Flush(); // Calculate Advection fireComputeShader.SetTexture(advectionHandle, "velocityTex", velocityTex); fireComputeShader.SetTexture(advectionHandle, "debugTex", debugTex); fireComputeShader.SetTexture(advectionHandle, "velocityTexRes", velocityTexRes); fireComputeShader.SetTexture(advectionHandle, "temperatureTex", temperatureTex); fireComputeShader.SetTexture(advectionHandle, "temperatureTexRes", temperatureTexRes); fireComputeShader.SetTexture(advectionHandle, "densityTex", densityTex); fireComputeShader.SetTexture(advectionHandle, "densityTexRes", densityTexRes); fireComputeShader.SetTexture(advectionHandle, "fuelTex", fuelTex); fireComputeShader.SetTexture(advectionHandle, "fuelTexRes", fuelTexRes); fireComputeShader.SetTexture(advectionHandle, "emberTex", emberTex); fireComputeShader.SetTexture(advectionHandle, "emberTexRes", emberTexRes); fireComputeShader.SetTexture(advectionHandle, "debugTex", debugTex); fireComputeShader.SetFloat("timeStep", 0.8f); fireComputeShader.SetInt("stepCount", stepCount); fireComputeShader.Dispatch(advectionHandle, size / 8, size / 8, size / 8); GL.Flush(); // Initialization fireComputeShader.SetTexture(initHandle, "debugTex", debugTex); fireComputeShader.SetTexture(initHandle, "fuelTexRes", fuelTexRes); fireComputeShader.SetTexture(initHandle, "velocityTexRes", velocityTexRes); fireComputeShader.SetTexture(initHandle, "densityTexRes", densityTexRes); fireComputeShader.SetTexture(initHandle, "temperatureTexRes", temperatureTexRes); fireComputeShader.SetTexture(initHandle, "emberTexRes", emberTexRes); fireComputeShader.Dispatch(initHandle, size / 8, size / 8, size / 8); swap(ref fuelTex, ref fuelTexRes); swap(ref emberTex, ref emberTexRes); // Calculate Buoyancy fireComputeShader.SetTexture(buoyancyHandle, "debugTex", debugTex); fireComputeShader.SetTexture(buoyancyHandle, "velocityTexRes", velocityTexRes); fireComputeShader.SetTexture(buoyancyHandle, "temperatureTex", temperatureTexRes); // Hot Read fireComputeShader.SetTexture(buoyancyHandle, "densityTex", densityTexRes); // Hot Read fireComputeShader.Dispatch(buoyancyHandle, size / 8, size / 8, size / 8); GL.Flush(); // Calculate Vorticity fireComputeShader.SetTexture(vorticityHandle, "debugTex", debugTex); fireComputeShader.SetTexture(vorticityHandle, "vorticityTex", vorticityTex); fireComputeShader.SetTexture(vorticityHandle, "velocityTex", velocityTexRes); fireComputeShader.Dispatch(vorticityHandle, size / 8, size / 8, size / 8); // Apply Vorticity fireComputeShader.SetTexture(vorticityApplyHandle, "debugTex", debugTex); fireComputeShader.SetTexture(vorticityApplyHandle, "vorticityTex", vorticityTex); fireComputeShader.SetTexture(vorticityApplyHandle, "velocityTexRes", velocityTexRes); fireComputeShader.SetFloat("vorticityStrength", vorticity); fireComputeShader.Dispatch(vorticityApplyHandle, size / 8, size / 8, size / 8); // Switch res swap(ref velocityTex, ref velocityTexRes); // Calculate divergence, jacobi, projection fireComputeShader.SetTexture(divergenceHandle, "debugTex", debugTex); fireComputeShader.SetTexture(divergenceHandle, "velocityTex", velocityTex); fireComputeShader.SetTexture(divergenceHandle, "velocityTexRes", velocityTexRes); fireComputeShader.SetTexture(jacobiHandle, "velocityTex", velocityTex); fireComputeShader.SetTexture(jacobiHandle, "velocityTexRes", velocityTexRes); fireComputeShader.Dispatch(divergenceHandle, size / 8, size / 8, size / 8); GL.Flush(); for (int itr = 0; itr < 20; itr++) { fireComputeShader.SetTexture(jacobiHandle, "debugTex", debugTex); fireComputeShader.SetTexture(jacobiHandle, "pressureTex", pressureTex); fireComputeShader.SetTexture(jacobiHandle, "pressureTexRes", pressureTexRes); fireComputeShader.Dispatch(jacobiHandle, size / 8, size / 8, size / 8); GL.Flush(); swap(ref pressureTex, ref pressureTexRes); } swap(ref temperatureTex, ref temperatureTexRes); swap(ref densityTex, ref densityTexRes); fireComputeShader.SetTexture(projectionHandle, "velocityTex", velocityTex); fireComputeShader.SetTexture(projectionHandle, "velocityTexRes", velocityTexRes); fireComputeShader.SetTexture(projectionHandle, "pressureTex", pressureTex); fireComputeShader.Dispatch(projectionHandle, size / 8, size / 8, size / 8); GL.Flush(); swap(ref velocityTex, ref velocityTexRes); // Output material.SetTexture("Velocity", velocityTex); material.SetTexture("Density", densityTex); material.SetTexture("Temperature", temperatureTex); material.SetTexture("Fuel", fuelTex); material.SetTexture("Ember", emberTex); material.SetTexture("Debug", debugTex); stepCount += 1; }
void IMustExit.Exit(GL gl) { fixed(uint* pB = &B) gl.DeleteBuffers(1,pB); }
public void Activate() { GL.UseProgram(myProgram); }
void Exit(GL gl) { if(TexCoord != null) TexCoord.Dispose(); if(Normal != null) Normal.Dispose(); }
/// <summary>頂点配列をシェーダに指定。</summary> public void SetVertex(float[] data) { GL.EnableVertexAttribArray(positionHandle); GL.VertexAttribPointer(positionHandle, 3, VertexAttribPointerType.Float, true, 0, data); }
static int _CreateGL(IntPtr L) { int count = LuaDLL.lua_gettop(L); if (count == 0) { GL obj = new GL(); LuaScriptMgr.PushObject(L, obj); return 1; } else { LuaDLL.luaL_error(L, "invalid arguments to method: GL.New"); } return 0; }
void IMustInit.Init(GL gl) { P = gl.CreateProgram(); gl.AttachShader(P,VShader.S); gl.AttachShader(P,FShader.S); gl.LinkProgram(P); //////////////////////////////////////////////////////////////// int ACount = 0; gl.GetProgramiv(P,ACTIVE_ATTRIBUTES,&ACount); if(ACount >= 0) { uint i = 0; while(i < ACount) { uint T; int Lng,Sze; sbyte* pName = stackalloc sbyte[64]; gl.GetActiveAttrib(P,i,64,&Lng,&Sze,&T,pName); int Location = gl.GetAttribLocation(P,pName); if(Location >= 0) { string AName = new string(pName); Attributes[AName] = new Attribute(Location,AName); } i++; } } int UCount = 0; gl.GetProgramiv(P,ACTIVE_UNIFORMS,&UCount); if(UCount >= 0) { uint i = 0; while(i < UCount) { int Lng,Sze; uint T; sbyte* pName = stackalloc sbyte[64]; gl.GetActiveUniform(P,i,64,&Lng,&Sze,&T,pName); int Location = gl.GetUniformLocation(P,pName); if(Location >= 0) { string UName = new string(pName); Uniforms[UName] = new Uniform(gl,Location,UName); } i++; } } }
/// <summary>法線配列をシェーダに指定。</summary> public void SetNormal(float[] data) { GL.EnableVertexAttribArray(normalHandle); GL.VertexAttribPointer(normalHandle, 3, VertexAttribPointerType.Float, true, 0, data); }
void LoadCSGL(GL gl,CSGL12Control csglControl1) { int clientWidth=csglControl1.ClientRectangle.Width; int clientHeight=csglControl1.ClientRectangle.Height; if(clientWidth<=0) clientWidth=1; if(clientHeight<=0) clientHeight=1; gl.glViewport(0,0,clientWidth,clientHeight); gl.glMatrixMode(GL.GL_PROJECTION); gl.glLoadIdentity(); double aspectRatio = 1.0; if (0 != clientHeight) { aspectRatio = (clientWidth / (double)(clientHeight)); } gl.gluPerspective(45.0f, aspectRatio, 0.1f, 100.0f); gl.glMatrixMode(GL.GL_MODELVIEW); gl.glLoadIdentity(); }
void IMustExit.Exit(GL gl) { gl.DeleteProgram(P); P = 0; }
/// <summary>テクスチャ座標配列をシェーダに指定。</summary> public void SetTexture(float[] data) { GL.EnableVertexAttribArray(textureHandle); GL.VertexAttribPointer(textureHandle, 2, VertexAttribPointerType.Float, true, 0, data); }
void IMustExit.Exit(GL gl) { gl.DeleteShader(S); S = 0; }
public void SetMaterial(Color4 color) { GL.Uniform4(materialDiffuseHandle, color.R, color.G, color.B, color.A); //拡散光 }
internal Uniform(GL gl,int Location,string UName) : base(gl) { Loc = Location; Name = UName; }
public static void Bind(GLTexture texture) { GL.BindTexture(TextureTarget.Texture2D, texture.Texture); bindedTexture = texture; }
public GLUTShapes(GL gl) { this.gl = gl; }
public static void Unbind() { GL.BindTexture(TextureTarget.Texture2D, 0); bindedTexture = null; }