Shader manages the compilation of your GLSL shaders into SPIR-V byte code and Dart code

Related tags

Templates shader
Overview

shader

Shader manages the compilation of your GLSL shaders into SPIR-V byte code and Dart code.

Quickstart

# Install cli
dart pub global activate shader

# Compile all glsl files in our project
shader --use-remote --to-dart

# Discover all features
shader --help

Table of Contents

Getting started

Usage

Writing shaders

Getting started

Install the command-line executable shader for your current user:

dart pub global activate shader

Now you can use the shader CLI tool:

shader --help

Hint: If pub binaries are not known to the path, you can also run it by:

dart pub global run shader --help

Usage

Compile to Dart

The easiest way of using shaders in your app, is to use it this way:

shader --use-remote --to-dart

It will scan your project for *.glsl files and use the hosted cloud service to compile it. Flutter needs SPR-V byte code at runtime.

A very simple shader red-shader.glsl could be this:

#version 320 es

precision highp float;

layout(location = 0) out vec4 fragColor;

void main() {
    fragColor = vec4(1.0, 0.0, 0.0, 1.0);
}

This shader has no uniforms (input parameters) and paints each pixel red.

The compiler created a dart file red_shader_sprv.dart that contains a function Future redShaderFragmentProgram() that will initialize the shader at runtime.

We can utilize a FutureBuilder to load that:

import 'dart:ui';
import 'package:flutter/material.dart';

/// Import file generated by cli
import 'package:flutter_app/shader/red_shader_sprv.dart';

class RedShaderWidget extends StatelessWidget {
  const RedShaderWidget({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<FragmentProgram>(
      /// Use the generated loader function here
      future: redShaderFragmentProgram(),
      builder: ((context, snapshot) {
        if (!snapshot.hasData) {
          /// Shader is loading
          return const WidgetWhenLoading();
        }

        /// Shader is ready to use
        return WidgetThatUsesShader(snapshot.data!);
      }),
    );
  }
}

You can find an app example of Red Shader.

Use of uniforms

Uniforms is the term in the GLSL world for input parameter. The uniforms can be changed for each frame, but they are constant for every pixel during a single frame.

Given the following GLSL file:

#version 320 es

precision highp float;

layout(location = 0) out vec4 fragColor;

// define uniforms:
layout(location = 0) uniform vec3 color1;
layout(location = 1) uniform vec3 color2;
layout(location = 2) uniform float someValue;
layout(location = 3) uniform vec2 size;

void main() {
    // ...
}

This can be addressed in FragmentProgram's shader() method:

@override
void paint(Canvas canvas, Size size) {
  /// Inputs
  Color color1 = Colors.blue;
  Color color2 = Colors.green;
  double someValue = 0.5;

  /// Create paint using a shader
  final paint = Paint()
    ..shader = fragmentProgram.shader(

        /// Specify input parameter (uniforms)
        floatUniforms: Float32List.fromList([
      /// color1 takes 3 floats and will be mapped to `vec3`
      color1.red / 255.0,
      color1.green / 255.0,
      color1.blue / 255.0,

      /// color2 also takes 3 floats and will be mapped to `vec3`
      color2.red / 255.0,
      color2.green / 255.0,
      color2.blue / 255.0,

      /// someValue takes 1 float and will be mapped to `float`
      someValue,

      /// size takes 2 floats and will be mapped to `vec2`
      size.width,
      size.height,
    ]));

  /// Draw a rectangle with the shader-paint
  canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), paint);
}

Also take a look at Color Shader example, that combines Flutter animtions and the use of uniforms.

Make use of sampler uniform

Image textures can be accessed via sampler2d uniforms:

layout(location = 0) uniform sampler2D image;

For that you need to create an ImageShader:

final asset = await rootBundle.load("assets/image.jpg");
final image = await decodeImageFromList(asset.buffer.asUint8List());

/// Create ImageShader that will provide a GLSL sampler
final ImageShader imageShader = ImageShader(
  image,
  // Specify how image repetition is handled for x and y dimension
  TileMode.repeated,
  TileMode.repeated,
  // Transformation matrix (identity matrix = no transformation)
  Matrix4.identity().storage,
);

