diff --git a/.gitignore b/.gitignore index e11de0a..4909f73 100644 --- a/.gitignore +++ b/.gitignore @@ -152,3 +152,6 @@ local.properties # TeXlipse plugin .texlipse + + +debug/ diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..ab3e67d --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,41 @@ +{ + "version": "0.1.0", + // List of configurations. Add new configurations or edit existing ones. + "configurations": [ + { + // Name of configuration; appears in the launch configuration drop down menu. + "name": "Launch app.js", + // Type of configuration. + "type": "node", + // Workspace relative or absolute path to the program. + "program": "app.js", + // Automatically stop program after launch. + "stopOnEntry": false, + // Command line arguments passed to the program. + "args": [], + // Workspace relative or absolute path to the working directory of the program being debugged. Default is the current workspace. + "cwd": ".", + // Workspace relative or absolute path to the runtime executable to be used. Default is the runtime executable on the PATH. + "runtimeExecutable": null, + // Optional arguments passed to the runtime executable. + "runtimeArgs": ["--nolazy"], + // Environment variables passed to the program. + "env": { + "NODE_ENV": "development" + }, + // Use JavaScript source maps (if they exist). + "sourceMaps": false, + // If JavaScript source maps are enabled, the generated code is expected in this directory. + "outDir": null + }, + { + "name": "Attach", + "type": "node", + // TCP/IP address. Default is "localhost". + "address": "localhost", + // Port to attach to. + "port": 5858, + "sourceMaps": false + } + ] +} diff --git a/README.md b/README.md index 09e7f12..262bae7 100644 --- a/README.md +++ b/README.md @@ -1,445 +1,101 @@ WebGL Deferred Shading ====================== -**University of Pennsylvania, CIS 565: GPU Programming and Architecture, Project 6** +**University of Pennsylvania, CIS 565: GPU Programming and Architecture, Project 5** -* (TODO) YOUR NAME HERE -* Tested on: (TODO) **Google Chrome 222.2** on - Windows 22, i7-2222 @ 2.22GHz 22GB, GTX 222 222MB (Moore 2222 Lab) +* Shuai Shao (Shrek) +* Tested on: **Google Chrome 46.0.2490.71 m** on + Windows 10, i7-4710HQ @ 2.50GHz 16GB, GeForce GTX 970M (Personal) ### Live Online -[![](img/thumb.png)](http://TODO.github.io/Project6-WebGL-Deferred-Shading) +[![](img/thumb.png)](http://shrekshao.github.io/Project6-WebGL-Deferred-Shading/) ### Demo Video -[![](img/video.png)](TODO) +[![](img/video.png)](https://youtu.be/QFfciB-AO1w) -### (TODO: Your README) -*DO NOT* leave the README to the last minute! It is a crucial part of the -project, and we will not be able to grade you without a good README. +Features +==================== -This assignment has a considerable amount of performance analysis compared -to implementation work. Complete the implementation early to leave time! +##### Deferred render +![](img/basic.png) -Instructions (delete me) -======================== +##### Debug Views -This is due at midnight on the evening of Tuesday, October 27. +|Depth| Geometry Position | Color map| +|--------------------------| --------------------|------| +|![](img/depth.png) |![](img/position.png) | ![](img/colormap.png)| +|**Geometry Normal**| **Normal map** | **Surface Normal**| +|![](img/geonor.png) |![](img/normap.png) | ![](img/nor.png)| -**Summary:** In this project, you'll be introduced to the basics of deferred -shading and WebGL. You'll use GLSL and WebGL to implement a deferred shading -pipeline and various lighting and visual effects. -**Recommendations:** -Take screenshots as you go. Use them to document your progress in your README! +##### Bloom -Read (or at least skim) the full README before you begin, so that you know what -to expect and what to prepare for. +![](img/bloom.png) -### Running the code +I used a box filter on the rendered buffer in post-process, to create a glowing effect on the bright part of the deferred render image. -If you have Python, you should be able to run `server.py` to start a server. -Then, open [`http://localhost:10565/`](http://localhost:10565/) in your browser. +Two-pass process is used for optimization. By doing this, we decrease the time complexity from N^2 to 2N. This can save memory bandwith. For a 20x20 filter I used, theoratically it takes 10% of the time of one-pass blurring. -This project requires a WebGL-capable web browser with support for -`WEBGL_draw_buffers`. You can check for support on -[WebGL Report](http://webglreport.com/). +##### Toon -Google Chrome seems to work best on all platforms. If you have problems running -the starter code, use Chrome or Chromium, and make sure you have updated your -browser and video drivers. +![](img/toon.png) -In Moore 100C, both Chrome and Firefox work. -See below for notes on profiling/debugging tools. +My toon shading consists of two parts. One is ramping the cos value in the Phong shading, which happens right in the deferred shading stage. The other part is drawing the contour, this happens after the image is rendered, by applying a Laplacian filter on the depth buffer, we can get the edge. -Use the screenshot button to save a screenshot. -## Requirements +Optimizations +======================= -**Ask on the mailing list for any clarifications.** +##### G-Buffer Format -In this project, you are given code for: +* Normal precomputation + * Moving the computing of surface normal from deferred step to copy step. Reduce one g-buffer directly. -* Loading OBJ files and color/normal map textures -* Camera control -* Partial implementation of deferred shading including many helper functions +* Discard z of normal + * Since normal vector is always normalized, we only need x and y to reconstruct the normal vector. We can save one float by doing so, which can make enough space for color compacting and other features like screen movements(though not implemented this time). -### Required Tasks +* Color packing + * Because color value has a limited range from 0-255 (if stored as int), we can pack the four color channel into one float using some encoding algorithm, and decode it in the deferred stage. + * However, color compacting can lose information, resulting in a relatively noisy color map. When I first use Aras compacting method, it is super noisy which is almost useless. By reading StoneBird's post, it's the issue with precision issue of glsl float. It can be fixed by changing the shifting amount. -**Before doing performance analysis,** you must disable debug mode by changing -`debugMode` to `false` in `framework.js`. Keep it enabled when developing - it -helps find WebGL errors *much* more easily. -You will need to perform the following tasks: +Finally, I manage to reduce the number of g-buffers from 4 to 2 (excluding the depth buffer). The following the graph shows the performance. The stats.js tool fails to record frame time in ms for my chrome, so I have to use FPS. Note that since bloom needs more memory accessing, the improvement is more obvious when it is turned on. -* Complete the deferred shading pipeline so that the Blinn-Phong and Post1 - shaders recieve the correct input. Go through the Starter Code Tour **before - continuing!** +![](img/gbuffer.png) -**Effects:** +##### Scissoring and Light Proxy -* Implement deferred Blinn-Phong shading (diffuse + specular) for point lights - * With normal mapping (code provided) - * For deferred shading, you want to use a lighting model for the point lights - which has a limited radius - so that adding a scissor or proxy geometry - will not cause parts of the lighting to disappear. It should look very - similar both with and without scissor/proxy optimization. Here is a - convenient lighting model, but you can also use others: - * `float attenuation = max(0.0, u_lightRad - dist_from_surface_to_light);` +In deferred shading, our fragment shading is done by rendering the screen quad zone, reading geometry info from g-buffers for each fragment. In this case, by using a scissor, stencil or light proxy, we can improve the performance by only render the lit area for each light, instead of rendering the whole quad, which can save a lot of memory accessing because each fragment shading process will read the g-buffer once. -* Implement one of the following effects: - * Bloom using post-process blur (box or Gaussian) [1] - * Toon shading (with ramp shading + simple depth-edge detection for outlines) + Using the debug view of scissor can show the render area of each of the lights. -**Optimizations:** +|Scissor| Light proxy using a sphere model| +|--------------------------| --------------------| +|![](img/scissordebug.png) |![](img/spheredebug.png) | -* Scissor test optimization: when accumulating shading from each point - light source, only render in a rectangle around the light. - * Show a debug view for this (showing scissor masks clearly), e.g. by - modifying and using `red.frag.glsl` with additive blending and alpha = 0.1. - * Code is provided to compute this rectangle for you, and there are - comments at the relevant place in `deferredRender.js` with more guidance. - * **NOTE:** The provided scissor function is not very accurate - it is a - quick hack which results in some errors (as can be seen in the live - demo). -* Optimized g-buffer format - reduce the number and size of g-buffers: - * Ideas: - * Pack values together into vec4s - * Use 2-component normals - * Quantize values by using smaller texture types instead of gl.FLOAT - * Reduce number of properties passed via g-buffer, e.g. by: - * Applying the normal map in the `copy` shader pass instead of - copying both geometry normals and normal maps - * Reconstructing world space position using camera matrices and X/Y/depth - * For credit, you must show a good optimization effort and record the - performance of each version you test, in a simple table. - * It is expected that you won't need all 4 provided g-buffers for a basic - pipeline - make sure you disable the unused ones. - * See mainly: `copy.frag.glsl`, `deferred/*.glsl`, `deferredSetup.js` - -### Extra Tasks - -You must do at least **10 points** worth of extra features (effects or -optimizations/analysis). - -**Effects:** - -* (3pts) The effect you didn't choose above (bloom or toon shading) - -* (3pts) Screen-space motion blur (blur along velocity direction) [3] - -* (2pts) Allow variability in additional material properties - * Include other properties (e.g. specular coeff/exponent) in g-buffers - * Use this to render objects with different material properties - * These may be uniform across one model draw call, but you'll have to show - multiple models - -**Optimizations/Analysis:** - -* (2pts) Improved screen-space AABB for scissor test - (smaller/more accurate than provided - but beware of CPU/GPU tradeoffs) - -* (3pts) Two-pass **Gaussian** blur using separable convolution (using a second - postprocess render pass) to improve bloom or other 2D blur performance - -* (4-6pts) Light proxies - * (4pts) Instead of rendering a scissored full-screen quad for every light, - render some proxy geometry which covers the part of the screen affected by - the light (e.g. a sphere, for an attenuated point light). - * A model called `sphereModel` is provided which can be drawn in the same - way as the code in `drawScene`. (Must be drawn with a vertex shader which - scales it to the light radius and translates it to the light position.) - * (+2pts) To avoid lighting geometry far behind the light, render the proxy - geometry (e.g. sphere) using an inverted depth test - (`gl.depthFunc(gl.GREATER)`) with depth writing disabled (`gl.depthMask`). - This test will pass only for parts of the screen for which the backside of - the sphere appears behind parts of the scene. - * Note that the copy pass's depth buffer must be bound to the FBO during - this operation! - * Show a debug view for this (showing light proxies) - * Compare performance of this, naive, and scissoring. - -* (8pts) Tile-based deferred shading with detailed performance comparison - * On the CPU, check which lights overlap which tiles. Then, render each tile - just once for all lights (instead of once for each light), applying only - the overlapping lights. - * The method is described very well in - [Yuqin & Sijie's README](https://github.com/YuqinShao/Tile_Based_WebGL_DeferredShader/blob/master/README.md#algorithm-details). - * This feature requires allocating the global light list and tile light - index lists as shown at this link. These can be implemented as textures. - * Show a debug view for this (number of lights per tile) - -* (6pts) Deferred shading without multiple render targets - (i.e. without WEBGL_draw_buffers). - * Render the scene once for each target g-buffer, each time into a different - framebuffer object. - * Include a detailed performance analysis, comparing with/without - WEBGL_draw_buffers (like in the - [Mozilla blog article](https://hacks.mozilla.org/2014/01/webgl-deferred-shading/)). - -* (2-6pts) Compare performance to equivalently-lit forward-rendering: - * (2pts) With no forward-rendering optimizations - * (+2pts) Coarse, per-object back-to-front sorting of geometry for early-z - * (Of course) must render many objects to test - * (+2pts) Z-prepass for early-z - -This extra feature list is not comprehensive. If you have a particular idea -that you would like to implement, please **contact us first** (preferably on -the mailing list). - -**Where possible, all features should be switchable using the GUI panel in -`ui.js`.** - -### Performance & Analysis - -**Before doing performance analysis,** you must disable debug mode by changing -`debugMode` to `false` in `framework.js`. Keep it enabled when developing - it -helps find WebGL errors *much* more easily. - -Optimize your JavaScript and/or GLSL code. Chrome/Firefox's profiling tools -(see Resources section) will be useful for this. For each change -that improves performance, show the before and after render times. - -For each new *effect* feature (required or extra), please -provide the following analysis: - -* Concise overview write-up of the feature. -* Performance change due to adding the feature. - * If applicable, how do parameters (such as number of lights, etc.) - affect performance? Show data with simple graphs. - * Show timing in milliseconds, not FPS. -* If you did something to accelerate the feature, what did you do and why? -* How might this feature be optimized beyond your current implementation? - -For each *performance* feature (required or extra), please provide: - -* Concise overview write-up of the feature. -* Detailed performance improvement analysis of adding the feature - * What is the best case scenario for your performance improvement? What is - the worst? Explain briefly. - * Are there tradeoffs to this performance feature? Explain briefly. - * How do parameters (such as number of lights, tile size, etc.) affect - performance? Show data with graphs. - * Show timing in milliseconds, not FPS. - * Show debug views when possible. - * If the debug view correlates with performance, explain how. - -### Starter Code Tour - -You'll be working mainly in `deferredRender.js` using raw WebGL. Three.js is -included in the project for various reasons. You won't use it for much, but its -matrix/vector types may come in handy. - -It's highly recommended that you use the browser debugger to inspect variables -to get familiar with the code. At any point, you can also -`console.log(some_var);` to show it in the console and inspect it. - -The setup in `deferredSetup` is already done for you, for many of the features. -If you want to add uniforms (textures or values), you'll change them here. -Therefore, it is recommended that you review the comments to understand the -process, BEFORE starting work in `deferredRender`. - -In `deferredRender`, start at the **START HERE!** comment. -Work through the appropriate `TODO`s as you go - most of them are very -small. Test incrementally (after implementing each part, instead of testing -all at once). -* (The first thing you should be doing is implementing the fullscreen quad!) -* See the note in the Debugging section on how to test the first part of the - pipeline incrementally. - -Your _next_ first goal should be to get the debug views working. -Add code in `debug.frag.glsl` to examine your g-buffers before trying to -render them. (Set the debugView in the UI to show them.) - -For editing JavaScript, you can use a simple editor with syntax highlighting -such as Sublime, Vim, Emacs, etc., or the editor built into Chrome. - -* `js/`: JavaScript files for this project. - * `main.js`: Handles initialization of other parts of the program. - * `framework.js`: Loads the scene, camera, etc., and calls your setup/render - functions. Hopefully, you won't need to change anything here. - * `deferredSetup.js`: Deferred shading pipeline setup code. - * `createAndBind(Depth/Color)TargetTexture`: Creates empty textures for - binding to frame buffer objects as render targets. - * `deferredRender.js`: Your deferred shading pipeline execution code. - * `renderFullScreenQuad`: Renders a full-screen quad with the given shader - program. - * `ui.js`: Defines the UI using - [dat.GUI](https://workshop.chromeexperiments.com/examples/gui/). - * The global variable `cfg` can be accessed anywhere in the code to read - configuration values. - * `utils.js`: Utilities for JavaScript and WebGL. - * `abort`: Aborts the program and shows an error. - * `loadTexture`: Loads a texture from a URL into WebGL. - * `loadShaderProgram`: Loads shaders from URLs into a WebGL shader program. - * `loadModel`: Loads a model into WebGL buffers. - * `readyModelForDraw`: Configures the WebGL state to draw a model. - * `drawReadyModel`: Draws a model which has been readied. - * `getScissorForLight`: Computes an approximate scissor rectangle for a - light in world space. -* `glsl/`: GLSL code for each part of the pipeline: - * `clear.*.glsl`: Clears each of the `NUM_GBUFFERS` g-buffers. - * `copy.*.glsl`: Performs standard rendering without any fragment shading, - storing all of the resulting values into the `NUM_GBUFFERS` g-buffers. - * `quad.vert.glsl`: Minimal vertex shader for rendering a single quad. - * `deferred.frag.glsl`: Deferred shading pass (for lighting calculations). - Reads from each of the `NUM_GBUFFERS` g-buffers. - * `post1.frag.glsl`: First post-processing pass. -* `lib/`: JavaScript libraries. -* `models/`: OBJ models for testing. Sponza is the default. -* `index.html`: Main HTML page. -* `server.bat` (Windows) or `server.py` (OS X/Linux): - Runs a web server at `localhost:10565`. - -### The Deferred Shading Pipeline - -See the comments in `deferredSetup.js`/`deferredRender.js` for low-level guidance. - -In order to enable and disable effects using the GUI, upload a vec4 uniform -where each component is an enable/disable flag. In JavaScript, the state of the -UI is accessible anywhere as `cfg.enableEffect0`, etc. - -**Pass 1:** Renders the scene geometry and its properties to the g-buffers. -* `copy.vert.glsl`, `copy.frag.glsl` -* The framebuffer object `pass_copy.fbo` must be bound during this pass. -* Renders into `pass_copy.depthTex` and `pass_copy.gbufs[i]`, which need to be - attached to the framebuffer. - -**Pass 2:** Performs lighting and shading into the color buffer. -* `quad.vert.glsl`, `deferred/blinnphong-pointlight.frag.glsl` -* Takes the g-buffers `pass_copy.gbufs`/`depthTex` as texture inputs to the - fragment shader, on uniforms `u_gbufs` and `u_depth`. -* `pass_deferred.fbo` must be bound. -* Renders into `pass_deferred.colorTex`. - -**Pass 3:** Performs post-processing. -* `quad.vert.glsl`, `post/one.frag.glsl` -* Takes `pass_BlinnPhong_PointLight.colorTex` as a texture input `u_color`. -* Renders directly to the screen if there are no additional passes. - -More passes may be added for additional effects (e.g. combining bloom with -motion blur) or optimizations (e.g. two-pass Gaussian blur for bloom) - -#### Debugging - -If there is a WebGL error, it will be displayed on the developer console and -the renderer will be aborted. To find out where the error came from, look at -the backtrace of the error (you may need to click the triangle to expand the -message). The line right below `wrapper @ webgl-debug.js` will point to the -WebGL call that failed. - -When working in the early pipeline (before you have a lit render), it can be -useful to render WITHOUT post-processing. To do this, you have to make sure -that there is NO framebuffer bound while rendering to the screen (that is, bind -null) so that the output will display to the screen instead of saving into a -texture. Writing to gl_FragData[0] is the same as writing to gl_FragColor, so -you'll see whatever you were storing into the first g-buffer. - -#### Changing the number of g-buffers - -Note that the g-buffers are just `vec4`s - you can put any values you want into -them. However, if you want to change the total number of g-buffers (add more -for additional effects or remove some for performance), you will need to make -changes in a number of places: - -* `deferredSetup.js`/`deferredRender.js`: search for `NUM_GBUFFERS` -* `copy.frag.glsl` -* `deferred.frag.glsl` -* `clear.frag.glsl` - - -## Resources - -* [1] Bloom: - [GPU Gems, Ch. 21](http://http.developer.nvidia.com/GPUGems/gpugems_ch21.html) -* [2] Screen-Space Ambient Occlusion: - [Floored Article](http://floored.com/blog/2013/ssao-screen-space-ambient-occlusion.html) -* [3] Post-Process Motion Blur: - [GPU Gems 3, Ch. 27](http://http.developer.nvidia.com/GPUGems3/gpugems3_ch27.html) - -**Also see:** The articles linked in the course schedule. - -### Profiling and debugging tools - -Built into Firefox: -* Canvas inspector -* Shader Editor -* JavaScript debugger and profiler - -Built into Chrome: -* JavaScript debugger and profiler - -Plug-ins: -* Web Tracing Framework - **Does not currently work with multiple render targets**, - which are used in the starter code. -* (Chrome) [Shader Editor](https://chrome.google.com/webstore/detail/shader-editor/ggeaidddejpbakgafapihjbgdlbbbpob) - -Libraries: -* Stats.js (already included) - -Firefox can also be useful - it has a canvas inspector, WebGL profiling and a -shader editor built in. +The basic idea is using scissor, which is a general step in WebGL. This method discard the fragments outside the scissor rect. -## README +We can further optimize by using a light proxy. We use a vertex shader to draw a sphere model provided by THREE.js, located at the position of the light, and make the radius the same as that of the light. Next we only render that area using the general fragment shader. We are using GPU to calculate the positions of the vertices to save time. -Replace the contents of this README.md in a clear manner with the following: +Similar result can be achieved by computing a stencil. However, doing this will make the computing of the vertices using CPU code, and in this case, JavaScript, which is quite slow. And using a stencil is not good at generating arbitrary shapes of mask comparing to use a vertex shader. -* A brief description of the project and the specific features you implemented. -* At least one screenshot of your project running. -* A 30+ second video of your project running showing all features. - [Open Broadcaster Software](http://obsproject.com) is recommended. - (Even though your demo can be seen online, using multiple render targets - means it won't run on many computers. A video will work everywhere.) -* A performance analysis (described below). +Here is the comparison of the performance using different scissor methods to accelrate. -### Performance Analysis +![](img/scissor_performance.png) -See above. -### GitHub Pages -Since this assignment is in WebGL, you can make your project easily viewable by -taking advantage of GitHub's project pages feature. +Reference +================ -Once you are done with the assignment, create a new branch: +[Aras code](http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/) -`git branch gh-pages` -Push the branch to GitHub: -`git push origin gh-pages` -Now, you can go to `.github.io/` to see your -renderer online from anywhere. Add this link to your README. -## Submit - -1. Open a GitHub pull request so that we can see that you have finished. - The title should be "Submission: YOUR NAME". - * **ADDITIONALLY:** - In the body of the pull request, include a link to your repository. -2. Send an email to the TA (gmail: kainino1+cis565@) with: - * **Subject**: in the form of `[CIS565] Project N: PENNKEY`. - * Direct link to your pull request on GitHub. - * Estimate the amount of time you spent on the project. - * If there were any outstanding problems, briefly explain. - * **List the extra features you did.** - * Feedback on the project itself, if any. - -### Third-Party Code Policy - -* Use of any third-party code must be approved by asking on our mailing list. -* If it is approved, all students are welcome to use it. Generally, we approve - use of third-party code that is not a core part of the project. For example, - for the path tracer, we would approve using a third-party library for loading - models, but would not approve copying and pasting a CUDA function for doing - refraction. -* Third-party code **MUST** be credited in README.md. -* Using third-party code without its approval, including using another - student's code, is an academic integrity violation, and will, at minimum, - result in you receiving an F for the semester. diff --git a/glsl/copy.frag.glsl b/glsl/copy.frag.glsl index 0f5f8f7..36ffc74 100644 --- a/glsl/copy.frag.glsl +++ b/glsl/copy.frag.glsl @@ -10,6 +10,42 @@ varying vec3 v_position; varying vec3 v_normal; varying vec2 v_uv; +vec3 applyNormalMap(vec3 geomnor, vec3 normap) { + normap = normap * 2.0 - 1.0; + vec3 up = normalize(vec3(0.001, 1, 0.001)); + vec3 surftan = normalize(cross(geomnor, up)); + vec3 surfbinor = cross(geomnor, surftan); + return normap.y * surftan + normap.x * surfbinor + normap.z * geomnor; +} + + + +float DecodeFloatRGBA( vec4 rgba ) { + return dot( rgba, vec4(1.0, 1.0/255.0, 1.0/65025.0, 1.0/160581375.0) ); +} + + + void main() { // TODO: copy values into gl_FragData[0], [1], etc. + + + vec3 nor = normalize(applyNormalMap (v_normal, texture2D(u_normap,v_uv).rgb)); + vec4 col = texture2D(u_colmap, v_uv); + + + //gl_FragData[0] = vec4( v_position, DecodeFloatRGBA(col)); + //gl_FragData[1] = vec4( nor.xy, 1.0, 1.0); + + gl_FragData[0] = vec4( v_position, col.b); + gl_FragData[1] = vec4( nor.xy, col.rg); + + + /* + // naive 4 gbuffers + gl_FragData[0] = vec4( v_position,1.0 ); + gl_FragData[1] = vec4( v_normal.xyz,1.0); + gl_FragData[2] = texture2D(u_colmap, v_uv); + gl_FragData[3] = texture2D(u_normap,v_uv); + */ } diff --git a/glsl/deferred/ambient.frag.glsl b/glsl/deferred/ambient.frag.glsl index 1fd4647..fc1df48 100644 --- a/glsl/deferred/ambient.frag.glsl +++ b/glsl/deferred/ambient.frag.glsl @@ -3,25 +3,37 @@ precision highp float; precision highp int; -#define NUM_GBUFFERS 4 +#define NUM_GBUFFERS 2 uniform sampler2D u_gbufs[NUM_GBUFFERS]; uniform sampler2D u_depth; varying vec2 v_uv; + +vec4 EncodeFloatRGBA( float v ) { + vec4 enc = vec4(1.0, 255.0, 65025.0, 160581375.0) * v; + enc = fract(enc); + enc -= enc.yzww * vec4(1.0/255.0,1.0/255.0,1.0/255.0,0.0); + return enc; + +} + + void main() { vec4 gb0 = texture2D(u_gbufs[0], v_uv); vec4 gb1 = texture2D(u_gbufs[1], v_uv); - vec4 gb2 = texture2D(u_gbufs[2], v_uv); - vec4 gb3 = texture2D(u_gbufs[3], v_uv); + float depth = texture2D(u_depth, v_uv).x; // TODO: Extract needed properties from the g-buffers into local variables + //vec3 colmap = EncodeFloatRGBA(gb0.w).rgb; + vec3 colmap = vec3(gb1.z,gb1.w,gb0.w); + if (depth == 1.0) { gl_FragColor = vec4(0, 0, 0, 0); // set alpha to 0 return; } - gl_FragColor = vec4(0.1, 0.1, 0.1, 1); // TODO: replace this + gl_FragColor = vec4(0.2*colmap, 1.0); // TODO: replace this } diff --git a/glsl/deferred/blinnphong-pointlight.frag.glsl b/glsl/deferred/blinnphong-pointlight.frag.glsl index b24a54a..81f2667 100644 --- a/glsl/deferred/blinnphong-pointlight.frag.glsl +++ b/glsl/deferred/blinnphong-pointlight.frag.glsl @@ -2,7 +2,14 @@ precision highp float; precision highp int; -#define NUM_GBUFFERS 4 +#define NUM_GBUFFERS 2 + +#define TOON_STEP 0.2 +#define TOON_DEPTH_THRESHOLD 1.0 + +uniform bool u_toonShading; + +uniform vec3 u_cameraPos; uniform vec3 u_lightCol; uniform vec3 u_lightPos; @@ -12,6 +19,7 @@ uniform sampler2D u_depth; varying vec2 v_uv; +/* vec3 applyNormalMap(vec3 geomnor, vec3 normap) { normap = normap * 2.0 - 1.0; vec3 up = normalize(vec3(0.001, 1, 0.001)); @@ -19,21 +27,82 @@ vec3 applyNormalMap(vec3 geomnor, vec3 normap) { vec3 surfbinor = cross(geomnor, surftan); return normap.y * surftan + normap.x * surfbinor + normap.z * geomnor; } +*/ + +vec4 EncodeFloatRGBA( float v ) { + vec4 enc = vec4(1.0, 255.0, 65025.0, 160581375.0) * v; + enc = fract(enc); + enc -= enc.yzww * vec4(1.0/255.0,1.0/255.0,1.0/255.0,0.0); + return enc; + +} + void main() { + + vec2 uv = vec2(gl_FragCoord.x / 800.0, gl_FragCoord.y / 600.0); + + vec4 gb0 = texture2D(u_gbufs[0], uv); + vec4 gb1 = texture2D(u_gbufs[1], uv); + + float depth = texture2D(u_depth, uv).x; + + + +/* vec4 gb0 = texture2D(u_gbufs[0], v_uv); vec4 gb1 = texture2D(u_gbufs[1], v_uv); - vec4 gb2 = texture2D(u_gbufs[2], v_uv); - vec4 gb3 = texture2D(u_gbufs[3], v_uv); + float depth = texture2D(u_depth, v_uv).x; + */ // TODO: Extract needed properties from the g-buffers into local variables - + + //TODO:optimize gbuffer structure + vec3 pos = gb0.xyz; + vec3 geomnor = gb1.xyz; + //vec3 colmap = EncodeFloatRGBA(gb0.w).rgb; + vec3 colmap = vec3(gb1.z,gb1.w,gb0.w); + + vec3 nor = gb1.xyy; + nor.z = sqrt(1.0 - nor.x*nor.x - nor.y*nor.y); + // If nothing was rendered to this pixel, set alpha to 0 so that the // postprocessing step can render the sky color. if (depth == 1.0) { gl_FragColor = vec4(0, 0, 0, 0); return; } - - gl_FragColor = vec4(0, 0, 1, 1); // TODO: perform lighting calculations + + + + vec3 l = u_lightPos - pos; + + float dist = length(l); + + l = l / dist; + + float attenuation = clamp(1.0 - dist/u_lightRad, 0.0, 1.0); + + float diffuse_cos = max(dot(l,nor),0.0); + if(u_toonShading) + { + diffuse_cos = TOON_STEP * float(floor(diffuse_cos/TOON_STEP)); + } + + + vec3 diffuse = diffuse_cos * u_lightCol * colmap; + + vec3 v = normalize(u_cameraPos - pos); + vec3 r = -l + 2.0 * dot(l,nor) * nor; + float specular_cos = max(dot(r,v),0.0); + if(u_toonShading) + { + specular_cos = TOON_STEP * float(floor(specular_cos/TOON_STEP)); + } + + vec3 specular = pow( specular_cos, 32.0) * u_lightCol * colmap; + + gl_FragColor = vec4 ( attenuation * (diffuse + specular) , 1.0); + + //gl_FragColor = vec4(v_uv,0.0,1.0); } diff --git a/glsl/deferred/bloom.frag.glsl b/glsl/deferred/bloom.frag.glsl new file mode 100644 index 0000000..9dd31c4 --- /dev/null +++ b/glsl/deferred/bloom.frag.glsl @@ -0,0 +1,56 @@ +#version 100 +precision highp float; +precision highp int; + +#define BLOOM_THRESHOLD 0.8 + +#define GAUSSIAN_R 3 + +uniform float u_width; +uniform float u_height; + +uniform int u_axis; + +uniform sampler2D u_color; + +varying vec2 v_uv; + + + + +//float weight[3] = float[3]( 0.33333333, 0.33333333, 0.33333333 ); + +void main() { + + vec2 offset = vec2( u_axis==0 ? 1.0/u_width : 0.0 + , u_axis==1 ? 1.0/u_height : 0.0); + vec4 color = texture2D(u_color, v_uv).rgba; + + if(color.a == 0.0) + { + gl_FragColor = color; + return; + } + + vec3 bloom = vec3(0.0); + + + + for(int i = -10 ; i <= 10; i++) + { + + vec3 cur_color = texture2D(u_color, v_uv + float(i) * offset ).rgb; + + //bloom += weight[i+1] * ( cur_color - vec3(BLOOM_THRESHOLD) ); + bloom += 0.2 * ( max(cur_color - vec3(BLOOM_THRESHOLD),0.0) ); + } + + + + + gl_FragColor = vec4(bloom,1.0); + + //gl_FragColor = vec4(1.0); + + +} diff --git a/glsl/deferred/contour.frag.glsl b/glsl/deferred/contour.frag.glsl new file mode 100644 index 0000000..e1bb785 --- /dev/null +++ b/glsl/deferred/contour.frag.glsl @@ -0,0 +1,66 @@ +#version 100 +precision highp float; +precision highp int; + + + +#define TOON_DEPTH_THRESHOLD 0.02 + +uniform float u_width; +uniform float u_height; + + +uniform sampler2D u_depth; + +varying vec2 v_uv; + + +float unpack_depth(const in vec4 rgba_depth){ +/* + const vec4 bit_shift = + vec4(1.0/(256.0*256.0*256.0) + , 1.0/(256.0*256.0) + , 1.0/256.0 + , 1.0); + float depth = dot(rgba_depth, bit_shift); + return depth; + */ + return rgba_depth.x; +} + +void main() { + float depth = texture2D(u_depth, v_uv).x; + + if (depth == 1.0) { + gl_FragColor = vec4(0, 0, 0, 0); // set alpha to 0 + return; + } + + + + + vec2 x_offset = vec2(1.0/u_width, 0.0); + vec2 y_offset = vec2(0.0, 1.0/u_height); + + //float laplacian = depth; + + + float laplacian = abs(texture2D(u_depth, v_uv + x_offset).x + + texture2D(u_depth, v_uv - x_offset).x + + texture2D(u_depth, v_uv + y_offset).x + + texture2D(u_depth, v_uv - y_offset).x + - 4.0 * depth); + + + if(laplacian > TOON_DEPTH_THRESHOLD) + { + //contour + //use black + gl_FragColor = vec4(0, 0, 0, 1); + return; + } + + + gl_FragColor = vec4(0,0,0,0); + +} diff --git a/glsl/deferred/debug.frag.glsl b/glsl/deferred/debug.frag.glsl index 9cbfae4..08ea8d0 100644 --- a/glsl/deferred/debug.frag.glsl +++ b/glsl/deferred/debug.frag.glsl @@ -2,7 +2,7 @@ precision highp float; precision highp int; -#define NUM_GBUFFERS 4 +#define NUM_GBUFFERS 2 uniform int u_debug; uniform sampler2D u_gbufs[NUM_GBUFFERS]; @@ -20,19 +20,31 @@ vec3 applyNormalMap(vec3 geomnor, vec3 normap) { return normap.y * surftan + normap.x * surfbinor + normap.z * geomnor; } +vec4 EncodeFloatRGBA( float v ) { + vec4 enc = vec4(1.0, 255.0, 65025.0, 160581375.0) * v; + enc = fract(enc); + enc -= enc.yzww * vec4(1.0/255.0,1.0/255.0,1.0/255.0,0.0); + return enc; +} + + void main() { vec4 gb0 = texture2D(u_gbufs[0], v_uv); vec4 gb1 = texture2D(u_gbufs[1], v_uv); - vec4 gb2 = texture2D(u_gbufs[2], v_uv); - vec4 gb3 = texture2D(u_gbufs[3], v_uv); float depth = texture2D(u_depth, v_uv).x; + // TODO: Extract needed properties from the g-buffers into local variables // These definitions are suggested for starting out, but you will probably want to change them. - vec3 pos; // World-space position - vec3 geomnor; // Normals of the geometry as defined, without normal mapping - vec3 colmap; // The color map - unlit "albedo" (surface color) - vec3 normap; // The raw normal map (normals relative to the surface they're on) - vec3 nor; // The true normals as we want to light them - with the normal map applied to the geometry normals (applyNormalMap above) + vec3 pos = gb0.xyz; // World-space position + + //TODO:optimize gbuffer structure + vec3 geomnor = gb1.xyy; // Normals of the geometry as defined, without normal mapping + //vec3 colmap = EncodeFloatRGBA(gb0.w).rgb; + vec3 colmap = vec3(gb1.z,gb1.w,gb0.w); + //vec3 normap = gb3.xyz; // The raw normal map (normals relative to the surface they're on) + + vec3 nor = gb1.xyy; + nor.z = sqrt(1.0 - nor.x*nor.x - nor.y*nor.y); if (u_debug == 0) { gl_FragColor = vec4(vec3(depth), 1.0); @@ -43,7 +55,7 @@ void main() { } else if (u_debug == 3) { gl_FragColor = vec4(colmap, 1.0); } else if (u_debug == 4) { - gl_FragColor = vec4(normap, 1.0); + //gl_FragColor = vec4(normap, 1.0); } else if (u_debug == 5) { gl_FragColor = vec4(abs(nor), 1.0); } else { diff --git a/glsl/post/one.frag.glsl b/glsl/post/one.frag.glsl index 94191cd..ffc69c3 100644 --- a/glsl/post/one.frag.glsl +++ b/glsl/post/one.frag.glsl @@ -4,6 +4,8 @@ precision highp int; uniform sampler2D u_color; +uniform sampler2D u_glow; + varying vec2 v_uv; const vec4 SKY_COLOR = vec4(0.01, 0.14, 0.42, 1.0); @@ -16,5 +18,9 @@ void main() { return; } + vec4 glow = texture2D(u_glow, v_uv); + gl_FragColor = color; + //gl_FragColor = color + glow; + //gl_FragColor = glow; } diff --git a/glsl/red.frag.glsl b/glsl/red.frag.glsl index f8ef1ec..e41993b 100644 --- a/glsl/red.frag.glsl +++ b/glsl/red.frag.glsl @@ -3,5 +3,5 @@ precision highp float; precision highp int; void main() { - gl_FragColor = vec4(1, 0, 0, 1); + gl_FragColor = vec4(1, 0, 0, 0.1); } diff --git a/glsl/sphere.vert.glsl b/glsl/sphere.vert.glsl new file mode 100644 index 0000000..ed6027f --- /dev/null +++ b/glsl/sphere.vert.glsl @@ -0,0 +1,24 @@ +#version 100 +precision highp float; +precision highp int; + +uniform mat4 u_cameraMat; +uniform mat4 u_transformMat; + +attribute vec3 a_position; + + +varying vec2 v_uv; + +void main() { + + vec4 tmp = u_cameraMat * u_transformMat * vec4(a_position, 1.0); + gl_Position = tmp; + + + + //v_uv = a_position.xy * 0.5 + 0.5; + + v_uv = tmp.xy * 0.5 + 0.5; + +} diff --git a/img/basic.png b/img/basic.png new file mode 100644 index 0000000..a610791 Binary files /dev/null and b/img/basic.png differ diff --git a/img/bloom.png b/img/bloom.png new file mode 100644 index 0000000..5cd4276 Binary files /dev/null and b/img/bloom.png differ diff --git a/img/colormap.png b/img/colormap.png new file mode 100644 index 0000000..23e29e8 Binary files /dev/null and b/img/colormap.png differ diff --git a/img/depth.png b/img/depth.png new file mode 100644 index 0000000..ec55ced Binary files /dev/null and b/img/depth.png differ diff --git a/img/gbuffer.png b/img/gbuffer.png new file mode 100644 index 0000000..2b0b886 Binary files /dev/null and b/img/gbuffer.png differ diff --git a/img/geonor.png b/img/geonor.png new file mode 100644 index 0000000..ea9c1dc Binary files /dev/null and b/img/geonor.png differ diff --git a/img/nor.png b/img/nor.png new file mode 100644 index 0000000..cdf6dad Binary files /dev/null and b/img/nor.png differ diff --git a/img/normap.png b/img/normap.png new file mode 100644 index 0000000..aff720b Binary files /dev/null and b/img/normap.png differ diff --git a/img/numlights.png b/img/numlights.png new file mode 100644 index 0000000..3c4e227 Binary files /dev/null and b/img/numlights.png differ diff --git a/img/position.png b/img/position.png new file mode 100644 index 0000000..76ef761 Binary files /dev/null and b/img/position.png differ diff --git a/img/scissor.png b/img/scissor.png new file mode 100644 index 0000000..4a177fa Binary files /dev/null and b/img/scissor.png differ diff --git a/img/scissor_performance.png b/img/scissor_performance.png new file mode 100644 index 0000000..f50fb29 Binary files /dev/null and b/img/scissor_performance.png differ diff --git a/img/scissordebug.png b/img/scissordebug.png new file mode 100644 index 0000000..f764a8a Binary files /dev/null and b/img/scissordebug.png differ diff --git a/img/spheredebug.png b/img/spheredebug.png new file mode 100644 index 0000000..a31c690 Binary files /dev/null and b/img/spheredebug.png differ diff --git a/img/thumb.png b/img/thumb.png index 9ec8ed0..aed4cfa 100644 Binary files a/img/thumb.png and b/img/thumb.png differ diff --git a/img/toon.png b/img/toon.png new file mode 100644 index 0000000..aed4cfa Binary files /dev/null and b/img/toon.png differ diff --git a/img/video.png b/img/video.png index 9ec8ed0..72d76c0 100644 Binary files a/img/video.png and b/img/video.png differ diff --git a/js/deferredRender.js b/js/deferredRender.js index b1f238b..6cdc76b 100644 --- a/js/deferredRender.js +++ b/js/deferredRender.js @@ -10,7 +10,14 @@ !R.prog_Ambient || !R.prog_BlinnPhong_PointLight || !R.prog_Debug || - !R.progPost1)) { + !R.progPost1 || + + !R.prog_Contour || + !R.prog_Bloom || + + !R.prog_BlinnPhong_PointLight_SphereProxy || + !R.progRedSphere + )) { console.log('waiting for programs to load...'); return; } @@ -28,12 +35,7 @@ // CHECKITOUT: START HERE! You can even uncomment this: //debugger; - { // TODO: this block should be removed after testing renderFullScreenQuad - gl.bindFramebuffer(gl.FRAMEBUFFER, null); - // TODO: Implement/test renderFullScreenQuad first - renderFullScreenQuad(R.progRed); - return; - } + R.pass_copy.render(state); @@ -44,8 +46,8 @@ } else { // * Deferred pass and postprocessing pass(es) // TODO: uncomment these - //R.pass_deferred.render(state); - //R.pass_post1.render(state); + R.pass_deferred.render(state); + R.pass_post1.render(state); // OPTIONAL TODO: call more postprocessing passes, if any } @@ -57,21 +59,26 @@ R.pass_copy.render = function(state) { // * Bind the framebuffer R.pass_copy.fbo // TODO: ^ + gl.bindFramebuffer(gl.FRAMEBUFFER,R.pass_copy.fbo); // * Clear screen using R.progClear - TODO: renderFullScreenQuad(R.progClear); + renderFullScreenQuad(R.progClear); // * Clear depth buffer to value 1.0 using gl.clearDepth and gl.clear // TODO: ^ // TODO: ^ + gl.clearDepth(1.0); + gl.clear(gl.DEPTH_BUFFER_BIT); // * "Use" the program R.progCopy.prog // TODO: ^ // TODO: Write glsl/copy.frag.glsl + gl.useProgram(R.progCopy.prog); var m = state.cameraMat.elements; // * Upload the camera matrix m to the uniform R.progCopy.u_cameraMat // using gl.uniformMatrix4fv // TODO: ^ + gl.uniformMatrix4fv(R.progCopy.u_cameraMat,false,m); // * Draw the scene drawScene(state); @@ -108,28 +115,163 @@ R.pass_deferred.render = function(state) { // * Bind R.pass_deferred.fbo to write into for later postprocessing gl.bindFramebuffer(gl.FRAMEBUFFER, R.pass_deferred.fbo); + //gl.bindFramebuffer(gl.FRAMEBUFFER, null); // * Clear depth to 1.0 and color to black gl.clearColor(0.0, 0.0, 0.0, 0.0); gl.clearDepth(1.0); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); + // * _ADD_ together the result of each lighting pass // Enable blending and use gl.blendFunc to blend with: // color = 1 * src_color + 1 * dst_color // TODO: ^ + gl.enable(gl.BLEND); + gl.blendEquation( gl.FUNC_ADD ); + gl.blendFunc(gl.ONE,gl.ONE); // * Bind/setup the ambient pass, and render using fullscreen quad bindTexturesForLightPass(R.prog_Ambient); renderFullScreenQuad(R.prog_Ambient); + + + // * Bind/setup the Blinn-Phong pass, and render using fullscreen quad - bindTexturesForLightPass(R.prog_BlinnPhong_PointLight); + var phongProg = R.prog_BlinnPhong_PointLight; + if(cfg.proxy == 2) + { + phongProg = R.prog_BlinnPhong_PointLight_SphereProxy; + } + bindTexturesForLightPass(phongProg); // TODO: add a loop here, over the values in R.lights, which sets the // uniforms R.prog_BlinnPhong_PointLight.u_lightPos/Col/Rad etc., // then does renderFullScreenQuad(R.prog_BlinnPhong_PointLight). + + if(cfg.proxy==1) + { + gl.enable(gl.SCISSOR_TEST); + } + else if(cfg.proxy == 2) + { + + var m = R.sphereModel; + var prog; + if(cfg.debugScissor) + { + prog = R.progRedSphere; + } + else + { + prog = phongProg; + } + + + gl.useProgram(prog.prog); + gl.enableVertexAttribArray(prog.a_position); + gl.bindBuffer(gl.ARRAY_BUFFER, m.position); + gl.vertexAttribPointer(prog.a_position, 3, gl.FLOAT, false, 0, 0); + + + //readyModelForDraw(prog, R.sphereModel); + } + + + if(!cfg.debugScissor) + { + gl.uniform1f(phongProg.u_toonShading ,cfg.enableToon ); + gl.uniform3f( phongProg.u_cameraPos,state.cameraPos.x,state.cameraPos.y,state.cameraPos.z ); + } + + + for(var i = 0; i < R.NUM_LIGHTS ; i++) + { + var light = R.lights[i]; + + + if(cfg.proxy == 1) + { + //Scissor + var sc = getScissorForLight(state.viewMat, state.projMat, light); + if(sc != null) + { + gl.scissor(sc[0],sc[1],sc[2],sc[3]); + if (cfg.debugScissor) + { + //? + gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); + renderFullScreenQuad(R.progRed); + } + else + { + + gl.uniform3fv( phongProg.u_lightCol, light.col ); + gl.uniform3fv( phongProg.u_lightPos, light.pos ); + gl.uniform1f( phongProg.u_lightRad, light.rad ); + renderFullScreenQuad(phongProg); + } + } + } + else if(cfg.proxy == 2) + { + //sphere proxy + + //debugger; + var S = new THREE.Matrix4(); + S.makeScale(light.rad,light.rad,light.rad); + var T = new THREE.Matrix4(); + T.makeTranslation(light.pos[0],light.pos[1],light.pos[2]); + var M = new THREE.Matrix4(); + M.multiplyMatrices(T,S); + //M.multiplyMatrices(S,T); + + + + if (cfg.debugScissor) + { + gl.uniformMatrix4fv(R.progRedSphere.u_cameraMat,false,state.cameraMat.elements); + gl.uniformMatrix4fv(R.progRedSphere.u_transformMat,false,M.elements); + gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); + drawReadyModel(R.sphereModel); + } + else + { + gl.uniformMatrix4fv(phongProg.u_cameraMat,false,state.cameraMat.elements); + gl.uniformMatrix4fv(phongProg.u_transformMat,false,M.elements); + + gl.uniform3fv( phongProg.u_lightCol, light.col ); + gl.uniform3fv( phongProg.u_lightPos, light.pos ); + gl.uniform1f( phongProg.u_lightRad, light.rad ); + + //readyModelForDraw(R.prog_BlinnPhong_PointLight_SphereProxy, R.sphereModel); + drawReadyModel(R.sphereModel); + //renderFullScreenQuad(R.prog_BlinnPhong_PointLight_SphereProxy); + } + + + } + else + { + //naive + + gl.uniform3fv( R.prog_BlinnPhong_PointLight.u_lightCol, light.col ); + gl.uniform3fv( R.prog_BlinnPhong_PointLight.u_lightPos, light.pos ); + gl.uniform1f( R.prog_BlinnPhong_PointLight.u_lightRad, light.rad ); + renderFullScreenQuad(R.prog_BlinnPhong_PointLight); + } + + + + + } + + if(cfg.proxy==1) + { + gl.disable(gl.SCISSOR_TEST); + } // TODO: In the lighting loop, use the scissor test optimization // Enable gl.SCISSOR_TEST, render all lights, then disable it. @@ -140,6 +282,63 @@ // var sc = getScissorForLight(state.viewMat, state.projMat, light); // Disable blending so that it doesn't affect other code + + + //bloom + if(cfg.enableBloom) + { + gl_draw_buffers.drawBuffersWEBGL([gl_draw_buffers.COLOR_ATTACHMENT0_WEBGL]); + gl.bindFramebuffer(gl.FRAMEBUFFER, R.pass_deferred.glowbuffer); + + gl.clearColor(0.0, 0.0, 0.0, 0.0); + //gl.clearDepth(1.0); + //gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); + gl.clear(gl.COLOR_BUFFER_BIT); + + gl.blendFunc(gl.ONE,gl.ONE); + var prog = R.prog_Bloom; + + gl.useProgram(prog.prog); + gl.activeTexture(gl['TEXTURE0']); + gl.bindTexture(gl.TEXTURE_2D, R.pass_deferred.colorTex); + gl.uniform1f(prog.u_width, width); + gl.uniform1f(prog.u_height,height); + gl.uniform1i(prog.u_color, 0); + + //x + gl.uniform1i(prog.u_axis, 0); + + renderFullScreenQuad(prog); + + //y + gl_draw_buffers.drawBuffersWEBGL([gl_draw_buffers.COLOR_ATTACHMENT0_WEBGL]); + gl.bindFramebuffer(gl.FRAMEBUFFER, R.pass_deferred.fbo); + gl.activeTexture(gl['TEXTURE0']); + gl.bindTexture(gl.TEXTURE_2D, R.pass_deferred.glowTex); + + gl.uniform1i(prog.u_axis, 1); + + renderFullScreenQuad(prog); + } + + + + + //Contour shader (part of toon shading) + //gl.bindFramebuffer(gl.FRAMEBUFFER, R.pass_deferred.fbo); + if( cfg.enableToon ) + { + gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); + var prog = R.prog_Contour; + gl.useProgram(prog.prog); + gl.activeTexture(gl['TEXTURE0']); + gl.bindTexture(gl.TEXTURE_2D, R.pass_copy.depthTex); + gl.uniform1i(prog.u_depth, 0); + gl.uniform1f(prog.u_width, width); + gl.uniform1f(prog.u_height,height); + renderFullScreenQuad(R.prog_Contour); + } + gl.disable(gl.BLEND); }; @@ -156,6 +355,8 @@ gl.activeTexture(gl['TEXTURE' + R.NUM_GBUFFERS]); gl.bindTexture(gl.TEXTURE_2D, R.pass_copy.depthTex); gl.uniform1i(prog.u_depth, R.NUM_GBUFFERS); + + }; /** @@ -175,13 +376,27 @@ // * Bind the deferred pass's color output as a texture input // Set gl.TEXTURE0 as the gl.activeTexture unit // TODO: ^ + gl.activeTexture(gl.TEXTURE0); + // Bind the TEXTURE_2D, R.pass_deferred.colorTex to the active texture unit // TODO: ^ + gl.bindTexture(gl.TEXTURE_2D, R.pass_deferred.colorTex); + // Configure the R.progPost1.u_color uniform to point at texture unit 0 gl.uniform1i(R.progPost1.u_color, 0); + + //if(cfg.enableBloom) + //{ + gl.activeTexture(gl.TEXTURE1); + gl.bindTexture(gl.TEXTURE_2D, R.pass_deferred.glowTex); + gl.uniform1i(R.progPost1.u_glow,1); + // } + + // * Render a fullscreen quad to perform shading on renderFullScreenQuad(R.progPost1); + }; var renderFullScreenQuad = (function() { @@ -205,12 +420,82 @@ var init = function() { // Create a new buffer with gl.createBuffer, and save it as vbo. // TODO: ^ + vbo = gl.createBuffer(); + + // Bind the VBO as the gl.ARRAY_BUFFER + // TODO: ^ + gl.bindBuffer(gl.ARRAY_BUFFER,vbo); + + // Upload the positions array to the currently-bound array buffer + // using gl.bufferData in static draw mode. + // TODO: ^ + gl.bufferData(gl.ARRAY_BUFFER,positions,gl.STATIC_DRAW); + }; + + return function(prog) { + if (!vbo) { + // If the vbo hasn't been initialized, initialize it. + init(); + } + + // Bind the program to use to draw the quad + gl.useProgram(prog.prog); + + // Bind the VBO as the gl.ARRAY_BUFFER + // TODO: ^ + gl.bindBuffer(gl.ARRAY_BUFFER,vbo); + + // Enable the bound buffer as the vertex attrib array for + // prog.a_position, using gl.enableVertexAttribArray + // TODO: ^ + gl.enableVertexAttribArray(prog.a_position); + + // Use gl.vertexAttribPointer to tell WebGL the type/layout for + // prog.a_position's access pattern. + // TODO: ^ + gl.vertexAttribPointer(prog.a_position, 3, gl.FLOAT, gl.FALSE, 0, 0); + + // Use gl.drawArrays (or gl.drawElements) to draw your quad. + // TODO: ^ + gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); + + // Unbind the array buffer. + gl.bindBuffer(gl.ARRAY_BUFFER, null); + }; + })(); + + + var renderSphere = (function() { + // The variables in this function are private to the implementation of + // renderFullScreenQuad. They work like static local variables in C++. + + // Create an array of floats, where each set of 3 is a vertex position. + // You can render in normalized device coordinates (NDC) so that the + // vertex shader doesn't have to do any transformation; draw two + // triangles which cover the screen over x = -1..1 and y = -1..1. + // This array is set up to use gl.drawArrays with gl.TRIANGLE_STRIP. + var positions = new Float32Array([ + -1.0, -1.0, 0.0, + 1.0, -1.0, 0.0, + -1.0, 1.0, 0.0, + 1.0, 1.0, 0.0 + ]); + + var vbo = null; + + var init = function() { + // Create a new buffer with gl.createBuffer, and save it as vbo. + // TODO: ^ + vbo = gl.createBuffer(); // Bind the VBO as the gl.ARRAY_BUFFER // TODO: ^ + gl.bindBuffer(gl.ARRAY_BUFFER,vbo); + // Upload the positions array to the currently-bound array buffer // using gl.bufferData in static draw mode. // TODO: ^ + gl.bufferData(gl.ARRAY_BUFFER,positions,gl.STATIC_DRAW); }; return function(prog) { @@ -224,18 +509,28 @@ // Bind the VBO as the gl.ARRAY_BUFFER // TODO: ^ + gl.bindBuffer(gl.ARRAY_BUFFER,vbo); + // Enable the bound buffer as the vertex attrib array for // prog.a_position, using gl.enableVertexAttribArray // TODO: ^ + gl.enableVertexAttribArray(prog.a_position); + // Use gl.vertexAttribPointer to tell WebGL the type/layout for // prog.a_position's access pattern. // TODO: ^ + gl.vertexAttribPointer(prog.a_position, 3, gl.FLOAT, gl.FALSE, 0, 0); // Use gl.drawArrays (or gl.drawElements) to draw your quad. // TODO: ^ + gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); // Unbind the array buffer. gl.bindBuffer(gl.ARRAY_BUFFER, null); }; })(); + + + + })(); diff --git a/js/deferredSetup.js b/js/deferredSetup.js index 65136e0..ad8483f 100644 --- a/js/deferredSetup.js +++ b/js/deferredSetup.js @@ -8,7 +8,8 @@ R.pass_post1 = {}; R.lights = []; - R.NUM_GBUFFERS = 4; + //R.NUM_GBUFFERS = 4; + R.NUM_GBUFFERS = 2; /** * Set up the deferred pipeline framebuffer objects and textures. @@ -94,8 +95,25 @@ // * Tell the WEBGL_draw_buffers extension which FBO attachments are // being used. (This extension allows for multiple render targets.) gl_draw_buffers.drawBuffersWEBGL([gl_draw_buffers.COLOR_ATTACHMENT0_WEBGL]); - gl.bindFramebuffer(gl.FRAMEBUFFER, null); + + + //bloom buffer + if(true) + { + R.pass_deferred.glowbuffer = gl.createFramebuffer(); + // * Create, bind, and store a single color target texture for the FBO + R.pass_deferred.glowTex = createAndBindColorTargetTexture( + R.pass_deferred.glowbuffer, gl_draw_buffers.COLOR_ATTACHMENT0_WEBGL); + + // * Check for framebuffer errors + abortIfFramebufferIncomplete(R.pass_deferred.glowbuffer); + + gl.clearColor(0.0, 0.0, 0.0, 0.0); + gl.clearDepth(1.0); + gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); + } + }; /** @@ -124,6 +142,18 @@ // Create an object to hold info about this shader program R.progRed = { prog: prog }; }); + + + loadShaderProgram(gl, 'glsl/sphere.vert.glsl', 'glsl/red.frag.glsl', + function(prog) { + // Create an object to hold info about this shader program + R.progRedSphere = { prog: prog }; + R.progRedSphere.a_position = gl.getAttribLocation(prog, 'a_position'); + + + R.progRedSphere.u_cameraMat = gl.getUniformLocation(prog, 'u_cameraMat'); + R.progRedSphere.u_transformMat = gl.getUniformLocation(prog, 'u_transformMat'); + }); loadShaderProgram(gl, 'glsl/quad.vert.glsl', 'glsl/clear.frag.glsl', function(prog) { @@ -141,6 +171,9 @@ p.u_lightPos = gl.getUniformLocation(p.prog, 'u_lightPos'); p.u_lightCol = gl.getUniformLocation(p.prog, 'u_lightCol'); p.u_lightRad = gl.getUniformLocation(p.prog, 'u_lightRad'); + p.u_cameraPos = gl.getUniformLocation(p.prog, 'u_cameraPos'); + p.u_toonShading = gl.getUniformLocation(p.prog, 'u_toonShading'); + R.prog_BlinnPhong_PointLight = p; }); @@ -152,13 +185,79 @@ loadPostProgram('one', function(p) { p.u_color = gl.getUniformLocation(p.prog, 'u_color'); + p.u_glow = gl.getUniformLocation(p.prog, 'u_glow'); // Save the object into this variable for access later R.progPost1 = p; }); // TODO: If you add more passes, load and set up their shader programs. + loadDeferredProgram('contour',function(p){ + // Save the object into this variable for access later + p.u_width = gl.getUniformLocation(p.prog, 'u_width'); + p.u_height = gl.getUniformLocation(p.prog, 'u_height'); + + R.prog_Contour = p; + }); + + + loadDeferredProgram('bloom',function(p){ + // Save the object into this variable for access later + p.u_width = gl.getUniformLocation(p.prog, 'u_width'); + p.u_height = gl.getUniformLocation(p.prog, 'u_height'); + p.u_axis = gl.getUniformLocation(p.prog, 'u_axis'); + p.u_color = gl.getUniformLocation(p.prog, 'u_color'); + R.prog_Bloom = p; + }); + + + + loadDeferredProgramSphereProxy('blinnphong-pointlight', function(p) { + // Save the object into this variable for access later + p.u_lightPos = gl.getUniformLocation(p.prog, 'u_lightPos'); + p.u_lightCol = gl.getUniformLocation(p.prog, 'u_lightCol'); + p.u_lightRad = gl.getUniformLocation(p.prog, 'u_lightRad'); + p.u_cameraPos = gl.getUniformLocation(p.prog, 'u_cameraPos'); + p.u_toonShading = gl.getUniformLocation(p.prog, 'u_toonShading'); + + R.prog_BlinnPhong_PointLight_SphereProxy = p; + }); + + /* + loadPostProgram('bloom',function(p){ + // Save the object into this variable for access later + p.u_width = gl.getUniformLocation(p.prog, 'u_width'); + p.u_height = gl.getUniformLocation(p.prog, 'u_height'); + p.u_axis = gl.getUniformLocation(p.prog, 'u_axis'); + R.prog_Bloom = p; + }); + */ + }; + + var loadDeferredProgramSphereProxy = function(name, callback) { + loadShaderProgram(gl, 'glsl/sphere.vert.glsl', + 'glsl/deferred/' + name + '.frag.glsl', + function(prog) { + // Create an object to hold info about this shader program + var p = { prog: prog }; + + // Retrieve the uniform and attribute locations + p.u_gbufs = []; + for (var i = 0; i < R.NUM_GBUFFERS; i++) { + p.u_gbufs[i] = gl.getUniformLocation(prog, 'u_gbufs[' + i + ']'); + } + p.u_depth = gl.getUniformLocation(prog, 'u_depth'); + p.a_position = gl.getAttribLocation(prog, 'a_position'); + + + p.u_cameraMat = gl.getUniformLocation(prog, 'u_cameraMat'); + p.u_transformMat = gl.getUniformLocation(prog, 'u_transformMat'); + + + callback(p); + }); }; + var loadDeferredProgram = function(name, callback) { loadShaderProgram(gl, 'glsl/quad.vert.glsl', 'glsl/deferred/' + name + '.frag.glsl', diff --git a/js/framework.js b/js/framework.js index 7c008df..c6a360b 100644 --- a/js/framework.js +++ b/js/framework.js @@ -67,7 +67,8 @@ var width, height; var init = function() { // TODO: For performance measurements, disable debug mode! - var debugMode = true; + //var debugMode = true; + var debugMode = false; canvas = document.getElementById('canvas'); renderer = new THREE.WebGLRenderer({ diff --git a/js/main.js b/js/main.js index bf01b17..0d89428 100644 --- a/js/main.js +++ b/js/main.js @@ -2,7 +2,7 @@ var handle_load = []; (function() { 'use strict'; - + //debugger; window.onload = function() { for (var i = 0; i < handle_load.length; i++) { handle_load[i](); diff --git a/js/ui.js b/js/ui.js index 05c1852..63bf44c 100644 --- a/js/ui.js +++ b/js/ui.js @@ -7,7 +7,11 @@ var cfg; // TODO: Define config fields and defaults here this.debugView = -1; this.debugScissor = false; - this.enableEffect0 = false; + this.enableToon = false; + + this.enableBloom = false; + + this.proxy = 1; }; var init = function() { @@ -26,9 +30,20 @@ var cfg; }); gui.add(cfg, 'debugScissor'); - var eff0 = gui.addFolder('EFFECT NAME HERE'); - eff0.add(cfg, 'enableEffect0'); + gui.add(cfg, 'proxy', { + '0 None': 0, + '1 Scissor': 1, + '2 Sphere': 2, + }); + + var eff0 = gui.addFolder('Effects'); + eff0.add(cfg, 'enableToon'); + //eff0.add(cfg, 'enableToon'); // TODO: add more effects toggles and parameters here + eff0.add(cfg,'enableBloom'); + + + }; window.handle_load.push(init); diff --git a/js/util.js b/js/util.js index 3119dd8..6e1adfe 100644 --- a/js/util.js +++ b/js/util.js @@ -115,12 +115,12 @@ window.readyModelForDraw = function(prog, m) { gl.bindBuffer(gl.ARRAY_BUFFER, m.position); gl.vertexAttribPointer(prog.a_position, 3, gl.FLOAT, false, 0, 0); - if (prog.a_normal !== -1 && m.normal) { + if (prog.a_normal >= 0 && m.normal) { gl.enableVertexAttribArray(prog.a_normal); gl.bindBuffer(gl.ARRAY_BUFFER, m.normal); gl.vertexAttribPointer(prog.a_normal, 3, gl.FLOAT, false, 0, 0); } - if (prog.a_uv !== -1 && m.uv) { + if (prog.a_uv >= 0 && m.uv) { gl.enableVertexAttribArray(prog.a_uv); gl.bindBuffer(gl.ARRAY_BUFFER, m.uv); gl.vertexAttribPointer(prog.a_uv, 2, gl.FLOAT, false, 0, 0);