diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 000000000..149b5351f
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,2 @@
+*.mtl binary
+*.obj binary
diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml
new file mode 100644
index 000000000..623e0c996
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/config.yml
@@ -0,0 +1,8 @@
+blank_issues_enabled: false
+contact_links:
+ - name: Issue or enhancement in wgpu-core
+ url: https://github.com/gfx-rs/wgpu/issues/new/choose
+ about: Issues with or enhancements for the core logic, validation, or the backends should go here.
+ - name: Question about wgpu
+ url: https://github.com/gfx-rs/wgpu-rs/discussions/new
+ about: Any questions about how to use wgpu should go here.
diff --git a/.github/ISSUE_TEMPLATE/other.md b/.github/ISSUE_TEMPLATE/other.md
index 52ef2e8a4..ea2d87974 100644
--- a/.github/ISSUE_TEMPLATE/other.md
+++ b/.github/ISSUE_TEMPLATE/other.md
@@ -4,7 +4,4 @@ about: Strange things you want to tell us
title: ''
labels: question
assignees: ''
-
---
-
-
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 4988231b1..4961a9fed 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -34,13 +34,18 @@ jobs:
- name: Additional core features
run: cargo check --manifest-path wgpu-core/Cargo.toml --features trace --target ${{ env.TARGET }}
- webgl_build:
+ wasm:
name: Web Assembly
runs-on: ubuntu-18.04
+ env:
+ RUSTFLAGS: --cfg=web_sys_unstable_apis
steps:
- - uses: actions/checkout@v2
- - run: rustup target add wasm32-unknown-unknown
- - run: cargo build --manifest-path wgpu-core/Cargo.toml --target wasm32-unknown-unknown
+ - uses: actions/checkout@v2
+ - run: rustup target add wasm32-unknown-unknown
+ - name: Check WebGPU
+ run: cargo check --all-targets --target=wasm32-unknown-unknown
+ - name: Check WebGL
+ run: cargo check --all-targets --target=wasm32-unknown-unknown --features webgl
build:
name: ${{ matrix.name }}
@@ -117,6 +122,20 @@ jobs:
- if: matrix.channel == 'nightly'
run: cargo test -- --nocapture
+ docs:
+ runs-on: [ubuntu-18.04]
+ steps:
+ - uses: actions/checkout@v2
+ - name: Install latest nightly
+ uses: actions-rs/toolchain@v1
+ with:
+ toolchain: nightly
+ override: true
+ continue-on-error: true
+ - name: cargo doc
+ run: cargo --version; cargo doc --no-deps
+ continue-on-error: true
+
lint:
name: Clippy
runs-on: ubuntu-latest
@@ -132,3 +151,7 @@ jobs:
with:
command: clippy
args: -- -D warnings
+ - uses: actions-rs/cargo@v1
+ with:
+ command: fmt
+ args: -- --check
diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml
new file mode 100644
index 000000000..8aaf466b8
--- /dev/null
+++ b/.github/workflows/docs.yml
@@ -0,0 +1,45 @@
+name: Documentation
+
+on:
+ push:
+ branches:
+ - master
+
+jobs:
+ build:
+ runs-on: ubuntu-latest
+
+ steps:
+ - name: Checkout the code
+ uses: actions/checkout@v2
+ with:
+ persist-credentials: false
+
+ - name: Install latest nightly
+ uses: actions-rs/toolchain@v1
+ with:
+ toolchain: nightly
+ override: true
+ continue-on-error: true
+
+ - name: Add EGL for OpenGL
+ run: |
+ sudo apt-get update -y -qq
+ sudo apt-get install -y -qq libegl1-mesa-dev
+
+ - name: Build the docs (nightly)
+ run: |
+ cargo +nightly doc --lib --all-features
+
+ - name: Build the docs (stable)
+ run: cargo +stable doc --lib --all-features
+ if: ${{ failure() }}
+
+ - name: Deploy the docs
+ uses: JamesIves/github-pages-deploy-action@releases/v3
+ with:
+ ACCESS_TOKEN: ${{ secrets.WEB_DEPLOY }}
+ FOLDER: target/doc
+ REPOSITORY_NAME: gfx-rs/wgpu-rs.github.io
+ BRANCH: master
+ TARGET_FOLDER: doc
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml
new file mode 100644
index 000000000..b1ebd4c66
--- /dev/null
+++ b/.github/workflows/publish.yml
@@ -0,0 +1,47 @@
+name: Publish
+
+on:
+ push:
+ branches:
+ - gecko
+
+env:
+ RUSTFLAGS: --cfg=web_sys_unstable_apis
+
+jobs:
+ build:
+ runs-on: ubuntu-latest
+
+ steps:
+ - name: Checkout the code
+ uses: actions/checkout@v2
+ with:
+ persist-credentials: false
+
+ - name: Install Rust WASM toolchain
+ uses: actions-rs/toolchain@v1
+ with:
+ toolchain: stable
+ target: wasm32-unknown-unknown
+
+ - name: Build the examples
+ run: cargo build --release --target wasm32-unknown-unknown --examples
+
+ - name: Install wasm-bindgen-cli
+ run: cargo install wasm-bindgen-cli
+
+ - name: Generate JS bindings for the examples
+ run: |
+ for i in target/wasm32-unknown-unknown/release/examples/*.wasm;
+ do
+ wasm-bindgen --no-typescript --out-dir target/generated --web "$i";
+ done
+
+ - name: Deploy the examples
+ uses: JamesIves/github-pages-deploy-action@releases/v3
+ with:
+ ACCESS_TOKEN: ${{ secrets.WEB_DEPLOY }}
+ FOLDER: target/generated
+ REPOSITORY_NAME: gfx-rs/wgpu-rs.github.io
+ BRANCH: master
+ TARGET_FOLDER: examples/wasm
diff --git a/.gitignore b/.gitignore
index c5b453f50..2f516ba67 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,8 +1,17 @@
-/target
+# Generated by Cargo
+# will have compiled files and executables
+/target/
+
+# These are backup files generated by rustfmt
**/*.rs.bk
-#Cargo.lock
+
+# Other
.fuse_hidden*
.DS_Store
+
+# IDE/Editor configuration files
.vscode
-.vs
.idea
+
+# Output from capture example
+wgpu/red.png
diff --git a/wgpu/CHANGELOG.md b/wgpu/CHANGELOG.md
new file mode 100644
index 000000000..dcfb7660c
--- /dev/null
+++ b/wgpu/CHANGELOG.md
@@ -0,0 +1,19 @@
+# Change Log
+
+### v0.8 (2021-04-29)
+- See https://github.com/gfx-rs/wgpu/blob/v0.8/CHANGELOG.md#v08-2021-04-29
+- Naga is the default shader conversion path on Metal, Vulkan, and OpenGL
+- SPIRV-Cross is optionally enabled with "cross" feature
+- All of the examples (except "texture-array") now use WGSL
+
+### v0.7 (2021-01-31)
+- See https://github.com/gfx-rs/wgpu/blob/v0.7/CHANGELOG.md#v07-2020-08-30
+- Features:
+ - (beta) WGSL support
+ - better error messages
+- API changes:
+ - new `ShaderModuleDescriptor`
+ - new `RenderEncoder`
+
+### v0.6.2 (2020-11-24)
+- don't panic in the staging belt if the channel is dropped
diff --git a/wgpu/Cargo.toml b/wgpu/Cargo.toml
new file mode 100644
index 000000000..af6a99906
--- /dev/null
+++ b/wgpu/Cargo.toml
@@ -0,0 +1,247 @@
+[package]
+name = "wgpu"
+version = "0.8.0"
+authors = ["wgpu developers"]
+edition = "2018"
+description = "Rusty WebGPU API wrapper"
+homepage = "https://github.com/gfx-rs/wgpu-rs"
+repository = "https://github.com/gfx-rs/wgpu-rs"
+keywords = ["graphics"]
+license = "MPL-2.0"
+exclude = ["etc/**/*", "examples/**/*", "tests/**/*", "Cargo.lock", "target/**/*"]
+
+[package.metadata.docs.rs]
+all-features = true
+
+[lib]
+
+[features]
+default = []
+trace = ["serde", "wgc/trace"]
+replay = ["serde", "wgc/replay"]
+webgl = ["wgc"]
+# Enable SPIRV-Cross
+cross = ["wgc/cross"]
+
+[target.'cfg(not(target_arch = "wasm32"))'.dependencies.wgc]
+package = "wgpu-core"
+git = "https://github.com/gfx-rs/wgpu"
+rev = "eadaa1b7d8f585761e28445904fe619b180aca0d"
+features = ["raw-window-handle"]
+
+[target.'cfg(target_arch = "wasm32")'.dependencies.wgc]
+package = "wgpu-core"
+git = "https://github.com/gfx-rs/wgpu"
+rev = "eadaa1b7d8f585761e28445904fe619b180aca0d"
+features = ["raw-window-handle"]
+optional = true
+
+[dependencies.wgt]
+package = "wgpu-types"
+git = "https://github.com/gfx-rs/wgpu"
+rev = "eadaa1b7d8f585761e28445904fe619b180aca0d"
+
+[dependencies]
+arrayvec = "0.5"
+log = "0.4"
+parking_lot = "0.11"
+raw-window-handle = "0.3"
+serde = { version = "1", features = ["derive"], optional = true }
+smallvec = "1"
+
+[dev-dependencies]
+bytemuck = { version = "1.4", features = ["derive"] }
+cgmath = "0.18"
+ddsfile = "0.4"
+log = "0.4"
+noise = "0.7"
+obj = "0.10"
+png = "0.16"
+rand = { version = "0.7.2", features = ["wasm-bindgen"] }
+winit = { version = "0.24", features = ["web-sys"] }
+
+[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies]
+async-executor = "1.0"
+pollster = "0.2"
+env_logger = "0.8"
+
+# used to test all the example shaders
+[dev-dependencies.naga]
+git = "https://github.com/gfx-rs/naga"
+tag = "gfx-25"
+features = ["wgsl-in"]
+
+# used to generate SPIR-V for the Web target
+[target.'cfg(target_arch = "wasm32")'.dependencies.naga]
+git = "https://github.com/gfx-rs/naga"
+tag = "gfx-25"
+features = ["wgsl-in", "spv-out"]
+
+[[example]]
+name="hello-compute"
+path="examples/hello-compute/main.rs"
+test = true
+
+[patch."https://github.com/gfx-rs/wgpu"]
+#wgpu-types = { path = "../wgpu/wgpu-types" }
+#wgpu-core = { path = "../wgpu/wgpu-core" }
+
+[patch."https://github.com/gfx-rs/subscriber"]
+#wgpu-subscriber = { version = "0.1", path = "../subscriber" }
+
+[patch."https://github.com/gfx-rs/naga"]
+#naga = { path = "../naga" }
+
+[patch."https://github.com/zakarumych/gpu-descriptor"]
+#gpu-descriptor = { path = "../gpu-descriptor/gpu-descriptor" }
+
+[patch."https://github.com/zakarumych/gpu-alloc"]
+#gpu-alloc = { path = "../gpu-alloc/gpu-alloc" }
+
+[patch."https://github.com/gfx-rs/gfx"]
+#gfx-hal = { path = "../gfx/src/hal" }
+#gfx-backend-empty = { path = "../gfx/src/backend/empty" }
+#gfx-backend-vulkan = { path = "../gfx/src/backend/vulkan" }
+#gfx-backend-gl = { path = "../gfx/src/backend/gl" }
+#gfx-backend-dx12 = { path = "../gfx/src/backend/dx12" }
+#gfx-backend-dx11 = { path = "../gfx/src/backend/dx11" }
+#gfx-backend-metal = { path = "../gfx/src/backend/metal" }
+
+[patch.crates-io]
+#web-sys = { path = "../wasm-bindgen/crates/web-sys" }
+#js-sys = { path = "../wasm-bindgen/crates/js-sys" }
+#wasm-bindgen = { path = "../wasm-bindgen" }
+
+[target.'cfg(target_arch = "wasm32")'.dependencies]
+wasm-bindgen = "0.2.73" # remember to change version in wiki as well
+web-sys = { version = "=0.3.50", features = [
+ "Document",
+ "Navigator",
+ "Node",
+ "NodeList",
+ "Gpu",
+ "GpuAdapter",
+ "GpuAdapterFeatures",
+ "GpuAdapterLimits",
+ "GpuAddressMode",
+ "GpuBindGroup",
+ "GpuBindGroupDescriptor",
+ "GpuBindGroupEntry",
+ "GpuBindGroupLayout",
+ "GpuBindGroupLayoutDescriptor",
+ "GpuBindGroupLayoutEntry",
+ "GpuBlendComponent",
+ "GpuBlendFactor",
+ "GpuBlendOperation",
+ "GpuBlendState",
+ "GpuBuffer",
+ "GpuBufferBinding",
+ "GpuBufferBindingLayout",
+ "GpuBufferBindingType",
+ "GpuBufferDescriptor",
+ "GpuBufferUsage",
+ "GpuCanvasContext",
+ "GpuColorDict",
+ "GpuColorTargetState",
+ "GpuColorWrite",
+ "GpuCommandBuffer",
+ "GpuCommandBufferDescriptor",
+ "GpuCommandEncoder",
+ "GpuCommandEncoderDescriptor",
+ "GpuCompareFunction",
+ "GpuCompilationInfo",
+ "GpuCompilationMessage",
+ "GpuCompilationMessageType",
+ "GpuComputePassDescriptor",
+ "GpuComputePassEncoder",
+ "GpuComputePipeline",
+ "GpuComputePipelineDescriptor",
+ "GpuCullMode",
+ "GpuDepthStencilState",
+ "GpuDevice",
+ "GpuDeviceDescriptor",
+ "GpuDeviceLostInfo",
+ "GpuDeviceLostReason",
+ "GpuErrorFilter",
+ "GpuExtent3dDict",
+ "GpuFeatureName",
+ "GpuFilterMode",
+ "GpuFragmentState",
+ "GpuFrontFace",
+ "GpuImageCopyBuffer",
+ "GpuImageCopyImageBitmap",
+ "GpuImageCopyTexture",
+ "GpuImageDataLayout",
+ "GpuIndexFormat",
+ "GpuInputStepMode",
+ "GpuLoadOp",
+ "GpuMapMode",
+ "GpuMultisampleState",
+ "GpuObjectDescriptorBase",
+ "GpuOrigin2dDict",
+ "GpuOrigin3dDict",
+ "GpuOutOfMemoryError",
+ "GpuPipelineDescriptorBase",
+ "GpuPipelineLayout",
+ "GpuPipelineLayoutDescriptor",
+ "GpuPipelineStatisticName",
+ "GpuPowerPreference",
+ "GpuPrimitiveState",
+ "GpuPrimitiveTopology",
+ "GpuProgrammableStage",
+ "GpuQuerySet",
+ "GpuQuerySetDescriptor",
+ "GpuQueryType",
+ "GpuQueue",
+ "GpuRenderBundle",
+ "GpuRenderBundleDescriptor",
+ "GpuRenderBundleEncoder",
+ "GpuRenderBundleEncoderDescriptor",
+ "GpuRenderPassColorAttachment",
+ "GpuRenderPassDepthStencilAttachment",
+ "GpuRenderPassDescriptor",
+ "GpuRenderPassEncoder",
+ "GpuRenderPipeline",
+ "GpuRenderPipelineDescriptor",
+ "GpuRequestAdapterOptions",
+ "GpuSampler",
+ "GpuSamplerBindingLayout",
+ "GpuSamplerBindingType",
+ "GpuSamplerDescriptor",
+ "GpuShaderModule",
+ "GpuShaderModuleDescriptor",
+ "GpuShaderStage",
+ "GpuStencilFaceState",
+ "GpuStencilOperation",
+ "GpuStorageTextureAccess",
+ "GpuStorageTextureBindingLayout",
+ "GpuStoreOp",
+ "GpuSwapChain",
+ "GpuSwapChainDescriptor",
+ "GpuTexture",
+ "GpuTextureAspect",
+ "GpuTextureBindingLayout",
+ "GpuTextureDescriptor",
+ "GpuTextureDimension",
+ "GpuTextureFormat",
+ "GpuTextureSampleType",
+ "GpuTextureUsage",
+ "GpuTextureView",
+ "GpuTextureViewDescriptor",
+ "GpuTextureViewDimension",
+ "GpuUncapturedErrorEvent",
+ "GpuUncapturedErrorEventInit",
+ "GpuValidationError",
+ "GpuVertexAttribute",
+ "GpuVertexBufferLayout",
+ "GpuVertexFormat",
+ "GpuVertexState",
+ "HtmlCanvasElement",
+ "Window",
+]}
+js-sys = "0.3.50"
+wasm-bindgen-futures = "0.4.23"
+
+[target.'cfg(target_arch = "wasm32")'.dev-dependencies]
+console_error_panic_hook = "0.1.6"
+console_log = "0.1.2"
diff --git a/wgpu/LICENSE b/wgpu/LICENSE
new file mode 100644
index 000000000..a612ad981
--- /dev/null
+++ b/wgpu/LICENSE
@@ -0,0 +1,373 @@
+Mozilla Public License Version 2.0
+==================================
+
+1. Definitions
+--------------
+
+1.1. "Contributor"
+ means each individual or legal entity that creates, contributes to
+ the creation of, or owns Covered Software.
+
+1.2. "Contributor Version"
+ means the combination of the Contributions of others (if any) used
+ by a Contributor and that particular Contributor's Contribution.
+
+1.3. "Contribution"
+ means Covered Software of a particular Contributor.
+
+1.4. "Covered Software"
+ means Source Code Form to which the initial Contributor has attached
+ the notice in Exhibit A, the Executable Form of such Source Code
+ Form, and Modifications of such Source Code Form, in each case
+ including portions thereof.
+
+1.5. "Incompatible With Secondary Licenses"
+ means
+
+ (a) that the initial Contributor has attached the notice described
+ in Exhibit B to the Covered Software; or
+
+ (b) that the Covered Software was made available under the terms of
+ version 1.1 or earlier of the License, but not also under the
+ terms of a Secondary License.
+
+1.6. "Executable Form"
+ means any form of the work other than Source Code Form.
+
+1.7. "Larger Work"
+ means a work that combines Covered Software with other material, in
+ a separate file or files, that is not Covered Software.
+
+1.8. "License"
+ means this document.
+
+1.9. "Licensable"
+ means having the right to grant, to the maximum extent possible,
+ whether at the time of the initial grant or subsequently, any and
+ all of the rights conveyed by this License.
+
+1.10. "Modifications"
+ means any of the following:
+
+ (a) any file in Source Code Form that results from an addition to,
+ deletion from, or modification of the contents of Covered
+ Software; or
+
+ (b) any new file in Source Code Form that contains any Covered
+ Software.
+
+1.11. "Patent Claims" of a Contributor
+ means any patent claim(s), including without limitation, method,
+ process, and apparatus claims, in any patent Licensable by such
+ Contributor that would be infringed, but for the grant of the
+ License, by the making, using, selling, offering for sale, having
+ made, import, or transfer of either its Contributions or its
+ Contributor Version.
+
+1.12. "Secondary License"
+ means either the GNU General Public License, Version 2.0, the GNU
+ Lesser General Public License, Version 2.1, the GNU Affero General
+ Public License, Version 3.0, or any later versions of those
+ licenses.
+
+1.13. "Source Code Form"
+ means the form of the work preferred for making modifications.
+
+1.14. "You" (or "Your")
+ means an individual or a legal entity exercising rights under this
+ License. For legal entities, "You" includes any entity that
+ controls, is controlled by, or is under common control with You. For
+ purposes of this definition, "control" means (a) the power, direct
+ or indirect, to cause the direction or management of such entity,
+ whether by contract or otherwise, or (b) ownership of more than
+ fifty percent (50%) of the outstanding shares or beneficial
+ ownership of such entity.
+
+2. License Grants and Conditions
+--------------------------------
+
+2.1. Grants
+
+Each Contributor hereby grants You a world-wide, royalty-free,
+non-exclusive license:
+
+(a) under intellectual property rights (other than patent or trademark)
+ Licensable by such Contributor to use, reproduce, make available,
+ modify, display, perform, distribute, and otherwise exploit its
+ Contributions, either on an unmodified basis, with Modifications, or
+ as part of a Larger Work; and
+
+(b) under Patent Claims of such Contributor to make, use, sell, offer
+ for sale, have made, import, and otherwise transfer either its
+ Contributions or its Contributor Version.
+
+2.2. Effective Date
+
+The licenses granted in Section 2.1 with respect to any Contribution
+become effective for each Contribution on the date the Contributor first
+distributes such Contribution.
+
+2.3. Limitations on Grant Scope
+
+The licenses granted in this Section 2 are the only rights granted under
+this License. No additional rights or licenses will be implied from the
+distribution or licensing of Covered Software under this License.
+Notwithstanding Section 2.1(b) above, no patent license is granted by a
+Contributor:
+
+(a) for any code that a Contributor has removed from Covered Software;
+ or
+
+(b) for infringements caused by: (i) Your and any other third party's
+ modifications of Covered Software, or (ii) the combination of its
+ Contributions with other software (except as part of its Contributor
+ Version); or
+
+(c) under Patent Claims infringed by Covered Software in the absence of
+ its Contributions.
+
+This License does not grant any rights in the trademarks, service marks,
+or logos of any Contributor (except as may be necessary to comply with
+the notice requirements in Section 3.4).
+
+2.4. Subsequent Licenses
+
+No Contributor makes additional grants as a result of Your choice to
+distribute the Covered Software under a subsequent version of this
+License (see Section 10.2) or under the terms of a Secondary License (if
+permitted under the terms of Section 3.3).
+
+2.5. Representation
+
+Each Contributor represents that the Contributor believes its
+Contributions are its original creation(s) or it has sufficient rights
+to grant the rights to its Contributions conveyed by this License.
+
+2.6. Fair Use
+
+This License is not intended to limit any rights You have under
+applicable copyright doctrines of fair use, fair dealing, or other
+equivalents.
+
+2.7. Conditions
+
+Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
+in Section 2.1.
+
+3. Responsibilities
+-------------------
+
+3.1. Distribution of Source Form
+
+All distribution of Covered Software in Source Code Form, including any
+Modifications that You create or to which You contribute, must be under
+the terms of this License. You must inform recipients that the Source
+Code Form of the Covered Software is governed by the terms of this
+License, and how they can obtain a copy of this License. You may not
+attempt to alter or restrict the recipients' rights in the Source Code
+Form.
+
+3.2. Distribution of Executable Form
+
+If You distribute Covered Software in Executable Form then:
+
+(a) such Covered Software must also be made available in Source Code
+ Form, as described in Section 3.1, and You must inform recipients of
+ the Executable Form how they can obtain a copy of such Source Code
+ Form by reasonable means in a timely manner, at a charge no more
+ than the cost of distribution to the recipient; and
+
+(b) You may distribute such Executable Form under the terms of this
+ License, or sublicense it under different terms, provided that the
+ license for the Executable Form does not attempt to limit or alter
+ the recipients' rights in the Source Code Form under this License.
+
+3.3. Distribution of a Larger Work
+
+You may create and distribute a Larger Work under terms of Your choice,
+provided that You also comply with the requirements of this License for
+the Covered Software. If the Larger Work is a combination of Covered
+Software with a work governed by one or more Secondary Licenses, and the
+Covered Software is not Incompatible With Secondary Licenses, this
+License permits You to additionally distribute such Covered Software
+under the terms of such Secondary License(s), so that the recipient of
+the Larger Work may, at their option, further distribute the Covered
+Software under the terms of either this License or such Secondary
+License(s).
+
+3.4. Notices
+
+You may not remove or alter the substance of any license notices
+(including copyright notices, patent notices, disclaimers of warranty,
+or limitations of liability) contained within the Source Code Form of
+the Covered Software, except that You may alter any license notices to
+the extent required to remedy known factual inaccuracies.
+
+3.5. Application of Additional Terms
+
+You may choose to offer, and to charge a fee for, warranty, support,
+indemnity or liability obligations to one or more recipients of Covered
+Software. However, You may do so only on Your own behalf, and not on
+behalf of any Contributor. You must make it absolutely clear that any
+such warranty, support, indemnity, or liability obligation is offered by
+You alone, and You hereby agree to indemnify every Contributor for any
+liability incurred by such Contributor as a result of warranty, support,
+indemnity or liability terms You offer. You may include additional
+disclaimers of warranty and limitations of liability specific to any
+jurisdiction.
+
+4. Inability to Comply Due to Statute or Regulation
+---------------------------------------------------
+
+If it is impossible for You to comply with any of the terms of this
+License with respect to some or all of the Covered Software due to
+statute, judicial order, or regulation then You must: (a) comply with
+the terms of this License to the maximum extent possible; and (b)
+describe the limitations and the code they affect. Such description must
+be placed in a text file included with all distributions of the Covered
+Software under this License. Except to the extent prohibited by statute
+or regulation, such description must be sufficiently detailed for a
+recipient of ordinary skill to be able to understand it.
+
+5. Termination
+--------------
+
+5.1. The rights granted under this License will terminate automatically
+if You fail to comply with any of its terms. However, if You become
+compliant, then the rights granted under this License from a particular
+Contributor are reinstated (a) provisionally, unless and until such
+Contributor explicitly and finally terminates Your grants, and (b) on an
+ongoing basis, if such Contributor fails to notify You of the
+non-compliance by some reasonable means prior to 60 days after You have
+come back into compliance. Moreover, Your grants from a particular
+Contributor are reinstated on an ongoing basis if such Contributor
+notifies You of the non-compliance by some reasonable means, this is the
+first time You have received notice of non-compliance with this License
+from such Contributor, and You become compliant prior to 30 days after
+Your receipt of the notice.
+
+5.2. If You initiate litigation against any entity by asserting a patent
+infringement claim (excluding declaratory judgment actions,
+counter-claims, and cross-claims) alleging that a Contributor Version
+directly or indirectly infringes any patent, then the rights granted to
+You by any and all Contributors for the Covered Software under Section
+2.1 of this License shall terminate.
+
+5.3. In the event of termination under Sections 5.1 or 5.2 above, all
+end user license agreements (excluding distributors and resellers) which
+have been validly granted by You or Your distributors under this License
+prior to termination shall survive termination.
+
+************************************************************************
+* *
+* 6. Disclaimer of Warranty *
+* ------------------------- *
+* *
+* Covered Software is provided under this License on an "as is" *
+* basis, without warranty of any kind, either expressed, implied, or *
+* statutory, including, without limitation, warranties that the *
+* Covered Software is free of defects, merchantable, fit for a *
+* particular purpose or non-infringing. The entire risk as to the *
+* quality and performance of the Covered Software is with You. *
+* Should any Covered Software prove defective in any respect, You *
+* (not any Contributor) assume the cost of any necessary servicing, *
+* repair, or correction. This disclaimer of warranty constitutes an *
+* essential part of this License. No use of any Covered Software is *
+* authorized under this License except under this disclaimer. *
+* *
+************************************************************************
+
+************************************************************************
+* *
+* 7. Limitation of Liability *
+* -------------------------- *
+* *
+* Under no circumstances and under no legal theory, whether tort *
+* (including negligence), contract, or otherwise, shall any *
+* Contributor, or anyone who distributes Covered Software as *
+* permitted above, be liable to You for any direct, indirect, *
+* special, incidental, or consequential damages of any character *
+* including, without limitation, damages for lost profits, loss of *
+* goodwill, work stoppage, computer failure or malfunction, or any *
+* and all other commercial damages or losses, even if such party *
+* shall have been informed of the possibility of such damages. This *
+* limitation of liability shall not apply to liability for death or *
+* personal injury resulting from such party's negligence to the *
+* extent applicable law prohibits such limitation. Some *
+* jurisdictions do not allow the exclusion or limitation of *
+* incidental or consequential damages, so this exclusion and *
+* limitation may not apply to You. *
+* *
+************************************************************************
+
+8. Litigation
+-------------
+
+Any litigation relating to this License may be brought only in the
+courts of a jurisdiction where the defendant maintains its principal
+place of business and such litigation shall be governed by laws of that
+jurisdiction, without reference to its conflict-of-law provisions.
+Nothing in this Section shall prevent a party's ability to bring
+cross-claims or counter-claims.
+
+9. Miscellaneous
+----------------
+
+This License represents the complete agreement concerning the subject
+matter hereof. If any provision of this License is held to be
+unenforceable, such provision shall be reformed only to the extent
+necessary to make it enforceable. Any law or regulation which provides
+that the language of a contract shall be construed against the drafter
+shall not be used to construe this License against a Contributor.
+
+10. Versions of the License
+---------------------------
+
+10.1. New Versions
+
+Mozilla Foundation is the license steward. Except as provided in Section
+10.3, no one other than the license steward has the right to modify or
+publish new versions of this License. Each version will be given a
+distinguishing version number.
+
+10.2. Effect of New Versions
+
+You may distribute the Covered Software under the terms of the version
+of the License under which You originally received the Covered Software,
+or under the terms of any subsequent version published by the license
+steward.
+
+10.3. Modified Versions
+
+If you create software not governed by this License, and you want to
+create a new license for such software, you may create and use a
+modified version of this License if you rename the license and remove
+any references to the name of the license steward (except to note that
+such modified license differs from this License).
+
+10.4. Distributing Source Code Form that is Incompatible With Secondary
+Licenses
+
+If You choose to distribute Source Code Form that is Incompatible With
+Secondary Licenses under the terms of this version of the License, the
+notice described in Exhibit B of this License must be attached.
+
+Exhibit A - Source Code Form License Notice
+-------------------------------------------
+
+ This Source Code Form is subject to the terms of the Mozilla Public
+ License, v. 2.0. If a copy of the MPL was not distributed with this
+ file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+If it is not possible or desirable to put the notice in a particular
+file, then You may include the notice in a location (such as a LICENSE
+file in a relevant directory) where a recipient would be likely to look
+for such a notice.
+
+You may add additional accurate notices of copyright ownership.
+
+Exhibit B - "Incompatible With Secondary Licenses" Notice
+---------------------------------------------------------
+
+ This Source Code Form is "Incompatible With Secondary Licenses", as
+ defined by the Mozilla Public License, v. 2.0.
diff --git a/wgpu/Makefile b/wgpu/Makefile
new file mode 100644
index 000000000..73d1d3b15
--- /dev/null
+++ b/wgpu/Makefile
@@ -0,0 +1,20 @@
+# This Makefile generates SPIR-V shaders from GLSL shaders in the examples.
+
+shader_compiler = glslangValidator
+
+# All input shaders.
+glsls = $(wildcard examples/*/*.vert examples/*/*.frag examples/*/*.comp)
+
+# All SPIR-V targets.
+spirvs = $(addsuffix .spv,$(glsls))
+
+.PHONY: default
+default: $(spirvs)
+
+# Rule for making a SPIR-V target.
+$(spirvs): %.spv: %
+ $(shader_compiler) -V $< -o $@
+
+.PHONY: clean
+clean:
+ rm -f $(spirvs)
diff --git a/wgpu/README.md b/wgpu/README.md
new file mode 100644
index 000000000..dbc5c9294
--- /dev/null
+++ b/wgpu/README.md
@@ -0,0 +1,101 @@
+
+
+# wgpu-rs
+
+[](https://github.com/gfx-rs/wgpu-rs/actions)
+[](https://crates.io/crates/wgpu)
+[](https://docs.rs/wgpu)
+
+[](https://matrix.to/#/#wgpu:matrix.org)
+[](https://matrix.to/#/#wgpu-users:matrix.org)
+
+wgpu-rs is an idiomatic Rust wrapper over [wgpu-core](https://github.com/gfx-rs/wgpu). It's designed to be suitable for general purpose graphics and computation needs of Rust community.
+
+wgpu-rs can target both the natively supported backends and WASM directly.
+
+See our [gallery](https://wgpu.rs/#showcase) and the [wiki page](https://github.com/gfx-rs/wgpu-rs/wiki/Applications-and-Libraries) for the list of libraries and applications using `wgpu-rs`.
+
+## Usage
+
+### How to Run Examples
+
+All examples are located under the [examples](examples) directory.
+
+These examples use the default syntax for running examples, as found in the [Cargo](https://doc.rust-lang.org/cargo/reference/manifest.html#examples) documentation. For example, to run the `cube` example:
+
+```bash
+cargo run --example cube
+```
+
+The `hello*` examples show bare-bones setup without any helper code. For `hello-compute`, pass 4 numbers separated by spaces as arguments:
+
+```bash
+cargo run --example hello-compute 1 2 3 4
+```
+
+The following environment variables can be used to configure how the framework examples run:
+
+- `WGPU_BACKEND`
+
+ Options: `vulkan`, `metal`, `dx11`, `dx12`, `gl`, `webgpu`
+
+ If unset a default backend is chosen based on what is supported
+ by your system.
+
+- `WGPU_POWER_PREF`
+
+ Options: `low`, `high`
+
+ If unset a low power adapter is preferred.
+
+#### Run Examples on the Web (`wasm32-unknown-unknown`)
+
+See [wiki article](https://github.com/gfx-rs/wgpu-rs/wiki/Running-on-the-Web-with-WebGPU-and-WebGL).
+
+## Logging
+
+`wgpu-core` uses `tracing` for logging and `wgpu-rs` uses `log` for logging.
+
+### Simple Setup
+
+If you just want log messages to show up and to use the chrome tracing infrastructure,
+take a dependency on the `wgpu-subscriber` crate then call `initialize_default_subscriber`. It will
+set up logging to stdout/stderr based on the `RUST_LOG` environment variable.
+
+### Manual Conversion
+
+`tracing` also has tools available to convert all `tracing` events into `log` events and vise versa.
+
+#### `log` events -> `tracing` events
+
+The `tracing_log` crate has a `log` logger to translate all events into `tracing` events. Call:
+
+```rust
+tracing_log::LogTracer::init().unwrap()
+```
+
+#### `tracing` events -> `log` events
+
+The `tracing` crate has a `log` feature which will automatically use `log` if no subscriber is added:
+
+```toml
+tracing = { version = "0.1", features = ["log"] }
+```
+
+If you want events to be handled both by `tracing` and `log`, enable the `log-always` feature of `tracing`:
+
+```toml
+tracing = { version = "0.1", features = ["log-always"] }
+```
+
+## Development
+
+If you need to test local fixes to gfx or other dependencies, the simplest way is to add a Cargo patch. For example, when working on DX12 backend on Windows, you can check out the latest release branch in the [gfx-hal repository](https://github.com/gfx-rs/gfx) (e.g. currently `hal-0.8`) and add this patch to the end of `Cargo.toml`:
+
+```toml
+[patch."https://github.com/gfx-rs/gfx"]
+gfx-backend-dx12 = { path = "../gfx/src/backend/dx12" }
+gfx-hal = { path = "../gfx/src/hal" }
+```
+
+If a version needs to be changed, you need to do `cargo update -p gfx-backend-dx12`.
diff --git a/wgpu/bors.toml b/wgpu/bors.toml
new file mode 100644
index 000000000..aaa83cfb8
--- /dev/null
+++ b/wgpu/bors.toml
@@ -0,0 +1,7 @@
+status = [
+ "build (macos-10.15)",
+ "build (ubuntu-18.04)",
+ "build (windows-2019)",
+ "wasm",
+ "docs",
+]
diff --git a/wgpu/examples/README.md b/wgpu/examples/README.md
new file mode 100644
index 000000000..46eeefebd
--- /dev/null
+++ b/wgpu/examples/README.md
@@ -0,0 +1,56 @@
+## Structure
+
+For the simplest examples without using any helping code (see `framework.rs` here), check out:
+ - `hello ` for printing adapter information
+ - `hello-triangle` for graphics and presentation
+ - `hello-compute` for pure computing
+
+Notably, `capture` example shows rendering without a surface/window. It reads back the contents and saves them to a file.
+
+All the examples use [WGSL](https://gpuweb.github.io/gpuweb/wgsl.html) shaders unless specified otherwise.
+
+All framework-based examples render to the window.
+
+## Feature matrix
+| Feature | boids | bunnymark | cube | mipmap | msaa-line | shadow | skybox | texture-arrays | water | conservative-raster |
+| ---------------------------- | ------ | --------- | ------ | ------ | --------- | ------ | ------ | -------------- | ------ | ------------------- |
+| vertex attributes | :star: | | :star: | | :star: | :star: | :star: | :star: | :star: | |
+| instancing | :star: | | | | | | | | | |
+| lines and points | | | | | :star: | | | | | :star: |
+| dynamic buffer offsets | | :star: | | | | :star: | | | | |
+| implicit layout | | | | :star: | | | | | | |
+| sampled color textures | :star: | :star: | :star: | :star: | | | :star: | :star: | :star: | :star: |
+| storage textures | :star: | | | | | | | | | |
+| binding array | | | | | | | | :star: | | |
+| comparison samplers | | | | | | :star: | | | | |
+| subresource views | | | | :star: | | :star: | | | | |
+| cubemaps | | | | | | | :star: | | | |
+| multisampling | | | | | :star: | | | | | |
+| off-screen rendering | | | | | | :star: | | | :star: | :star: |
+| stencil testing | | | | | | | | | | |
+| depth testing | | | | | | :star: | :star: | | :star: | |
+| depth biasing | | | | | | :star: | | | | |
+| read-only depth | | | | | | | | | :star: | |
+| blending | | :star: | :star: | | | | | | :star: | |
+| render bundles | | | | | :star: | | | | :star: | |
+| compute passes | :star: | | | | | | | | | |
+| *optional extensions* | | | | | | | | :star: | | |
+| - SPIR-V shaders | | | | | | | | :star: | | |
+| - binding indexing | | | | | | | | :star: | | |
+| - push constants | | | | | | | | :star: | | |
+| - depth clamping | | | | | | :star: | | | | |
+| - compressed textures | | | | | | | :star: | | | |
+| - polygon mode | | | :star: | | | | | | | |
+| - queries | | | | :star: | | | | | | |
+| - conservative rasterization | | | | | | | | | | :star: |
+| *integrations* | | | | | | | | | | |
+| - staging belt | | | | | | | | | | |
+| - typed arena | | | | | | | | | | |
+| - obj loading | | | | | | | :star: | | | |
+
+## Hacking
+
+You can record an API trace any of the framework-based examples by starting them as:
+```sh
+mkdir -p trace && WGPU_TRACE=trace cargo run --features trace --example
+```
diff --git a/wgpu/examples/boids/README.md b/wgpu/examples/boids/README.md
new file mode 100644
index 000000000..28c7c88bb
--- /dev/null
+++ b/wgpu/examples/boids/README.md
@@ -0,0 +1,13 @@
+# boids
+
+Flocking boids example with gpu compute update pass
+
+## To Run
+
+```
+cargo run --example boids
+```
+
+## Screenshots
+
+
diff --git a/wgpu/examples/boids/compute.wgsl b/wgpu/examples/boids/compute.wgsl
new file mode 100644
index 000000000..bddb260a2
--- /dev/null
+++ b/wgpu/examples/boids/compute.wgsl
@@ -0,0 +1,108 @@
+struct Particle {
+ pos : vec2;
+ vel : vec2;
+};
+
+[[block]]
+struct SimParams {
+ deltaT : f32;
+ rule1Distance : f32;
+ rule2Distance : f32;
+ rule3Distance : f32;
+ rule1Scale : f32;
+ rule2Scale : f32;
+ rule3Scale : f32;
+};
+
+[[block]]
+struct Particles {
+ particles : [[stride(16)]] array;
+};
+
+[[group(0), binding(0)]] var params : SimParams;
+[[group(0), binding(1)]] var particlesSrc : [[access(read)]] Particles;
+[[group(0), binding(2)]] var particlesDst : [[access(read_write)]] Particles;
+
+// https://github.com/austinEng/Project6-Vulkan-Flocking/blob/master/data/shaders/computeparticles/particle.comp
+[[stage(compute), workgroup_size(64)]]
+fn main([[builtin(global_invocation_id)]] global_invocation_id: vec3) {
+ let total = arrayLength(&particlesSrc.particles);
+ let index = global_invocation_id.x;
+ if (index >= total) {
+ return;
+ }
+
+ var vPos : vec2 = particlesSrc.particles[index].pos;
+ var vVel : vec2 = particlesSrc.particles[index].vel;
+
+ var cMass : vec2 = vec2(0.0, 0.0);
+ var cVel : vec2 = vec2(0.0, 0.0);
+ var colVel : vec2 = vec2(0.0, 0.0);
+ var cMassCount : i32 = 0;
+ var cVelCount : i32 = 0;
+
+ var pos : vec2;
+ var vel : vec2;
+ var i : u32 = 0u;
+ loop {
+ if (i >= total) {
+ break;
+ }
+ if (i == index) {
+ continue;
+ }
+
+ pos = particlesSrc.particles[i].pos;
+ vel = particlesSrc.particles[i].vel;
+
+ if (distance(pos, vPos) < params.rule1Distance) {
+ cMass = cMass + pos;
+ cMassCount = cMassCount + 1;
+ }
+ if (distance(pos, vPos) < params.rule2Distance) {
+ colVel = colVel - (pos - vPos);
+ }
+ if (distance(pos, vPos) < params.rule3Distance) {
+ cVel = cVel + vel;
+ cVelCount = cVelCount + 1;
+ }
+
+ continuing {
+ i = i + 1u;
+ }
+ }
+ if (cMassCount > 0) {
+ cMass = cMass * (1.0 / f32(cMassCount)) - vPos;
+ }
+ if (cVelCount > 0) {
+ cVel = cVel * (1.0 / f32(cVelCount));
+ }
+
+ vVel = vVel + (cMass * params.rule1Scale) +
+ (colVel * params.rule2Scale) +
+ (cVel * params.rule3Scale);
+
+ // clamp velocity for a more pleasing simulation
+ vVel = normalize(vVel) * clamp(length(vVel), 0.0, 0.1);
+
+ // kinematic update
+ vPos = vPos + (vVel * params.deltaT);
+
+ // Wrap around boundary
+ if (vPos.x < -1.0) {
+ vPos.x = 1.0;
+ }
+ if (vPos.x > 1.0) {
+ vPos.x = -1.0;
+ }
+ if (vPos.y < -1.0) {
+ vPos.y = 1.0;
+ }
+ if (vPos.y > 1.0) {
+ vPos.y = -1.0;
+ }
+
+ // Write back
+ particlesDst.particles[index].pos = vPos;
+ particlesDst.particles[index].vel = vVel;
+}
diff --git a/wgpu/examples/boids/draw.wgsl b/wgpu/examples/boids/draw.wgsl
new file mode 100644
index 000000000..8980eb7d1
--- /dev/null
+++ b/wgpu/examples/boids/draw.wgsl
@@ -0,0 +1,18 @@
+[[stage(vertex)]]
+fn main(
+ [[location(0)]] particle_pos: vec2,
+ [[location(1)]] particle_vel: vec2,
+ [[location(2)]] position: vec2,
+) -> [[builtin(position)]] vec4 {
+ let angle = -atan2(particle_vel.x, particle_vel.y);
+ let pos = vec2(
+ position.x * cos(angle) - position.y * sin(angle),
+ position.x * sin(angle) + position.y * cos(angle)
+ );
+ return vec4(pos + particle_pos, 0.0, 1.0);
+}
+
+[[stage(fragment)]]
+fn main() -> [[location(0)]] vec4 {
+ return vec4(1.0, 1.0, 1.0, 1.0);
+}
diff --git a/wgpu/examples/boids/main.rs b/wgpu/examples/boids/main.rs
new file mode 100644
index 000000000..cfd57c23a
--- /dev/null
+++ b/wgpu/examples/boids/main.rs
@@ -0,0 +1,326 @@
+// Flocking boids example with gpu compute update pass
+// adapted from https://github.com/austinEng/webgpu-samples/blob/master/src/examples/computeBoids.ts
+
+use rand::distributions::{Distribution, Uniform};
+use std::{borrow::Cow, mem};
+use wgpu::util::DeviceExt;
+
+#[path = "../framework.rs"]
+mod framework;
+
+// number of boid particles to simulate
+
+const NUM_PARTICLES: u32 = 1500;
+
+// number of single-particle calculations (invocations) in each gpu work group
+
+const PARTICLES_PER_GROUP: u32 = 64;
+
+/// Example struct holds references to wgpu resources and frame persistent data
+struct Example {
+ particle_bind_groups: Vec,
+ particle_buffers: Vec,
+ vertices_buffer: wgpu::Buffer,
+ compute_pipeline: wgpu::ComputePipeline,
+ render_pipeline: wgpu::RenderPipeline,
+ work_group_count: u32,
+ frame_num: usize,
+}
+
+impl framework::Example for Example {
+ /// constructs initial instance of Example struct
+ fn init(
+ sc_desc: &wgpu::SwapChainDescriptor,
+ adapter: &wgpu::Adapter,
+ device: &wgpu::Device,
+ _queue: &wgpu::Queue,
+ ) -> Self {
+ // load and compile the shader
+ let mut flags = wgpu::ShaderFlags::VALIDATION;
+ match adapter.get_info().backend {
+ wgt::Backend::Vulkan | wgt::Backend::Metal | wgt::Backend::Gl => {
+ flags |= wgpu::ShaderFlags::EXPERIMENTAL_TRANSLATION;
+ }
+ _ => {} //TODO
+ }
+ let compute_shader = device.create_shader_module(&wgpu::ShaderModuleDescriptor {
+ label: None,
+ source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("compute.wgsl"))),
+ flags,
+ });
+ let draw_shader = device.create_shader_module(&wgpu::ShaderModuleDescriptor {
+ label: None,
+ source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("draw.wgsl"))),
+ flags,
+ });
+
+ // buffer for simulation parameters uniform
+
+ let sim_param_data = [
+ 0.04f32, // deltaT
+ 0.1, // rule1Distance
+ 0.025, // rule2Distance
+ 0.025, // rule3Distance
+ 0.02, // rule1Scale
+ 0.05, // rule2Scale
+ 0.005, // rule3Scale
+ ]
+ .to_vec();
+ let sim_param_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("Simulation Parameter Buffer"),
+ contents: bytemuck::cast_slice(&sim_param_data),
+ usage: wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST,
+ });
+
+ // create compute bind layout group and compute pipeline layout
+
+ let compute_bind_group_layout =
+ device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ entries: &[
+ wgpu::BindGroupLayoutEntry {
+ binding: 0,
+ visibility: wgpu::ShaderStage::COMPUTE,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Uniform,
+ has_dynamic_offset: false,
+ min_binding_size: wgpu::BufferSize::new(
+ (sim_param_data.len() * mem::size_of::()) as _,
+ ),
+ },
+ count: None,
+ },
+ wgpu::BindGroupLayoutEntry {
+ binding: 1,
+ visibility: wgpu::ShaderStage::COMPUTE,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Storage { read_only: true },
+ has_dynamic_offset: false,
+ min_binding_size: wgpu::BufferSize::new((NUM_PARTICLES * 16) as _),
+ },
+ count: None,
+ },
+ wgpu::BindGroupLayoutEntry {
+ binding: 2,
+ visibility: wgpu::ShaderStage::COMPUTE,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Storage { read_only: false },
+ has_dynamic_offset: false,
+ min_binding_size: wgpu::BufferSize::new((NUM_PARTICLES * 16) as _),
+ },
+ count: None,
+ },
+ ],
+ label: None,
+ });
+ let compute_pipeline_layout =
+ device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: Some("compute"),
+ bind_group_layouts: &[&compute_bind_group_layout],
+ push_constant_ranges: &[],
+ });
+
+ // create render pipeline with empty bind group layout
+
+ let render_pipeline_layout =
+ device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: Some("render"),
+ bind_group_layouts: &[],
+ push_constant_ranges: &[],
+ });
+
+ let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
+ label: None,
+ layout: Some(&render_pipeline_layout),
+ vertex: wgpu::VertexState {
+ module: &draw_shader,
+ entry_point: "main",
+ buffers: &[
+ wgpu::VertexBufferLayout {
+ array_stride: 4 * 4,
+ step_mode: wgpu::InputStepMode::Instance,
+ attributes: &wgpu::vertex_attr_array![0 => Float32x2, 1 => Float32x2],
+ },
+ wgpu::VertexBufferLayout {
+ array_stride: 2 * 4,
+ step_mode: wgpu::InputStepMode::Vertex,
+ attributes: &wgpu::vertex_attr_array![2 => Float32x2],
+ },
+ ],
+ },
+ fragment: Some(wgpu::FragmentState {
+ module: &draw_shader,
+ entry_point: "main",
+ targets: &[sc_desc.format.into()],
+ }),
+ primitive: wgpu::PrimitiveState::default(),
+ depth_stencil: None,
+ multisample: wgpu::MultisampleState::default(),
+ });
+
+ // create compute pipeline
+
+ let compute_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
+ label: Some("Compute pipeline"),
+ layout: Some(&compute_pipeline_layout),
+ module: &compute_shader,
+ entry_point: "main",
+ });
+
+ // buffer for the three 2d triangle vertices of each instance
+
+ let vertex_buffer_data = [-0.01f32, -0.02, 0.01, -0.02, 0.00, 0.02];
+ let vertices_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("Vertex Buffer"),
+ contents: bytemuck::bytes_of(&vertex_buffer_data),
+ usage: wgpu::BufferUsage::VERTEX | wgpu::BufferUsage::COPY_DST,
+ });
+
+ // buffer for all particles data of type [(posx,posy,velx,vely),...]
+
+ let mut initial_particle_data = vec![0.0f32; (4 * NUM_PARTICLES) as usize];
+ let mut rng = rand::thread_rng();
+ let unif = Uniform::new_inclusive(-1.0, 1.0);
+ for particle_instance_chunk in initial_particle_data.chunks_mut(4) {
+ particle_instance_chunk[0] = unif.sample(&mut rng); // posx
+ particle_instance_chunk[1] = unif.sample(&mut rng); // posy
+ particle_instance_chunk[2] = unif.sample(&mut rng) * 0.1; // velx
+ particle_instance_chunk[3] = unif.sample(&mut rng) * 0.1; // vely
+ }
+
+ // creates two buffers of particle data each of size NUM_PARTICLES
+ // the two buffers alternate as dst and src for each frame
+
+ let mut particle_buffers = Vec::::new();
+ let mut particle_bind_groups = Vec::::new();
+ for i in 0..2 {
+ particle_buffers.push(
+ device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some(&format!("Particle Buffer {}", i)),
+ contents: bytemuck::cast_slice(&initial_particle_data),
+ usage: wgpu::BufferUsage::VERTEX
+ | wgpu::BufferUsage::STORAGE
+ | wgpu::BufferUsage::COPY_DST,
+ }),
+ );
+ }
+
+ // create two bind groups, one for each buffer as the src
+ // where the alternate buffer is used as the dst
+
+ for i in 0..2 {
+ particle_bind_groups.push(device.create_bind_group(&wgpu::BindGroupDescriptor {
+ layout: &compute_bind_group_layout,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: sim_param_buffer.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: particle_buffers[i].as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: particle_buffers[(i + 1) % 2].as_entire_binding(), // bind to opposite buffer
+ },
+ ],
+ label: None,
+ }));
+ }
+
+ // calculates number of work groups from PARTICLES_PER_GROUP constant
+ let work_group_count =
+ ((NUM_PARTICLES as f32) / (PARTICLES_PER_GROUP as f32)).ceil() as u32;
+
+ // returns Example struct and No encoder commands
+
+ Example {
+ particle_bind_groups,
+ particle_buffers,
+ vertices_buffer,
+ compute_pipeline,
+ render_pipeline,
+ work_group_count,
+ frame_num: 0,
+ }
+ }
+
+ /// update is called for any WindowEvent not handled by the framework
+ fn update(&mut self, _event: winit::event::WindowEvent) {
+ //empty
+ }
+
+ /// resize is called on WindowEvent::Resized events
+ fn resize(
+ &mut self,
+ _sc_desc: &wgpu::SwapChainDescriptor,
+ _device: &wgpu::Device,
+ _queue: &wgpu::Queue,
+ ) {
+ //empty
+ }
+
+ /// render is called each frame, dispatching compute groups proportional
+ /// a TriangleList draw call for all NUM_PARTICLES at 3 vertices each
+ fn render(
+ &mut self,
+ frame: &wgpu::SwapChainTexture,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ _spawner: &framework::Spawner,
+ ) {
+ // create render pass descriptor and its color attachments
+ let color_attachments = [wgpu::RenderPassColorAttachment {
+ view: &frame.view,
+ resolve_target: None,
+ ops: wgpu::Operations {
+ load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
+ store: true,
+ },
+ }];
+ let render_pass_descriptor = wgpu::RenderPassDescriptor {
+ label: None,
+ color_attachments: &color_attachments,
+ depth_stencil_attachment: None,
+ };
+
+ // get command encoder
+ let mut command_encoder =
+ device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
+
+ command_encoder.push_debug_group("compute boid movement");
+ {
+ // compute pass
+ let mut cpass =
+ command_encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { label: None });
+ cpass.set_pipeline(&self.compute_pipeline);
+ cpass.set_bind_group(0, &self.particle_bind_groups[self.frame_num % 2], &[]);
+ cpass.dispatch(self.work_group_count, 1, 1);
+ }
+ command_encoder.pop_debug_group();
+
+ command_encoder.push_debug_group("render boids");
+ {
+ // render pass
+ let mut rpass = command_encoder.begin_render_pass(&render_pass_descriptor);
+ rpass.set_pipeline(&self.render_pipeline);
+ // render dst particles
+ rpass.set_vertex_buffer(0, self.particle_buffers[(self.frame_num + 1) % 2].slice(..));
+ // the three instance-local vertices
+ rpass.set_vertex_buffer(1, self.vertices_buffer.slice(..));
+ rpass.draw(0..3, 0..NUM_PARTICLES);
+ }
+ command_encoder.pop_debug_group();
+
+ // update frame count
+ self.frame_num += 1;
+
+ // done
+ queue.submit(Some(command_encoder.finish()));
+ }
+}
+
+/// run example
+fn main() {
+ framework::run::("boids");
+}
diff --git a/wgpu/examples/boids/screenshot.png b/wgpu/examples/boids/screenshot.png
new file mode 100644
index 000000000..e510c1c16
Binary files /dev/null and b/wgpu/examples/boids/screenshot.png differ
diff --git a/wgpu/examples/bunnymark/main.rs b/wgpu/examples/bunnymark/main.rs
new file mode 100644
index 000000000..acb591f6d
--- /dev/null
+++ b/wgpu/examples/bunnymark/main.rs
@@ -0,0 +1,354 @@
+use bytemuck::{Pod, Zeroable};
+use std::{borrow::Cow, mem};
+use wgpu::util::DeviceExt;
+
+#[path = "../framework.rs"]
+mod framework;
+
+const MAX_BUNNIES: usize = 1 << 20;
+const BUNNY_SIZE: f32 = 0.15 * 256.0;
+const GRAVITY: f32 = -9.8 * 100.0;
+const MAX_VELOCITY: f32 = 750.0;
+
+#[repr(C)]
+#[derive(Clone, Copy, Pod, Zeroable)]
+struct Globals {
+ mvp: [[f32; 4]; 4],
+ size: [f32; 2],
+ pad: [f32; 2],
+}
+
+#[repr(C, align(256))]
+#[derive(Clone, Copy, Zeroable)]
+struct Locals {
+ position: [f32; 2],
+ velocity: [f32; 2],
+ color: u32,
+ _pad: u32,
+}
+
+/// Example struct holds references to wgpu resources and frame persistent data
+struct Example {
+ global_group: wgpu::BindGroup,
+ local_group: wgpu::BindGroup,
+ pipeline: wgpu::RenderPipeline,
+ bunnies: Vec,
+ local_buffer: wgpu::Buffer,
+ extent: [u32; 2],
+}
+
+impl framework::Example for Example {
+ fn init(
+ sc_desc: &wgpu::SwapChainDescriptor,
+ _adapter: &wgpu::Adapter,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ ) -> Self {
+ let shader = device.create_shader_module(&wgpu::ShaderModuleDescriptor {
+ label: None,
+ source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("shader.wgsl"))),
+ flags: wgpu::ShaderFlags::all(),
+ });
+
+ let global_bind_group_layout =
+ device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ entries: &[
+ wgpu::BindGroupLayoutEntry {
+ binding: 0,
+ visibility: wgpu::ShaderStage::VERTEX,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Uniform,
+ has_dynamic_offset: false,
+ min_binding_size: wgpu::BufferSize::new(mem::size_of::() as _),
+ },
+ count: None,
+ },
+ wgpu::BindGroupLayoutEntry {
+ binding: 1,
+ visibility: wgpu::ShaderStage::FRAGMENT,
+ ty: wgpu::BindingType::Texture {
+ sample_type: wgpu::TextureSampleType::Float { filterable: true },
+ view_dimension: wgpu::TextureViewDimension::D2,
+ multisampled: false,
+ },
+ count: None,
+ },
+ wgpu::BindGroupLayoutEntry {
+ binding: 2,
+ visibility: wgpu::ShaderStage::FRAGMENT,
+ ty: wgpu::BindingType::Sampler {
+ filtering: true,
+ comparison: false,
+ },
+ count: None,
+ },
+ ],
+ label: None,
+ });
+ let local_bind_group_layout =
+ device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ entries: &[wgpu::BindGroupLayoutEntry {
+ binding: 0,
+ visibility: wgpu::ShaderStage::VERTEX,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Uniform,
+ has_dynamic_offset: true,
+ min_binding_size: wgpu::BufferSize::new(mem::size_of::() as _),
+ },
+ count: None,
+ }],
+ label: None,
+ });
+ let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: None,
+ bind_group_layouts: &[&global_bind_group_layout, &local_bind_group_layout],
+ push_constant_ranges: &[],
+ });
+
+ let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
+ label: None,
+ layout: Some(&pipeline_layout),
+ vertex: wgpu::VertexState {
+ module: &shader,
+ entry_point: "vs_main",
+ buffers: &[],
+ },
+ fragment: Some(wgpu::FragmentState {
+ module: &shader,
+ entry_point: "fs_main",
+ targets: &[wgpu::ColorTargetState {
+ format: sc_desc.format,
+ blend: Some(wgpu::BlendState::ALPHA_BLENDING),
+ write_mask: wgpu::ColorWrite::default(),
+ }],
+ }),
+ primitive: wgpu::PrimitiveState {
+ topology: wgpu::PrimitiveTopology::TriangleStrip,
+ ..wgpu::PrimitiveState::default()
+ },
+ depth_stencil: None,
+ multisample: wgpu::MultisampleState::default(),
+ });
+
+ let texture = {
+ let img_data = include_bytes!("../../logo.png");
+ let decoder = png::Decoder::new(std::io::Cursor::new(img_data));
+ let (info, mut reader) = decoder.read_info().unwrap();
+ let mut buf = vec![0; info.buffer_size()];
+ reader.next_frame(&mut buf).unwrap();
+
+ let size = wgpu::Extent3d {
+ width: info.width,
+ height: info.height,
+ depth_or_array_layers: 1,
+ };
+ let texture = device.create_texture(&wgpu::TextureDescriptor {
+ label: None,
+ size,
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: wgpu::TextureFormat::Rgba8UnormSrgb,
+ usage: wgpu::TextureUsage::COPY_DST | wgpu::TextureUsage::SAMPLED,
+ });
+ queue.write_texture(
+ wgpu::ImageCopyTexture {
+ texture: &texture,
+ mip_level: 0,
+ origin: wgpu::Origin3d::ZERO,
+ },
+ &buf,
+ wgpu::ImageDataLayout {
+ offset: 0,
+ bytes_per_row: std::num::NonZeroU32::new(info.width * 4),
+ rows_per_image: None,
+ },
+ size,
+ );
+ texture
+ };
+
+ let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
+ label: None,
+ address_mode_u: wgpu::AddressMode::ClampToEdge,
+ address_mode_v: wgpu::AddressMode::ClampToEdge,
+ address_mode_w: wgpu::AddressMode::ClampToEdge,
+ mag_filter: wgpu::FilterMode::Linear,
+ min_filter: wgpu::FilterMode::Nearest,
+ mipmap_filter: wgpu::FilterMode::Nearest,
+ ..Default::default()
+ });
+
+ let globals = Globals {
+ mvp: cgmath::ortho(
+ 0.0,
+ sc_desc.width as f32,
+ 0.0,
+ sc_desc.height as f32,
+ -1.0,
+ 1.0,
+ )
+ .into(),
+ size: [BUNNY_SIZE; 2],
+ pad: [0.0; 2],
+ };
+ let global_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("global"),
+ contents: bytemuck::bytes_of(&globals),
+ usage: wgpu::BufferUsage::COPY_DST | wgpu::BufferUsage::UNIFORM,
+ });
+ let local_buffer = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("local"),
+ size: (MAX_BUNNIES as wgpu::BufferAddress) * wgpu::BIND_BUFFER_ALIGNMENT,
+ usage: wgpu::BufferUsage::COPY_DST | wgpu::BufferUsage::UNIFORM,
+ mapped_at_creation: false,
+ });
+
+ let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
+ let global_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
+ layout: &global_bind_group_layout,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: global_buffer.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(&view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: wgpu::BindingResource::Sampler(&sampler),
+ },
+ ],
+ label: None,
+ });
+ let local_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
+ layout: &local_bind_group_layout,
+ entries: &[wgpu::BindGroupEntry {
+ binding: 0,
+ resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
+ buffer: &local_buffer,
+ offset: 0,
+ size: wgpu::BufferSize::new(mem::size_of::() as _),
+ }),
+ }],
+ label: None,
+ });
+
+ Example {
+ pipeline,
+ global_group,
+ local_group,
+ bunnies: Vec::new(),
+ local_buffer,
+ extent: [sc_desc.width, sc_desc.height],
+ }
+ }
+
+ fn update(&mut self, event: winit::event::WindowEvent) {
+ if let winit::event::WindowEvent::KeyboardInput {
+ input:
+ winit::event::KeyboardInput {
+ virtual_keycode: Some(winit::event::VirtualKeyCode::Space),
+ state: winit::event::ElementState::Pressed,
+ ..
+ },
+ ..
+ } = event
+ {
+ let spawn_count = 64 + self.bunnies.len() / 2;
+ let color = rand::random::();
+ println!(
+ "Spawning {} bunnies, total at {}",
+ spawn_count,
+ self.bunnies.len() + spawn_count
+ );
+ for _ in 0..spawn_count {
+ let speed = rand::random::() * MAX_VELOCITY - (MAX_VELOCITY * 0.5);
+ self.bunnies.push(Locals {
+ position: [0.0, 0.5 * (self.extent[1] as f32)],
+ velocity: [speed, 0.0],
+ color,
+ _pad: 0,
+ });
+ }
+ }
+ }
+
+ fn resize(
+ &mut self,
+ _sc_desc: &wgpu::SwapChainDescriptor,
+ _device: &wgpu::Device,
+ _queue: &wgpu::Queue,
+ ) {
+ //empty
+ }
+
+ fn render(
+ &mut self,
+ frame: &wgpu::SwapChainTexture,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ _spawner: &framework::Spawner,
+ ) {
+ let delta = 0.01;
+ for bunny in self.bunnies.iter_mut() {
+ bunny.position[0] += bunny.velocity[0] * delta;
+ bunny.position[1] += bunny.velocity[1] * delta;
+ bunny.velocity[1] += GRAVITY * delta;
+ if (bunny.velocity[0] > 0.0
+ && bunny.position[0] + 0.5 * BUNNY_SIZE > self.extent[0] as f32)
+ || (bunny.velocity[0] < 0.0 && bunny.position[0] - 0.5 * BUNNY_SIZE < 0.0)
+ {
+ bunny.velocity[0] *= -1.0;
+ }
+ if bunny.velocity[1] < 0.0 && bunny.position[1] < 0.5 * BUNNY_SIZE {
+ bunny.velocity[1] *= -1.0;
+ }
+ }
+
+ queue.write_buffer(&self.local_buffer, 0, unsafe {
+ std::slice::from_raw_parts(
+ self.bunnies.as_ptr() as *const u8,
+ self.bunnies.len() * wgpu::BIND_BUFFER_ALIGNMENT as usize,
+ )
+ });
+
+ let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor::default());
+ {
+ let clear_color = wgpu::Color {
+ r: 0.1,
+ g: 0.2,
+ b: 0.3,
+ a: 1.0,
+ };
+ let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: None,
+ color_attachments: &[wgpu::RenderPassColorAttachment {
+ view: &frame.view,
+ resolve_target: None,
+ ops: wgpu::Operations {
+ load: wgpu::LoadOp::Clear(clear_color),
+ store: true,
+ },
+ }],
+ depth_stencil_attachment: None,
+ });
+ rpass.set_pipeline(&self.pipeline);
+ rpass.set_bind_group(0, &self.global_group, &[]);
+ for i in 0..self.bunnies.len() {
+ let offset = (i as wgpu::DynamicOffset)
+ * (wgpu::BIND_BUFFER_ALIGNMENT as wgpu::DynamicOffset);
+ rpass.set_bind_group(1, &self.local_group, &[offset]);
+ rpass.draw(0..4, 0..1);
+ }
+ }
+
+ queue.submit(Some(encoder.finish()));
+ }
+}
+
+fn main() {
+ framework::run::("bunnymark");
+}
diff --git a/wgpu/examples/bunnymark/shader.wgsl b/wgpu/examples/bunnymark/shader.wgsl
new file mode 100644
index 000000000..b8639d1ca
--- /dev/null
+++ b/wgpu/examples/bunnymark/shader.wgsl
@@ -0,0 +1,43 @@
+[[block]]
+struct Globals {
+ mvp: mat4x4;
+ size: vec2;
+};
+
+[[block]]
+struct Locals {
+ position: vec2;
+ velocity: vec2;
+ color: u32;
+};
+
+[[group(0), binding(0)]]
+var globals: Globals;
+
+[[group(1), binding(0)]]
+var locals: Locals;
+
+struct VertexOutput {
+ [[builtin(position)]] position: vec4;
+ [[location(0)]] tex_coords: vec2;
+ [[location(1)]] color: vec4;
+};
+
+[[stage(vertex)]]
+fn vs_main([[builtin(vertex_index)]] vi: u32) -> VertexOutput {
+ let tc = vec2(f32(vi & 1u), 0.5 * f32(vi & 2u));
+ let offset = vec2(tc.x * globals.size.x, tc.y * globals.size.y);
+ let pos = globals.mvp * vec4(locals.position + offset, 0.0, 1.0);
+ let color = vec4((vec4(locals.color) >> vec4(0u, 8u, 16u, 24u)) & vec4(255u)) / 255.0;
+ return VertexOutput(pos, tc, color);
+}
+
+[[group(0), binding(1)]]
+var texture: texture_2d;
+[[group(0), binding(2)]]
+var sampler: sampler;
+
+[[stage(fragment)]]
+fn fs_main(in: VertexOutput) -> [[location(0)]] vec4 {
+ return in.color * textureSampleLevel(texture, sampler, in.tex_coords, 0.0);
+}
diff --git a/wgpu/examples/capture/README.md b/wgpu/examples/capture/README.md
new file mode 100644
index 000000000..b9c0ee22b
--- /dev/null
+++ b/wgpu/examples/capture/README.md
@@ -0,0 +1,18 @@
+# capture
+
+This example shows how to capture an image by rendering it to a texture, copying the texture to
+a buffer, and retrieving it from the buffer.
+
+This could be used for "taking a screenshot," with the added benefit that this method doesn't
+require a window to be created.
+
+## To Run
+
+```
+cargo run --example capture
+open examples/capture/red.png
+```
+
+## Screenshots
+
+
diff --git a/wgpu/examples/capture/main.rs b/wgpu/examples/capture/main.rs
new file mode 100644
index 000000000..319dea25a
--- /dev/null
+++ b/wgpu/examples/capture/main.rs
@@ -0,0 +1,248 @@
+use std::env;
+/// This example shows how to capture an image by rendering it to a texture, copying the texture to
+/// a buffer, and retrieving it from the buffer. This could be used for "taking a screenshot," with
+/// the added benefit that this method doesn't require a window to be created.
+use std::fs::File;
+use std::io::Write;
+use std::mem::size_of;
+use wgpu::{Buffer, Device};
+
+async fn run(png_output_path: &str) {
+ let args: Vec<_> = env::args().collect();
+ let (width, height) = match args.len() {
+ // 0 on wasm, 1 on desktop
+ 0 | 1 => (100usize, 200usize),
+ 3 => (args[1].parse().unwrap(), args[2].parse().unwrap()),
+ _ => {
+ println!("Incorrect number of arguments, possible usages:");
+ println!("* 0 arguments - uses default width and height of (100, 200)");
+ println!("* 2 arguments - uses specified width and height values");
+ return;
+ }
+ };
+ let (device, buffer, buffer_dimensions) = create_red_image_with_dimensions(width, height).await;
+ create_png(png_output_path, device, buffer, &buffer_dimensions).await;
+}
+
+async fn create_red_image_with_dimensions(
+ width: usize,
+ height: usize,
+) -> (Device, Buffer, BufferDimensions) {
+ let adapter = wgpu::Instance::new(wgpu::BackendBit::PRIMARY)
+ .request_adapter(&wgpu::RequestAdapterOptions::default())
+ .await
+ .unwrap();
+
+ let (device, queue) = adapter
+ .request_device(
+ &wgpu::DeviceDescriptor {
+ label: None,
+ features: wgpu::Features::empty(),
+ limits: wgpu::Limits::default(),
+ },
+ None,
+ )
+ .await
+ .unwrap();
+
+ // It is a WebGPU requirement that ImageCopyBuffer.layout.bytes_per_row % wgpu::COPY_BYTES_PER_ROW_ALIGNMENT == 0
+ // So we calculate padded_bytes_per_row by rounding unpadded_bytes_per_row
+ // up to the next multiple of wgpu::COPY_BYTES_PER_ROW_ALIGNMENT.
+ // https://en.wikipedia.org/wiki/Data_structure_alignment#Computing_padding
+ let buffer_dimensions = BufferDimensions::new(width, height);
+ // The output buffer lets us retrieve the data as an array
+ let output_buffer = device.create_buffer(&wgpu::BufferDescriptor {
+ label: None,
+ size: (buffer_dimensions.padded_bytes_per_row * buffer_dimensions.height) as u64,
+ usage: wgpu::BufferUsage::MAP_READ | wgpu::BufferUsage::COPY_DST,
+ mapped_at_creation: false,
+ });
+
+ let texture_extent = wgpu::Extent3d {
+ width: buffer_dimensions.width as u32,
+ height: buffer_dimensions.height as u32,
+ depth_or_array_layers: 1,
+ };
+
+ // The render pipeline renders data into this texture
+ let texture = device.create_texture(&wgpu::TextureDescriptor {
+ size: texture_extent,
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: wgpu::TextureFormat::Rgba8UnormSrgb,
+ usage: wgpu::TextureUsage::RENDER_ATTACHMENT | wgpu::TextureUsage::COPY_SRC,
+ label: None,
+ });
+
+ // Set the background to be red
+ let command_buffer = {
+ let mut encoder =
+ device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
+ encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: None,
+ color_attachments: &[wgpu::RenderPassColorAttachment {
+ view: &texture.create_view(&wgpu::TextureViewDescriptor::default()),
+ resolve_target: None,
+ ops: wgpu::Operations {
+ load: wgpu::LoadOp::Clear(wgpu::Color::RED),
+ store: true,
+ },
+ }],
+ depth_stencil_attachment: None,
+ });
+
+ // Copy the data from the texture to the buffer
+ encoder.copy_texture_to_buffer(
+ wgpu::ImageCopyTexture {
+ texture: &texture,
+ mip_level: 0,
+ origin: wgpu::Origin3d::ZERO,
+ },
+ wgpu::ImageCopyBuffer {
+ buffer: &output_buffer,
+ layout: wgpu::ImageDataLayout {
+ offset: 0,
+ bytes_per_row: Some(
+ std::num::NonZeroU32::new(buffer_dimensions.padded_bytes_per_row as u32)
+ .unwrap(),
+ ),
+ rows_per_image: None,
+ },
+ },
+ texture_extent,
+ );
+
+ encoder.finish()
+ };
+
+ queue.submit(Some(command_buffer));
+ (device, output_buffer, buffer_dimensions)
+}
+
+async fn create_png(
+ png_output_path: &str,
+ device: Device,
+ output_buffer: Buffer,
+ buffer_dimensions: &BufferDimensions,
+) {
+ // Note that we're not calling `.await` here.
+ let buffer_slice = output_buffer.slice(..);
+ let buffer_future = buffer_slice.map_async(wgpu::MapMode::Read);
+
+ // Poll the device in a blocking manner so that our future resolves.
+ // In an actual application, `device.poll(...)` should
+ // be called in an event loop or on another thread.
+ device.poll(wgpu::Maintain::Wait);
+ // If a file system is available, write the buffer as a PNG
+ let has_file_system_available = cfg!(not(target_arch = "wasm32"));
+ if !has_file_system_available {
+ return;
+ }
+
+ if let Ok(()) = buffer_future.await {
+ let padded_buffer = buffer_slice.get_mapped_range();
+
+ let mut png_encoder = png::Encoder::new(
+ File::create(png_output_path).unwrap(),
+ buffer_dimensions.width as u32,
+ buffer_dimensions.height as u32,
+ );
+ png_encoder.set_depth(png::BitDepth::Eight);
+ png_encoder.set_color(png::ColorType::RGBA);
+ let mut png_writer = png_encoder
+ .write_header()
+ .unwrap()
+ .into_stream_writer_with_size(buffer_dimensions.unpadded_bytes_per_row);
+
+ // from the padded_buffer we write just the unpadded bytes into the image
+ for chunk in padded_buffer.chunks(buffer_dimensions.padded_bytes_per_row) {
+ png_writer
+ .write_all(&chunk[..buffer_dimensions.unpadded_bytes_per_row])
+ .unwrap();
+ }
+ png_writer.finish().unwrap();
+
+ // With the current interface, we have to make sure all mapped views are
+ // dropped before we unmap the buffer.
+ drop(padded_buffer);
+
+ output_buffer.unmap();
+ }
+}
+
+struct BufferDimensions {
+ width: usize,
+ height: usize,
+ unpadded_bytes_per_row: usize,
+ padded_bytes_per_row: usize,
+}
+
+impl BufferDimensions {
+ fn new(width: usize, height: usize) -> Self {
+ let bytes_per_pixel = size_of::();
+ let unpadded_bytes_per_row = width * bytes_per_pixel;
+ let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as usize;
+ let padded_bytes_per_row_padding = (align - unpadded_bytes_per_row % align) % align;
+ let padded_bytes_per_row = unpadded_bytes_per_row + padded_bytes_per_row_padding;
+ Self {
+ width,
+ height,
+ unpadded_bytes_per_row,
+ padded_bytes_per_row,
+ }
+ }
+}
+
+fn main() {
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ env_logger::init();
+ pollster::block_on(run("red.png"));
+ }
+ #[cfg(target_arch = "wasm32")]
+ {
+ std::panic::set_hook(Box::new(console_error_panic_hook::hook));
+ console_log::init().expect("could not initialize logger");
+ wasm_bindgen_futures::spawn_local(run("red.png"));
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use wgpu::BufferView;
+
+ #[test]
+ fn ensure_generated_data_matches_expected() {
+ pollster::block_on(assert_generated_data_matches_expected());
+ }
+
+ async fn assert_generated_data_matches_expected() {
+ let (device, output_buffer, dimensions) =
+ create_red_image_with_dimensions(100usize, 200usize).await;
+ let buffer_slice = output_buffer.slice(..);
+ let buffer_future = buffer_slice.map_async(wgpu::MapMode::Read);
+ device.poll(wgpu::Maintain::Wait);
+ buffer_future
+ .await
+ .expect("failed to map buffer slice for capture test");
+ let padded_buffer = buffer_slice.get_mapped_range();
+ let expected_buffer_size = dimensions.padded_bytes_per_row * dimensions.height;
+ assert_eq!(padded_buffer.len(), expected_buffer_size);
+ assert_that_content_is_all_red(&dimensions, padded_buffer);
+ }
+
+ fn assert_that_content_is_all_red(dimensions: &BufferDimensions, padded_buffer: BufferView) {
+ let red = [0xFFu8, 0, 0, 0xFFu8];
+ let single_rgba = 4;
+ padded_buffer
+ .chunks(dimensions.padded_bytes_per_row)
+ .map(|padded_buffer_row| &padded_buffer_row[..dimensions.unpadded_bytes_per_row])
+ .for_each(|unpadded_row| {
+ unpadded_row
+ .chunks(single_rgba)
+ .for_each(|chunk| assert_eq!(chunk, &red))
+ });
+ }
+}
diff --git a/wgpu/examples/capture/screenshot.png b/wgpu/examples/capture/screenshot.png
new file mode 100644
index 000000000..4021a58f6
Binary files /dev/null and b/wgpu/examples/capture/screenshot.png differ
diff --git a/wgpu/examples/conservative-raster/README.md b/wgpu/examples/conservative-raster/README.md
new file mode 100644
index 000000000..bd157319b
--- /dev/null
+++ b/wgpu/examples/conservative-raster/README.md
@@ -0,0 +1,20 @@
+# conservative-raster
+
+This example shows how to render with conservative rasterization (native extension with limited support).
+
+When enabled, any pixel touched by a triangle primitive is rasterized.
+This is useful for various advanced techniques, most prominently for implementing realtime voxelization.
+
+The demonstration here is implemented by rendering a triangle to a low-resolution target and then upscaling it with nearest-neighbor filtering.
+The outlines of the triangle are then rendered in the original solution, using the same vertex shader as the triangle.
+Pixels only drawn with conservative rasterization enabled are depicted red.
+
+## To Run
+
+```
+cargo run --example conservative-raster
+```
+
+## Screenshots
+
+
diff --git a/wgpu/examples/conservative-raster/main.rs b/wgpu/examples/conservative-raster/main.rs
new file mode 100644
index 000000000..763b7e9a7
--- /dev/null
+++ b/wgpu/examples/conservative-raster/main.rs
@@ -0,0 +1,316 @@
+#[path = "../framework.rs"]
+mod framework;
+
+use std::borrow::Cow;
+
+const RENDER_TARGET_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8UnormSrgb;
+
+struct Example {
+ low_res_target: wgpu::TextureView,
+ bind_group_upscale: wgpu::BindGroup,
+
+ pipeline_triangle_conservative: wgpu::RenderPipeline,
+ pipeline_triangle_regular: wgpu::RenderPipeline,
+ pipeline_upscale: wgpu::RenderPipeline,
+ pipeline_lines: Option,
+ bind_group_layout_upscale: wgpu::BindGroupLayout,
+}
+
+impl Example {
+ fn create_low_res_target(
+ sc_desc: &wgpu::SwapChainDescriptor,
+ device: &wgpu::Device,
+ bind_group_layout_upscale: &wgpu::BindGroupLayout,
+ ) -> (wgpu::TextureView, wgpu::BindGroup) {
+ let texture_view = device
+ .create_texture(&wgpu::TextureDescriptor {
+ label: Some("Low Resolution Target"),
+ size: wgpu::Extent3d {
+ width: sc_desc.width / 16,
+ height: sc_desc.width / 16,
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: RENDER_TARGET_FORMAT,
+ usage: wgpu::TextureUsage::SAMPLED | wgpu::TextureUsage::RENDER_ATTACHMENT,
+ })
+ .create_view(&Default::default());
+
+ let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
+ label: Some("Nearest Neighbor Sampler"),
+ mag_filter: wgpu::FilterMode::Nearest,
+ min_filter: wgpu::FilterMode::Nearest,
+ ..Default::default()
+ });
+
+ let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("upscale bind group"),
+ layout: &bind_group_layout_upscale,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: wgpu::BindingResource::TextureView(&texture_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::Sampler(&sampler),
+ },
+ ],
+ });
+
+ (texture_view, bind_group)
+ }
+}
+
+impl framework::Example for Example {
+ fn required_features() -> wgpu::Features {
+ wgpu::Features::CONSERVATIVE_RASTERIZATION
+ }
+ fn optional_features() -> wgpu::Features {
+ wgpu::Features::NON_FILL_POLYGON_MODE
+ }
+ fn init(
+ sc_desc: &wgpu::SwapChainDescriptor,
+ adapter: &wgpu::Adapter,
+ device: &wgpu::Device,
+ _queue: &wgpu::Queue,
+ ) -> Self {
+ let pipeline_layout_empty =
+ device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: None,
+ bind_group_layouts: &[],
+ push_constant_ranges: &[],
+ });
+
+ let shader_triangle_and_lines =
+ device.create_shader_module(&wgpu::ShaderModuleDescriptor {
+ label: None,
+ source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!(
+ "triangle_and_lines.wgsl"
+ ))),
+ flags: wgpu::ShaderFlags::all(),
+ });
+
+ let pipeline_triangle_conservative =
+ device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
+ label: Some("Conservative Rasterization"),
+ layout: Some(&pipeline_layout_empty),
+ vertex: wgpu::VertexState {
+ module: &shader_triangle_and_lines,
+ entry_point: "vs_main",
+ buffers: &[],
+ },
+ fragment: Some(wgpu::FragmentState {
+ module: &shader_triangle_and_lines,
+ entry_point: "fs_main_red",
+ targets: &[RENDER_TARGET_FORMAT.into()],
+ }),
+ primitive: wgpu::PrimitiveState {
+ conservative: true,
+ ..Default::default()
+ },
+ depth_stencil: None,
+ multisample: wgpu::MultisampleState::default(),
+ });
+
+ let pipeline_triangle_regular =
+ device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
+ label: Some("Regular Rasterization"),
+ layout: Some(&pipeline_layout_empty),
+ vertex: wgpu::VertexState {
+ module: &shader_triangle_and_lines,
+ entry_point: "vs_main",
+ buffers: &[],
+ },
+ fragment: Some(wgpu::FragmentState {
+ module: &shader_triangle_and_lines,
+ entry_point: "fs_main_blue",
+ targets: &[RENDER_TARGET_FORMAT.into()],
+ }),
+ primitive: wgpu::PrimitiveState::default(),
+ depth_stencil: None,
+ multisample: wgpu::MultisampleState::default(),
+ });
+
+ let pipeline_lines = if adapter
+ .features()
+ .contains(wgpu::Features::NON_FILL_POLYGON_MODE)
+ {
+ Some(
+ device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
+ label: Some("Lines"),
+ layout: Some(&pipeline_layout_empty),
+ vertex: wgpu::VertexState {
+ module: &shader_triangle_and_lines,
+ entry_point: "vs_main",
+ buffers: &[],
+ },
+ fragment: Some(wgpu::FragmentState {
+ module: &shader_triangle_and_lines,
+ entry_point: "fs_main_white",
+ targets: &[sc_desc.format.into()],
+ }),
+ primitive: wgpu::PrimitiveState {
+ polygon_mode: wgpu::PolygonMode::Line,
+ topology: wgpu::PrimitiveTopology::LineStrip,
+ ..Default::default()
+ },
+ depth_stencil: None,
+ multisample: wgpu::MultisampleState::default(),
+ }),
+ )
+ } else {
+ None
+ };
+
+ let (pipeline_upscale, bind_group_layout_upscale) = {
+ let bind_group_layout =
+ device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ label: Some("upscale bindgroup"),
+ entries: &[
+ wgpu::BindGroupLayoutEntry {
+ binding: 0,
+ visibility: wgpu::ShaderStage::FRAGMENT,
+ ty: wgpu::BindingType::Texture {
+ sample_type: wgpu::TextureSampleType::Float { filterable: false },
+ view_dimension: wgpu::TextureViewDimension::D2,
+ multisampled: false,
+ },
+ count: None,
+ },
+ wgpu::BindGroupLayoutEntry {
+ binding: 1,
+ visibility: wgpu::ShaderStage::FRAGMENT,
+ ty: wgpu::BindingType::Sampler {
+ filtering: false,
+ comparison: false,
+ },
+ count: None,
+ },
+ ],
+ });
+
+ let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: None,
+ bind_group_layouts: &[&bind_group_layout],
+ push_constant_ranges: &[],
+ });
+ let shader = device.create_shader_module(&wgpu::ShaderModuleDescriptor {
+ label: None,
+ source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("upscale.wgsl"))),
+ flags: wgpu::ShaderFlags::all(),
+ });
+ (
+ device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
+ label: Some("Upscale"),
+ layout: Some(&pipeline_layout),
+ vertex: wgpu::VertexState {
+ module: &shader,
+ entry_point: "vs_main",
+ buffers: &[],
+ },
+ fragment: Some(wgpu::FragmentState {
+ module: &shader,
+ entry_point: "fs_main",
+ targets: &[sc_desc.format.into()],
+ }),
+ primitive: wgpu::PrimitiveState::default(),
+ depth_stencil: None,
+ multisample: wgpu::MultisampleState::default(),
+ }),
+ bind_group_layout,
+ )
+ };
+
+ let (low_res_target, bind_group_upscale) =
+ Self::create_low_res_target(sc_desc, device, &bind_group_layout_upscale);
+
+ Self {
+ low_res_target,
+ bind_group_upscale,
+
+ pipeline_triangle_conservative,
+ pipeline_triangle_regular,
+ pipeline_upscale,
+ pipeline_lines,
+ bind_group_layout_upscale,
+ }
+ }
+
+ fn resize(
+ &mut self,
+ sc_desc: &wgpu::SwapChainDescriptor,
+ device: &wgpu::Device,
+ _queue: &wgpu::Queue,
+ ) {
+ let (low_res_target, bind_group_upscale) =
+ Self::create_low_res_target(sc_desc, device, &self.bind_group_layout_upscale);
+ self.low_res_target = low_res_target;
+ self.bind_group_upscale = bind_group_upscale;
+ }
+
+ fn update(&mut self, _event: winit::event::WindowEvent) {}
+
+ fn render(
+ &mut self,
+ frame: &wgpu::SwapChainTexture,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ _spawner: &framework::Spawner,
+ ) {
+ let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("primary"),
+ });
+
+ {
+ let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: Some("low resolution"),
+ color_attachments: &[wgpu::RenderPassColorAttachment {
+ view: &self.low_res_target,
+ resolve_target: None,
+ ops: wgpu::Operations {
+ load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
+ store: true,
+ },
+ }],
+ depth_stencil_attachment: None,
+ });
+
+ rpass.set_pipeline(&self.pipeline_triangle_conservative);
+ rpass.draw(0..3, 0..1);
+ rpass.set_pipeline(&self.pipeline_triangle_regular);
+ rpass.draw(0..3, 0..1);
+ }
+ {
+ let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: Some("full resolution"),
+ color_attachments: &[wgpu::RenderPassColorAttachment {
+ view: &frame.view,
+ resolve_target: None,
+ ops: wgpu::Operations {
+ load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
+ store: true,
+ },
+ }],
+ depth_stencil_attachment: None,
+ });
+
+ rpass.set_pipeline(&self.pipeline_upscale);
+ rpass.set_bind_group(0, &self.bind_group_upscale, &[]);
+ rpass.draw(0..3, 0..1);
+
+ if let Some(pipeline_lines) = &self.pipeline_lines {
+ rpass.set_pipeline(pipeline_lines);
+ rpass.draw(0..4, 0..1);
+ }
+ }
+
+ queue.submit(Some(encoder.finish()));
+ }
+}
+
+fn main() {
+ framework::run::("conservative-raster");
+}
diff --git a/wgpu/examples/conservative-raster/screenshot.png b/wgpu/examples/conservative-raster/screenshot.png
new file mode 100644
index 000000000..e227e10e6
Binary files /dev/null and b/wgpu/examples/conservative-raster/screenshot.png differ
diff --git a/wgpu/examples/conservative-raster/triangle_and_lines.wgsl b/wgpu/examples/conservative-raster/triangle_and_lines.wgsl
new file mode 100644
index 000000000..a553ff4f6
--- /dev/null
+++ b/wgpu/examples/conservative-raster/triangle_and_lines.wgsl
@@ -0,0 +1,22 @@
+[[stage(vertex)]]
+fn vs_main([[builtin(vertex_index)]] vertex_index: u32) -> [[builtin(position)]] vec4 {
+ let i: i32 = i32(vertex_index % 3u);
+ let x: f32 = f32(i - 1) * 0.75;
+ let y: f32 = f32((i & 1) * 2 - 1) * 0.75 + x * 0.2 + 0.1;
+ return vec4(x, y, 0.0, 1.0);
+}
+
+[[stage(fragment)]]
+fn fs_main_red() -> [[location(0)]] vec4 {
+ return vec4(1.0, 0.0, 0.0, 1.0);
+}
+
+[[stage(fragment)]]
+fn fs_main_blue() -> [[location(0)]] vec4 {
+ return vec4(0.13, 0.31, 0.85, 1.0); // cornflower blue in linear space
+}
+
+[[stage(fragment)]]
+fn fs_main_white() -> [[location(0)]] vec4 {
+ return vec4(1.0, 1.0, 1.0, 1.0);
+}
\ No newline at end of file
diff --git a/wgpu/examples/conservative-raster/upscale.wgsl b/wgpu/examples/conservative-raster/upscale.wgsl
new file mode 100644
index 000000000..edb87df17
--- /dev/null
+++ b/wgpu/examples/conservative-raster/upscale.wgsl
@@ -0,0 +1,24 @@
+struct VertexOutput {
+ [[builtin(position)]] position: vec4;
+ [[location(0)]] tex_coords: vec2;
+};
+
+[[stage(vertex)]]
+fn vs_main([[builtin(vertex_index)]] vertex_index: u32) -> VertexOutput {
+ let x: f32 = f32(i32(vertex_index & 1u) << 2u) - 1.0;
+ let y: f32 = f32(i32(vertex_index & 2u) << 1u) - 1.0;
+ var output: VertexOutput;
+ output.position = vec4(x, -y, 0.0, 1.0);
+ output.tex_coords = vec2(x + 1.0, y + 1.0) * 0.5;
+ return output;
+}
+
+[[group(0), binding(0)]]
+var r_color: texture_2d;
+[[group(0), binding(1)]]
+var r_sampler: sampler;
+
+[[stage(fragment)]]
+fn fs_main(in: VertexOutput) -> [[location(0)]] vec4 {
+ return textureSample(r_color, r_sampler, in.tex_coords);
+}
\ No newline at end of file
diff --git a/wgpu/examples/cube/README.md b/wgpu/examples/cube/README.md
new file mode 100644
index 000000000..8b3f32872
--- /dev/null
+++ b/wgpu/examples/cube/README.md
@@ -0,0 +1,13 @@
+# cube
+
+This example renders a textured cube.
+
+## To Run
+
+```
+cargo run --example cube
+```
+
+## Screenshots
+
+
diff --git a/wgpu/examples/cube/main.rs b/wgpu/examples/cube/main.rs
new file mode 100644
index 000000000..a745791d0
--- /dev/null
+++ b/wgpu/examples/cube/main.rs
@@ -0,0 +1,393 @@
+#[path = "../framework.rs"]
+mod framework;
+
+use bytemuck::{Pod, Zeroable};
+use std::{borrow::Cow, mem};
+use wgpu::util::DeviceExt;
+
+#[repr(C)]
+#[derive(Clone, Copy, Pod, Zeroable)]
+struct Vertex {
+ _pos: [f32; 4],
+ _tex_coord: [f32; 2],
+}
+
+fn vertex(pos: [i8; 3], tc: [i8; 2]) -> Vertex {
+ Vertex {
+ _pos: [pos[0] as f32, pos[1] as f32, pos[2] as f32, 1.0],
+ _tex_coord: [tc[0] as f32, tc[1] as f32],
+ }
+}
+
+fn create_vertices() -> (Vec, Vec) {
+ let vertex_data = [
+ // top (0, 0, 1)
+ vertex([-1, -1, 1], [0, 0]),
+ vertex([1, -1, 1], [1, 0]),
+ vertex([1, 1, 1], [1, 1]),
+ vertex([-1, 1, 1], [0, 1]),
+ // bottom (0, 0, -1)
+ vertex([-1, 1, -1], [1, 0]),
+ vertex([1, 1, -1], [0, 0]),
+ vertex([1, -1, -1], [0, 1]),
+ vertex([-1, -1, -1], [1, 1]),
+ // right (1, 0, 0)
+ vertex([1, -1, -1], [0, 0]),
+ vertex([1, 1, -1], [1, 0]),
+ vertex([1, 1, 1], [1, 1]),
+ vertex([1, -1, 1], [0, 1]),
+ // left (-1, 0, 0)
+ vertex([-1, -1, 1], [1, 0]),
+ vertex([-1, 1, 1], [0, 0]),
+ vertex([-1, 1, -1], [0, 1]),
+ vertex([-1, -1, -1], [1, 1]),
+ // front (0, 1, 0)
+ vertex([1, 1, -1], [1, 0]),
+ vertex([-1, 1, -1], [0, 0]),
+ vertex([-1, 1, 1], [0, 1]),
+ vertex([1, 1, 1], [1, 1]),
+ // back (0, -1, 0)
+ vertex([1, -1, 1], [0, 0]),
+ vertex([-1, -1, 1], [1, 0]),
+ vertex([-1, -1, -1], [1, 1]),
+ vertex([1, -1, -1], [0, 1]),
+ ];
+
+ let index_data: &[u16] = &[
+ 0, 1, 2, 2, 3, 0, // top
+ 4, 5, 6, 6, 7, 4, // bottom
+ 8, 9, 10, 10, 11, 8, // right
+ 12, 13, 14, 14, 15, 12, // left
+ 16, 17, 18, 18, 19, 16, // front
+ 20, 21, 22, 22, 23, 20, // back
+ ];
+
+ (vertex_data.to_vec(), index_data.to_vec())
+}
+
+fn create_texels(size: usize) -> Vec {
+ (0..size * size)
+ .map(|id| {
+ // get high five for recognizing this ;)
+ let cx = 3.0 * (id % size) as f32 / (size - 1) as f32 - 2.0;
+ let cy = 2.0 * (id / size) as f32 / (size - 1) as f32 - 1.0;
+ let (mut x, mut y, mut count) = (cx, cy, 0);
+ while count < 0xFF && x * x + y * y < 4.0 {
+ let old_x = x;
+ x = x * x - y * y + cx;
+ y = 2.0 * old_x * y + cy;
+ count += 1;
+ }
+ count
+ })
+ .collect()
+}
+
+struct Example {
+ vertex_buf: wgpu::Buffer,
+ index_buf: wgpu::Buffer,
+ index_count: usize,
+ bind_group: wgpu::BindGroup,
+ uniform_buf: wgpu::Buffer,
+ pipeline: wgpu::RenderPipeline,
+ pipeline_wire: Option,
+}
+
+impl Example {
+ fn generate_matrix(aspect_ratio: f32) -> cgmath::Matrix4 {
+ let mx_projection = cgmath::perspective(cgmath::Deg(45f32), aspect_ratio, 1.0, 10.0);
+ let mx_view = cgmath::Matrix4::look_at_rh(
+ cgmath::Point3::new(1.5f32, -5.0, 3.0),
+ cgmath::Point3::new(0f32, 0.0, 0.0),
+ cgmath::Vector3::unit_z(),
+ );
+ let mx_correction = framework::OPENGL_TO_WGPU_MATRIX;
+ mx_correction * mx_projection * mx_view
+ }
+}
+
+impl framework::Example for Example {
+ fn optional_features() -> wgt::Features {
+ wgt::Features::NON_FILL_POLYGON_MODE
+ }
+
+ fn init(
+ sc_desc: &wgpu::SwapChainDescriptor,
+ adapter: &wgpu::Adapter,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ ) -> Self {
+ // Create the vertex and index buffers
+ let vertex_size = mem::size_of::();
+ let (vertex_data, index_data) = create_vertices();
+
+ let vertex_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("Vertex Buffer"),
+ contents: bytemuck::cast_slice(&vertex_data),
+ usage: wgpu::BufferUsage::VERTEX,
+ });
+
+ let index_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("Index Buffer"),
+ contents: bytemuck::cast_slice(&index_data),
+ usage: wgpu::BufferUsage::INDEX,
+ });
+
+ // Create pipeline layout
+ let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ label: None,
+ entries: &[
+ wgpu::BindGroupLayoutEntry {
+ binding: 0,
+ visibility: wgpu::ShaderStage::VERTEX,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Uniform,
+ has_dynamic_offset: false,
+ min_binding_size: wgpu::BufferSize::new(64),
+ },
+ count: None,
+ },
+ wgpu::BindGroupLayoutEntry {
+ binding: 1,
+ visibility: wgpu::ShaderStage::FRAGMENT,
+ ty: wgpu::BindingType::Texture {
+ multisampled: false,
+ sample_type: wgpu::TextureSampleType::Uint,
+ view_dimension: wgpu::TextureViewDimension::D2,
+ },
+ count: None,
+ },
+ ],
+ });
+ let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: None,
+ bind_group_layouts: &[&bind_group_layout],
+ push_constant_ranges: &[],
+ });
+
+ // Create the texture
+ let size = 256u32;
+ let texels = create_texels(size as usize);
+ let texture_extent = wgpu::Extent3d {
+ width: size,
+ height: size,
+ depth_or_array_layers: 1,
+ };
+ let texture = device.create_texture(&wgpu::TextureDescriptor {
+ label: None,
+ size: texture_extent,
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: wgpu::TextureFormat::R8Uint,
+ usage: wgpu::TextureUsage::SAMPLED | wgpu::TextureUsage::COPY_DST,
+ });
+ let texture_view = texture.create_view(&wgpu::TextureViewDescriptor::default());
+ queue.write_texture(
+ wgpu::ImageCopyTexture {
+ texture: &texture,
+ mip_level: 0,
+ origin: wgpu::Origin3d::ZERO,
+ },
+ &texels,
+ wgpu::ImageDataLayout {
+ offset: 0,
+ bytes_per_row: Some(std::num::NonZeroU32::new(size).unwrap()),
+ rows_per_image: None,
+ },
+ texture_extent,
+ );
+
+ // Create other resources
+ let mx_total = Self::generate_matrix(sc_desc.width as f32 / sc_desc.height as f32);
+ let mx_ref: &[f32; 16] = mx_total.as_ref();
+ let uniform_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("Uniform Buffer"),
+ contents: bytemuck::cast_slice(mx_ref),
+ usage: wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST,
+ });
+
+ // Create bind group
+ let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
+ layout: &bind_group_layout,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: uniform_buf.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(&texture_view),
+ },
+ ],
+ label: None,
+ });
+
+ let mut flags = wgpu::ShaderFlags::VALIDATION;
+ match adapter.get_info().backend {
+ wgpu::Backend::Metal | wgpu::Backend::Vulkan | wgpu::Backend::Gl => {
+ flags |= wgpu::ShaderFlags::EXPERIMENTAL_TRANSLATION
+ }
+ _ => (), //TODO
+ }
+ let shader = device.create_shader_module(&wgpu::ShaderModuleDescriptor {
+ label: None,
+ source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("shader.wgsl"))),
+ flags,
+ });
+
+ let vertex_buffers = [wgpu::VertexBufferLayout {
+ array_stride: vertex_size as wgpu::BufferAddress,
+ step_mode: wgpu::InputStepMode::Vertex,
+ attributes: &[
+ wgpu::VertexAttribute {
+ format: wgpu::VertexFormat::Float32x4,
+ offset: 0,
+ shader_location: 0,
+ },
+ wgpu::VertexAttribute {
+ format: wgpu::VertexFormat::Float32x2,
+ offset: 4 * 4,
+ shader_location: 1,
+ },
+ ],
+ }];
+
+ let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
+ label: None,
+ layout: Some(&pipeline_layout),
+ vertex: wgpu::VertexState {
+ module: &shader,
+ entry_point: "vs_main",
+ buffers: &vertex_buffers,
+ },
+ fragment: Some(wgpu::FragmentState {
+ module: &shader,
+ entry_point: "fs_main",
+ targets: &[sc_desc.format.into()],
+ }),
+ primitive: wgpu::PrimitiveState {
+ cull_mode: Some(wgpu::Face::Back),
+ ..Default::default()
+ },
+ depth_stencil: None,
+ multisample: wgpu::MultisampleState::default(),
+ });
+
+ let pipeline_wire = if device
+ .features()
+ .contains(wgt::Features::NON_FILL_POLYGON_MODE)
+ {
+ let pipeline_wire = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
+ label: None,
+ layout: Some(&pipeline_layout),
+ vertex: wgpu::VertexState {
+ module: &shader,
+ entry_point: "vs_main",
+ buffers: &vertex_buffers,
+ },
+ fragment: Some(wgpu::FragmentState {
+ module: &shader,
+ entry_point: "fs_wire",
+ targets: &[wgpu::ColorTargetState {
+ format: sc_desc.format,
+ blend: Some(wgpu::BlendState {
+ color: wgpu::BlendComponent {
+ operation: wgpu::BlendOperation::Add,
+ src_factor: wgpu::BlendFactor::SrcAlpha,
+ dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
+ },
+ alpha: wgpu::BlendComponent::REPLACE,
+ }),
+ write_mask: wgpu::ColorWrite::ALL,
+ }],
+ }),
+ primitive: wgpu::PrimitiveState {
+ front_face: wgpu::FrontFace::Ccw,
+ cull_mode: Some(wgpu::Face::Back),
+ polygon_mode: wgpu::PolygonMode::Line,
+ ..Default::default()
+ },
+ depth_stencil: None,
+ multisample: wgpu::MultisampleState::default(),
+ });
+ Some(pipeline_wire)
+ } else {
+ None
+ };
+
+ // Done
+ Example {
+ vertex_buf,
+ index_buf,
+ index_count: index_data.len(),
+ bind_group,
+ uniform_buf,
+ pipeline,
+ pipeline_wire,
+ }
+ }
+
+ fn update(&mut self, _event: winit::event::WindowEvent) {
+ //empty
+ }
+
+ fn resize(
+ &mut self,
+ sc_desc: &wgpu::SwapChainDescriptor,
+ _device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ ) {
+ let mx_total = Self::generate_matrix(sc_desc.width as f32 / sc_desc.height as f32);
+ let mx_ref: &[f32; 16] = mx_total.as_ref();
+ queue.write_buffer(&self.uniform_buf, 0, bytemuck::cast_slice(mx_ref));
+ }
+
+ fn render(
+ &mut self,
+ frame: &wgpu::SwapChainTexture,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ _spawner: &framework::Spawner,
+ ) {
+ let mut encoder =
+ device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
+ {
+ let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: None,
+ color_attachments: &[wgpu::RenderPassColorAttachment {
+ view: &frame.view,
+ resolve_target: None,
+ ops: wgpu::Operations {
+ load: wgpu::LoadOp::Clear(wgpu::Color {
+ r: 0.1,
+ g: 0.2,
+ b: 0.3,
+ a: 1.0,
+ }),
+ store: true,
+ },
+ }],
+ depth_stencil_attachment: None,
+ });
+ rpass.push_debug_group("Prepare data for draw.");
+ rpass.set_pipeline(&self.pipeline);
+ rpass.set_bind_group(0, &self.bind_group, &[]);
+ rpass.set_index_buffer(self.index_buf.slice(..), wgpu::IndexFormat::Uint16);
+ rpass.set_vertex_buffer(0, self.vertex_buf.slice(..));
+ rpass.pop_debug_group();
+ rpass.insert_debug_marker("Draw!");
+ rpass.draw_indexed(0..self.index_count as u32, 0, 0..1);
+ if let Some(ref pipe) = self.pipeline_wire {
+ rpass.set_pipeline(pipe);
+ rpass.draw_indexed(0..self.index_count as u32, 0, 0..1);
+ }
+ }
+
+ queue.submit(Some(encoder.finish()));
+ }
+}
+
+fn main() {
+ framework::run::("cube");
+}
diff --git a/wgpu/examples/cube/screenshot.png b/wgpu/examples/cube/screenshot.png
new file mode 100644
index 000000000..784ffc463
Binary files /dev/null and b/wgpu/examples/cube/screenshot.png differ
diff --git a/wgpu/examples/cube/shader.wgsl b/wgpu/examples/cube/shader.wgsl
new file mode 100644
index 000000000..58599f284
--- /dev/null
+++ b/wgpu/examples/cube/shader.wgsl
@@ -0,0 +1,37 @@
+struct VertexOutput {
+ [[location(0)]] tex_coord: vec2;
+ [[builtin(position)]] position: vec4;
+};
+
+[[block]]
+struct Locals {
+ transform: mat4x4;
+};
+[[group(0), binding(0)]]
+var r_locals: Locals;
+
+[[stage(vertex)]]
+fn vs_main(
+ [[location(0)]] position: vec4,
+ [[location(1)]] tex_coord: vec2,
+) -> VertexOutput {
+ var out: VertexOutput;
+ out.tex_coord = tex_coord;
+ out.position = r_locals.transform * position;
+ return out;
+}
+
+[[group(0), binding(1)]]
+var r_color: texture_2d;
+
+[[stage(fragment)]]
+fn fs_main(in: VertexOutput) -> [[location(0)]] vec4 {
+ let tex = textureLoad(r_color, vec2(in.tex_coord * 256.0), 0);
+ let v = f32(tex.x) / 255.0;
+ return vec4(1.0 - (v * 5.0), 1.0 - (v * 15.0), 1.0 - (v * 50.0), 1.0);
+}
+
+[[stage(fragment)]]
+fn fs_wire() -> [[location(0)]] vec4 {
+ return vec4(0.0, 0.5, 0.0, 0.5);
+}
diff --git a/wgpu/examples/framework.rs b/wgpu/examples/framework.rs
new file mode 100644
index 000000000..6f8e875af
--- /dev/null
+++ b/wgpu/examples/framework.rs
@@ -0,0 +1,370 @@
+use std::future::Future;
+#[cfg(not(target_arch = "wasm32"))]
+use std::time::{Duration, Instant};
+use winit::{
+ event::{self, WindowEvent},
+ event_loop::{ControlFlow, EventLoop},
+};
+
+#[rustfmt::skip]
+#[allow(unused)]
+pub const OPENGL_TO_WGPU_MATRIX: cgmath::Matrix4 = cgmath::Matrix4::new(
+ 1.0, 0.0, 0.0, 0.0,
+ 0.0, 1.0, 0.0, 0.0,
+ 0.0, 0.0, 0.5, 0.0,
+ 0.0, 0.0, 0.5, 1.0,
+);
+
+#[allow(dead_code)]
+pub fn cast_slice(data: &[T]) -> &[u8] {
+ use std::{mem::size_of, slice::from_raw_parts};
+
+ unsafe { from_raw_parts(data.as_ptr() as *const u8, data.len() * size_of::()) }
+}
+
+#[allow(dead_code)]
+pub enum ShaderStage {
+ Vertex,
+ Fragment,
+ Compute,
+}
+
+pub trait Example: 'static + Sized {
+ fn optional_features() -> wgpu::Features {
+ wgpu::Features::empty()
+ }
+ fn required_features() -> wgpu::Features {
+ wgpu::Features::empty()
+ }
+ fn required_limits() -> wgpu::Limits {
+ wgpu::Limits::default()
+ }
+ fn init(
+ sc_desc: &wgpu::SwapChainDescriptor,
+ adapter: &wgpu::Adapter,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ ) -> Self;
+ fn resize(
+ &mut self,
+ sc_desc: &wgpu::SwapChainDescriptor,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ );
+ fn update(&mut self, event: WindowEvent);
+ fn render(
+ &mut self,
+ frame: &wgpu::SwapChainTexture,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ spawner: &Spawner,
+ );
+}
+
+struct Setup {
+ window: winit::window::Window,
+ event_loop: EventLoop<()>,
+ instance: wgpu::Instance,
+ size: winit::dpi::PhysicalSize,
+ surface: wgpu::Surface,
+ adapter: wgpu::Adapter,
+ device: wgpu::Device,
+ queue: wgpu::Queue,
+}
+
+async fn setup(title: &str) -> Setup {
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ env_logger::init();
+ };
+
+ let event_loop = EventLoop::new();
+ let mut builder = winit::window::WindowBuilder::new();
+ builder = builder.with_title(title);
+ #[cfg(windows_OFF)] // TODO
+ {
+ use winit::platform::windows::WindowBuilderExtWindows;
+ builder = builder.with_no_redirection_bitmap(true);
+ }
+ let window = builder.build(&event_loop).unwrap();
+
+ #[cfg(target_arch = "wasm32")]
+ {
+ use winit::platform::web::WindowExtWebSys;
+ console_log::init().expect("could not initialize logger");
+ std::panic::set_hook(Box::new(console_error_panic_hook::hook));
+ // On wasm, append the canvas to the document body
+ web_sys::window()
+ .and_then(|win| win.document())
+ .and_then(|doc| doc.body())
+ .and_then(|body| {
+ body.append_child(&web_sys::Element::from(window.canvas()))
+ .ok()
+ })
+ .expect("couldn't append canvas to document body");
+ }
+
+ log::info!("Initializing the surface...");
+
+ let backend = if let Ok(backend) = std::env::var("WGPU_BACKEND") {
+ match backend.to_lowercase().as_str() {
+ "vulkan" => wgpu::BackendBit::VULKAN,
+ "metal" => wgpu::BackendBit::METAL,
+ "dx12" => wgpu::BackendBit::DX12,
+ "dx11" => wgpu::BackendBit::DX11,
+ "gl" => wgpu::BackendBit::GL,
+ "webgpu" => wgpu::BackendBit::BROWSER_WEBGPU,
+ other => panic!("Unknown backend: {}", other),
+ }
+ } else {
+ wgpu::BackendBit::PRIMARY
+ };
+ let power_preference = if let Ok(power_preference) = std::env::var("WGPU_POWER_PREF") {
+ match power_preference.to_lowercase().as_str() {
+ "low" => wgpu::PowerPreference::LowPower,
+ "high" => wgpu::PowerPreference::HighPerformance,
+ other => panic!("Unknown power preference: {}", other),
+ }
+ } else {
+ wgpu::PowerPreference::default()
+ };
+ let instance = wgpu::Instance::new(backend);
+ let (size, surface) = unsafe {
+ let size = window.inner_size();
+ let surface = instance.create_surface(&window);
+ (size, surface)
+ };
+ let adapter = instance
+ .request_adapter(&wgpu::RequestAdapterOptions {
+ power_preference,
+ compatible_surface: Some(&surface),
+ })
+ .await
+ .expect("No suitable GPU adapters found on the system!");
+
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ let adapter_info = adapter.get_info();
+ println!("Using {} ({:?})", adapter_info.name, adapter_info.backend);
+ }
+
+ let optional_features = E::optional_features();
+ let required_features = E::required_features();
+ let adapter_features = adapter.features();
+ assert!(
+ adapter_features.contains(required_features),
+ "Adapter does not support required features for this example: {:?}",
+ required_features - adapter_features
+ );
+
+ let needed_limits = E::required_limits();
+
+ let trace_dir = std::env::var("WGPU_TRACE");
+ let (device, queue) = adapter
+ .request_device(
+ &wgpu::DeviceDescriptor {
+ label: None,
+ features: (optional_features & adapter_features) | required_features,
+ limits: needed_limits,
+ },
+ trace_dir.ok().as_ref().map(std::path::Path::new),
+ )
+ .await
+ .expect("Unable to find a suitable GPU adapter!");
+
+ Setup {
+ window,
+ event_loop,
+ instance,
+ size,
+ surface,
+ adapter,
+ device,
+ queue,
+ }
+}
+
+fn start(
+ Setup {
+ window,
+ event_loop,
+ instance,
+ size,
+ surface,
+ adapter,
+ device,
+ queue,
+ }: Setup,
+) {
+ let spawner = Spawner::new();
+ let mut sc_desc = wgpu::SwapChainDescriptor {
+ usage: wgpu::TextureUsage::RENDER_ATTACHMENT,
+ format: adapter.get_swap_chain_preferred_format(&surface).unwrap(),
+ width: size.width,
+ height: size.height,
+ present_mode: wgpu::PresentMode::Mailbox,
+ };
+ let mut swap_chain = device.create_swap_chain(&surface, &sc_desc);
+
+ log::info!("Initializing the example...");
+ let mut example = E::init(&sc_desc, &adapter, &device, &queue);
+
+ #[cfg(not(target_arch = "wasm32"))]
+ let mut last_update_inst = Instant::now();
+ #[cfg(not(target_arch = "wasm32"))]
+ let mut last_frame_inst = Instant::now();
+ #[cfg(not(target_arch = "wasm32"))]
+ let (mut frame_count, mut accum_time) = (0, 0.0);
+
+ log::info!("Entering render loop...");
+ event_loop.run(move |event, _, control_flow| {
+ let _ = (&instance, &adapter); // force ownership by the closure
+ *control_flow = if cfg!(feature = "metal-auto-capture") {
+ ControlFlow::Exit
+ } else {
+ ControlFlow::Poll
+ };
+ match event {
+ event::Event::RedrawEventsCleared => {
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ // Clamp to some max framerate to avoid busy-looping too much
+ // (we might be in wgpu::PresentMode::Mailbox, thus discarding superfluous frames)
+ //
+ // winit has window.current_monitor().video_modes() but that is a list of all full screen video modes.
+ // So without extra dependencies it's a bit tricky to get the max refresh rate we can run the window on.
+ // Therefore we just go with 60fps - sorry 120hz+ folks!
+ let target_frametime = Duration::from_secs_f64(1.0 / 60.0);
+ let time_since_last_frame = last_update_inst.elapsed();
+ if time_since_last_frame >= target_frametime {
+ window.request_redraw();
+ last_update_inst = Instant::now();
+ } else {
+ *control_flow = ControlFlow::WaitUntil(
+ Instant::now() + target_frametime - time_since_last_frame,
+ );
+ }
+
+ spawner.run_until_stalled();
+ }
+
+ #[cfg(target_arch = "wasm32")]
+ window.request_redraw();
+ }
+ event::Event::WindowEvent {
+ event: WindowEvent::Resized(size),
+ ..
+ } => {
+ log::info!("Resizing to {:?}", size);
+ sc_desc.width = size.width.max(1);
+ sc_desc.height = size.height.max(1);
+ example.resize(&sc_desc, &device, &queue);
+ swap_chain = device.create_swap_chain(&surface, &sc_desc);
+ }
+ event::Event::WindowEvent { event, .. } => match event {
+ WindowEvent::KeyboardInput {
+ input:
+ event::KeyboardInput {
+ virtual_keycode: Some(event::VirtualKeyCode::Escape),
+ state: event::ElementState::Pressed,
+ ..
+ },
+ ..
+ }
+ | WindowEvent::CloseRequested => {
+ *control_flow = ControlFlow::Exit;
+ }
+ _ => {
+ example.update(event);
+ }
+ },
+ event::Event::RedrawRequested(_) => {
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ accum_time += last_frame_inst.elapsed().as_secs_f32();
+ last_frame_inst = Instant::now();
+ frame_count += 1;
+ if frame_count == 100 {
+ println!(
+ "Avg frame time {}ms",
+ accum_time * 1000.0 / frame_count as f32
+ );
+ accum_time = 0.0;
+ frame_count = 0;
+ }
+ }
+
+ let frame = match swap_chain.get_current_frame() {
+ Ok(frame) => frame,
+ Err(_) => {
+ swap_chain = device.create_swap_chain(&surface, &sc_desc);
+ swap_chain
+ .get_current_frame()
+ .expect("Failed to acquire next swap chain texture!")
+ }
+ };
+
+ example.render(&frame.output, &device, &queue, &spawner);
+ }
+ _ => {}
+ }
+ });
+}
+
+#[cfg(not(target_arch = "wasm32"))]
+pub struct Spawner<'a> {
+ executor: async_executor::LocalExecutor<'a>,
+}
+
+#[cfg(not(target_arch = "wasm32"))]
+impl<'a> Spawner<'a> {
+ fn new() -> Self {
+ Self {
+ executor: async_executor::LocalExecutor::new(),
+ }
+ }
+
+ #[allow(dead_code)]
+ pub fn spawn_local(&self, future: impl Future