패키지, 저장소 및 앱 카테고리 검색

shader 표지
패키지 상세v1.0.1

shader

GLSL 쉐이더를 Flutter 호환 SPR-V 바이트 코드로 컴파일하기 위한 명령줄 애플리케이션입니다.

AndroidiOSmacOSWindowsLinux
30일 다운로드
35
좋아요
64
Pub 점수
150

패키지 설치

flutter pub add shader

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

GLSL 쉐이더를 Flutter 호환 SPIR-V 바이트 코드로 컴파일하는 명령줄 도구로, Flutter 앱에서 고성능 사용자 정의 그래픽 효과를 가능하게 합니다. 이 도구는 모바일 및 데스크톱 플랫폼에 적합한 최적화된 바이너리 형식으로 GLSL 소스 코드를 변환함으로써 쉐이더 개발과 Flutter의 렌더링 파이프라인 사이의 격차를 메웁니다. 이를 통해 개발자는 GPU의 저수준 제어를 활용해 동적 그라디언트, 포스트 프로세싱 필터, 인터랙티브 애니메이션과 같은 고급 시각 효과를 구현할 수 있습니다. 이 도구는 pub.dev를 통해 Flutter 워크플로우에 원활하게 통합될 수 있도록 설계되었습니다.

사용 사례

  • 사용자 정의 애니메이션 배경 만들기
  • 실시간 시각 효과 구현
  • 포스트 처리 필터 추가
  • GPU 가속을 사용하여 상호작용 가능한 UI 요소 개발
  • 몰입형 AR/VR 경험 구축

주요 기능

  • GLSL에서 SPIR-V 컴파일
  • 크로스 플랫폼 지원 (Android, iOS, macOS, Windows, Linux)
  • 간편한 통합을 위한 명령줄 인터페이스
  • Flutter 렌더링을 위한 최적화된 출력
  • 복잡한 셰이더 로직과 유니폼을 지원합니다

적합한 대상

  • 고급 그래픽을 작업하는 플러터 개발자
  • 동적 시각 효과가 필요한 UI 디자이너
  • 게임 또는 AR/VR 앱 제작자
  • 성능 중심의 애니메이션 구현

고려 사항

  • GLSL 및 GPU 프로그래밍에 대한 지식이 필요합니다
  • 제한된 런타임 디버깅 기능
  • 빌드 파이프라인에 수동으로 통합
  • 런타임 쉐이더 생성을 위한 것이 아님
  • 사전 컴파일된 정적 쉐이더에 가장 적합

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

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<FragmentProgram> 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:

카테고리

의존성

의존성 목록 5 개

소스 저장소

이 패키지를 사용하는 프로젝트

아직 데이터가 없습니다.