That ImageShader can be passed into the FragmentProgram's shader() method as samplerUniform:

final paint = Paint()
  ..shader = fragmentProgram.shader(
    samplerUniforms: [
      imageShader,
    ],
  );

You can see everything wired up in the Image Scale app example.

Use a local compiler

If you don't want to rely on the hosted cloud service or the cloud service not available, you can use local compiler.

You can download the compiler at https://github.com/google/shaderc.

The --use-local option takes a path that roughly points to the compiler binary:

shader --use-local $HOME/sdk/shaderc --to-dart

Improve development cycle

In order to iterate faster and use the hot-reload, you can use the --watch flag:

shader --use-remote --to-dart --watch

shader --use-local $HOME/sdk/shaderc --to-dart --watch

Other features

The shader executable also supports some other options and output format. Type to find get information:

shader --help

Writing shaders

This section covers useful information and resources writing own shader code.

Constraints in Flutter

Shaders are not supported for Flutter web, yet. But there is a project plan for the Flutter engine developers to enable it.

Also the capabilities of GLSL language feature are restricted. Take a look at the specifications of the SPIR-V Transpiler.

This package compiles GLSL code to SPIR-V code, and at runtime SPIR-V transpiler converts it to native API (e.g. OpenGL, Vulkan). So it might be that shader will compile fine, but it fails at runtime.

Learning GLSL

There are various sources to learn GLSL:

You might also like...

Ruqe brings the convenient types and methods found in Rust into Dart, such as the Result, Option, pattern-matching, etc.

ruqe Ruqe brings the convenient types and methods found in Rust into Dart, such as the Result, Option, pattern-matching, etc. Additionally, the librar

Dec 28, 2022

Combine a set of dart files into one

dart-merger Combine a set of dart files into one. This is useful when you want to organize a group of files automatically generated by generator. Inst

Mar 17, 2022

Flutter Local Notifications - Learn how to implement local notifications into both Android and iOS using flutter_local_notifications plugin.

Flutter Local Notifications - Learn how to implement local notifications into both Android and iOS using flutter_local_notifications plugin.

Flutter Local Notifications Example Flutter Local Notifications - Learn how to implement local notifications into both Android and iOS using flutter_l

Nov 29, 2022

Flutter Control is complex library to maintain App and State management. Library merges multiple functionality under one hood. This approach helps to tidily bound separated logic into complex solution.

Flutter Control is complex library to maintain App and State management. Library merges multiple functionality under one hood. This approach helps to tidily bound separated logic into complex solution.

Flutter Control is complex library to maintain App and State management. Library merges multiple functionality under one hood. This approach helps to

Feb 23, 2022

Polymaker is an application that can create polygon locations dynamically in mobile apps and save the data into SQFlite to be permanent.

Polymaker is an application that can create polygon locations dynamically in mobile apps and save the data into SQFlite to be permanent.

Polymaker Polymaker is an application that can create polygon locations dynamically in mobile apps and save the data into SQFlite to be permanent. Ins

Apr 17, 2022

A simple button that gives you the possibility to transform into a circular one and shows a progress indicator

A simple button that gives you the possibility to transform into a circular one and shows a progress indicator

Progress Button A simple button that gives you the possibility to transform into

Dec 22, 2021

Deep Dive Into Flutter

Deep Dive Into Flutter

Deep Dive Into Flutter This my more formalized version of a Rosetta Stone of Flutter Demos to encourage you to take a deep dive into flutter to master

Nov 2, 2022

A Flutter widget that forces the device rotates into the set of orientations the application interface can be displayed in.

A Flutter widget that forces the device rotates into the set of orientations the application interface can be displayed in. Features Force device keep

Nov 30, 2021

All four are used to log into a Firebase backend.

All four are used to log into a Firebase backend.

Auth This library package works with four plugins: firebase_auth google_sign_in flutter_facebook_login flutter_twitter All four are used to log into a

