├── .gitignore ├── .travis.yml ├── COPYRIGHT ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md └── src ├── color.rs ├── geometry.rs ├── layers.rs ├── lib.rs ├── platform ├── android │ └── surface.rs ├── egl │ └── surface.rs ├── linux │ └── surface.rs ├── macos │ └── surface.rs ├── surface.rs └── windows │ └── surface.rs ├── rendergl.rs ├── scene.rs ├── texturegl.rs ├── tiling.rs └── util.rs /.gitignore: -------------------------------------------------------------------------------- 1 | /doc 2 | /target 3 | /Cargo.lock 4 | *~ 5 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | os: 3 | - osx 4 | - linux 5 | addons: 6 | apt: 7 | packages: 8 | - libxxf86vm-dev 9 | - libosmesa6-dev 10 | - libgles2-mesa-dev 11 | before_install: 12 | - if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then sudo add-apt-repository -y ppa:ubuntu-toolchain-r/test; fi 13 | - if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then sudo apt-get update; fi 14 | - if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then sudo apt-get install gcc-4.7 g++-4.7; fi 15 | - if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.7 20; fi 16 | - if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-4.7 20; fi 17 | 18 | rust: 19 | - nightly 20 | - beta 21 | 22 | script: 23 | - cargo test 24 | - cargo test --features heapsize 25 | 26 | notifications: 27 | webhooks: http://build.servo.org:54856/travis 28 | -------------------------------------------------------------------------------- /COPYRIGHT: -------------------------------------------------------------------------------- 1 | Licensed under the Apache License, Version 2.0 or the MIT license 3 | , at your 4 | option. All files in the project carrying such notice may not be 5 | copied, modified, or distributed except according to those terms. 6 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | 3 | name = "layers" 4 | version = "0.5.3" 5 | authors = ["The Servo Project Developers"] 6 | license = "MIT/Apache-2.0" 7 | 8 | [features] 9 | default = [] 10 | plugins = ["heapsize"] 11 | 12 | [dependencies] 13 | libc = "0.2" 14 | rustc-serialize = "0.3.16" 15 | log = "0.3.4" 16 | gleam = "0.2" 17 | euclid = "0.10" 18 | servo-skia = "0.20130412.23" 19 | 20 | [dependencies.heapsize] 21 | version = ">=0.2.2, <0.4" 22 | optional = true 23 | 24 | [target.x86_64-apple-darwin.dependencies] 25 | core-foundation = "0.2.0" 26 | cgl = "0.1" 27 | io-surface = "0.5.0" 28 | 29 | [target.'cfg(target_os = "linux")'.dependencies] 30 | glx = "0.1.0" 31 | servo-egl = "0.2" 32 | x11 = { version = "2.3.0", features = ["xlib"] } 33 | 34 | [target.arm-linux-androideabi.dependencies] 35 | servo-egl = "0.2" 36 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2012-2013 Mozilla Foundation 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # rust-layers 2 | 3 | [Documentation](http://doc.servo.org/layers/index.html) 4 | -------------------------------------------------------------------------------- /src/color.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Servo Project Developers. See the COPYRIGHT 2 | // file at the top-level directory of this distribution. 3 | // 4 | // Licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your 7 | // option. This file may not be copied, modified, or distributed 8 | // except according to those terms. 9 | 10 | #[derive(Copy, Clone, Debug)] 11 | pub struct Color { 12 | pub r: f32, 13 | pub g: f32, 14 | pub b: f32, 15 | pub a: f32, 16 | } 17 | 18 | #[cfg(feature = "heapsize")] 19 | known_heap_size!(0, Color); 20 | -------------------------------------------------------------------------------- /src/geometry.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The Servo Project Developers. See the COPYRIGHT 2 | // file at the top-level directory of this distribution. 3 | // 4 | // Licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your 7 | // option. This file may not be copied, modified, or distributed 8 | // except according to those terms. 9 | 10 | // Units for use with euclid::length and euclid::scale_factor. 11 | 12 | /// One hardware pixel. 13 | /// 14 | /// This unit corresponds to the smallest addressable element of the display hardware. 15 | #[derive(Copy, Clone, RustcEncodable, Debug)] 16 | pub enum DevicePixel {} 17 | 18 | #[cfg(feature = "heapsize")] 19 | known_heap_size!(0, DevicePixel); 20 | 21 | /// One pixel in layer coordinate space. 22 | /// 23 | /// This unit corresponds to a "pixel" in layer coordinate space, which after scaling and 24 | /// transformation becomes a device pixel. 25 | #[derive(Copy, Clone, RustcEncodable, Debug)] 26 | pub enum LayerPixel {} 27 | 28 | #[cfg(feature = "heapsize")] 29 | known_heap_size!(0, LayerPixel); 30 | -------------------------------------------------------------------------------- /src/layers.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Servo Project Developers. See the COPYRIGHT 2 | // file at the top-level directory of this distribution. 3 | // 4 | // Licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your 7 | // option. This file may not be copied, modified, or distributed 8 | // except according to those terms. 9 | 10 | use color::Color; 11 | use geometry::{DevicePixel, LayerPixel}; 12 | use tiling::{Tile, TileGrid}; 13 | 14 | use euclid::Matrix4D; 15 | use euclid::scale_factor::ScaleFactor; 16 | use euclid::size::{Size2D, TypedSize2D}; 17 | use euclid::point::{Point2D, TypedPoint2D}; 18 | use euclid::rect::{Rect, TypedRect}; 19 | use platform::surface::{NativeDisplay, NativeSurface}; 20 | use std::cell::{RefCell, RefMut}; 21 | use std::rc::Rc; 22 | use util::{project_rect_to_screen, ScreenRect}; 23 | 24 | #[derive(Clone, Copy, PartialEq, PartialOrd)] 25 | pub struct ContentAge { 26 | age: usize, 27 | } 28 | 29 | #[cfg(feature = "heapsize")] 30 | known_heap_size!(0, ContentAge); 31 | 32 | impl ContentAge { 33 | pub fn new() -> ContentAge { 34 | ContentAge { 35 | age: 0, 36 | } 37 | } 38 | 39 | pub fn next(&mut self) { 40 | self.age += 1; 41 | } 42 | } 43 | 44 | pub struct TransformState { 45 | /// Final, concatenated transform + perspective matrix for this layer 46 | pub final_transform: Matrix4D, 47 | 48 | /// If this is none, the rect was clipped and is not visible at all! 49 | pub screen_rect: Option, 50 | 51 | /// Rectangle in global coordinates, but not transformed. 52 | pub world_rect: Rect, 53 | 54 | /// True if this layer has a non-identity transform 55 | pub has_transform: bool, 56 | } 57 | 58 | #[cfg(feature = "heapsize")] 59 | known_heap_size!(0, TransformState); 60 | 61 | impl TransformState { 62 | fn new() -> TransformState { 63 | TransformState { 64 | final_transform: Matrix4D::identity(), 65 | screen_rect: None, 66 | world_rect: Rect::zero(), 67 | has_transform: false, 68 | } 69 | } 70 | } 71 | 72 | pub struct Layer { 73 | pub children: RefCell>>>, 74 | pub transform: RefCell>, 75 | pub perspective: RefCell>, 76 | pub tile_size: usize, 77 | pub extra_data: RefCell, 78 | tile_grid: RefCell, 79 | 80 | /// The boundaries of this layer in the coordinate system of the parent layer. 81 | pub bounds: RefCell>, 82 | 83 | /// A monotonically increasing counter that keeps track of the current content age. 84 | pub content_age: RefCell, 85 | 86 | /// The content offset for this layer in unscaled layer pixels. 87 | pub content_offset: RefCell>, 88 | 89 | /// Whether this layer clips its children to its boundaries. 90 | pub masks_to_bounds: RefCell, 91 | 92 | /// The background color for this layer. 93 | pub background_color: RefCell, 94 | 95 | /// The opacity of this layer, from 0.0 (fully transparent) to 1.0 (fully opaque). 96 | pub opacity: RefCell, 97 | 98 | /// Whether this stacking context creates a new 3d rendering context. 99 | pub establishes_3d_context: bool, 100 | 101 | /// Collection of state related to transforms for this layer. 102 | pub transform_state: RefCell, 103 | } 104 | 105 | impl Layer { 106 | pub fn new(bounds: TypedRect, 107 | tile_size: usize, 108 | background_color: Color, 109 | opacity: f32, 110 | establishes_3d_context: bool, 111 | data: T) 112 | -> Layer { 113 | Layer { 114 | children: RefCell::new(vec!()), 115 | transform: RefCell::new(Matrix4D::identity()), 116 | perspective: RefCell::new(Matrix4D::identity()), 117 | bounds: RefCell::new(bounds), 118 | tile_size: tile_size, 119 | extra_data: RefCell::new(data), 120 | tile_grid: RefCell::new(TileGrid::new(tile_size)), 121 | content_age: RefCell::new(ContentAge::new()), 122 | masks_to_bounds: RefCell::new(false), 123 | content_offset: RefCell::new(TypedPoint2D::zero()), 124 | background_color: RefCell::new(background_color), 125 | opacity: RefCell::new(opacity), 126 | establishes_3d_context: establishes_3d_context, 127 | transform_state: RefCell::new(TransformState::new()), 128 | } 129 | } 130 | 131 | pub fn children(&self) -> RefMut>>> { 132 | self.children.borrow_mut() 133 | } 134 | 135 | pub fn add_child(&self, new_child: Rc>) { 136 | self.children().push(new_child); 137 | } 138 | 139 | pub fn remove_child_at_index(&self, index: usize) { 140 | self.children().remove(index); 141 | } 142 | 143 | /// Returns buffer requests inside the given dirty rect, and simultaneously throws out tiles 144 | /// outside the given viewport rect. 145 | pub fn get_buffer_requests(&self, 146 | rect_in_layer: TypedRect, 147 | viewport_in_layer: TypedRect, 148 | scale: ScaleFactor) 149 | -> Vec { 150 | let mut tile_grid = self.tile_grid.borrow_mut(); 151 | tile_grid.get_buffer_requests_in_rect(rect_in_layer * scale, 152 | viewport_in_layer * scale, 153 | self.bounds.borrow().size * scale, 154 | &(self.transform_state.borrow().world_rect.origin * 155 | scale.get()), 156 | &self.transform_state.borrow().final_transform, 157 | *self.content_age.borrow()) 158 | } 159 | 160 | pub fn resize(&self, new_size: TypedSize2D) { 161 | self.bounds.borrow_mut().size = new_size; 162 | } 163 | 164 | pub fn add_buffer(&self, tile: Box) { 165 | self.tile_grid.borrow_mut().add_buffer(tile); 166 | } 167 | 168 | pub fn collect_unused_buffers(&self) -> Vec> { 169 | self.tile_grid.borrow_mut().take_unused_buffers() 170 | } 171 | 172 | pub fn collect_buffers(&self) -> Vec> { 173 | self.tile_grid.borrow_mut().collect_buffers() 174 | } 175 | 176 | pub fn contents_changed(&self) { 177 | self.content_age.borrow_mut().next(); 178 | } 179 | 180 | pub fn create_textures(&self, display: &NativeDisplay) { 181 | self.tile_grid.borrow_mut().create_textures(display); 182 | } 183 | 184 | pub fn do_for_all_tiles(&self, f: F) { 185 | self.tile_grid.borrow().do_for_all_tiles(f); 186 | } 187 | 188 | pub fn update_transform_state(&self, 189 | parent_transform: &Matrix4D, 190 | parent_perspective: &Matrix4D, 191 | parent_origin: &Point2D) { 192 | let mut ts = self.transform_state.borrow_mut(); 193 | let rect_without_scroll = self.bounds.borrow() 194 | .to_untyped() 195 | .translate(parent_origin); 196 | 197 | ts.world_rect = rect_without_scroll.translate(&self.content_offset.borrow().to_untyped()); 198 | 199 | let x0 = ts.world_rect.origin.x; 200 | let y0 = ts.world_rect.origin.y; 201 | 202 | // Build world space transform 203 | let local_transform = Matrix4D::identity() 204 | .pre_translated(x0, y0, 0.0) 205 | .pre_mul(&*self.transform.borrow()) 206 | .pre_translated(-x0, -y0, 0.0); 207 | 208 | ts.final_transform = parent_perspective 209 | .pre_mul(&local_transform) 210 | .pre_mul(&parent_transform); 211 | ts.screen_rect = project_rect_to_screen(&ts.world_rect, &ts.final_transform); 212 | 213 | // TODO(gw): This is quite bogus. It's a hack to allow the paint task 214 | // to avoid "optimizing" 3d layers with an incorrect clip rect. 215 | // We should probably make the display list optimizer work with transforms! 216 | // This layer is part of a 3d context if its concatenated transform 217 | // is not identity, since 2d transforms don't get layers. 218 | ts.has_transform = ts.final_transform != Matrix4D::identity(); 219 | 220 | // Build world space perspective transform 221 | let perspective_transform = Matrix4D::identity() 222 | .pre_translated(x0, y0, 0.0) 223 | .pre_mul(&*self.perspective.borrow()) 224 | .pre_translated(-x0, -y0, 0.0); 225 | 226 | for child in self.children().iter() { 227 | child.update_transform_state(&ts.final_transform, 228 | &perspective_transform, 229 | &rect_without_scroll.origin); 230 | } 231 | } 232 | 233 | /// Calculate the amount of memory used by this layer and all its children. 234 | /// The memory may be allocated on the heap or in GPU memory. 235 | pub fn get_memory_usage(&self) -> usize { 236 | let size_of_children : usize = self.children().iter().map(|ref child| -> usize { 237 | child.get_memory_usage() 238 | }).sum(); 239 | size_of_children + self.tile_grid.borrow().get_memory_usage() 240 | } 241 | } 242 | 243 | /// A request from the compositor to the renderer for tiles that need to be (re)displayed. 244 | pub struct BufferRequest { 245 | /// The rect in pixels that will be drawn to the screen 246 | pub screen_rect: Rect, 247 | 248 | /// The rect in page coordinates that this tile represents 249 | pub page_rect: Rect, 250 | 251 | /// The content age of that this BufferRequest corresponds to. 252 | pub content_age: ContentAge, 253 | 254 | /// A cached NativeSurface that can be used to avoid allocating a new one. 255 | pub native_surface: Option, 256 | } 257 | 258 | impl BufferRequest { 259 | pub fn new(screen_rect: Rect, page_rect: Rect, content_age: ContentAge) 260 | -> BufferRequest { 261 | BufferRequest { 262 | screen_rect: screen_rect, 263 | page_rect: page_rect, 264 | content_age: content_age, 265 | native_surface: None, 266 | } 267 | } 268 | } 269 | 270 | pub struct LayerBuffer { 271 | /// The native surface which can be shared between threads or processes. On Mac this is an 272 | /// `IOSurface`; on Linux this is an X Pixmap; on Android this is an `EGLImageKHR`. 273 | pub native_surface: NativeSurface, 274 | 275 | /// The rect in the containing RenderLayer that this represents. 276 | pub rect: Rect, 277 | 278 | /// The rect in pixels that will be drawn to the screen. 279 | pub screen_pos: Rect, 280 | 281 | /// The scale at which this tile is rendered 282 | pub resolution: f32, 283 | 284 | /// Whether or not this buffer was painted with the CPU rasterization. 285 | pub painted_with_cpu: bool, 286 | 287 | /// The content age of that this buffer request corresponds to. 288 | pub content_age: ContentAge, 289 | } 290 | 291 | impl LayerBuffer { 292 | /// Returns the amount of memory used by the tile 293 | pub fn get_mem(&self) -> usize { 294 | self.native_surface.get_memory_usage() 295 | } 296 | 297 | /// Returns true if the tile is displayable at the given scale 298 | pub fn is_valid(&self, scale: f32) -> bool { 299 | (self.resolution - scale).abs() < 1.0e-6 300 | } 301 | 302 | /// Returns the Size2D of the tile 303 | pub fn get_size_2d(&self) -> Size2D { 304 | self.screen_pos.size 305 | } 306 | 307 | /// Marks the layer buffer as not leaking. See comments on 308 | /// `NativeSurfaceMethods::mark_wont_leak` for how this is used. 309 | pub fn mark_wont_leak(&mut self) { 310 | self.native_surface.mark_wont_leak() 311 | } 312 | 313 | /// Destroys the layer buffer. Painting task only. 314 | pub fn destroy(self, display: &NativeDisplay) { 315 | let mut this = self; 316 | this.native_surface.destroy(display) 317 | } 318 | } 319 | 320 | /// A set of layer buffers. This is an atomic unit used to switch between the front and back 321 | /// buffers. 322 | pub struct LayerBufferSet { 323 | pub buffers: Vec> 324 | } 325 | 326 | impl LayerBufferSet { 327 | /// Notes all buffer surfaces will leak if not destroyed via a call to `destroy`. 328 | pub fn mark_will_leak(&mut self) { 329 | for buffer in &mut self.buffers { 330 | buffer.native_surface.mark_will_leak() 331 | } 332 | } 333 | } 334 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Servo Project Developers. See the COPYRIGHT 2 | // file at the top-level directory of this distribution. 3 | // 4 | // Licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your 7 | // option. This file may not be copied, modified, or distributed 8 | // except according to those terms. 9 | 10 | #![crate_name = "layers"] 11 | #![crate_type = "rlib"] 12 | 13 | extern crate euclid; 14 | #[cfg(feature = "heapsize")] 15 | #[macro_use] 16 | extern crate heapsize; 17 | extern crate libc; 18 | #[macro_use] 19 | extern crate log; 20 | extern crate rustc_serialize; 21 | extern crate gleam; 22 | extern crate skia; 23 | 24 | #[cfg(target_os="macos")] 25 | extern crate core_foundation; 26 | #[cfg(target_os="macos")] 27 | extern crate io_surface; 28 | #[cfg(target_os="macos")] 29 | extern crate cgl; 30 | 31 | #[cfg(target_os="linux")] 32 | extern crate x11; 33 | #[cfg(target_os="linux")] 34 | extern crate glx; 35 | 36 | #[cfg(any(target_os = "linux", target_os = "android"))] 37 | extern crate egl; 38 | 39 | pub mod color; 40 | pub mod geometry; 41 | pub mod layers; 42 | pub mod rendergl; 43 | pub mod scene; 44 | pub mod texturegl; 45 | pub mod tiling; 46 | pub mod util; 47 | 48 | pub mod platform { 49 | #[cfg(target_os="linux")] 50 | pub mod linux { 51 | pub mod surface; 52 | } 53 | #[cfg(target_os="macos")] 54 | pub mod macos { 55 | pub mod surface; 56 | } 57 | #[cfg(target_os="android")] 58 | pub mod android { 59 | pub mod surface; 60 | } 61 | #[cfg(any(target_os="android",target_os="linux"))] 62 | pub mod egl { 63 | pub mod surface; 64 | } 65 | #[cfg(target_os="windows")] 66 | pub mod windows { 67 | pub mod surface; 68 | } 69 | pub mod surface; 70 | } 71 | -------------------------------------------------------------------------------- /src/platform/android/surface.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Servo Project Developers. See the COPYRIGHT 2 | // file at the top-level directory of this distribution. 3 | // 4 | // Licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your 7 | // option. This file may not be copied, modified, or distributed 8 | // except according to those terms. 9 | 10 | //! Implementation of cross-process surfaces for Android. This uses EGL surface. 11 | 12 | use texturegl::Texture; 13 | 14 | use egl::egl::{EGLDisplay, GetCurrentDisplay}; 15 | use egl::eglext::{EGLImageKHR, DestroyImageKHR}; 16 | use euclid::size::Size2D; 17 | use gleam::gl::{egl_image_target_texture2d_oes, TEXTURE_2D, TexImage2D, BGRA_EXT, UNSIGNED_BYTE}; 18 | use skia::gl_context::{GLContext, PlatformDisplayData}; 19 | use skia::gl_rasterization_context::GLRasterizationContext; 20 | use std::iter::repeat; 21 | use std::mem; 22 | use std::os::raw::c_void; 23 | use std::sync::Arc; 24 | use std::vec::Vec; 25 | 26 | /// FIXME(Aydin Kim) :Currently, native surface is consist of 2 types of hybrid image 27 | /// buffer. EGLImageKHR is used to GPU rendering and vector is used to CPU rendering. EGL 28 | /// extension seems not provide simple way to accessing its bitmap directly. In the 29 | /// future, we need to find out the way to integrate them. 30 | 31 | #[derive(Clone, Copy)] 32 | pub struct NativeDisplay { 33 | pub display: EGLDisplay, 34 | } 35 | unsafe impl Send for NativeDisplay {} 36 | 37 | impl NativeDisplay { 38 | pub fn new() -> NativeDisplay { 39 | NativeDisplay::new_with_display(GetCurrentDisplay()) 40 | } 41 | 42 | pub fn new_with_display(display: EGLDisplay) -> NativeDisplay { 43 | NativeDisplay { 44 | display: display, 45 | } 46 | } 47 | 48 | pub fn platform_display_data(&self) -> PlatformDisplayData { 49 | PlatformDisplayData { 50 | display: self.display, 51 | } 52 | } 53 | } 54 | 55 | pub struct EGLImageNativeSurface { 56 | /// An EGLImage for the case of GPU rendering. 57 | image: Option, 58 | 59 | /// A heap-allocated bitmap for the case of CPU rendering. 60 | bitmap: Option>, 61 | 62 | /// Whether this pixmap will leak if the destructor runs. This is for debugging purposes. 63 | will_leak: bool, 64 | 65 | /// The size of this surface. 66 | pub size: Size2D, 67 | } 68 | 69 | unsafe impl Send for EGLImageNativeSurface {} 70 | 71 | impl EGLImageNativeSurface { 72 | pub fn new(_: &NativeDisplay, size: Size2D) -> EGLImageNativeSurface { 73 | let len = size.width * size.height * 4; 74 | let bitmap: Vec = repeat(0).take(len as usize).collect(); 75 | 76 | EGLImageNativeSurface { 77 | image: None, 78 | bitmap: Some(bitmap), 79 | will_leak: true, 80 | size: size, 81 | } 82 | } 83 | 84 | /// This may only be called on the compositor side. 85 | pub fn bind_to_texture(&self, _: &NativeDisplay, texture: &Texture) { 86 | let _bound = texture.bind(); 87 | match self.image { 88 | None => match self.bitmap { 89 | Some(ref bitmap) => { 90 | let data = bitmap.as_ptr() as *const c_void; 91 | unsafe { 92 | TexImage2D(TEXTURE_2D, 93 | 0, 94 | BGRA_EXT as i32, 95 | self.size.width as i32, 96 | self.size.height as i32, 97 | 0, 98 | BGRA_EXT as u32, 99 | UNSIGNED_BYTE, 100 | data); 101 | } 102 | } 103 | None => { 104 | debug!("Cannot bind the buffer(CPU rendering), there is no bitmap"); 105 | } 106 | }, 107 | Some(image_khr) => { 108 | egl_image_target_texture2d_oes(TEXTURE_2D, image_khr as *const c_void); 109 | } 110 | } 111 | } 112 | 113 | /// This may only be called on the painting side. 114 | pub fn upload(&mut self, _: &NativeDisplay, data: &[u8]) { 115 | match self.bitmap { 116 | Some(ref mut bitmap) => { 117 | bitmap.clear(); 118 | bitmap.extend_from_slice(data); 119 | } 120 | None => { 121 | debug!("Cannot upload the buffer(CPU rendering), there is no bitmap"); 122 | } 123 | } 124 | } 125 | 126 | pub fn get_id(&self) -> isize { 127 | match self.image { 128 | None => 0, 129 | Some(image_khr) => image_khr as isize, 130 | } 131 | } 132 | 133 | pub fn destroy(&mut self, graphics_context: &NativeDisplay) { 134 | match self.image { 135 | None => {}, 136 | Some(image_khr) => { 137 | DestroyImageKHR(graphics_context.display, image_khr); 138 | mem::replace(&mut self.image, None); 139 | } 140 | } 141 | self.mark_wont_leak() 142 | } 143 | 144 | pub fn mark_will_leak(&mut self) { 145 | self.will_leak = true 146 | } 147 | 148 | pub fn mark_wont_leak(&mut self) { 149 | self.will_leak = false 150 | } 151 | 152 | pub fn gl_rasterization_context(&mut self, 153 | gl_context: Arc) 154 | -> Option { 155 | // TODO: Eventually we should preserve the previous GLRasterizationContext, 156 | // so that we don't have to keep destroying and recreating the image. 157 | if let Some(egl_image) = self.image.take() { 158 | DestroyImageKHR(gl_context.platform_context.display, egl_image); 159 | } 160 | 161 | let gl_rasterization_context = GLRasterizationContext::new(gl_context, self.size); 162 | if let Some(ref gl_rasterization_context) = gl_rasterization_context { 163 | self.bitmap = None; 164 | self.image = Some(gl_rasterization_context.egl_image); 165 | } 166 | gl_rasterization_context 167 | } 168 | } 169 | -------------------------------------------------------------------------------- /src/platform/egl/surface.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The Servo Project Developers. See the COPYRIGHT 2 | // file at the top-level directory of this distribution. 3 | // 4 | // Licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your 7 | // option. This file may not be copied, modified, or distributed 8 | // except according to those terms. 9 | 10 | //! Implementation of cross-process surfaces implementing EGL surface. 11 | 12 | use texturegl::Texture; 13 | 14 | use egl::eglext::EGLImageKHR; 15 | use euclid::size::Size2D; 16 | use gleam::gl::{TEXTURE_2D, TexImage2D, UNSIGNED_BYTE}; 17 | use skia::gl_context::GLContext; 18 | use skia::gl_rasterization_context::GLRasterizationContext; 19 | use std::iter::repeat; 20 | use std::os::raw::c_void; 21 | use std::sync::Arc; 22 | use std::vec::Vec; 23 | 24 | use gleam::gl; 25 | 26 | #[cfg(target_os = "linux")] 27 | const GL_FORMAT_BGRA: gl::GLuint = gl::BGRA; 28 | 29 | #[cfg(any(target_os = "android", target_os = "gonk"))] 30 | const GL_FORMAT_BGRA: gl::GLuint = gl::BGRA_EXT; 31 | 32 | #[cfg(target_os="linux")] 33 | pub use platform::linux::surface::NativeDisplay; 34 | 35 | #[cfg(target_os="android")] 36 | pub use platform::android::surface::NativeDisplay; 37 | 38 | pub struct EGLImageNativeSurface { 39 | /// An EGLImage for the case of GPU rendering. 40 | image: Option, 41 | 42 | /// A heap-allocated bitmap for the case of CPU rendering. 43 | bitmap: Option>, 44 | 45 | /// Whether this pixmap will leak if the destructor runs. This is for debugging purposes. 46 | will_leak: bool, 47 | 48 | /// The size of this surface. 49 | pub size: Size2D, 50 | } 51 | 52 | unsafe impl Send for EGLImageNativeSurface {} 53 | 54 | impl EGLImageNativeSurface { 55 | pub fn new(_: &NativeDisplay, size: Size2D) -> EGLImageNativeSurface { 56 | let len = size.width * size.height * 4; 57 | let bitmap: Vec = repeat(0).take(len as usize).collect(); 58 | 59 | EGLImageNativeSurface { 60 | image: None, 61 | bitmap: Some(bitmap), 62 | will_leak: true, 63 | size: size, 64 | } 65 | } 66 | 67 | /// This may only be called on the compositor side. 68 | pub fn bind_to_texture(&self, _: &NativeDisplay, texture: &Texture) { 69 | let _bound = texture.bind(); 70 | match self.image { 71 | None => match self.bitmap { 72 | Some(ref bitmap) => { 73 | let data = bitmap.as_ptr() as *const c_void; 74 | unsafe { 75 | TexImage2D(TEXTURE_2D, 76 | 0, 77 | GL_FORMAT_BGRA as i32, 78 | self.size.width as i32, 79 | self.size.height as i32, 80 | 0, 81 | GL_FORMAT_BGRA as u32, 82 | UNSIGNED_BYTE, 83 | data); 84 | } 85 | } 86 | None => { 87 | debug!("Cannot bind the buffer(CPU rendering), there is no bitmap"); 88 | } 89 | }, 90 | Some(_image_khr) => { 91 | panic!("TODO: Support GPU rasterizer path on EGL"); 92 | } 93 | } 94 | } 95 | 96 | /// This may only be called on the painting side. 97 | pub fn upload(&mut self, _: &NativeDisplay, data: &[u8]) { 98 | match self.bitmap { 99 | Some(ref mut bitmap) => { 100 | bitmap.clear(); 101 | bitmap.extend_from_slice(data); 102 | } 103 | None => { 104 | debug!("Cannot upload the buffer(CPU rendering), there is no bitmap"); 105 | } 106 | } 107 | } 108 | 109 | pub fn get_id(&self) -> isize { 110 | match self.image { 111 | None => 0, 112 | Some(image_khr) => image_khr as isize, 113 | } 114 | } 115 | 116 | pub fn destroy(&mut self, _graphics_context: &NativeDisplay) { 117 | if self.image.is_some() { 118 | panic!("TODO: Support GPU rendering path on Android"); 119 | } 120 | self.mark_wont_leak() 121 | } 122 | 123 | pub fn mark_will_leak(&mut self) { 124 | self.will_leak = true 125 | } 126 | 127 | pub fn mark_wont_leak(&mut self) { 128 | self.will_leak = false 129 | } 130 | 131 | pub fn gl_rasterization_context(&mut self, 132 | _gl_context: Arc) 133 | -> Option { 134 | panic!("TODO: Support GL context on EGL"); 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /src/platform/linux/surface.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Servo Project Developers. See the COPYRIGHT 2 | // file at the top-level directory of this distribution. 3 | // 4 | // Licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your 7 | // option. This file may not be copied, modified, or distributed 8 | // except according to those terms. 9 | 10 | //! Implementation of cross-process surfaces for Linux. This uses X pixmaps. 11 | 12 | #![allow(non_snake_case)] 13 | 14 | //TODO: Linking EGL here is probably wrong - should it be done in gleam / glutin etc? 15 | #[link(name = "EGL")] 16 | extern {} 17 | 18 | use texturegl::Texture; 19 | 20 | use euclid::size::Size2D; 21 | use libc::{c_int, c_uint, c_void}; 22 | use glx; 23 | use skia::gl_context::{GLContext, PlatformDisplayData}; 24 | use skia::gl_rasterization_context::GLRasterizationContext; 25 | use std::ascii::AsciiExt; 26 | use std::ffi::CStr; 27 | use std::mem; 28 | use std::ptr; 29 | use std::str; 30 | use std::sync::Arc; 31 | use x11::xlib; 32 | 33 | use egl::egl::{EGLDisplay, GetCurrentDisplay}; 34 | 35 | /// The display, visual info, and framebuffer configuration. This is needed in order to bind to a 36 | /// texture on the compositor side. This holds only a *weak* reference to the display and does not 37 | /// close it. 38 | /// 39 | /// FIXME(pcwalton): Unchecked weak references are bad and can violate memory safety. This is hard 40 | /// to fix because the Display is given to us by the native windowing system, but we should fix it 41 | /// someday. 42 | /// FIXME(pcwalton): Mark nonsendable. 43 | 44 | #[derive(Copy, Clone)] 45 | pub struct GLXDisplayInfo { 46 | pub display: *mut xlib::Display, 47 | visual_info: *mut xlib::XVisualInfo, 48 | framebuffer_configuration: Option, 49 | } 50 | #[derive(Copy, Clone)] 51 | pub struct EGLDisplayInfo { 52 | pub display: EGLDisplay, 53 | } 54 | 55 | #[derive(Copy, Clone)] 56 | pub enum NativeDisplay { 57 | EGL(EGLDisplayInfo), 58 | GLX(GLXDisplayInfo), 59 | } 60 | 61 | 62 | 63 | unsafe impl Send for NativeDisplay {} 64 | 65 | impl NativeDisplay { 66 | pub fn new(display: *mut xlib::Display) -> NativeDisplay { 67 | // FIXME(pcwalton): It would be more robust to actually have the compositor pass the 68 | // visual. 69 | let (compositor_visual_info, frambuffer_configuration) = 70 | NativeDisplay::compositor_visual_info(display); 71 | 72 | NativeDisplay::GLX(GLXDisplayInfo { 73 | display: display, 74 | visual_info: compositor_visual_info, 75 | framebuffer_configuration: frambuffer_configuration, 76 | }) 77 | } 78 | 79 | /// Chooses the compositor visual info using the same algorithm that the compositor uses. 80 | /// 81 | /// FIXME(pcwalton): It would be more robust to actually have the compositor pass the visual. 82 | fn compositor_visual_info(display: *mut xlib::Display) 83 | -> (*mut xlib::XVisualInfo, Option) { 84 | // If display is null, we'll assume we are going to be rendering 85 | // in headless mode without X running. 86 | if display == ptr::null_mut() { 87 | return (ptr::null_mut(), None); 88 | } 89 | 90 | unsafe { 91 | let fbconfig_attributes = [ 92 | glx::DOUBLEBUFFER as i32, 0, 93 | glx::DRAWABLE_TYPE as i32, glx::PIXMAP_BIT as i32 | glx::WINDOW_BIT as i32, 94 | glx::BIND_TO_TEXTURE_RGBA_EXT as i32, 1, 95 | glx::RENDER_TYPE as i32, glx::RGBA_BIT as i32, 96 | glx::ALPHA_SIZE as i32, 8, 97 | 0 98 | ]; 99 | 100 | let screen = xlib::XDefaultScreen(display); 101 | let mut number_of_configs = 0; 102 | let configs = glx::ChooseFBConfig(mem::transmute(display), 103 | screen, 104 | fbconfig_attributes.as_ptr(), 105 | &mut number_of_configs); 106 | NativeDisplay::get_compatible_configuration(display, configs, number_of_configs) 107 | } 108 | } 109 | 110 | fn get_compatible_configuration(display: *mut xlib::Display, 111 | configs: *mut glx::types::GLXFBConfig, 112 | number_of_configs: i32) 113 | -> (*mut xlib::XVisualInfo, Option) { 114 | unsafe { 115 | if number_of_configs == 0 { 116 | panic!("glx::ChooseFBConfig returned no configurations."); 117 | } 118 | 119 | if !NativeDisplay::need_to_find_32_bit_depth_visual(display) { 120 | let config = *configs.offset(0); 121 | let visual = glx::GetVisualFromFBConfig(mem::transmute(display), config); 122 | 123 | xlib::XFree(configs as *mut _); 124 | return (mem::transmute(visual), Some(config)); 125 | } 126 | 127 | // NVidia (and AMD/ATI) drivers have RGBA configurations that use 24-bit 128 | // XVisual, not capable of representing an alpha-channel in Pixmap form, 129 | // so we look for the configuration with a full set of 32 bits. 130 | for i in 0..number_of_configs as isize { 131 | let config = *configs.offset(i); 132 | let visual: *mut xlib::XVisualInfo = 133 | mem::transmute(glx::GetVisualFromFBConfig(mem::transmute(display), config)); 134 | if (*visual).depth == 32 { 135 | xlib::XFree(configs as *mut _); 136 | return (visual, Some(config)); 137 | } 138 | xlib::XFree(visual as *mut _); 139 | } 140 | 141 | xlib::XFree(configs as *mut _); 142 | panic!("Could not find 32-bit visual."); 143 | } 144 | } 145 | 146 | fn need_to_find_32_bit_depth_visual(display: *mut xlib::Display) -> bool { 147 | unsafe { 148 | let glx_vendor = glx::GetClientString(mem::transmute(display), glx::VENDOR as i32); 149 | if glx_vendor == ptr::null() { 150 | panic!("Could not determine GLX vendor."); 151 | } 152 | let glx_vendor = 153 | str::from_utf8(CStr::from_ptr(glx_vendor).to_bytes()) 154 | .ok() 155 | .expect("GLX client vendor string not in UTF-8 format.") 156 | .to_string() 157 | .to_ascii_lowercase(); 158 | glx_vendor.contains("nvidia") || glx_vendor.contains("ati") 159 | } 160 | } 161 | 162 | pub fn platform_display_data(&self) -> PlatformDisplayData { 163 | match *self { 164 | NativeDisplay::GLX(info) => { 165 | PlatformDisplayData { 166 | display: info.display, 167 | visual_info: info.visual_info, 168 | } 169 | } 170 | NativeDisplay::EGL(_) => unreachable!(), 171 | } 172 | } 173 | 174 | pub fn new_egl_display() -> NativeDisplay { 175 | NativeDisplay::EGL(EGLDisplayInfo { 176 | display: GetCurrentDisplay() 177 | }) 178 | } 179 | } 180 | 181 | #[derive(RustcDecodable, RustcEncodable)] 182 | pub struct PixmapNativeSurface { 183 | /// The pixmap. 184 | pixmap: xlib::Pixmap, 185 | 186 | /// Whether this pixmap will leak if the destructor runs. This is for debugging purposes. 187 | will_leak: bool, 188 | 189 | /// The size of this surface. 190 | pub size: Size2D, 191 | } 192 | 193 | impl Drop for PixmapNativeSurface { 194 | fn drop(&mut self) { 195 | if self.will_leak { 196 | panic!("You should have disposed of the pixmap properly with destroy()! This pixmap \ 197 | will leak!"); 198 | } 199 | } 200 | } 201 | 202 | impl PixmapNativeSurface { 203 | pub fn new(display: &GLXDisplayInfo, size: Size2D) -> PixmapNativeSurface { 204 | unsafe { 205 | // Create the pixmap. 206 | let screen = xlib::XDefaultScreen(display.display); 207 | let window = xlib::XRootWindow(display.display, screen); 208 | // The X server we use for testing on build machines always returns 209 | // visuals that report 24 bit depth. But creating a 32 bit pixmap does work, so 210 | // hard code the depth here. 211 | let pixmap = xlib::XCreatePixmap(display.display, 212 | window, 213 | size.width as c_uint, 214 | size.height as c_uint, 215 | 32); 216 | PixmapNativeSurface { 217 | pixmap: pixmap, 218 | will_leak: true, 219 | size: size, 220 | } 221 | } 222 | } 223 | 224 | /// This may only be called on the compositor side. 225 | pub fn bind_to_texture(&self, display: &NativeDisplay, texture: &Texture) { 226 | // Create the GLX pixmap. 227 | // 228 | // FIXME(pcwalton): RAII for exception safety? 229 | unsafe { 230 | let display = match display { 231 | &NativeDisplay::GLX(info) => info, 232 | &NativeDisplay::EGL(_) => unreachable!(), 233 | }; 234 | 235 | let pixmap_attributes = [ 236 | glx::TEXTURE_TARGET_EXT as i32, glx::TEXTURE_2D_EXT as i32, 237 | glx::TEXTURE_FORMAT_EXT as i32, glx::TEXTURE_FORMAT_RGBA_EXT as i32, 238 | 0 239 | ]; 240 | 241 | let glx_display = mem::transmute(display.display); 242 | 243 | let glx_pixmap = glx::CreatePixmap(glx_display, 244 | display.framebuffer_configuration.expect( 245 | "GLX 1.3 should have a framebuffer_configuration"), 246 | self.pixmap, 247 | pixmap_attributes.as_ptr()); 248 | 249 | let glx_bind_tex_image: extern "C" fn(*mut xlib::Display, glx::types::GLXDrawable, c_int, *mut c_int) = 250 | mem::transmute(glx::GetProcAddress(mem::transmute(&"glXBindTexImageEXT\x00".as_bytes()[0]))); 251 | assert!(glx_bind_tex_image as *mut c_void != ptr::null_mut()); 252 | let _bound = texture.bind(); 253 | glx_bind_tex_image(display.display, 254 | mem::transmute(glx_pixmap), 255 | glx::FRONT_EXT as i32, 256 | ptr::null_mut()); 257 | 258 | // FIXME(pcwalton): Recycle these for speed? 259 | glx::DestroyPixmap(glx_display, glx_pixmap); 260 | } 261 | } 262 | 263 | /// This may only be called on the painting side. 264 | pub fn upload(&mut self, display: &NativeDisplay, data: &[u8]) { 265 | unsafe { 266 | let display = match display { 267 | &NativeDisplay::GLX(info) => info, 268 | &NativeDisplay::EGL(_) => unreachable!(), 269 | }; 270 | 271 | let image = xlib::XCreateImage(display.display, 272 | (*display.visual_info).visual, 273 | 32, 274 | xlib::ZPixmap, 275 | 0, 276 | mem::transmute(&data[0]), 277 | self.size.width as c_uint, 278 | self.size.height as c_uint, 279 | 32, 280 | 0); 281 | 282 | let gc = xlib::XCreateGC(display.display, self.pixmap, 0, ptr::null_mut()); 283 | let _ = xlib::XPutImage(display.display, 284 | self.pixmap, 285 | gc, 286 | image, 287 | 0, 288 | 0, 289 | 0, 290 | 0, 291 | self.size.width as c_uint, 292 | self.size.height as c_uint); 293 | } 294 | } 295 | 296 | pub fn get_id(&self) -> isize { 297 | self.pixmap as isize 298 | } 299 | 300 | pub fn destroy(&mut self, display: &NativeDisplay) { 301 | unsafe { 302 | let display = match display { 303 | &NativeDisplay::GLX(info) => info, 304 | &NativeDisplay::EGL(_) => unreachable!(), 305 | }; 306 | 307 | assert!(self.pixmap != 0); 308 | xlib::XFreePixmap(display.display, self.pixmap); 309 | self.mark_wont_leak() 310 | } 311 | } 312 | 313 | pub fn mark_will_leak(&mut self) { 314 | self.will_leak = true; 315 | } 316 | 317 | pub fn mark_wont_leak(&mut self) { 318 | self.will_leak = false; 319 | } 320 | 321 | pub fn gl_rasterization_context(&mut self, 322 | gl_context: Arc) 323 | -> Option { 324 | GLRasterizationContext::new(gl_context, self.pixmap, self.size) 325 | } 326 | } 327 | -------------------------------------------------------------------------------- /src/platform/macos/surface.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Servo Project Developers. See the COPYRIGHT 2 | // file at the top-level directory of this distribution. 3 | // 4 | // Licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your 7 | // option. This file may not be copied, modified, or distributed 8 | // except according to those terms. 9 | 10 | //! Mac OS-specific implementation of cross-process surfaces. This uses `IOSurface`, introduced 11 | //! in Mac OS X 10.6 Snow Leopard. 12 | 13 | use texturegl::Texture; 14 | 15 | use cgl; 16 | use core_foundation::base::TCFType; 17 | use core_foundation::boolean::CFBoolean; 18 | use core_foundation::dictionary::CFDictionary; 19 | use core_foundation::number::CFNumber; 20 | use core_foundation::string::CFString; 21 | use euclid::size::Size2D; 22 | use io_surface; 23 | use rustc_serialize::{Decoder, Decodable, Encoder, Encodable}; 24 | use skia::gl_context::{GLContext, PlatformDisplayData}; 25 | use skia::gl_rasterization_context::GLRasterizationContext; 26 | use std::sync::Arc; 27 | 28 | #[derive(Clone, Copy)] 29 | pub struct NativeDisplay { 30 | pub pixel_format: cgl::CGLPixelFormatObj, 31 | } 32 | unsafe impl Send for NativeDisplay {} 33 | 34 | impl NativeDisplay { 35 | pub fn new() -> NativeDisplay { 36 | unsafe { 37 | NativeDisplay { 38 | pixel_format: cgl::CGLGetPixelFormat(cgl::CGLGetCurrentContext()), 39 | } 40 | } 41 | } 42 | 43 | pub fn platform_display_data(&self) -> PlatformDisplayData { 44 | PlatformDisplayData { 45 | pixel_format: self.pixel_format, 46 | } 47 | } 48 | } 49 | 50 | pub struct IOSurfaceNativeSurface { 51 | surface: Option, 52 | will_leak: bool, 53 | pub size: Size2D, 54 | } 55 | 56 | unsafe impl Send for IOSurfaceNativeSurface {} 57 | unsafe impl Sync for IOSurfaceNativeSurface {} 58 | 59 | impl Decodable for IOSurfaceNativeSurface { 60 | fn decode(d: &mut D) -> Result { 61 | let id: Option = try!(Decodable::decode(d)); 62 | Ok(IOSurfaceNativeSurface { 63 | surface: id.map(io_surface::lookup), 64 | will_leak: try!(Decodable::decode(d)), 65 | size: try!(Decodable::decode(d)), 66 | }) 67 | } 68 | } 69 | impl Encodable for IOSurfaceNativeSurface { 70 | fn encode(&self, e: &mut E) -> Result<(), E::Error> { 71 | try!(self.surface.as_ref().map(io_surface::IOSurface::get_id).encode(e)); 72 | try!(self.will_leak.encode(e)); 73 | try!(self.size.encode(e)); 74 | Ok(()) 75 | } 76 | } 77 | 78 | impl IOSurfaceNativeSurface { 79 | pub fn new(_: &NativeDisplay, size: Size2D) -> IOSurfaceNativeSurface { 80 | unsafe { 81 | let width_key: CFString = TCFType::wrap_under_get_rule(io_surface::kIOSurfaceWidth); 82 | let width_value: CFNumber = CFNumber::from_i32(size.width); 83 | 84 | let height_key: CFString = TCFType::wrap_under_get_rule(io_surface::kIOSurfaceHeight); 85 | let height_value: CFNumber = CFNumber::from_i32(size.height); 86 | 87 | let bytes_per_row_key: CFString = 88 | TCFType::wrap_under_get_rule(io_surface::kIOSurfaceBytesPerRow); 89 | let bytes_per_row_value: CFNumber = CFNumber::from_i32(size.width * 4); 90 | 91 | let bytes_per_elem_key: CFString = 92 | TCFType::wrap_under_get_rule(io_surface::kIOSurfaceBytesPerElement); 93 | let bytes_per_elem_value: CFNumber = CFNumber::from_i32(4); 94 | 95 | let is_global_key: CFString = 96 | TCFType::wrap_under_get_rule(io_surface::kIOSurfaceIsGlobal); 97 | let is_global_value = CFBoolean::true_value(); 98 | 99 | let surface = io_surface::new(&CFDictionary::from_CFType_pairs(&[ 100 | (width_key.as_CFType(), width_value.as_CFType()), 101 | (height_key.as_CFType(), height_value.as_CFType()), 102 | (bytes_per_row_key.as_CFType(), bytes_per_row_value.as_CFType()), 103 | (bytes_per_elem_key.as_CFType(), bytes_per_elem_value.as_CFType()), 104 | (is_global_key.as_CFType(), is_global_value.as_CFType()), 105 | ])); 106 | 107 | IOSurfaceNativeSurface { 108 | surface: Some(surface), 109 | will_leak: true, 110 | size: size, 111 | } 112 | } 113 | } 114 | 115 | pub fn bind_to_texture(&self, _: &NativeDisplay, texture: &Texture) { 116 | let _bound_texture = texture.bind(); 117 | let io_surface = self.surface.as_ref().unwrap(); 118 | io_surface.bind_to_gl_texture(self.size.width, self.size.height); 119 | } 120 | 121 | pub fn upload(&mut self, _: &NativeDisplay, data: &[u8]) { 122 | let io_surface = self.surface.as_ref().unwrap(); 123 | io_surface.upload(data) 124 | } 125 | 126 | pub fn get_id(&self) -> isize { 127 | match self.surface { 128 | None => 0, 129 | Some(ref io_surface) => io_surface.get_id() as isize, 130 | } 131 | } 132 | 133 | pub fn destroy(&mut self, _: &NativeDisplay) { 134 | self.surface = None; 135 | self.mark_wont_leak() 136 | } 137 | 138 | pub fn mark_will_leak(&mut self) { 139 | self.will_leak = true 140 | } 141 | 142 | pub fn mark_wont_leak(&mut self) { 143 | self.will_leak = false 144 | } 145 | 146 | pub fn gl_rasterization_context(&mut self, 147 | gl_context: Arc) 148 | -> Option { 149 | GLRasterizationContext::new(gl_context, 150 | self.surface.as_ref().unwrap().obj, 151 | self.size) 152 | } 153 | } 154 | -------------------------------------------------------------------------------- /src/platform/surface.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Servo Project Developers. See the COPYRIGHT 2 | // file at the top-level directory of this distribution. 3 | // 4 | // Licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your 7 | // option. This file may not be copied, modified, or distributed 8 | // except according to those terms. 9 | 10 | //! Implementation of cross-process surfaces. This delegates to the platform-specific 11 | //! implementation. 12 | 13 | use texturegl::Texture; 14 | 15 | use euclid::size::Size2D; 16 | use skia::gl_rasterization_context::GLRasterizationContext; 17 | use skia::gl_context::GLContext; 18 | use std::sync::Arc; 19 | 20 | #[cfg(not(target_os="android"))] 21 | use gleam::gl; 22 | 23 | #[cfg(target_os="macos")] 24 | pub use platform::macos::surface::{NativeDisplay, 25 | IOSurfaceNativeSurface}; 26 | 27 | #[cfg(target_os="linux")] 28 | pub use platform::linux::surface::{NativeDisplay, 29 | PixmapNativeSurface}; 30 | #[cfg(target_os="linux")] 31 | use std::ptr; 32 | 33 | #[cfg(any(target_os="android",target_os="linux"))] 34 | pub use platform::egl::surface::{EGLImageNativeSurface}; 35 | 36 | #[cfg(target_os="android")] 37 | pub use platform::android::surface::NativeDisplay; 38 | 39 | #[cfg(target_os="windows")] 40 | pub use platform::windows::surface::NativeDisplay; 41 | 42 | pub enum NativeSurface { 43 | MemoryBuffer(MemoryBufferNativeSurface), 44 | #[cfg(target_os="linux")] 45 | Pixmap(PixmapNativeSurface), 46 | #[cfg(target_os="macos")] 47 | IOSurface(IOSurfaceNativeSurface), 48 | #[cfg(any(target_os="android",target_os="linux"))] 49 | EGLImage(EGLImageNativeSurface), 50 | } 51 | 52 | #[cfg(target_os="linux")] 53 | impl NativeSurface { 54 | /// Creates a new native surface with uninitialized data. 55 | pub fn new(display: &NativeDisplay, size: Size2D) -> NativeSurface { 56 | match display { 57 | &NativeDisplay::EGL(_info) => { 58 | NativeSurface::EGLImage(EGLImageNativeSurface::new(display, size)) 59 | } 60 | &NativeDisplay::GLX(info) => { 61 | if info.display == ptr::null_mut() { 62 | NativeSurface::MemoryBuffer(MemoryBufferNativeSurface::new(display, size)) 63 | } else { 64 | NativeSurface::Pixmap(PixmapNativeSurface::new(&info, size)) 65 | } 66 | } 67 | } 68 | } 69 | } 70 | 71 | #[cfg(target_os="macos")] 72 | impl NativeSurface { 73 | /// Creates a new native surface with uninitialized data. 74 | pub fn new(display: &NativeDisplay, size: Size2D) -> NativeSurface { 75 | NativeSurface::IOSurface(IOSurfaceNativeSurface::new(display, size)) 76 | } 77 | } 78 | 79 | #[cfg(target_os="android")] 80 | impl NativeSurface { 81 | /// Creates a new native surface with uninitialized data. 82 | pub fn new(display: &NativeDisplay, size: Size2D) -> NativeSurface { 83 | NativeSurface::EGLImage(EGLImageNativeSurface::new(display, size)) 84 | } 85 | } 86 | 87 | #[cfg(target_os="windows")] 88 | impl NativeSurface { 89 | /// Creates a new native surface with uninitialized data. 90 | pub fn new(display: &NativeDisplay, size: Size2D) -> NativeSurface { 91 | NativeSurface::MemoryBuffer(MemoryBufferNativeSurface::new(display, size)) 92 | } 93 | } 94 | 95 | macro_rules! native_surface_method_with_mutability { 96 | ($self_:ident, $function_name:ident, $surface:ident, $pattern:pat, $($argument:ident),*) => { 97 | match *$self_ { 98 | NativeSurface::MemoryBuffer($pattern) => 99 | $surface.$function_name($($argument), *), 100 | #[cfg(target_os="linux")] 101 | NativeSurface::Pixmap($pattern) => 102 | $surface.$function_name($($argument), *), 103 | #[cfg(target_os="macos")] 104 | NativeSurface::IOSurface($pattern) => 105 | $surface.$function_name($($argument), *), 106 | #[cfg(any(target_os="android",target_os="linux"))] 107 | NativeSurface::EGLImage($pattern) => 108 | $surface.$function_name($($argument), *), 109 | } 110 | }; 111 | } 112 | 113 | macro_rules! native_surface_method_mut { 114 | ($self_:ident $function_name:ident ($($argument:ident),*)) => { 115 | native_surface_method_with_mutability!($self_, 116 | $function_name, 117 | surface, 118 | ref mut surface, 119 | $($argument), 120 | *) 121 | }; 122 | } 123 | 124 | macro_rules! native_surface_method { 125 | ($self_:ident $function_name:ident ($($argument:ident),*)) => { 126 | native_surface_method_with_mutability!($self_, 127 | $function_name, 128 | surface, 129 | ref surface, 130 | $($argument), 131 | *) 132 | }; 133 | } 134 | 135 | macro_rules! native_surface_property { 136 | ($self_:ident $property_name:ident) => { 137 | match *$self_ { 138 | NativeSurface::MemoryBuffer(ref surface) => surface.$property_name, 139 | #[cfg(target_os="linux")] 140 | NativeSurface::Pixmap(ref surface) => surface.$property_name, 141 | #[cfg(target_os="macos")] 142 | NativeSurface::IOSurface(ref surface) => surface.$property_name, 143 | #[cfg(any(target_os="android",target_os="linux"))] 144 | NativeSurface::EGLImage(ref surface) => surface.$property_name, 145 | } 146 | }; 147 | } 148 | 149 | impl NativeSurface { 150 | /// Binds the surface to a GPU texture. Compositing task only. 151 | pub fn bind_to_texture(&self, display: &NativeDisplay, texture: &Texture) { 152 | native_surface_method!(self bind_to_texture (display, texture)) 153 | } 154 | 155 | /// Uploads pixel data to the surface. Painting task only. 156 | pub fn upload(&mut self, display: &NativeDisplay, data: &[u8]) { 157 | native_surface_method_mut!(self upload (display, data)) 158 | } 159 | 160 | /// Returns an opaque ID identifying the surface for debugging. 161 | pub fn get_id(&self) -> isize { 162 | native_surface_method!(self get_id ()) 163 | } 164 | 165 | /// Destroys the surface. After this, it is an error to use the surface. Painting task only. 166 | pub fn destroy(&mut self, display: &NativeDisplay) { 167 | native_surface_method_mut!(self destroy (display)) 168 | } 169 | 170 | /// Records that the surface will leak if destroyed. This is done by the compositor immediately 171 | /// after receiving the surface. 172 | pub fn mark_will_leak(&mut self) { 173 | native_surface_method_mut!(self mark_will_leak ()) 174 | } 175 | 176 | /// Marks the surface as not leaking. The painting task and the compositing task call this when 177 | /// they are certain that the surface will not leak. For example: 178 | /// 179 | /// 1. When sending buffers back to the render task, either the render task will receive them 180 | /// or the render task has crashed. In the former case, they're the render task's 181 | /// responsibility, so this is OK. In the latter case, the kernel or window server is going 182 | /// to clean up the layer buffers. Either way, no leaks. 183 | /// 184 | /// 2. If the compositor is shutting down, the render task is also shutting down. In that case 185 | /// it will destroy all its pixmaps, so no leak. 186 | /// 187 | /// 3. If the painting task is sending buffers to the compositor, then they are marked as not 188 | /// leaking, because of the possibility that the compositor will die before the buffers are 189 | /// destroyed. 190 | /// 191 | /// This helps debug leaks. For performance this may want to become a no-op in the future. 192 | pub fn mark_wont_leak(&mut self) { 193 | native_surface_method_mut!(self mark_wont_leak ()) 194 | } 195 | 196 | pub fn gl_rasterization_context(&mut self, 197 | gl_context: Arc) 198 | -> Option> { 199 | match native_surface_method_mut!(self gl_rasterization_context (gl_context)) { 200 | Some(context) => Some(Arc::new(context)), 201 | None => None, 202 | } 203 | 204 | } 205 | 206 | /// Get the memory usage of this native surface. This memory may be allocated 207 | /// on the GPU or on the heap. 208 | pub fn get_memory_usage(&self) -> usize { 209 | // This works for now, but in the future we may want a better heuristic 210 | let size = self.get_size(); 211 | size.width as usize * size.height as usize 212 | } 213 | 214 | /// Get the size of this native surface. 215 | pub fn get_size(&self) -> Size2D { 216 | native_surface_property!(self size) 217 | } 218 | } 219 | 220 | #[derive(RustcDecodable, RustcEncodable)] 221 | pub struct MemoryBufferNativeSurface { 222 | bytes: Vec, 223 | pub size: Size2D, 224 | } 225 | 226 | impl MemoryBufferNativeSurface { 227 | pub fn new(_: &NativeDisplay, size: Size2D) -> MemoryBufferNativeSurface { 228 | MemoryBufferNativeSurface{ 229 | bytes: vec!(), 230 | size: size, 231 | } 232 | } 233 | 234 | /// This may only be called on the compositor side. 235 | #[cfg(not(target_os="android"))] 236 | pub fn bind_to_texture(&self, _: &NativeDisplay, texture: &Texture) { 237 | let _bound = texture.bind(); 238 | gl::tex_image_2d(gl::TEXTURE_2D, 239 | 0, 240 | gl::RGBA as i32, 241 | self.size.width as i32, 242 | self.size.height as i32, 243 | 0, 244 | gl::BGRA, 245 | gl::UNSIGNED_BYTE, 246 | Some(&self.bytes)); 247 | } 248 | 249 | #[cfg(target_os="android")] 250 | pub fn bind_to_texture(&self, _: &NativeDisplay, _: &Texture) { 251 | panic!("Binding a memory surface to a texture is not yet supported on Android."); 252 | } 253 | 254 | /// This may only be called on the painting side. 255 | pub fn upload(&mut self, _: &NativeDisplay, data: &[u8]) { 256 | self.bytes.clear(); 257 | self.bytes.extend_from_slice(data); 258 | } 259 | 260 | pub fn get_id(&self) -> isize { 261 | 0 262 | } 263 | 264 | pub fn destroy(&mut self, _: &NativeDisplay) { 265 | } 266 | 267 | pub fn mark_will_leak(&mut self) { 268 | } 269 | 270 | pub fn mark_wont_leak(&mut self) { 271 | } 272 | 273 | pub fn gl_rasterization_context(&mut self, 274 | _: Arc) 275 | -> Option { 276 | None 277 | } 278 | } 279 | -------------------------------------------------------------------------------- /src/platform/windows/surface.rs: -------------------------------------------------------------------------------- 1 | use skia::gl_context::PlatformDisplayData; 2 | 3 | #[derive(Copy, Clone)] 4 | pub struct NativeDisplay; 5 | 6 | #[cfg(target_os="windows")] 7 | impl NativeDisplay { 8 | pub fn new() -> NativeDisplay { 9 | NativeDisplay 10 | } 11 | 12 | pub fn platform_display_data(&self) -> PlatformDisplayData { 13 | PlatformDisplayData::new() 14 | } 15 | } 16 | 17 | -------------------------------------------------------------------------------- /src/rendergl.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Servo Project Developers. See the COPYRIGHT 2 | // file at the top-level directory of this distribution. 3 | // 4 | // Licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your 7 | // option. This file may not be copied, modified, or distributed 8 | // except according to those terms. 9 | 10 | use color::Color; 11 | use layers::Layer; 12 | use scene::Scene; 13 | use texturegl::Texture; 14 | use texturegl::Flip::VerticalFlip; 15 | use texturegl::TextureTarget::{TextureTarget2D, TextureTargetRectangle}; 16 | use tiling::Tile; 17 | use platform::surface::NativeDisplay; 18 | 19 | use euclid::{Matrix4D, Point2D, Rect, Size2D}; 20 | use libc::c_int; 21 | use gleam::gl; 22 | use gleam::gl::{GLenum, GLfloat, GLint, GLsizei, GLuint}; 23 | use std::fmt; 24 | use std::mem; 25 | use std::rc::Rc; 26 | use std::cmp::Ordering; 27 | 28 | #[derive(Copy, Clone, Debug)] 29 | pub struct ColorVertex { 30 | x: f32, 31 | y: f32, 32 | } 33 | 34 | #[cfg(feature = "heapsize")] 35 | known_heap_size!(0, ColorVertex); 36 | 37 | impl ColorVertex { 38 | pub fn new(point: Point2D) -> ColorVertex { 39 | ColorVertex { 40 | x: point.x, 41 | y: point.y, 42 | } 43 | } 44 | } 45 | 46 | #[derive(Copy, Clone, Debug)] 47 | pub struct TextureVertex { 48 | x: f32, 49 | y: f32, 50 | u: f32, 51 | v: f32, 52 | } 53 | 54 | #[cfg(feature = "heapsize")] 55 | known_heap_size!(0, TextureVertex); 56 | 57 | impl TextureVertex { 58 | pub fn new(point: Point2D, texture_coordinates: Point2D) -> TextureVertex { 59 | TextureVertex { 60 | x: point.x, 61 | y: point.y, 62 | u: texture_coordinates.x, 63 | v: texture_coordinates.y, 64 | } 65 | } 66 | } 67 | 68 | const ORTHO_NEAR_PLANE: f32 = -1000000.0; 69 | const ORTHO_FAR_PLANE: f32 = 1000000.0; 70 | 71 | fn create_ortho(scene_size: &Size2D) -> Matrix4D { 72 | Matrix4D::ortho(0.0, scene_size.width, scene_size.height, 0.0, ORTHO_NEAR_PLANE, ORTHO_FAR_PLANE) 73 | } 74 | 75 | static TEXTURE_FRAGMENT_SHADER_SOURCE: &'static str = " 76 | #ifdef GL_ES 77 | precision mediump float; 78 | #endif 79 | 80 | varying vec2 vTextureCoord; 81 | uniform samplerType uSampler; 82 | uniform float uOpacity; 83 | 84 | void main(void) { 85 | vec4 lFragColor = uOpacity * samplerFunction(uSampler, vTextureCoord); 86 | gl_FragColor = lFragColor; 87 | } 88 | "; 89 | 90 | static SOLID_COLOR_FRAGMENT_SHADER_SOURCE: &'static str = " 91 | #ifdef GL_ES 92 | precision mediump float; 93 | #endif 94 | 95 | uniform vec4 uColor; 96 | void main(void) { 97 | gl_FragColor = uColor; 98 | } 99 | "; 100 | 101 | static TEXTURE_VERTEX_SHADER_SOURCE: &'static str = " 102 | attribute vec2 aVertexPosition; 103 | attribute vec2 aVertexUv; 104 | 105 | uniform mat4 uMVMatrix; 106 | uniform mat4 uPMatrix; 107 | uniform mat4 uTextureSpaceTransform; 108 | 109 | varying vec2 vTextureCoord; 110 | 111 | void main(void) { 112 | gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 0.0, 1.0); 113 | vTextureCoord = (uTextureSpaceTransform * vec4(aVertexUv, 0., 1.)).xy; 114 | } 115 | "; 116 | 117 | static SOLID_COLOR_VERTEX_SHADER_SOURCE: &'static str = " 118 | attribute vec2 aVertexPosition; 119 | 120 | uniform mat4 uMVMatrix; 121 | uniform mat4 uPMatrix; 122 | 123 | void main(void) { 124 | gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 0.0, 1.0); 125 | } 126 | "; 127 | 128 | static TILE_DEBUG_BORDER_COLOR: Color = Color { r: 0., g: 1., b: 1., a: 1.0 }; 129 | static TILE_DEBUG_BORDER_THICKNESS: usize = 1; 130 | static LAYER_DEBUG_BORDER_COLOR: Color = Color { r: 1., g: 0.5, b: 0., a: 1.0 }; 131 | static LAYER_DEBUG_BORDER_THICKNESS: usize = 2; 132 | static LAYER_AABB_DEBUG_BORDER_COLOR: Color = Color { r: 1., g: 0.0, b: 0., a: 1.0 }; 133 | static LAYER_AABB_DEBUG_BORDER_THICKNESS: usize = 1; 134 | 135 | #[derive(Copy, Clone)] 136 | struct Buffers { 137 | quad_vertex_buffer: GLuint, 138 | line_quad_vertex_buffer: GLuint, 139 | } 140 | 141 | #[derive(Copy, Clone)] 142 | struct ShaderProgram { 143 | id: GLuint, 144 | } 145 | 146 | impl ShaderProgram { 147 | pub fn new(vertex_shader_source: &str, fragment_shader_source: &str) -> ShaderProgram { 148 | let id = gl::create_program(); 149 | gl::attach_shader(id, ShaderProgram::compile_shader(fragment_shader_source, gl::FRAGMENT_SHADER)); 150 | gl::attach_shader(id, ShaderProgram::compile_shader(vertex_shader_source, gl::VERTEX_SHADER)); 151 | gl::link_program(id); 152 | if gl::get_program_iv(id, gl::LINK_STATUS) == (0 as GLint) { 153 | panic!("Failed to compile shader program: {}", gl::get_program_info_log(id)); 154 | } 155 | 156 | ShaderProgram { 157 | id: id, 158 | } 159 | } 160 | 161 | pub fn compile_shader(source_string: &str, shader_type: GLenum) -> GLuint { 162 | let id = gl::create_shader(shader_type); 163 | gl::shader_source(id, &[ source_string.as_bytes() ]); 164 | gl::compile_shader(id); 165 | if gl::get_shader_iv(id, gl::COMPILE_STATUS) == (0 as GLint) { 166 | panic!("Failed to compile shader: {}", gl::get_shader_info_log(id)); 167 | } 168 | 169 | id 170 | } 171 | 172 | pub fn get_attribute_location(&self, name: &str) -> GLint { 173 | gl::get_attrib_location(self.id, name) 174 | } 175 | 176 | pub fn get_uniform_location(&self, name: &str) -> GLint { 177 | gl::get_uniform_location(self.id, name) 178 | } 179 | } 180 | 181 | #[derive(Copy, Clone)] 182 | struct TextureProgram { 183 | program: ShaderProgram, 184 | vertex_position_attr: c_int, 185 | vertex_uv_attr: c_int, 186 | modelview_uniform: c_int, 187 | projection_uniform: c_int, 188 | sampler_uniform: c_int, 189 | texture_space_transform_uniform: c_int, 190 | opacity_uniform: c_int, 191 | } 192 | 193 | impl TextureProgram { 194 | fn new(sampler_function: &str, sampler_type: &str) -> TextureProgram { 195 | let fragment_shader_source 196 | = fmt::format(format_args!("#define samplerFunction {}\n#define samplerType {}\n{}", 197 | sampler_function, 198 | sampler_type, 199 | TEXTURE_FRAGMENT_SHADER_SOURCE)); 200 | let program = ShaderProgram::new(TEXTURE_VERTEX_SHADER_SOURCE, &fragment_shader_source); 201 | TextureProgram { 202 | program: program, 203 | vertex_position_attr: program.get_attribute_location("aVertexPosition"), 204 | vertex_uv_attr: program.get_attribute_location("aVertexUv"), 205 | modelview_uniform: program.get_uniform_location("uMVMatrix"), 206 | projection_uniform: program.get_uniform_location("uPMatrix"), 207 | sampler_uniform: program.get_uniform_location("uSampler"), 208 | texture_space_transform_uniform: program.get_uniform_location("uTextureSpaceTransform"), 209 | opacity_uniform: program.get_uniform_location("uOpacity"), 210 | } 211 | } 212 | 213 | fn bind_uniforms_and_attributes(&self, 214 | vertices: &[TextureVertex; 4], 215 | transform: &Matrix4D, 216 | projection_matrix: &Matrix4D, 217 | texture_space_transform: &Matrix4D, 218 | buffers: &Buffers, 219 | opacity: f32) { 220 | gl::uniform_1i(self.sampler_uniform, 0); 221 | gl::uniform_matrix_4fv(self.modelview_uniform, 222 | false, 223 | &transform.to_row_major_array()); 224 | gl::uniform_matrix_4fv(self.projection_uniform, 225 | false, 226 | &projection_matrix.to_row_major_array()); 227 | 228 | let vertex_size = mem::size_of::(); 229 | 230 | gl::bind_buffer(gl::ARRAY_BUFFER, buffers.quad_vertex_buffer); 231 | gl::buffer_data(gl::ARRAY_BUFFER, vertices, gl::DYNAMIC_DRAW); 232 | gl::vertex_attrib_pointer_f32(self.vertex_position_attr as GLuint,2, false, vertex_size as i32, 0); 233 | gl::vertex_attrib_pointer_f32(self.vertex_uv_attr as GLuint, 2, false, vertex_size as i32, 8); 234 | 235 | gl::uniform_matrix_4fv(self.texture_space_transform_uniform, 236 | false, 237 | &texture_space_transform.to_row_major_array()); 238 | 239 | gl::uniform_1f(self.opacity_uniform, opacity); 240 | } 241 | 242 | fn enable_attribute_arrays(&self) { 243 | gl::enable_vertex_attrib_array(self.vertex_position_attr as GLuint); 244 | gl::enable_vertex_attrib_array(self.vertex_uv_attr as GLuint); 245 | } 246 | 247 | fn disable_attribute_arrays(&self) { 248 | gl::disable_vertex_attrib_array(self.vertex_uv_attr as GLuint); 249 | gl::disable_vertex_attrib_array(self.vertex_position_attr as GLuint); 250 | } 251 | 252 | fn create_2d_program() -> TextureProgram { 253 | TextureProgram::new("texture2D", "sampler2D") 254 | } 255 | 256 | #[cfg(target_os="macos")] 257 | fn create_rectangle_program_if_necessary() -> Option { 258 | gl::enable(gl::TEXTURE_RECTANGLE_ARB); 259 | Some(TextureProgram::new("texture2DRect", "sampler2DRect")) 260 | } 261 | 262 | #[cfg(not(target_os="macos"))] 263 | fn create_rectangle_program_if_necessary() -> Option { 264 | None 265 | } 266 | } 267 | 268 | #[derive(Copy, Clone)] 269 | struct SolidColorProgram { 270 | program: ShaderProgram, 271 | vertex_position_attr: c_int, 272 | modelview_uniform: c_int, 273 | projection_uniform: c_int, 274 | color_uniform: c_int, 275 | } 276 | 277 | impl SolidColorProgram { 278 | fn new() -> SolidColorProgram { 279 | let program = ShaderProgram::new(SOLID_COLOR_VERTEX_SHADER_SOURCE, 280 | SOLID_COLOR_FRAGMENT_SHADER_SOURCE); 281 | SolidColorProgram { 282 | program: program, 283 | vertex_position_attr: program.get_attribute_location("aVertexPosition"), 284 | modelview_uniform: program.get_uniform_location("uMVMatrix"), 285 | projection_uniform: program.get_uniform_location("uPMatrix"), 286 | color_uniform: program.get_uniform_location("uColor"), 287 | } 288 | } 289 | 290 | fn bind_uniforms_and_attributes_common(&self, 291 | transform: &Matrix4D, 292 | projection_matrix: &Matrix4D, 293 | color: &Color) { 294 | gl::uniform_matrix_4fv(self.modelview_uniform, 295 | false, 296 | &transform.to_row_major_array()); 297 | gl::uniform_matrix_4fv(self.projection_uniform, 298 | false, 299 | &projection_matrix.to_row_major_array()); 300 | gl::uniform_4f(self.color_uniform, 301 | color.r as GLfloat, 302 | color.g as GLfloat, 303 | color.b as GLfloat, 304 | color.a as GLfloat); 305 | } 306 | 307 | fn bind_uniforms_and_attributes_for_lines(&self, 308 | vertices: &[ColorVertex; 5], 309 | transform: &Matrix4D, 310 | projection_matrix: &Matrix4D, 311 | buffers: &Buffers, 312 | color: &Color) { 313 | self.bind_uniforms_and_attributes_common(transform, projection_matrix, color); 314 | 315 | gl::bind_buffer(gl::ARRAY_BUFFER, buffers.line_quad_vertex_buffer); 316 | gl::buffer_data(gl::ARRAY_BUFFER, vertices, gl::DYNAMIC_DRAW); 317 | gl::vertex_attrib_pointer_f32(self.vertex_position_attr as GLuint, 2, false, 0, 0); 318 | } 319 | 320 | fn bind_uniforms_and_attributes_for_quad(&self, 321 | vertices: &[ColorVertex; 4], 322 | transform: &Matrix4D, 323 | projection_matrix: &Matrix4D, 324 | buffers: &Buffers, 325 | color: &Color) { 326 | self.bind_uniforms_and_attributes_common(transform, projection_matrix, color); 327 | 328 | gl::bind_buffer(gl::ARRAY_BUFFER, buffers.quad_vertex_buffer); 329 | gl::buffer_data(gl::ARRAY_BUFFER, vertices, gl::DYNAMIC_DRAW); 330 | gl::vertex_attrib_pointer_f32(self.vertex_position_attr as GLuint, 2, false, 0, 0); 331 | } 332 | 333 | fn enable_attribute_arrays(&self) { 334 | gl::enable_vertex_attrib_array(self.vertex_position_attr as GLuint); 335 | } 336 | 337 | fn disable_attribute_arrays(&self) { 338 | gl::disable_vertex_attrib_array(self.vertex_position_attr as GLuint); 339 | } 340 | } 341 | 342 | struct RenderContextChild { 343 | layer: Option>>, 344 | context: Option>, 345 | paint_order: usize, 346 | z_center: f32, 347 | } 348 | 349 | pub struct RenderContext3D{ 350 | children: Vec>, 351 | clip_rect: Option>, 352 | } 353 | 354 | impl RenderContext3D { 355 | fn new(layer: Rc>) -> RenderContext3D { 356 | let mut render_context = RenderContext3D { 357 | children: vec!(), 358 | clip_rect: RenderContext3D::calculate_context_clip(layer.clone(), None), 359 | }; 360 | layer.build(&mut render_context); 361 | render_context.sort_children(); 362 | render_context 363 | } 364 | 365 | fn build_child(layer: Rc>, 366 | parent_clip_rect: Option>) 367 | -> Option> { 368 | let clip_rect = RenderContext3D::calculate_context_clip(layer.clone(), parent_clip_rect); 369 | if let Some(ref clip_rect) = clip_rect { 370 | if clip_rect.is_empty() { 371 | return None; 372 | } 373 | } 374 | 375 | let mut render_context = RenderContext3D { 376 | children: vec!(), 377 | clip_rect: clip_rect, 378 | }; 379 | 380 | for child in layer.children().iter() { 381 | child.build(&mut render_context); 382 | } 383 | 384 | render_context.sort_children(); 385 | Some(render_context) 386 | } 387 | 388 | fn sort_children(&mut self) { 389 | // TODO(gw): This is basically what FF does, which breaks badly 390 | // when there are intersecting polygons. Need to split polygons 391 | // to handle this case correctly (Blink uses a BSP tree). 392 | self.children.sort_by(|a, b| { 393 | if a.z_center < b.z_center { 394 | Ordering::Less 395 | } else if a.z_center > b.z_center { 396 | Ordering::Greater 397 | } else if a.paint_order < b.paint_order { 398 | Ordering::Less 399 | } else if a.paint_order > b.paint_order { 400 | Ordering::Greater 401 | } else { 402 | Ordering::Equal 403 | } 404 | }); 405 | } 406 | 407 | fn calculate_context_clip(layer: Rc>, 408 | parent_clip_rect: Option>) 409 | -> Option> { 410 | // TODO(gw): This doesn't work for iframes that are transformed. 411 | if !*layer.masks_to_bounds.borrow() { 412 | return parent_clip_rect; 413 | } 414 | 415 | let layer_clip = match layer.transform_state.borrow().screen_rect.as_ref() { 416 | Some(screen_rect) => screen_rect.rect, 417 | None => return Some(Rect::zero()), // Layer is entirely clipped away. 418 | }; 419 | 420 | match parent_clip_rect { 421 | Some(parent_clip_rect) => match layer_clip.intersection(&parent_clip_rect) { 422 | Some(intersected_clip) => Some(intersected_clip), 423 | None => Some(Rect::zero()), // No intersection. 424 | }, 425 | None => Some(layer_clip), 426 | } 427 | } 428 | 429 | fn add_child(&mut self, 430 | layer: Option>>, 431 | child_context: Option>, 432 | z_center: f32) { 433 | let paint_order = self.children.len(); 434 | self.children.push(RenderContextChild { 435 | layer: layer, 436 | context: child_context, 437 | z_center: z_center, 438 | paint_order: paint_order, 439 | }); 440 | } 441 | } 442 | 443 | pub trait RenderContext3DBuilder { 444 | fn build(&self, current_context: &mut RenderContext3D); 445 | } 446 | 447 | impl RenderContext3DBuilder for Rc> { 448 | fn build(&self, current_context: &mut RenderContext3D) { 449 | let (layer, z_center) = match self.transform_state.borrow().screen_rect { 450 | Some(ref rect) => (Some(self.clone()), rect.z_center), 451 | None => (None, 0.), // Layer is entirely clipped. 452 | }; 453 | 454 | if !self.children.borrow().is_empty() && self.establishes_3d_context { 455 | let child_context = 456 | RenderContext3D::build_child(self.clone(), current_context.clip_rect); 457 | if child_context.is_some() { 458 | current_context.add_child(layer, child_context, z_center); 459 | return; 460 | } 461 | }; 462 | 463 | // If we are completely clipped out, don't add anything to this context. 464 | if layer.is_none() { 465 | return; 466 | } 467 | 468 | current_context.add_child(layer, None, z_center); 469 | 470 | for child in self.children().iter() { 471 | child.build(current_context); 472 | } 473 | } 474 | } 475 | 476 | #[derive(Copy, Clone)] 477 | pub struct RenderContext { 478 | texture_2d_program: TextureProgram, 479 | texture_rectangle_program: Option, 480 | solid_color_program: SolidColorProgram, 481 | buffers: Buffers, 482 | 483 | /// The platform-specific graphics context. 484 | compositing_display: NativeDisplay, 485 | 486 | /// Whether to show lines at border and tile boundaries for debugging purposes. 487 | show_debug_borders: bool, 488 | 489 | force_near_texture_filter: bool, 490 | } 491 | 492 | impl RenderContext { 493 | pub fn new(compositing_display: NativeDisplay, 494 | show_debug_borders: bool, 495 | force_near_texture_filter: bool) -> RenderContext { 496 | gl::enable(gl::TEXTURE_2D); 497 | 498 | // Each layer uses premultiplied alpha! 499 | gl::enable(gl::BLEND); 500 | gl::blend_func(gl::ONE, gl::ONE_MINUS_SRC_ALPHA); 501 | 502 | let texture_2d_program = TextureProgram::create_2d_program(); 503 | let solid_color_program = SolidColorProgram::new(); 504 | let texture_rectangle_program = TextureProgram::create_rectangle_program_if_necessary(); 505 | 506 | RenderContext { 507 | texture_2d_program: texture_2d_program, 508 | texture_rectangle_program: texture_rectangle_program, 509 | solid_color_program: solid_color_program, 510 | buffers: RenderContext::init_buffers(), 511 | compositing_display: compositing_display, 512 | show_debug_borders: show_debug_borders, 513 | force_near_texture_filter: force_near_texture_filter, 514 | } 515 | } 516 | 517 | fn init_buffers() -> Buffers { 518 | let quad_vertex_buffer = gl::gen_buffers(1)[0]; 519 | gl::bind_buffer(gl::ARRAY_BUFFER, quad_vertex_buffer); 520 | 521 | let line_quad_vertex_buffer = gl::gen_buffers(1)[0]; 522 | gl::bind_buffer(gl::ARRAY_BUFFER, line_quad_vertex_buffer); 523 | 524 | Buffers { 525 | quad_vertex_buffer: quad_vertex_buffer, 526 | line_quad_vertex_buffer: line_quad_vertex_buffer, 527 | } 528 | } 529 | 530 | fn bind_and_render_solid_quad(&self, 531 | vertices: &[ColorVertex; 4], 532 | transform: &Matrix4D, 533 | projection: &Matrix4D, 534 | color: &Color) { 535 | self.solid_color_program.enable_attribute_arrays(); 536 | gl::use_program(self.solid_color_program.program.id); 537 | self.solid_color_program.bind_uniforms_and_attributes_for_quad(vertices, 538 | transform, 539 | projection, 540 | &self.buffers, 541 | color); 542 | gl::draw_arrays(gl::TRIANGLE_STRIP, 0, 4); 543 | self.solid_color_program.disable_attribute_arrays(); 544 | } 545 | 546 | fn bind_and_render_quad(&self, 547 | vertices: &[TextureVertex; 4], 548 | texture: &Texture, 549 | transform: &Matrix4D, 550 | projection_matrix: &Matrix4D, 551 | opacity: f32) { 552 | let mut texture_coordinates_need_to_be_scaled_by_size = false; 553 | let program = match texture.target { 554 | TextureTarget2D => self.texture_2d_program, 555 | TextureTargetRectangle => match self.texture_rectangle_program { 556 | Some(program) => { 557 | texture_coordinates_need_to_be_scaled_by_size = true; 558 | program 559 | } 560 | None => panic!("There is no shader program for texture rectangle"), 561 | }, 562 | }; 563 | program.enable_attribute_arrays(); 564 | 565 | gl::use_program(program.program.id); 566 | gl::active_texture(gl::TEXTURE0); 567 | gl::bind_texture(texture.target.as_gl_target(), texture.native_texture()); 568 | 569 | let filter_mode = if self.force_near_texture_filter { 570 | gl::NEAREST 571 | } else { 572 | gl::LINEAR 573 | } as GLint; 574 | gl::tex_parameter_i(texture.target.as_gl_target(), gl::TEXTURE_MAG_FILTER, filter_mode); 575 | gl::tex_parameter_i(texture.target.as_gl_target(), gl::TEXTURE_MIN_FILTER, filter_mode); 576 | 577 | // We calculate a transformation matrix for the texture coordinates 578 | // which is useful for flipping the texture vertically or scaling the 579 | // coordinates when dealing with GL_ARB_texture_rectangle. 580 | let mut texture_transform = Matrix4D::identity(); 581 | if texture.flip == VerticalFlip { 582 | texture_transform = texture_transform.pre_scaled(1.0, -1.0, 1.0); 583 | } 584 | if texture_coordinates_need_to_be_scaled_by_size { 585 | texture_transform = texture_transform.pre_scaled( 586 | texture.size.width as f32, texture.size.height as f32, 1.0); 587 | } 588 | if texture.flip == VerticalFlip { 589 | texture_transform = texture_transform.pre_translated(0.0, -1.0, 0.0); 590 | } 591 | 592 | program.bind_uniforms_and_attributes(vertices, 593 | transform, 594 | &projection_matrix, 595 | &texture_transform, 596 | &self.buffers, 597 | opacity); 598 | 599 | // Draw! 600 | gl::draw_arrays(gl::TRIANGLE_STRIP, 0, 4); 601 | gl::bind_texture(gl::TEXTURE_2D, 0); 602 | 603 | gl::bind_texture(texture.target.as_gl_target(), 0); 604 | program.disable_attribute_arrays() 605 | } 606 | 607 | pub fn bind_and_render_quad_lines(&self, 608 | vertices: &[ColorVertex; 5], 609 | transform: &Matrix4D, 610 | projection: &Matrix4D, 611 | color: &Color, 612 | line_thickness: usize) { 613 | self.solid_color_program.enable_attribute_arrays(); 614 | gl::use_program(self.solid_color_program.program.id); 615 | self.solid_color_program.bind_uniforms_and_attributes_for_lines(vertices, 616 | transform, 617 | projection, 618 | &self.buffers, 619 | color); 620 | gl::line_width(line_thickness as GLfloat); 621 | gl::draw_arrays(gl::LINE_STRIP, 0, 5); 622 | self.solid_color_program.disable_attribute_arrays(); 623 | } 624 | 625 | fn render_layer(&self, 626 | layer: Rc>, 627 | transform: &Matrix4D, 628 | projection: &Matrix4D, 629 | clip_rect: Option>, 630 | gfx_context: &NativeDisplay) { 631 | let ts = layer.transform_state.borrow(); 632 | let transform = transform.pre_mul(&ts.final_transform); 633 | let background_color = *layer.background_color.borrow(); 634 | 635 | // Create native textures for this layer 636 | layer.create_textures(gfx_context); 637 | 638 | let layer_rect = clip_rect.map_or(ts.world_rect, |clip_rect| { 639 | match clip_rect.intersection(&ts.world_rect) { 640 | Some(layer_rect) => layer_rect, 641 | None => Rect::zero(), 642 | } 643 | }); 644 | 645 | if layer_rect.is_empty() { 646 | return; 647 | } 648 | 649 | if background_color.a != 0.0 { 650 | let bg_vertices = [ 651 | ColorVertex::new(layer_rect.origin), 652 | ColorVertex::new(layer_rect.top_right()), 653 | ColorVertex::new(layer_rect.bottom_left()), 654 | ColorVertex::new(layer_rect.bottom_right()), 655 | ]; 656 | 657 | self.bind_and_render_solid_quad(&bg_vertices, 658 | &transform, 659 | &projection, 660 | &background_color); 661 | } 662 | 663 | layer.do_for_all_tiles(|tile: &Tile| { 664 | self.render_tile(tile, 665 | &ts.world_rect.origin, 666 | &transform, 667 | projection, 668 | clip_rect, 669 | *layer.opacity.borrow()); 670 | }); 671 | 672 | if self.show_debug_borders { 673 | let debug_vertices = [ 674 | ColorVertex::new(layer_rect.origin), 675 | ColorVertex::new(layer_rect.top_right()), 676 | ColorVertex::new(layer_rect.bottom_right()), 677 | ColorVertex::new(layer_rect.bottom_left()), 678 | ColorVertex::new(layer_rect.origin), 679 | ]; 680 | self.bind_and_render_quad_lines(&debug_vertices, 681 | &transform, 682 | projection, 683 | &LAYER_DEBUG_BORDER_COLOR, 684 | LAYER_DEBUG_BORDER_THICKNESS); 685 | 686 | let aabb = ts.screen_rect.as_ref().unwrap().rect; 687 | let debug_vertices = [ 688 | ColorVertex::new(aabb.origin), 689 | ColorVertex::new(aabb.top_right()), 690 | ColorVertex::new(aabb.bottom_right()), 691 | ColorVertex::new(aabb.bottom_left()), 692 | ColorVertex::new(aabb.origin), 693 | ]; 694 | self.bind_and_render_quad_lines(&debug_vertices, 695 | &Matrix4D::identity(), 696 | projection, 697 | &LAYER_AABB_DEBUG_BORDER_COLOR, 698 | LAYER_AABB_DEBUG_BORDER_THICKNESS); 699 | } 700 | } 701 | 702 | fn render_tile(&self, 703 | tile: &Tile, 704 | layer_origin: &Point2D, 705 | transform: &Matrix4D, 706 | projection: &Matrix4D, 707 | clip_rect: Option>, 708 | opacity: f32) { 709 | if tile.texture.is_zero() || !tile.bounds.is_some() { 710 | return; 711 | } 712 | 713 | let tile_rect = tile.bounds.unwrap().to_untyped().translate(layer_origin); 714 | let clipped_tile_rect = clip_rect.map_or(tile_rect, |clip_rect| { 715 | match clip_rect.intersection(&tile_rect) { 716 | Some(clipped_tile_rect) => clipped_tile_rect, 717 | None => Rect::zero(), 718 | } 719 | }); 720 | 721 | if clipped_tile_rect.is_empty() { 722 | return; 723 | } 724 | 725 | let texture_rect_origin = clipped_tile_rect.origin - tile_rect.origin; 726 | let texture_rect = Rect::new( 727 | Point2D::new(texture_rect_origin.x / tile_rect.size.width, 728 | texture_rect_origin.y / tile_rect.size.height), 729 | Size2D::new(clipped_tile_rect.size.width / tile_rect.size.width, 730 | clipped_tile_rect.size.height / tile_rect.size.height)); 731 | 732 | let tile_vertices: [TextureVertex; 4] = [ 733 | TextureVertex::new(clipped_tile_rect.origin, texture_rect.origin), 734 | TextureVertex::new(clipped_tile_rect.top_right(), texture_rect.top_right()), 735 | TextureVertex::new(clipped_tile_rect.bottom_left(), texture_rect.bottom_left()), 736 | TextureVertex::new(clipped_tile_rect.bottom_right(), texture_rect.bottom_right()), 737 | ]; 738 | 739 | if self.show_debug_borders { 740 | let debug_vertices = [ 741 | // The weird ordering is converting from triangle-strip into a line-strip. 742 | ColorVertex::new(clipped_tile_rect.origin), 743 | ColorVertex::new(clipped_tile_rect.top_right()), 744 | ColorVertex::new(clipped_tile_rect.bottom_right()), 745 | ColorVertex::new(clipped_tile_rect.bottom_left()), 746 | ColorVertex::new(clipped_tile_rect.origin), 747 | ]; 748 | self.bind_and_render_quad_lines(&debug_vertices, 749 | &transform, 750 | projection, 751 | &TILE_DEBUG_BORDER_COLOR, 752 | TILE_DEBUG_BORDER_THICKNESS); 753 | } 754 | 755 | self.bind_and_render_quad(&tile_vertices, 756 | &tile.texture, 757 | &transform, 758 | projection, 759 | opacity); 760 | } 761 | 762 | fn render_3d_context(&self, 763 | context: &RenderContext3D, 764 | transform: &Matrix4D, 765 | projection: &Matrix4D, 766 | gfx_context: &NativeDisplay) { 767 | if context.children.is_empty() { 768 | return; 769 | } 770 | 771 | // Clear the z-buffer for each 3d render context 772 | // TODO(gw): Potential optimization here if there are no 773 | // layer intersections to disable z-buffering and 774 | // avoid clear. 775 | gl::clear(gl::DEPTH_BUFFER_BIT); 776 | 777 | // Render child layers with z-testing. 778 | for child in &context.children { 779 | if let Some(ref layer) = child.layer { 780 | // TODO(gw): Disable clipping on 3d layers for now. 781 | // Need to implement proper polygon clipping to 782 | // make this work correctly. 783 | let clip_rect = context.clip_rect.and_then(|cr| { 784 | let m = layer.transform_state.borrow().final_transform; 785 | 786 | // See https://drafts.csswg.org/css-transforms/#2d-matrix 787 | let is_3d_transform = m.m31 != 0.0 || m.m32 != 0.0 || 788 | m.m13 != 0.0 || m.m23 != 0.0 || 789 | m.m43 != 0.0 || m.m14 != 0.0 || 790 | m.m24 != 0.0 || m.m34 != 0.0 || 791 | m.m33 != 1.0 || m.m44 != 1.0; 792 | 793 | if is_3d_transform { 794 | None 795 | } else { 796 | // If the transform is 2d, invert it and back-transform 797 | // the clip rect into world space. 798 | let transform = m.inverse().unwrap(); 799 | let xform_2d = transform.to_2d(); 800 | Some(xform_2d.transform_rect(&cr)) 801 | } 802 | 803 | }); 804 | self.render_layer(layer.clone(), 805 | transform, 806 | projection, 807 | clip_rect, 808 | gfx_context); 809 | } 810 | 811 | if let Some(ref context) = child.context { 812 | self.render_3d_context(context, 813 | transform, 814 | projection, 815 | gfx_context); 816 | 817 | } 818 | } 819 | } 820 | } 821 | 822 | pub fn render_scene(root_layer: Rc>, 823 | render_context: RenderContext, 824 | scene: &Scene) { 825 | // Set the viewport. 826 | let v = scene.viewport.to_untyped(); 827 | gl::viewport(v.origin.x as GLint, v.origin.y as GLint, 828 | v.size.width as GLsizei, v.size.height as GLsizei); 829 | 830 | // Enable depth testing for 3d transforms. Set z-mode to LESS-EQUAL 831 | // so that layers with equal Z are able to paint correctly in 832 | // the order they are specified. 833 | gl::enable(gl::DEPTH_TEST); 834 | gl::clear_color(1.0, 1.0, 1.0, 1.0); 835 | gl::clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT); 836 | gl::depth_func(gl::LEQUAL); 837 | 838 | // Set up the initial modelview matrix. 839 | let transform = Matrix4D::identity().pre_scaled(scene.scale.get(), scene.scale.get(), 1.0); 840 | let projection = create_ortho(&scene.viewport.size.to_untyped()); 841 | 842 | // Build the list of render items 843 | render_context.render_3d_context(&RenderContext3D::new(root_layer.clone()), 844 | &transform, 845 | &projection, 846 | &render_context.compositing_display); 847 | } 848 | -------------------------------------------------------------------------------- /src/scene.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Servo Project Developers. See the COPYRIGHT 2 | // file at the top-level directory of this distribution. 3 | // 4 | // Licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your 7 | // option. This file may not be copied, modified, or distributed 8 | // except according to those terms. 9 | 10 | use euclid::rect::TypedRect; 11 | use euclid::scale_factor::ScaleFactor; 12 | use euclid::size::TypedSize2D; 13 | use euclid::point::TypedPoint2D; 14 | use geometry::{DevicePixel, LayerPixel}; 15 | use layers::{BufferRequest, Layer, LayerBuffer}; 16 | use std::rc::Rc; 17 | 18 | pub struct Scene { 19 | pub root: Option>>, 20 | pub viewport: TypedRect, 21 | 22 | /// The scene scale, to allow for zooming and high-resolution painting. 23 | pub scale: ScaleFactor, 24 | } 25 | 26 | impl Scene { 27 | pub fn new(viewport: TypedRect) -> Scene { 28 | Scene { 29 | root: None, 30 | viewport: viewport, 31 | scale: ScaleFactor::new(1.0), 32 | } 33 | } 34 | 35 | pub fn get_buffer_requests_for_layer(&mut self, 36 | layer: Rc>, 37 | dirty_rect: TypedRect, 38 | viewport_rect: TypedRect, 39 | layers_and_requests: &mut Vec<(Rc>, 40 | Vec)>, 41 | unused_buffers: &mut Vec>) { 42 | // Get buffers for this layer, in global (screen) coordinates. 43 | let requests = layer.get_buffer_requests(dirty_rect, viewport_rect, self.scale); 44 | if !requests.is_empty() { 45 | layers_and_requests.push((layer.clone(), requests)); 46 | } 47 | unused_buffers.extend(layer.collect_unused_buffers().into_iter()); 48 | 49 | // If this layer masks its children, we don't need to ask for tiles outside the 50 | // boundaries of this layer. 51 | let child_dirty_rect = if !*layer.masks_to_bounds.borrow() { 52 | dirty_rect 53 | } else { 54 | match layer.transform_state.borrow().screen_rect { 55 | Some(ref screen_rect) => { 56 | match dirty_rect.to_untyped().intersection(&screen_rect.rect) { 57 | Some(ref child_dirty_rect) => TypedRect::from_untyped(child_dirty_rect), 58 | None => return, // The layer is entirely outside the dirty rect. 59 | } 60 | }, 61 | None => return, // The layer is entirely clipped. 62 | } 63 | }; 64 | 65 | for kid in layer.children().iter() { 66 | self.get_buffer_requests_for_layer(kid.clone(), 67 | child_dirty_rect, 68 | viewport_rect, 69 | layers_and_requests, 70 | unused_buffers); 71 | } 72 | } 73 | 74 | pub fn get_buffer_requests(&mut self, 75 | requests: &mut Vec<(Rc>, Vec)>, 76 | unused_buffers: &mut Vec>) { 77 | let root_layer = match self.root { 78 | Some(ref root_layer) => root_layer.clone(), 79 | None => return, 80 | }; 81 | 82 | self.get_buffer_requests_for_layer(root_layer.clone(), 83 | *root_layer.bounds.borrow(), 84 | *root_layer.bounds.borrow(), 85 | requests, 86 | unused_buffers); 87 | } 88 | 89 | pub fn mark_layer_contents_as_changed_recursively_for_layer(&self, layer: Rc>) { 90 | layer.contents_changed(); 91 | for kid in layer.children().iter() { 92 | self.mark_layer_contents_as_changed_recursively_for_layer(kid.clone()); 93 | } 94 | } 95 | 96 | pub fn mark_layer_contents_as_changed_recursively(&self) { 97 | let root_layer = match self.root { 98 | Some(ref root_layer) => root_layer.clone(), 99 | None => return, 100 | }; 101 | self.mark_layer_contents_as_changed_recursively_for_layer(root_layer); 102 | } 103 | 104 | pub fn set_root_layer_size(&self, new_size: TypedSize2D) { 105 | if let Some(ref root_layer) = self.root { 106 | *root_layer.bounds.borrow_mut() = TypedRect::new(TypedPoint2D::zero(), 107 | new_size / self.scale); 108 | } 109 | } 110 | 111 | /// Calculate the amount of memory used by all the layers in the 112 | /// scene graph. The memory may be allocated on the heap or in GPU memory. 113 | pub fn get_memory_usage(&self) -> usize { 114 | match self.root { 115 | Some(ref root_layer) => root_layer.get_memory_usage(), 116 | None => 0, 117 | } 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /src/texturegl.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Servo Project Developers. See the COPYRIGHT 2 | // file at the top-level directory of this distribution. 3 | // 4 | // Licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your 7 | // option. This file may not be copied, modified, or distributed 8 | // except according to those terms. 9 | 10 | //! OpenGL-specific implementation of texturing. 11 | 12 | use layers::LayerBuffer; 13 | 14 | use euclid::size::Size2D; 15 | use gleam::gl; 16 | use gleam::gl::{GLenum, GLint, GLuint}; 17 | 18 | #[derive(Copy, Clone)] 19 | pub enum Format { 20 | ARGB32Format, 21 | RGB24Format 22 | } 23 | 24 | #[cfg(feature = "heapsize")] 25 | known_heap_size!(0, Format); 26 | 27 | #[derive(Copy, Clone)] 28 | pub enum FilterMode { 29 | Nearest, 30 | Linear 31 | } 32 | 33 | #[cfg(feature = "heapsize")] 34 | known_heap_size!(0, FilterMode); 35 | 36 | /// The texture target. 37 | #[derive(Copy, Clone)] 38 | pub enum TextureTarget { 39 | /// TEXTURE_2D. 40 | TextureTarget2D, 41 | /// TEXTURE_RECTANGLE_ARB, with the size included. 42 | TextureTargetRectangle, 43 | } 44 | 45 | #[cfg(feature = "heapsize")] 46 | known_heap_size!(0, TextureTarget); 47 | 48 | impl TextureTarget { 49 | 50 | #[cfg(not(target_os = "android"))] 51 | pub fn as_gl_target(self) -> GLenum { 52 | match self { 53 | TextureTarget::TextureTarget2D => gl::TEXTURE_2D, 54 | TextureTarget::TextureTargetRectangle => gl::TEXTURE_RECTANGLE_ARB, 55 | } 56 | } 57 | 58 | #[cfg(target_os = "android")] 59 | pub fn as_gl_target(self) -> GLenum { 60 | match self { 61 | TextureTarget::TextureTarget2D => gl::TEXTURE_2D, 62 | TextureTarget::TextureTargetRectangle => panic!("android doesn't supported rectangle targets"), 63 | } 64 | } 65 | } 66 | 67 | /// A texture. 68 | /// 69 | /// TODO: Include client storage here for `GL_CLIENT_STORAGE_APPLE`. 70 | pub struct Texture { 71 | /// The OpenGL texture ID. 72 | id: GLuint, 73 | 74 | /// The texture target. 75 | pub target: TextureTarget, 76 | 77 | /// Whether this texture is weak. Weak textures will not be cleaned up by 78 | /// the destructor. 79 | weak: bool, 80 | 81 | // Whether or not this texture needs to be flipped upon display. 82 | pub flip: Flip, 83 | 84 | // The size of this texture in device pixels. 85 | pub size: Size2D 86 | } 87 | 88 | impl Drop for Texture { 89 | fn drop(&mut self) { 90 | if !self.weak { 91 | gl::delete_textures(&[ self.id ]) 92 | } 93 | } 94 | } 95 | 96 | impl Texture { 97 | pub fn zero() -> Texture { 98 | Texture { 99 | id: 0, 100 | target: TextureTarget::TextureTarget2D, 101 | weak: true, 102 | flip: Flip::NoFlip, 103 | size: Size2D::new(0, 0), 104 | } 105 | } 106 | pub fn is_zero(&self) -> bool { 107 | self.id == 0 108 | } 109 | } 110 | 111 | /// Encapsulates a bound texture. This ensures that the texture is unbound 112 | /// properly. 113 | pub struct BoundTexture { 114 | pub target: TextureTarget 115 | } 116 | 117 | impl Drop for BoundTexture { 118 | fn drop(&mut self) { 119 | gl::bind_texture(self.target.as_gl_target(), 0); 120 | } 121 | } 122 | 123 | impl Texture { 124 | /// Creates a new blank texture. 125 | pub fn new(target: TextureTarget, size: Size2D) -> Texture { 126 | let this = Texture { 127 | id: gl::gen_textures(1)[0], 128 | target: target, 129 | weak: false, 130 | flip: Flip::NoFlip, 131 | size: size, 132 | }; 133 | this.set_default_params(); 134 | this 135 | } 136 | 137 | pub fn new_with_buffer(buffer: &Box) -> Texture { 138 | let (flip, target) = Texture::texture_flip_and_target(buffer.painted_with_cpu); 139 | let mut texture = Texture::new(target, buffer.screen_pos.size); 140 | texture.flip = flip; 141 | texture 142 | } 143 | 144 | // Returns whether the layer should be vertically flipped. 145 | #[cfg(target_os="macos")] 146 | pub fn texture_flip_and_target(cpu_painting: bool) -> (Flip, TextureTarget) { 147 | let flip = if cpu_painting { 148 | Flip::NoFlip 149 | } else { 150 | Flip::VerticalFlip 151 | }; 152 | 153 | (flip, TextureTarget::TextureTargetRectangle) 154 | } 155 | 156 | #[cfg(target_os="android")] 157 | pub fn texture_flip_and_target(cpu_painting: bool) -> (Flip, TextureTarget) { 158 | let flip = if cpu_painting { 159 | Flip::NoFlip 160 | } else { 161 | Flip::VerticalFlip 162 | }; 163 | 164 | (flip, TextureTarget::TextureTarget2D) 165 | } 166 | 167 | #[cfg(target_os="linux")] 168 | pub fn texture_flip_and_target(_: bool) -> (Flip, TextureTarget) { 169 | (Flip::NoFlip, TextureTarget::TextureTarget2D) 170 | } 171 | 172 | #[cfg(target_os="windows")] 173 | pub fn texture_flip_and_target(_: bool) -> (Flip, TextureTarget) { 174 | (Flip::NoFlip, TextureTarget::TextureTarget2D) 175 | } 176 | 177 | /// Returns the raw OpenGL texture underlying this texture. 178 | pub fn native_texture(&self) -> GLuint { 179 | self.id 180 | } 181 | 182 | /// Sets default parameters for this texture. 183 | fn set_default_params(&self) { 184 | let _bound_texture = self.bind(); 185 | gl::tex_parameter_i(self.target.as_gl_target(), gl::TEXTURE_MAG_FILTER, gl::LINEAR as GLint); 186 | gl::tex_parameter_i(self.target.as_gl_target(), gl::TEXTURE_MIN_FILTER, gl::LINEAR as GLint); 187 | gl::tex_parameter_i(self.target.as_gl_target(), gl::TEXTURE_WRAP_S, gl::CLAMP_TO_EDGE as GLint); 188 | gl::tex_parameter_i(self.target.as_gl_target(), gl::TEXTURE_WRAP_T, gl::CLAMP_TO_EDGE as GLint); 189 | } 190 | 191 | /// Sets the filter mode for this texture. 192 | pub fn set_filter_mode(&self, mode: FilterMode) { 193 | let _bound_texture = self.bind(); 194 | let gl_mode = match mode { 195 | FilterMode::Nearest => gl::NEAREST, 196 | FilterMode::Linear => gl::LINEAR, 197 | } as GLint; 198 | gl::tex_parameter_i(self.target.as_gl_target(), gl::TEXTURE_MAG_FILTER, gl_mode); 199 | gl::tex_parameter_i(self.target.as_gl_target(), gl::TEXTURE_MIN_FILTER, gl_mode); 200 | } 201 | 202 | /// Binds the texture to the current context. 203 | pub fn bind(&self) -> BoundTexture { 204 | gl::bind_texture(self.target.as_gl_target(), self.id); 205 | 206 | BoundTexture { 207 | target: self.target, 208 | } 209 | } 210 | } 211 | 212 | /// Whether a texture should be flipped. 213 | #[derive(PartialEq, Copy, Clone)] 214 | pub enum Flip { 215 | /// The texture should not be flipped. 216 | NoFlip, 217 | /// The texture should be flipped vertically. 218 | VerticalFlip, 219 | } 220 | 221 | #[cfg(feature = "heapsize")] 222 | known_heap_size!(0, Flip); 223 | -------------------------------------------------------------------------------- /src/tiling.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The Servo Project Developers. See the COPYRIGHT 2 | // file at the top-level directory of this distribution. 3 | // 4 | // Licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your 7 | // option. This file may not be copied, modified, or distributed 8 | // except according to those terms. 9 | 10 | use geometry::{DevicePixel, LayerPixel}; 11 | use layers::{BufferRequest, ContentAge, LayerBuffer}; 12 | use platform::surface::NativeDisplay; 13 | use texturegl::Texture; 14 | use util::project_rect_to_screen; 15 | 16 | use euclid::length::Length; 17 | use euclid::{Matrix4D, Point2D, TypedPoint2D}; 18 | use euclid::rect::{Rect, TypedRect}; 19 | use euclid::size::{Size2D, TypedSize2D}; 20 | use std::collections::HashMap; 21 | use std::collections::hash_map::Entry; 22 | use std::mem; 23 | 24 | pub struct Tile { 25 | /// The buffer displayed by this tile. 26 | buffer: Option>, 27 | 28 | /// The content age of any pending buffer request to avoid re-requesting 29 | /// a buffer while waiting for it to come back from rendering. 30 | content_age_of_pending_buffer: Option, 31 | 32 | /// A handle to the GPU texture. 33 | pub texture: Texture, 34 | 35 | /// The tile boundaries in the parent layer coordinates. 36 | pub bounds: Option>, 37 | } 38 | 39 | impl Tile { 40 | fn new() -> Tile { 41 | Tile { 42 | buffer: None, 43 | texture: Texture::zero(), 44 | content_age_of_pending_buffer: None, 45 | bounds: None, 46 | } 47 | } 48 | 49 | fn should_use_new_buffer(&self, new_buffer: &Box) -> bool { 50 | match self.buffer { 51 | Some(ref buffer) => new_buffer.content_age >= buffer.content_age, 52 | None => true, 53 | } 54 | } 55 | 56 | fn replace_buffer(&mut self, buffer: Box) -> Option> { 57 | if !self.should_use_new_buffer(&buffer) { 58 | warn!("Layer received an old buffer."); 59 | return Some(buffer); 60 | } 61 | 62 | let old_buffer = self.buffer.take(); 63 | self.buffer = Some(buffer); 64 | self.texture = Texture::zero(); // The old texture is bound to the old buffer. 65 | self.content_age_of_pending_buffer = None; 66 | old_buffer 67 | } 68 | 69 | fn create_texture(&mut self, display: &NativeDisplay) { 70 | if let Some(ref buffer) = self.buffer { 71 | // If we already have a texture it should still be valid. 72 | if !self.texture.is_zero() { 73 | return; 74 | } 75 | 76 | // Make a new texture and bind the LayerBuffer's surface to it. 77 | self.texture = Texture::new_with_buffer(buffer); 78 | debug!("Tile: binding to native surface {}", 79 | buffer.native_surface.get_id() as isize); 80 | buffer.native_surface.bind_to_texture(display, &self.texture); 81 | 82 | // Set the layer's rect. 83 | self.bounds = Some(TypedRect::from_untyped(&buffer.rect)); 84 | } 85 | } 86 | 87 | fn should_request_buffer(&self, content_age: ContentAge) -> bool { 88 | // Don't resend a request if our buffer's content age matches the current content age. 89 | if let Some(ref buffer) = self.buffer { 90 | if buffer.content_age >= content_age { 91 | return false; 92 | } 93 | } 94 | 95 | // Don't resend a request, if we already have one pending. 96 | match self.content_age_of_pending_buffer { 97 | Some(pending_content_age) => pending_content_age != content_age, 98 | None => true, 99 | } 100 | } 101 | } 102 | 103 | pub struct TileGrid { 104 | pub tiles: HashMap, Tile>, 105 | 106 | /// The size of tiles in this grid in device pixels. 107 | tile_size: Length, 108 | 109 | // Buffers that are currently unused. 110 | unused_buffers: Vec>, 111 | } 112 | 113 | pub fn rect_uint_as_rect_f32(rect: Rect) -> Rect { 114 | TypedRect::new(Point2D::new(rect.origin.x as f32, rect.origin.y as f32), 115 | Size2D::new(rect.size.width as f32, rect.size.height as f32)) 116 | } 117 | 118 | impl TileGrid { 119 | pub fn new(tile_size: usize) -> TileGrid { 120 | TileGrid { 121 | tiles: HashMap::new(), 122 | tile_size: Length::new(tile_size), 123 | unused_buffers: Vec::new(), 124 | } 125 | } 126 | 127 | pub fn get_rect_for_tile_index(&self, 128 | tile_index: Point2D, 129 | current_layer_size: TypedSize2D) 130 | -> TypedRect { 131 | 132 | let origin : TypedPoint2D = 133 | TypedPoint2D::new(self.tile_size.get() * tile_index.x, 134 | self.tile_size.get() * tile_index.y); 135 | 136 | // Don't let tiles extend beyond the layer boundaries. 137 | let tile_size = self.tile_size.get() as f32; 138 | let size = Size2D::new(tile_size.min(current_layer_size.width - origin.x as f32), 139 | tile_size.min(current_layer_size.height - origin.y as f32)); 140 | 141 | // Round up to texture pixels. 142 | let size = TypedSize2D::new(size.width.ceil() as usize, size.height.ceil() as usize); 143 | 144 | TypedRect::new(origin, size) 145 | } 146 | 147 | pub fn take_unused_buffers(&mut self) -> Vec> { 148 | let mut unused_buffers = Vec::new(); 149 | mem::swap(&mut unused_buffers, &mut self.unused_buffers); 150 | unused_buffers 151 | } 152 | 153 | pub fn add_unused_buffer(&mut self, buffer: Option>) { 154 | if let Some(buffer) = buffer { 155 | self.unused_buffers.push(buffer); 156 | } 157 | } 158 | 159 | pub fn tile_intersects_rect(&self, 160 | tile_index: &Point2D, 161 | test_rect: &Rect, 162 | current_layer_size: TypedSize2D, 163 | layer_world_origin: &Point2D, 164 | layer_transform: &Matrix4D) -> bool { 165 | let tile_rect = self.get_rect_for_tile_index(*tile_index, 166 | current_layer_size); 167 | let tile_rect = tile_rect.to_f32() 168 | .to_untyped() 169 | .translate(layer_world_origin); 170 | 171 | let screen_rect = project_rect_to_screen(&tile_rect, layer_transform); 172 | 173 | if let Some(screen_rect) = screen_rect { 174 | if screen_rect.rect.intersection(&test_rect).is_some() { 175 | return true; 176 | } 177 | } 178 | 179 | false 180 | } 181 | 182 | pub fn mark_tiles_outside_of_rect_as_unused(&mut self, 183 | rect: TypedRect, 184 | layer_world_origin: &Point2D, 185 | layer_transform: &Matrix4D, 186 | current_layer_size: TypedSize2D) { 187 | let mut tile_indexes_to_take = Vec::new(); 188 | 189 | for tile_index in self.tiles.keys() { 190 | if !self.tile_intersects_rect(tile_index, 191 | &rect.to_untyped(), 192 | current_layer_size, 193 | layer_world_origin, 194 | layer_transform) { 195 | tile_indexes_to_take.push(tile_index.clone()); 196 | } 197 | } 198 | 199 | for tile_index in &tile_indexes_to_take { 200 | if let Some(ref mut tile) = self.tiles.remove(tile_index) { 201 | self.add_unused_buffer(tile.buffer.take()); 202 | } 203 | } 204 | } 205 | 206 | pub fn get_buffer_request_for_tile(&mut self, 207 | tile_index: Point2D, 208 | current_layer_size: TypedSize2D, 209 | current_content_age: ContentAge) 210 | -> Option { 211 | let tile_rect = self.get_rect_for_tile_index(tile_index, current_layer_size); 212 | let tile = match self.tiles.entry(tile_index) { 213 | Entry::Occupied(occupied) => occupied.into_mut(), 214 | Entry::Vacant(vacant) => vacant.insert(Tile::new()), 215 | }; 216 | 217 | if tile_rect.is_empty() { 218 | return None; 219 | } 220 | 221 | if !tile.should_request_buffer(current_content_age) { 222 | return None; 223 | } 224 | 225 | tile.content_age_of_pending_buffer = Some(current_content_age); 226 | 227 | Some(BufferRequest::new(tile_rect.to_untyped(), 228 | tile_rect.to_f32().to_untyped(), 229 | current_content_age)) 230 | } 231 | 232 | /// Returns buffer requests inside the given dirty rect, and simultaneously throws out tiles 233 | /// outside the given viewport rect. 234 | pub fn get_buffer_requests_in_rect(&mut self, 235 | dirty_rect: TypedRect, 236 | viewport: TypedRect, 237 | current_layer_size: TypedSize2D, 238 | layer_world_origin: &Point2D, 239 | layer_transform: &Matrix4D, 240 | current_content_age: ContentAge) 241 | -> Vec { 242 | let mut buffer_requests = Vec::new(); 243 | 244 | // Get the range of tiles that can fit into the current layer size. 245 | // Step through each, transform/clip them to 2d rect 246 | // Check if visible against rect 247 | 248 | let tile_size = self.tile_size.get() as f32; 249 | let x_tile_count = ((current_layer_size.to_untyped().width + tile_size - 1.0) / tile_size) as usize; 250 | let y_tile_count = ((current_layer_size.to_untyped().height + tile_size - 1.0) / tile_size) as usize; 251 | 252 | for x in 0..x_tile_count { 253 | for y in 0..y_tile_count { 254 | let tile_index = Point2D::new(x, y); 255 | if self.tile_intersects_rect(&tile_index, 256 | &dirty_rect.to_untyped(), 257 | current_layer_size, 258 | layer_world_origin, 259 | layer_transform) { 260 | if let Some(buffer) = self.get_buffer_request_for_tile(tile_index, 261 | current_layer_size, 262 | current_content_age) { 263 | buffer_requests.push(buffer); 264 | } 265 | } 266 | } 267 | } 268 | 269 | self.mark_tiles_outside_of_rect_as_unused(viewport, 270 | layer_world_origin, 271 | layer_transform, 272 | current_layer_size); 273 | 274 | buffer_requests 275 | } 276 | 277 | pub fn get_tile_index_for_point(&self, point: Point2D) -> Point2D { 278 | assert!(point.x % self.tile_size.get() == 0); 279 | assert!(point.y % self.tile_size.get() == 0); 280 | Point2D::new((point.x / self.tile_size.get()) as usize, 281 | (point.y / self.tile_size.get()) as usize) 282 | } 283 | 284 | pub fn add_buffer(&mut self, buffer: Box) { 285 | let index = self.get_tile_index_for_point(buffer.screen_pos.origin.clone()); 286 | if !self.tiles.contains_key(&index) { 287 | warn!("Received buffer for non-existent tile!"); 288 | self.add_unused_buffer(Some(buffer)); 289 | return; 290 | } 291 | 292 | let replaced_buffer = self.tiles.get_mut(&index).unwrap().replace_buffer(buffer); 293 | self.add_unused_buffer(replaced_buffer); 294 | } 295 | 296 | pub fn do_for_all_tiles(&self, mut f: F) where F: FnMut(&Tile) { 297 | for tile in self.tiles.values() { 298 | f(tile); 299 | } 300 | } 301 | 302 | pub fn collect_buffers(&mut self) -> Vec> { 303 | let mut collected_buffers = self.take_unused_buffers(); 304 | collected_buffers.extend(self.tiles.drain().flat_map(|(_, mut tile)| tile.buffer.take())); 305 | collected_buffers 306 | } 307 | 308 | pub fn create_textures(&mut self, display: &NativeDisplay) { 309 | for (_, ref mut tile) in &mut self.tiles { 310 | tile.create_texture(display); 311 | } 312 | } 313 | 314 | /// Calculate the amount of memory used by all the tiles in the 315 | /// tile grid. The memory may be allocated on the heap or in GPU memory. 316 | pub fn get_memory_usage(&self) -> usize { 317 | self.tiles.values().map(|ref tile| { 318 | // We cannot use Option::map_or here because rust will 319 | // complain about moving out of borrowed content. 320 | match tile.buffer { 321 | Some(ref buffer) => buffer.get_mem(), 322 | None => 0, 323 | } 324 | }).sum() 325 | } 326 | } 327 | -------------------------------------------------------------------------------- /src/util.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Servo Project Developers. See the COPYRIGHT 2 | // file at the top-level directory of this distribution. 3 | // 4 | // Licensed under the Apache License, Version 2.0 or the MIT license 6 | // , at your 7 | // option. This file may not be copied, modified, or distributed 8 | // except according to those terms. 9 | 10 | // Miscellaneous utilities. 11 | 12 | use std::iter::repeat; 13 | use euclid::{Matrix4D, Point2D, Point3D, Point4D, Rect, Size2D}; 14 | use std::f32; 15 | 16 | const W_CLIPPING_PLANE: f32 = 0.00001; 17 | 18 | #[derive(Debug)] 19 | pub struct ScreenRect { 20 | pub rect: Rect, 21 | pub z_center: f32, 22 | } 23 | 24 | #[cfg(feature = "heapsize")] 25 | known_heap_size!(0, ScreenRect); 26 | 27 | pub fn convert_rgb32_to_rgb24(buffer: &[u8]) -> Vec { 28 | let mut i = 0; 29 | repeat(buffer.len() * 3 / 4).map(|j| { 30 | match j % 3 { 31 | 0 => { 32 | buffer[i + 2] 33 | } 34 | 1 => { 35 | buffer[i + 1] 36 | } 37 | 2 => { 38 | let val = buffer[i]; 39 | i += 4; 40 | val 41 | } 42 | _ => { 43 | panic!() 44 | } 45 | } 46 | }).collect() 47 | } 48 | 49 | // Sutherland-Hodgman clipping algorithm 50 | fn clip_polygon_to_near_plane(clip_space_vertices: &[Point4D; 4]) 51 | -> Option>> { 52 | let mut out_vertices = vec!(); 53 | 54 | // TODO(gw): Check for trivial accept / reject if all 55 | // input vertices are on the same side of the near plane. 56 | 57 | for (i, current_vertex) in clip_space_vertices.iter().enumerate() { 58 | let previous_vertex = if i == 0 { 59 | clip_space_vertices.last().unwrap() 60 | } else { 61 | &clip_space_vertices[i-1] 62 | }; 63 | 64 | let previous_dot = if previous_vertex.w < W_CLIPPING_PLANE { -1 } else { 1 }; 65 | let current_dot = if current_vertex.w < W_CLIPPING_PLANE { -1 } else { 1 }; 66 | 67 | if previous_dot * current_dot < 0 { 68 | let int_factor = (previous_vertex.w - W_CLIPPING_PLANE) / (previous_vertex.w - current_vertex.w); 69 | 70 | // TODO(gw): Impl operators on Point4D for this 71 | let int_point = Point4D::new( 72 | previous_vertex.x + int_factor * (current_vertex.x - previous_vertex.x), 73 | previous_vertex.y + int_factor * (current_vertex.y - previous_vertex.y), 74 | previous_vertex.z + int_factor * (current_vertex.z - previous_vertex.z), 75 | previous_vertex.w + int_factor * (current_vertex.w - previous_vertex.w), 76 | ); 77 | 78 | out_vertices.push(int_point); 79 | } 80 | 81 | if current_dot > 0 { 82 | out_vertices.push(*current_vertex); 83 | } 84 | } 85 | 86 | if out_vertices.len() < 3 { 87 | return None 88 | } 89 | 90 | Some(out_vertices) 91 | } 92 | 93 | pub fn project_rect_to_screen(rect: &Rect, 94 | transform: &Matrix4D) -> Option { 95 | let mut result = None; 96 | 97 | let x0 = rect.min_x(); 98 | let x1 = rect.max_x(); 99 | 100 | let y0 = rect.min_y(); 101 | let y1 = rect.max_y(); 102 | 103 | let xc = (x0 + x1) * 0.5; 104 | let yc = (y0 + y1) * 0.5; 105 | let vc = Point4D::new(xc, yc, 0.0, 1.0); 106 | let vc = transform.transform_point4d(&vc); 107 | 108 | let vertices = [ 109 | Point4D::new(x0, y0, 0.0, 1.0), 110 | Point4D::new(x1, y0, 0.0, 1.0), 111 | Point4D::new(x0, y1, 0.0, 1.0), 112 | Point4D::new(x1, y1, 0.0, 1.0) 113 | ]; 114 | 115 | // Transform vertices to clip space 116 | let vertices_clip_space = [ 117 | transform.transform_point4d(&vertices[0]), 118 | transform.transform_point4d(&vertices[1]), 119 | transform.transform_point4d(&vertices[2]), 120 | transform.transform_point4d(&vertices[3]), 121 | ]; 122 | 123 | // Clip the resulting quad against the near-plane 124 | // There's no need to clip against other planes for correctness, 125 | // since as long as w > 0, we will get valid homogenous coords. 126 | // TODO(gw): Potential optimization to clip against other planes. 127 | let clipped_vertices = clip_polygon_to_near_plane(&vertices_clip_space); 128 | 129 | if let Some(clipped_vertices) = clipped_vertices { 130 | // Perform perspective division on the clip space vertices 131 | // to get homogenous space vertices. Then calculate the 132 | // 2d AABB for this polygon in screen space. 133 | 134 | let mut min_vertex = Point3D::new(f32::MAX, f32::MAX, f32::MAX); 135 | let mut max_vertex = Point3D::new(-f32::MAX, -f32::MAX, -f32::MAX); 136 | 137 | for vertex_cs in &clipped_vertices { 138 | // This should be enforced by the clipper above 139 | debug_assert!(vertex_cs.w > 0.0); 140 | let inv_w = 1.0 / vertex_cs.w; 141 | let x = vertex_cs.x * inv_w; 142 | let y = vertex_cs.y * inv_w; 143 | let z = vertex_cs.z * inv_w; 144 | 145 | // Calculate the min/max z-depths of this layer. 146 | // This is used for simple depth sorting later. 147 | min_vertex.x = min_vertex.x.min(x); 148 | max_vertex.x = max_vertex.x.max(x); 149 | min_vertex.y = min_vertex.y.min(y); 150 | max_vertex.y = max_vertex.y.max(y); 151 | min_vertex.z = min_vertex.z.min(z); 152 | max_vertex.z = max_vertex.z.max(z); 153 | } 154 | 155 | let origin = Point2D::new(min_vertex.x, min_vertex.y); 156 | let size = Size2D::new(max_vertex.x - min_vertex.x, 157 | max_vertex.y - min_vertex.y); 158 | 159 | result = Some(ScreenRect { 160 | rect: Rect::new(origin, size), 161 | z_center: vc.z, 162 | }); 163 | } 164 | 165 | result 166 | } 167 | --------------------------------------------------------------------------------