Dec 14, 2022
Comments
  • How to use textures as input?

    How to use textures as input?

    Hi, I am trying to use these shaders for image processing. I've read in the flutter documentation that sampler2D is a valid uniform as an input to the shader. However I cannot find a way to generate that uniform in dart since it is not just a double. Is there a specific type for that exposed in the API?

    talk 
    opened by MindStudioOfficial 6
  • Does the shaders work normally on IOs using the Metal API?

    Does the shaders work normally on IOs using the Metal API?

    I just have one question/curiosity if I'm not mistaken, opengl is deprecated in IOs, and I believe Apple will kill at some point and just use their new Metal API. The question is, will the glsl code work on IOS? We will be able to run these shaders without depending on the OS? Sorry for the newbie question, I'm starting with shaders :/

    opened by reiko-dev 2
  • Flutter will provide build-time transpilation of GLSLs in the future

    Flutter will provide build-time transpilation of GLSLs in the future

    This is not an issue, I just want to tell you about flutter's great new feature! Flutter provides a better way to compile GLSL into SPIR-V in the master branch: https://github.com/flutter/flutter/issues/93498#issuecomment-1141658172

    opened by mj-hd 1
Owner
Felix Blaschke
Software Developer, M.Sc. Visual Computing
Felix Blaschke
⚡FQuery is a powerful async state management solution for flutter. It caches, updates and fully manages asynchronous data in your flutter apps.

⚡ FQuery is a powerful async state management solution for flutter. It caches, updates and fully manages asynchronous data in your flutter apps. It ca

Piyush 21 Dec 22, 2022
QUICKNOTES is a simple Note taking app, you can easily manages your TODOs

QUICKNOTES is a simple Note taking app, you can easily manages your TODOs. It has a simple UI with Dark & Light Themes.

Abdul Basit 2 May 2, 2022
Call Kit is a prebuilt feature-rich call component, which enables you to build one-on-one and group voice/video calls into your app with only a few lines of code.

Call Kit (ZegoUIKitPrebuiltCall) Call Kit is a prebuilt feature-rich call component, which enables you to build one-on-one and group voice/video calls

ZEGOCLOUD 9 Dec 26, 2022
A flutter plugin about qr code or bar code scan , it can scan from file、url、memory and camera qr code or bar code .Welcome to feedback your issue.

r_scan A flutter plugin about qr code or bar code scan , it can scan from file、url、memory and camera qr code or bar code .Welcome to feedback your iss

PengHui Li 112 Nov 11, 2022
Extract pubspec details (such as package version, author and description) into Dart code.

build_pubspec This package helps you convert fields from your pubspec.yaml file into Dart code. Based on the fields in your pubspec, this package will

dartside.dev 9 Jul 15, 2021
Package your Flutter app into OS-specific bundles (.dmg, .exe, etc.) via Dart or the command line.

flutter_distributor Package your Flutter app into OS-specific bundles (.dmg, .exe, etc.) via Dart or the command line. The flutter_distributor source

LeanFlutter 416 Dec 24, 2022
It's OK to love Flutter and hate hand-coding design elements. Parabeac-Core converts design files into Flutter code.

Parabeac-Core Parabeac-Core converts design files into Flutter code driven by open-source & community. Contribute · Discord Community · Designer Proto

Parabeac 536 Jan 4, 2023
A builder for extracting a package version into code

Include the version of your package in our source code. Add build_version to pubspec.yaml. Also make sure there is a version field. name: my_pkg versi

Kevin Moore 39 Dec 7, 2022
A cross-platform flutter package to convert your links into rich beautiful previews.

Link Preview Generator A cross-platform flutter package to convert your links into rich beautiful previews. This package is inspired from Any Link Pre

Pranav Bedre 12 Oct 21, 2022
Croco: Stylized widgets ready to plug into your Flutter Web project

TODO: Put a short description of the package here that helps potential users know whether this package might be useful for them. Features TODO: List w

Diego Romero-Lovo 1 Jul 7, 2022