Giter Site home page Giter Site logo

wasabia / flutter_gl Goto Github PK

View Code? Open in Web Editor NEW
245.0 6.0 60.0 2.4 MB

cross-platform call OpenGL API by Dart through dart:ffi. Provides OpenGL with Texture Widget on Flutter.

Kotlin 0.43% Ruby 0.08% Swift 0.78% Objective-C 2.84% Dart 26.45% HTML 1.61% C 64.64% CMake 0.84% C++ 0.62% SCSS 0.17% CSS 0.64% JavaScript 0.90%
flutter dart android ios web webgl opengl opengl-es

flutter_gl's Introduction

Flutter GL

cross-platform call OpenGL API by Dart through dart:ffi. Provides OpenGL with Texture Widget on Flutter.

Support iOS, Android, Web, macOS, Windows

Linux TODO

Used by three_dart

OpenGL API

the api is similar to WebGL

only support draw to FBO. then share the FBO texture to Native side.

import

import 'package:flutter_gl/flutter_gl.dart';

Usage

int width = 200;
int height = 200;
num dpr = 1.0;

flutterGlPlugin = FlutterGlPlugin();

Map<String, dynamic> _options = {
    "width": width, 
    "height": height, 
    "dpr": dpr,
    "antialias": true,
    "alpha": false
};    
await flutterGlPlugin.initialize(options: _options);

// on web this need called after web canvas dom was added to document
await flutterGlPlugin.prepareContext();

// you can get gl by
gl = flutterGlPlugin.gl;

// then you can call OpenGL ES API by gl like
gl.clearColor(0.0, 0.0, 0.0, 1.0);
gl.clear(gl.COLOR_BUFFER_BIT);

// use this method to notify Flutter update Texture Widget
// sourceTextue is a texture which bind to FBO framebuffer
flutterGlPlugin.updateTexture(sourceTexture);

why use NativeArray replace Dart List

Dart List convert to ffi pointer need memeory copy.

Run Examples

Clone or download this repo

cd flutter_gl/flutter_gl/example

flutter run

share opengl context with flutter_gl

Android

when init the plugin, save share opengl context with ThreeEgl,

ThreeEgl.setContext("shareContext", shareEglEnv.eglContext);

so you can get it use ThreeEgl lib, then create yourself opengl context share with "shareContext"

shareContext = ThreeEgl.getContext("shareContext");

iOS

for iOS the key is 3 ...

eAGLShareContext = ThreeEgl.getContext(key: 3);

Web

no need ? just webgl

Windows

not support get share context now

Android

check the example project copy the example/android/app/libs/aars/threeegl.aar to your app android project same path

change minSdkVersion 24

Screenshot

screen0

screen1

Issues

File any issues, bugs, or feature requests.

Contributing

Pull request please!

flutter_gl's People

Contributors

daniellangh avatar kdet avatar kevingogii avatar linies avatar mark-nicepants avatar wasabia avatar yodesoft avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

flutter_gl's Issues

I thought opengl is deprecated on iOS and MacOS?

Hi,

I don't know if you know that I started a similar libary called Flutter_webgl and I used MetalAngle as replacement for opengl.
I just saw, that it seems not be necessary in your library. can you explain how this works?

Thanks
Thomas

Just a question with textures

Hello,
I am working on a project with flutter iOS and android with rendering 2D video texture. Currently creating flutter platform views embedding to flutter and do render in native java/c++ in android and in Objc/c++ in iOS.

I need to check the possibility of using this plugin instead of current native rendering. Here I can pass RGB video data to flutter, and does this plugin ready for 2D projection and render the texture in iOS and Android?

Thanks

Instruction for developers & line width

Hello! Could you create an instruction how to use all methods from gl? And can you help me pls with line width? When I write "_gl.lineWidth(5);" width doesn't change:(

physics

does this support physics? and detects collisions?

Texture Problem

I write code for generate texture on rectangle. My code
`import 'dart:async';
import 'dart:ffi';
import 'dart:io';
import 'dart:math';
import 'dart:typed_data';

import 'dart:ui' as ui;
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import 'package:flutter/widgets.dart';
import 'package:flutter_gl/flutter_gl.dart';
import 'package:flutter_gl/openGL/opengl/opengl_es_bindings/opengl_es_bindings.dart';

typedef NativeUint8Array = Pointer;

class ExampleTexture extends StatefulWidget {
_MyAppState createState() => _MyAppState();
}

class _MyAppState extends State {
late FlutterGlPlugin flutterGlPlugin;

int? fboId;
num dpr = 1.0;
late double width;
late double height;

ui.Size? screenSize;

dynamic glProgram;
dynamic _vao;
dynamic _vbo;
dynamic _ebo;
dynamic _texture;

dynamic sourceTexture;

dynamic defaultFramebuffer;
dynamic defaultFramebufferTexture;

int n = 0;

int t = DateTime.now().millisecondsSinceEpoch;

@OverRide
void initState() {
super.initState();

print(" init state..... ");

}

// Platform messages are asynchronous, so we initialize in an async method.
Future initPlatformState() async {
width = screenSize!.width;
height = width;

flutterGlPlugin = FlutterGlPlugin();

Map<String, dynamic> _options = {
  "antialias": true,
  "alpha": false,
  "width": width.toInt(),
  "height": height.toInt(),
  "dpr": dpr
};

await flutterGlPlugin.initialize(options: _options);

print(" flutterGlPlugin: textureid: ${flutterGlPlugin.textureId} ");

setState(() {});

// web need wait dom ok!!!
Future.delayed(Duration(milliseconds: 100), () {
  setup();
});

}

setup() async {
// web no need use fbo
if (!kIsWeb) {
await flutterGlPlugin.prepareContext();

  setupDefaultFBO();
  sourceTexture = defaultFramebufferTexture;
}

setState(() {

});

prepare();


// animate();

}

initSize(BuildContext context) {
if (screenSize != null) {
return;
}

final mq = MediaQuery.of(context);

screenSize = mq.size;
dpr = mq.devicePixelRatio;

print(" screenSize: ${screenSize} dpr: ${dpr} ");

initPlatformState();

}

@OverRide
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Example app'),
),
body: Builder(
builder: (BuildContext context) {
initSize(context);
return SingleChildScrollView(child: _build(context));
},
),
floatingActionButton: FloatingActionButton(
onPressed: () {
clickRender();
},
child: Text("Render"),
),
),
);
}

Widget _build(BuildContext context) {
return Column(
children: [
Container(
width: width,
height: width,
color: Colors.black,
child: Builder(builder: (BuildContext context) {
if (kIsWeb) {
return flutterGlPlugin.isInitialized
? HtmlElementView(
viewType: flutterGlPlugin.textureId!.toString())
: Container();
} else {
return flutterGlPlugin.isInitialized
? Texture(textureId: flutterGlPlugin.textureId!)
: Container();
}
})),
],
);
}

animate() {
render();

// Future.delayed(Duration(milliseconds: 40), () {
//   animate();
// });

}

setupDefaultFBO() {
final _gl = flutterGlPlugin.gl;
int glWidth = (width * dpr).toInt();
int glHeight = (height * dpr).toInt();

print("glWidth: ${glWidth} glHeight: ${glHeight} ");

defaultFramebuffer = _gl.createFramebuffer();
defaultFramebufferTexture = _gl.createTexture();
_gl.activeTexture(_gl.TEXTURE0);

_gl.bindTexture(_gl.TEXTURE_2D, defaultFramebufferTexture);
_gl.texImage2D(_gl.TEXTURE_2D, 0, _gl.RGBA, glWidth, glHeight, 0, _gl.RGBA,
    _gl.UNSIGNED_BYTE, null);
_gl.texParameteri(_gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.LINEAR);
_gl.texParameteri(_gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.LINEAR);

_gl.bindFramebuffer(_gl.FRAMEBUFFER, defaultFramebuffer);
_gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0,
    _gl.TEXTURE_2D, defaultFramebufferTexture, 0);

}

clickRender() {
print(" click render ... ");
render();
}

render() {
final _gl = flutterGlPlugin.gl;

int _current = DateTime.now().millisecondsSinceEpoch;

_gl.viewport(0, 0, (width * dpr).toInt(), (height * dpr).toInt());

num _blue = sin((_current - t) / 500);
// Clear canvas
_gl.clearColor(0.2, 0.3, 0.3, 1.0);
_gl.clear(_gl.COLOR_BUFFER_BIT);

_gl.drawElements(_gl.TRIANGLES, 6, GL_UNSIGNED_INT, 0);

print(" render n: $n ");

_gl.finish();

if (!kIsWeb) {
  flutterGlPlugin.updateTexture(sourceTexture);
}

}

prepare() {
final _gl = flutterGlPlugin.gl;

String _version = "300 es";

if(!kIsWeb) {
  if (Platform.isMacOS || Platform.isWindows) {
    _version = "150";
  }
}

var vs = """#version ${_version}

precision mediump float; // add a precision qualifier

#define attribute in
#define varying out

layout (location = 0) in vec3 a_Position;
layout (location = 1) in vec3 a_Color;
layout (location = 2) in vec2 a_TexCoord;

out vec3 ourColor;
out vec2 TexCoord;

void main() {
gl_Position = vec4(a_Position, 1.0);
ourColor = a_Color;
TexCoord = vec2(a_TexCoord.x, a_TexCoord.y);
}
""";

var fs = """#version ${_version}

precision mediump float;

out highp vec4 pc_fragColor;
#define gl_FragColor pc_fragColor

in highp vec3 ourColor;
in highp vec2 TexCoord;

uniform highp sampler2D ourTexture;

void main() {
gl_FragColor = texture(ourTexture, TexCoord) * vec4(ourColor, 1.0);
}
""";

if (!initShaders(_gl, vs, fs)) {
  print('Failed to intialize shaders.');
  return;
}

// Write the positions of vertices to a vertex shader
n = initVertexBuffers(_gl);
if (n < 0) {
  print('Failed to set the positions of the vertices');
  return;
}

}

initVertexBuffers(gl) {
// Vertices
var dim = 3;

var vertices = Float32Array.fromList([
  // position    // colors    // texture coords
  0.5, 0.5, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, // top right
  0.5, -0.5, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, // bottom right
  -0.5, -0.5, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, // bottom left
  -0.5, 0.5, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, // top left
]);

var indices = Int32Array.fromList([
  0,1,3, // first triangle
  1,2,3, // second triangle
]);

_vao = gl.createVertexArray();
gl.bindVertexArray(_vao);

// Create a buffer object
var vertexBuffer = gl.createBuffer();
if (vertexBuffer == null) {
  print('Failed to create the buffer object');
  return -1;
}
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);

_ebo = gl.createVertexArray();
gl.bindVertexArray(_ebo);

// Create a buffer object
var indicesBuffer = gl.createBuffer();
if (indicesBuffer == null) {
  print('Failed to create the buffer object');
  return -1;
}
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indicesBuffer);

if(kIsWeb) {
  gl.bufferData(gl.ARRAY_BUFFER, vertices.length, vertices, gl.STATIC_DRAW);
  gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices.length, indices, gl.STATIC_DRAW);
} else {
  gl.bufferData(gl.ARRAY_BUFFER, vertices.lengthInBytes, vertices, gl.STATIC_DRAW);
  gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices.lengthInBytes, indices, gl.STATIC_DRAW);
}

// Assign the vertices in buffer object to a_Position variable
var a_Position = gl.getAttribLocation(glProgram, 'a_Position');
if (a_Position < 0) {
  print('Failed to get the storage location of a_Position');
  return -1;
}

var b_Position = gl.getAttribLocation(glProgram, 'a_Color');
if(b_Position < 0){
  print('Failed to get the storage location of a_Color');
  return -1;
}

var c_Position = gl.getAttribLocation(glProgram, 'a_TexCoord');
if(c_Position < 0){
  print('Failed to get the storage location of a_TexCoord');
  return -1;
}

gl.vertexAttribPointer(
    a_Position, dim, gl.FLOAT, false, Float32List.bytesPerElement * 8, 0);
gl.enableVertexAttribArray(a_Position);

gl.vertexAttribPointer(
    b_Position, dim, gl.FLOAT, false, Float32List.bytesPerElement * 8, Float32List.bytesPerElement * 3);
gl.enableVertexAttribArray(b_Position);

gl.vertexAttribPointer(
  c_Position, 2, gl.FLOAT, false, Float32List.bytesPerElement * 8, Float32List.bytesPerElement * 6);
gl.enableVertexAttribArray(c_Position);

_texture = gl.createTexture();
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(GL_TEXTURE_2D, _texture);
// set the texture wrapping parameters
gl.texParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
gl.texParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
// set texture filtering parameters
gl.texParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
gl.texParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

// load image, create texture and generate mipmaps
loadImage('assets/images/flutter.jpg').then((bytes) {
  final List<int> dataList = bytes.toList();
  Uint8Array data = Uint8Array.from(dataList);
  gl.texImage2D(GL_TEXTURE_2D, 0, gl.RGB, 80, 80, 0, gl.RGB, GL_UNSIGNED_BYTE, data);
  gl.generateMipmap(GL_TEXTURE_2D);
});

// Return number of vertices
return (vertices.length / dim).toInt();

}

initShaders(gl, vs_source, fs_source) {
// Compile shaders
var vertexShader = makeShader(gl, vs_source, gl.VERTEX_SHADER);
var fragmentShader = makeShader(gl, fs_source, gl.FRAGMENT_SHADER);

// Create program
glProgram = gl.createProgram();

// Attach and link shaders to the program
gl.attachShader(glProgram, vertexShader);
gl.attachShader(glProgram, fragmentShader);
gl.linkProgram(glProgram);
var _res = gl.getProgramParameter(glProgram, gl.LINK_STATUS);
print(" initShaders LINK_STATUS _res: ${_res} ");
if (_res == false || _res == 0) {
  print("Unable to initialize the shader program");
  return false;
}

// Use program
gl.useProgram(glProgram);

return true;

}

makeShader(gl, src, type) {
var shader = gl.createShader(type);
gl.shaderSource(shader, src);
gl.compileShader(shader);
var _res = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
if (_res == 0 || _res == false) {
print("Error compiling shader: ${gl.getShaderInfoLog(shader)}");
return;
}
return shader;
}

Future loadImage(String imgPath) async{
ByteData byteData = await rootBundle.load(imgPath);
Uint8List bytes = byteData.buffer.asUint8List();

return bytes;

}

}`
When I run
Screenshot_20230320_163430
My image
flutter

Question on IOS Context

Hello!

Thanks again for making this useful plugin.

I'm having a hard time understanding how the context is made current on iOS devices. From reading the source code it looks like dart ffi pulls a reference to "makeCurrent" function.

However, on my ios device, the symbol "makeCurrent" is not found, even though the symbol "glGetIntegerv" is correctly found.

Could you please explain how ios sets the context?

Image example

Can you add an example where you use images/videos and manipulate them?

Would be helpful for beginners like me.

Thanks!

Update ffi dependency

FFI is now at version 2.0.1.
Would it be possible to update the dependency requirement?

Thank you.

Example doesn't render triangle on iOS

I was trying the plugin on iOS but the Triangle didn't render.
Do you have any tips on what to try to make it work?

I did some basic digging around the shaders and went through the openGL calls, seemed to be fine.
I'm new to Flutter so still getting used to the interoperability.

Any tips would be welcome.

Linux Support

I know that this is probably a lot of work, but is a linux support currently planned or maybe already in work?

Null safety is not there

is it possible to make flutter_gl package with null safety ? because i am unable to compile it with sound null safety

iOS deployment target

While the plugin did work nicely in a pure Flutter project, when I try to include it a Flutter module, I get the following error:

.../ios/Classes/CustomRender.swift:7:8: Compiling for iOS 8.0, but module 'three3d_egl' has a minimum deployment target of iOS 9.0

flutter_gl podspec defines iOS 8 as the deployment target here:

s.ios.deployment_target = "8.0"

While threed3d_egl requires iOS 9.0 here:
https://github.com/wasabia/three3d_egl/blob/1d428f666319e22ba4b4adab4389d30b41035cc3/three3d_egl.podspec#L20

I think flutter_gl podspec needs to be updated to iOS 9.0 as well. What do you think?

Runing the example with error.

I tried to run this project on my device, but i got some error:

2022-03-28 18:28:58.750 21107-21107/com.futouapp.fluttergl.example W/FlutterActivityAndFragmentDelegate: A splash screen was provided to Flutter, but this is deprecated. See flutter.dev/go/android-splash-migration for migration steps.
2022-03-28 18:28:58.860 21107-21160/com.futouapp.fluttergl.example D/OpenGLRenderer: HWUI GL Pipeline
2022-03-28 18:28:58.885 21107-21107/com.futouapp.fluttergl.example W/Looper: Dispatch took 2430ms on main, h=Handler (android.app.ActivityThread$H) {96d5911} cb=null msg=100
2022-03-28 18:28:58.887 21107-21107/com.futouapp.fluttergl.example W/Looper: Dispatch delayed 1818ms on main, h=Handler (android.app.ActivityThread$H) {96d5911} cb=null msg=149
2022-03-28 18:28:59.008 21107-21160/com.futouapp.fluttergl.example I/OpenGLRenderer: Initialized EGL, version 1.4
2022-03-28 18:28:59.009 21107-21160/com.futouapp.fluttergl.example D/OpenGLRenderer: Swap behavior 0
2022-03-28 18:28:59.029 21107-21160/com.futouapp.fluttergl.example D/mali_winsys: EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, EGLBoolean) returns 0x3000
2022-03-28 18:28:59.048 21107-21140/com.futouapp.fluttergl.example D/mali_winsys: EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, EGLBoolean) returns 0x3000
2022-03-28 18:28:59.607 21107-21162/com.futouapp.fluttergl.example I/flutter: Observatory listening on http://127.0.0.1:33373/2wQz_KwT-3I=/
2022-03-28 18:29:05.285 21107-21139/com.futouapp.fluttergl.example I/flutter:  init state..... 
2022-03-28 18:29:08.645 21107-21139/com.futouapp.fluttergl.example I/flutter:  screenSize: Size(958.1, 561.4) dpr: 1.068750023841858 
2022-03-28 18:29:13.610 21107-21184/com.futouapp.fluttergl.example D/mali_winsys: EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, EGLBoolean) returns 0x3000
2022-03-28 18:29:13.615 21107-21184/com.futouapp.fluttergl.example D/com.futouapp.flutter_gl.flutter_gl.EglEnv:  egl make current 
2022-03-28 18:29:13.936 21107-21139/com.futouapp.fluttergl.example I/flutter:  flutterGlPlugin: textureid: 0 
2022-03-28 18:29:15.678 21107-21139/com.futouapp.fluttergl.example I/flutter: Error compiling shader: 
    Error compiling shader:
    0:1: L0003: Keyword 'attribute' is reserved
2022-03-28 18:29:15.681 21107-21139/com.futouapp.fluttergl.example I/flutter: Error compiling shader: 
    Error compiling shader:
    0:5: L0002: Undeclared variable 'gl_FragColor'
2022-03-28 18:29:15.710 21107-21139/com.futouapp.fluttergl.example E/flutter: [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type 'Null' is not a subtype of type 'int' of 'shader'
    #0      OpenGLContextES.attachShader (package:flutter_gl/openGL/opengl/OpenGLContextES.dart:496:15)
    #1      _MyAppState.initShaders (package:flutter_gl_example/ExampleTriangle01.dart:301:8)
    #2      _MyAppState.prepare (package:flutter_gl_example/ExampleTriangle01.dart:242:10)
    #3      _MyAppState.setup (package:flutter_gl_example/ExampleTriangle01.dart:81:5)
    <asynchronous suspension>

[UNIDENTIFIED] pub.dev

ERROR: The name 'platformViewRegistry' is being referenced through the prefix 'ui', but it isn't defined in any of the libraries imported using that prefix.
lib/openGL/OpenGL-Web.dart:39:8

โ•ท
39 โ”‚ ui.platformViewRegistry.registerViewFactory(divId, (int viewId) {
โ”‚ ^^^^^^^^^^^^^^^^^^^^
โ•ต

flutter pub get
Running "flutter pub get" in example...
Because example depends on flutter_gl from path which doesn't exist (could not find package flutter_gl at "....\flutter_gl\flutter_gl"), version solving failed.
pub get failed (66; Because example depends on flutter_gl from path which doesn't exist (could not find package flutter_gl at "....\flutter_gl\flutter_gl"), version solving failed.)
exit code 66

Class 'LibOpenGLES' has no instance method 'glUniform4fv' with matching arguments.

I get this Exception when I try to set the colors

// setup the colors.

String vs = """
    attribute vec4 a_position;

    uniform mat4 u_matrix;

    void main() {
      // Multiply the position by the matrix.
      gl_Position = u_matrix * a_position;
    }
  """;


  String fs = """
    precision mediump float;

    uniform vec4 u_color;

    void main() {
      gl_FragColor = u_color;
    }
  """;

dynamic color = [
    Random().nextDouble(),
    Random().nextDouble(),
    Random().nextDouble(),
    1,
  ];

colorLocation = gl.getUniformLocation(program, "u_color");

gl.uniform4fv(colorLocation, color); <--- error
Exception has occurred.
NoSuchMethodError (NoSuchMethodError: Class 'LibOpenGLES' has no instance method 'glUniform4fv' with matching arguments.
Receiver: Instance of 'LibOpenGLES'
Tried calling: glUniform4fv(1, Instance(length:4) of '_GrowableList')
Found: glUniform4fv(int, int, Pointer<Float>) => void)

I get this error when I use the app on an android device.

The web app works without issues but my app will run on an android device.

What I should do to fix this issue?

Example doesn't work correctly on Windows

Hello.
Thank you for creating such an amazing package!

I tried to run example app (flutter_gl/example), but when I run it on Windows, the triangle doesn't show up. When I run it on the Web under the same condition, it displays correctly.
Could you see what's wrong?

  • Windows
    image

  • Web
    image

Missing `glUniform2fv`

I was wondering if there's a reason the above function was omitted.
I was able to work around it using glUniform3fv for now, but it might be a good idea to add it for completeness.

Thank you.

Not finding Flutter_gl 0.0.15 or ffi packages

Starting 4 PM PDT, on 6/4/22 started getting many messages similar to the following: flutter_gl-0.0.15/lib/native-array/NativeArray.app.dart:1:8: Error: Not found: 'dart:ffi'
A reboot did not solve this. Updating ffi to 2.0.0 did not solve this (subsequently restored to ffi 1.2.1 in pubspec.yaml). Going back to older working examples did not solve this. Tried different targets, Chrome, Edge, Windows, Android device did not solve this. Working on a Windows 10 laptop in latest Android Studio with latest Flutter/Dart SDK's.

Could not find threeegl.aar

First off, thanks for making this repo, I'm really excited to start graphics programming in flutter.

I'm having an issue with building with flutter_gl 0.0.18

FAILURE: Build failed with an exception.
What went wrong:
Could not determine the dependencies of task ':app:lintVitalRelease'.

Could not resolve all artifacts for configuration ':app:debugRuntimeClasspath'.
Could not find :threeegl:.
Searched in the following locations:
- file:/C:/Users/xyz/myproject/android/app/libs/aars/threeegl.aar
Required by:
project :app > project :flutter_gl

I tried manually copying the aar into the project folder where it searched, but that did not work.

Any ideas on what is going wrong? And where can I find the code for the threeegl.aar class?

gl.bufferData call with too few arguments. Expected: 4 Actual: 3

I have updated the flutter_gl package from 0.0.3 to 0.0.5 and I notice an issue

I have a code that sets the colors with buffer data but the lib complains about adding one more parameter in gl.bufferData.

Code to reproduce

This is the code that worked before the update.

setColors(gl) {
    Float32List data = Float32List.fromList([
      Random().nextDouble(), Random().nextDouble(), Random().nextDouble(), 1, //
      Random().nextDouble(), Random().nextDouble(), Random().nextDouble(), 1, //
      Random().nextDouble(), Random().nextDouble(), Random().nextDouble(), 1, //
      Random().nextDouble(), Random().nextDouble(), Random().nextDouble(), 1, //
      Random().nextDouble(), Random().nextDouble(), Random().nextDouble(), 1, //
      Random().nextDouble(), Random().nextDouble(), Random().nextDouble(), 1, //
    ]);

    gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);
}

and I get this error

 OpenGLContextWeb 
{gl: [object WebGL2RenderingContext]}
Error: NoSuchMethodError: 'bufferData'
Dynamic call with too few arguments. Expected: 4 Actual: 3

In your example, ExampleDemoTest.dart I saw that you provide 4 arguments

var vertices = new Float32List.fromList([
    0.0, 0.5,  0.0,  // Vertice #1
   -0.5, -0.5, 0.0, // Vertice #2
    0.5, -0.5, 0.0  // Vertice #3
 ]);

final verticesPtr = calloc<Float>(vertices.length);
verticesPtr.asTypedList(vertices.length).setAll(0, vertices);

gl.bufferData(gl.ARRAY_BUFFER, vertices.length * Float32List.bytesPerElement, verticesPtr, gl.STATIC_DRAW);

What do you think we need to provide the size parameter? or it will be better to have it like it was before with only 3 params

now you have this method

bufferData(int target, int size, data, int usage) {
    gl.glBufferData(target, size, data.cast<Void>(), usage);
}

after the change

bufferData(int target, data, int usage) {
    late Pointer<Void> nativeData;
    late int size;
    if (data is List<double> || data is Float32List) {
      nativeData = floatListToArrayPointer(data as List<double>).cast();
      size = data.length * sizeOf<Float>();
    } else if (data is Int32List) {
      nativeData = int32ListToArrayPointer(data).cast();
      size = data.length * sizeOf<Int32>();
    } else if (data is Uint16List) {
      nativeData = uInt16ListToArrayPointer(data).cast();
      size = data.length * sizeOf<Uint16>();
    } else if (data is Uint32List) {
      nativeData = uInt32ListToArrayPointer(data).cast();
      size = data.length * sizeOf<Uint32>();  
    } else {
      throw ('bufferData: unsupported native type ${data.runtimeType}');
    }
    gl.glBufferData(target, size, nativeData, usage);
    calloc.free(nativeData);
}

I think is better for the user to provide the Float32List and handle all the native code inside the OpenGLContextES.dart file as you did before.

Also notice by importing the dart:ffi package breaks the web version of the app.

and I get all these errors.

flutter run
Multiple devices found:
Chrome (web) โ€ข chrome โ€ข web-javascript โ€ข Google Chrome 93.0.4577.82
Edge (web)   โ€ข edge   โ€ข web-javascript โ€ข Microsoft Edge 93.0.961.52
[1]: Chrome (chrome)
[2]: Edge (edge)
Please choose one (To quit, press "q/Q"): 1
Launching lib\main.dart on Chrome in debug mode...
lib/engine.dart:6:8: Error: Not found: 'dart:ffi'
import 'dart:ffi';
       ^
/G:/Programs/flutter/.pub-cache/hosted/pub.dartlang.org/ffi-1.1.2/lib/src/allocation.dart:5:8: Error: Not found: 'dart:ffi'
import 'dart:ffi';
       ^
/G:/Programs/flutter/.pub-cache/hosted/pub.dartlang.org/ffi-1.1.2/lib/src/arena.dart:8:8: Error: Not found: 'dart:ffi'
import 'dart:ffi';
       ^
/G:/Programs/flutter/.pub-cache/hosted/pub.dartlang.org/ffi-1.1.2/lib/src/utf8.dart:6:8: Error: Not found: 'dart:ffi'
import 'dart:ffi';
       ^
/G:/Programs/flutter/.pub-cache/hosted/pub.dartlang.org/ffi-1.1.2/lib/src/utf16.dart:5:8: Error: Not found: 'dart:ffi'
import 'dart:ffi';
       ^
/G:/Programs/flutter/.pub-cache/hosted/pub.dartlang.org/ffi-1.1.2/lib/src/allocation.dart:9:7: Error: Type 'DynamicLibrary' not found.
final DynamicLibrary stdlib = Platform.isWindows

also when try to run the app into an android device I get this errors

flutter run
Launching lib\main.dart on Lenovo TB J606F in debug mode...

FAILURE: Build failed with an exception.

Execution failed for task ':app:checkDebugAarMetadata'.
> Could not resolve all files for configuration ':app:debugRuntimeClasspath'.
   > Could not find :threeegl:.
     Searched in the following locations:
     Required by:
         project :app > project :flutter_gl

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 4s

Thanks

iOS Error

The example app crashes on iOS after opening any of the examples.

The error message is the following:

flutter_gl/CustomRender.swift:149: Fatal error: Unexpectedly found nil while unwrapping an Optional value

Am I missing something? Please let me know!

Disable updateTexture print

how can I disable print when calling updateTexture function?
I'm doing loop at 40ms interval when animating my render, but the print keep appears repeatly, and it's so annoying
The terminal console will looked like this:

D/com.futouapp.flutter_gl.flutter_gl.EglEnv(21522):  egl make current 
D/com.futouapp.flutter_gl.flutter_gl.EglEnv(21522):  egl make current 
D/com.futouapp.flutter_gl.flutter_gl.EglEnv(21522):  egl make current 
D/com.futouapp.flutter_gl.flutter_gl.EglEnv(21522):  egl make current 
D/com.futouapp.flutter_gl.flutter_gl.EglEnv(21522):  egl make current 
D/com.futouapp.flutter_gl.flutter_gl.EglEnv(21522):  egl make current 
D/com.futouapp.flutter_gl.flutter_gl.EglEnv(21522):  egl make current 
D/com.futouapp.flutter_gl.flutter_gl.EglEnv(21522):  egl make current 
D/com.futouapp.flutter_gl.flutter_gl.EglEnv(21522):  egl make current 
D/com.futouapp.flutter_gl.flutter_gl.EglEnv(21522):  egl make current 
...

Example failing with v0.0.16

Hello,
I'm barely getting started...

Trying to use the example triangle code I'm getting errors with FlutterGlPlatform.

Error: The method 'initialize_interface' isn't defined for the class 'FlutterGlPlatform'.
As if it's not seeing anything in flutter_gl_platform_interface-0.0.3/lib/method_channel_flutter_gl.dart.

I'm an absolute beginner with Flutter so I haven't figured out how to try to force the import.

e.g. Adding import package:flutter_gl_platform_interface/method_channel_flutter_gl.dart';
did me no good

Android Builds fail - Kotlin Gradle

I'm unable to build a flutter project that depends on the latest published version of flutter_gl (v0.0.21); I'm getting this error:

$ flutter run -d "SM G988W"
Launching lib/main.dart on SM G988W in debug mode...

FAILURE: Build failed with an exception.

* What went wrong:
The Android Gradle plugin supports only Kotlin Gradle plugin version 1.5.20 and higher.
The following dependencies do not satisfy the required version:
project ':flutter_gl' -> org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.61

my system environment:

$ flutter --version  
Flutter 3.13.9 โ€ข channel stable โ€ข https://github.com/flutter/flutter.git
Framework โ€ข revision d211f42860 (2 weeks ago) โ€ข 2023-10-25 13:42:25 -0700
Engine โ€ข revision 0545f8705d
Tools โ€ข Dart 3.1.5 โ€ข DevTools 2.25.0
$ sw_vers                
ProductName:            macOS
ProductVersion:         14.1
BuildVersion:           23B74

build failed could not find threeegl.aar UPD:SOLVED(NOOB ISSUE)

When I build for android, i have this exception:
FAILURE: Build failed with an exception.

  • What went wrong:
    Execution failed for task ':app:checkReleaseAarMetadata'.

Could not resolve all files for configuration ':app:releaseRuntimeClasspath'.
Could not find :threeegl:.
Searched in the following locations:
- file:/Users/usergerik/Documents/FlutterProjects/multitool/android/app/libs/aars/threeegl.aar
Required by:
project :app > project :flutter_gl

No display with AMD graphics cards?

We've tested the display on two AMD Ryzen Windows machines and we don't get the render, but on two other Intel Windows machines it does.

Have you identified problems with AMD graphics cards and their OpenGL drivers?

can't render properly in release apk

both in running the example flutter project in this repo and my own app based on three_dart, release apk can't get proper display. have you ever try build release apk like "flutter build apk --split-per-abi".

Here are the stack infos:

--------- beginning of crash
--------- beginning of system
--------- beginning of main
12-07 02:03:28.774 21654 21684 E flutter : [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception:  flutter_gl OpenGLContextES.dart toPointer _GrowableList<double> TODO 
12-07 02:03:28.774 21654 21684 E flutter : #0      toPointer (package:flutter_gl/openGL/opengl/OpenGLContextES.dart:928)
12-07 02:03:28.774 21654 21684 E flutter : #1      OpenGLContextES.uniform3fvNormal (package:flutter_gl/openGL/opengl/OpenGLContextES.dart:778)
12-07 02:03:28.774 21654 21684 E flutter : #2      OpenGLContextES.uniform3fv (package:flutter_gl/openGL/opengl/OpenGLContextES.dart:772)
12-07 02:03:28.774 21654 21684 E flutter : #3      WebGLUniformsHelper.setValueV3f (package:three_dart/three3d/renderers/webgl/WebGLUniformsHelper.dart:493)
12-07 02:03:28.774 21654 21684 E flutter : #4      WebGLUniforms.upload (package:three_dart/three3d/renderers/webgl/WebGLUniforms.dart:120)
12-07 02:03:28.774 21654 21684 E flutter : #5      WebGLRenderer.setProgram (package:three_dart/three3d/renderers/WebGLRenderer.dart:1564)
12-07 02:03:28.774 21654 21684 E flutter : #6      WebGLRenderer.renderBufferDirect (package:three_dart/three3d/renderers/WebGLRenderer.dart:568)
12-07 02:03:28.774 21654 21684 E flutter : #7      WebGLRenderer.renderObject (package:three_dart/three3d/renderers/WebGLRenderer.dart:1120)
12-07 02:03:28.774 21654 21684 E flutter : #8      WebGLRenderer.renderObjects (package:three_dart/three3d/renderers/WebGLRenderer.dart:1068)
12-07 02:03:28.774 21654 21684 E flutter : #9      WebGLRenderer.render (package:three_dart/three3d/renderers/WebGLRenderer.dart:819)
12-07 02:03:28.774 21654 21684 E flutter : #10     _ThreeJsScreenState.render (package:try_on_cloth/three_screen.dart:161)
12-07 02:03:28.774 21654 21684 E flutter : #11     _ThreeJsScreenState.animate (package:try_on_cloth/three_screen.dart:152)
12-07 02:03:28.774 21654 21684 E flutter : #12     _ThreeJsScreenState.initPlatformState.<anonymous closure> (package:try_on_cloth/three_screen.dart:92)
12-07 02:03:28.774 21654 21684 E flutter : <asynchronous suspension>
12-07 02:03:28.774 21654 21684 E flutter : 
12-07 02:06:41.657 22048 22078 E flutter : [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception:  flutter_gl OpenGLContextES.dart toPointer _GrowableList<double> TODO 

I found the issule, the type is "_GrowableList", not "List". However when I fixed it, it comes up with another problem. I get white screen. Below is the flutter log for flutter_gl.

12-07 03:32:51.896 508 568 I flutter : device pixel ratio is 3.5
12-07 03:32:51.896 508 568 I flutter : width is 411.42857142857144, height is 898.2857142857143
12-07 03:32:52.025 508 568 I flutter : OpenGLContextES
12-07 03:32:52.025 508 568 I flutter : {gl: Instance of 'LibOpenGLES'}
12-07 03:32:52.026 508 568 I flutter : OpenGLES getExtension key: EXT_color_buffer_float _v: Pointer: address=0xb9a5e400
12-07 03:32:52.027 508 568 I flutter : WebGLState..................init...........
12-07 03:32:52.027 508 568 I flutter : WebGLState. getParameter _data: 0
12-07 03:32:52.100 508 568 I flutter : THREE.WebGLProgram: gl.getProgramInfoLog() programLog: null vertexLog: null fragmentLog: null
12-07 03:35:03.371 811 840 I flutter : device pixel ratio is 3.5
12-07 03:35:03.371 811 840 I flutter : width is 411.42857142857144, height is 898.2857142857143
12-07 03:35:03.499 811 840 I flutter : OpenGLContextES
12-07 03:35:03.499 811 840 I flutter : {gl: Instance of 'LibOpenGLES'}
12-07 03:35:03.499 811 840 I flutter : OpenGLES getExtension key: EXT_color_buffer_float _v: Pointer: address=0xb9fa3800
12-07 03:35:03.501 811 840 I flutter : WebGLState..................init...........
12-07 03:35:03.501 811 840 I flutter : WebGLState. getParameter _data: 0
12-07 03:35:03.558 811 840 I flutter : THREE.WebGLProgram: gl.getProgramInfoLog() programLog: null vertexLog: null fragmentLog: null
12-07 03:37:08.844 1035 1131 I flutter : device pixel ratio is 3.5
12-07 03:37:08.844 1035 1131 I flutter : width is 411.42857142857144, height is 898.2857142857143
12-07 03:37:08.972 1035 1131 I flutter : OpenGLContextES
12-07 03:37:08.972 1035 1131 I flutter : {gl: Instance of 'LibOpenGLES'}
12-07 03:37:08.973 1035 1131 I flutter : OpenGLES getExtension key: EXT_color_buffer_float _v: Pointer: address=0xba0ce800
12-07 03:37:08.974 1035 1131 I flutter : WebGLState..................init...........
12-07 03:37:08.974 1035 1131 I flutter : WebGLState. getParameter _data: 0
12-07 03:37:09.033 1035 1131 I flutter : THREE.WebGLProgram: gl.getProgramInfoLog() programLog: null vertexLog: null fragmentLog: null

it seems the initialization of gles meet some problems and retry for many times.

Problems running example projects

Hello! Your project looks very promising, our team is considering using it in our following app. I had some problems running the examples, and I'd appreciate your help.

The ExampleTriangle01 demo doesn't show any triangles, rather I only see the canvas. The image I see is the same for every platform.
image

Logs per platform:

  • Android emulator
Launching lib\main.dart on Android SDK built for x86 in debug mode...
Running Gradle task 'assembleDebug'...
โˆš  Built build\app\outputs\flutter-apk\app-debug.apk.
Installing build\app\outputs\flutter-apk\app.apk...
W/FlutterActivityAndFragmentDelegate( 3536): A splash screen was provided to Flutter, but this is deprecated. See flutter.dev/go/android-splash-migration for migration steps.
Debug service listening on ws://127.0.0.1:61591/5a9boQmKzkA=/ws
Syncing files to device Android SDK built for x86...
I/flutter ( 3536):  init state..... 
I/flutter ( 3536):  screenSize: Size(392.7, 781.1) dpr: 2.75 

======== Exception caught by widgets library =======================================================
The following LateError was thrown building Builder(dirty, dependencies: [MediaQuery]):
LateInitializationError: Field 'width' has not been initialized.

The relevant error-causing widget was: 
  Builder Builder:file:///D:/Prog/Github_examples/flutter_gl/flutter_gl/example/lib/ExampleTriangle01.dart:110:15
When the exception was thrown, this was the stack: 
#0      _MyAppState.width (package:flutter_gl_example/ExampleTriangle01.dart)
#1      _MyAppState._build (package:flutter_gl_example/ExampleTriangle01.dart:130:20)
#2      _MyAppState.build.<anonymous closure> (package:flutter_gl_example/ExampleTriangle01.dart:113:49)
#3      Builder.build (package:flutter/src/widgets/basic.dart:7398:48)
#4      StatelessElement.build (package:flutter/src/widgets/framework.dart:4827:28)
#5      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4754:15)
#6      Element.rebuild (package:flutter/src/widgets/framework.dart:4477:5)
#7      ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4735:5)
#8      ComponentElement.mount (package:flutter/src/widgets/framework.dart:4729:5)
...     Normal element mounting (19 frames)
#27     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3790:14)
#28     MultiChildRenderObjectElement.inflateWidget (package:flutter/src/widgets/framework.dart:6422:36)
#29     MultiChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:6433:32)
...     Normal element mounting (255 frames)
#284    Element.inflateWidget (package:flutter/src/widgets/framework.dart:3790:14)
#285    MultiChildRenderObjectElement.inflateWidget (package:flutter/src/widgets/framework.dart:6422:36)
#286    MultiChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:6433:32)
...     Normal element mounting (387 frames)
#673    Element.inflateWidget (package:flutter/src/widgets/framework.dart:3790:14)
#674    Element.updateChild (package:flutter/src/widgets/framework.dart:3540:18)
#675    RenderObjectToWidgetElement._rebuild (package:flutter/src/widgets/binding.dart:1198:16)
#676    RenderObjectToWidgetElement.mount (package:flutter/src/widgets/binding.dart:1167:5)
#677    RenderObjectToWidgetAdapter.attachToRenderTree.<anonymous closure> (package:flutter/src/widgets/binding.dart:1112:18)
#678    BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2600:19)
#679    RenderObjectToWidgetAdapter.attachToRenderTree (package:flutter/src/widgets/binding.dart:1111:13)
#680    WidgetsBinding.attachRootWidget (package:flutter/src/widgets/binding.dart:944:7)
#681    WidgetsBinding.scheduleAttachRootWidget.<anonymous closure> (package:flutter/src/widgets/binding.dart:924:7)
(elided 11 frames from class _RawReceivePortImpl, class _Timer, dart:async, and dart:async-patch)
====================================================================================================
D/HostConnection( 3536): HostConnection::get() New Host Connection established 0xef188dd0, tid 3590
D/HostConnection( 3536): HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV_Cache ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_has_shared_slots_host_memory_allocator ANDROID_EMU_vulkan_free_memory_sync ANDROID_EMU_vulkan_shader_float16_int8 ANDROID_EMU_vulkan_async_queue_submit ANDROID_EMU_sync_buffer_data ANDROID_EMU_read_color_buffer_dma GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_gles_max_version_3_0 
D/EGL_emulation( 3536): eglCreateContext: 0xef1891c0: maj 3 min 0 rcv 3
D/EGL_emulation( 3536): eglCreateContext: 0xef188f20: maj 3 min 0 rcv 3
D/EGL_emulation( 3536): eglCreateContext: 0xef189000: maj 3 min 0 rcv 3
W/Gralloc4( 3536): allocator 3.x is not supported
D/com.futouapp.flutter_gl.flutter_gl.EglEnv( 3536):  egl make current 
D/EGL_emulation( 3536): eglMakeCurrent: 0xef188f20: ver 3 0 (tinfo 0xbc055410) (first time)
I/flutter ( 3536):  flutterGlPlugin: textureid: 0 
D/HostConnection( 3536): HostConnection::get() New Host Connection established 0xef1a2210, tid 3574
D/HostConnection( 3536): HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV_Cache ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_has_shared_slots_host_memory_allocator ANDROID_EMU_vulkan_free_memory_sync ANDROID_EMU_vulkan_shader_float16_int8 ANDROID_EMU_vulkan_async_queue_submit ANDROID_EMU_sync_buffer_data ANDROID_EMU_read_color_buffer_dma GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_gles_max_version_3_0 
D/EGL_emulation( 3536): eglMakeCurrent: 0xef189000: ver 3 0 (tinfo 0xbc055af0) (first time)
I/flutter ( 3536): Error compiling shader: 
I/flutter ( 3536): Error compiling shader:
I/flutter ( 3536): ERROR: 0:5: 'attribute' : Illegal use of reserved word
I/flutter ( 3536): ERROR: 0:5: 'attribute' : syntax error
I/flutter ( 3536): Error compiling shader: 
I/flutter ( 3536): Error compiling shader:
I/flutter ( 3536): ERROR: 0:5: 'gl_FragColor' : undeclared identifier
I/flutter ( 3536): ERROR: 0:5: 'assign' : l-value required (can't modify a const)
I/flutter ( 3536): ERROR: 0:5: '=' : dimension mismatch
I/flutter ( 3536): ERROR: 0:5: 'assign' : cannot convert from 'const 4-component vector of float' to 'const highp float'
E/flutter ( 3536): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type 'Null' is not a subtype of type 'int' of 'shader'
E/flutter ( 3536): #0      OpenGLContextES.attachShader (package:flutter_gl/openGL/opengl/OpenGLContextES.dart:488:15)
E/flutter ( 3536): #1      _MyAppState.initShaders (package:flutter_gl_example/ExampleTriangle01.dart:298:8)
E/flutter ( 3536): #2      _MyAppState.prepare (package:flutter_gl_example/ExampleTriangle01.dart:239:10)
E/flutter ( 3536): #3      _MyAppState.setup (package:flutter_gl_example/ExampleTriangle01.dart:81:5)
E/flutter ( 3536): <asynchronous suspension>
E/flutter ( 3536): 
I/flutter ( 3536):  click render ... 
I/flutter ( 3536):  render n: 0 
I/System.out( 3536): Results of compiling source:
I/System.out( 3536): Results of compiling source:
I/flutter ( 3536):  click render ... 
I/flutter ( 3536):  render n: 0 
  • Web Chrome
Launching lib\main.dart on Chrome in debug mode...
Waiting for connection from debug service on Chrome...
This app is linked to the debug service: ws://127.0.0.1:51155/9GmCwH8CdUc=/ws
Debug service listening on ws://127.0.0.1:51155/9GmCwH8CdUc=/ws

 Running with sound null safety 
Debug service listening on ws://127.0.0.1:51155/9GmCwH8CdUc=/ws
 init state..... 
 screenSize: Size(1036.0, 718.4) dpr: 1.25 
 flutterGlPlugin: textureid: 1650533741854000 
Height of Platform View type: [1650533741854000] may not be set. Defaulting to `height: 100%`.
Set `style.height` to any appropriate value to stop this message.
Width of Platform View type: [1650533741854000] may not be set. Defaulting to `width: 100%`.
Set `style.width` to any appropriate value to stop this message.
 OpenGLContextWeb 
{gl: [object WebGL2RenderingContext]}
Error: Unsupported operation: Platform._operatingSystem
    at Object.throw_ [as throw] (http://localhost:51102/dart_sdk.js:5067:11)
    at Function._operatingSystem (http://localhost:51102/dart_sdk.js:57544:17)
    at Function.get operatingSystem [as operatingSystem] (http://localhost:51102/dart_sdk.js:57590:27)
    at get _operatingSystem (http://localhost:51102/dart_sdk.js:57503:27)
    at Function.desc.get [as _operatingSystem] (http://localhost:51102/dart_sdk.js:5560:17)
    at get isMacOS (http://localhost:51102/dart_sdk.js:57518:26)
    at Function.desc.get [as isMacOS] (http://localhost:51102/dart_sdk.js:5560:17)
    at ExampleTriangle01._MyAppState.new.prepare (http://localhost:51102/packages/flutter_gl_example/ExampleTriangle01.dart.lib.js:383:23)
    at ExampleTriangle01._MyAppState.new.setup (http://localhost:51102/packages/flutter_gl_example/ExampleTriangle01.dart.lib.js:311:14)
    at setup.next (<anonymous>)
    at runBody (http://localhost:51102/dart_sdk.js:40590:34)
    at Object._async [as async] (http://localhost:51102/dart_sdk.js:40621:7)
    at ExampleTriangle01._MyAppState.new.setup (http://localhost:51102/packages/flutter_gl_example/ExampleTriangle01.dart.lib.js:305:20)
    at http://localhost:51102/packages/flutter_gl_example/ExampleTriangle01.dart.lib.js:300:16
    at http://localhost:51102/dart_sdk.js:34918:33
    at internalCallback (http://localhost:51102/dart_sdk.js:26619:11)

======== Exception caught by widgets library =======================================================
The following LateError was thrown building Builder(dirty, dependencies: [MediaQuery]):
LateInitializationError: Field 'width' has not been initialized.

The relevant error-causing widget was: 
  Builder Builder:file:///D:/Prog/Github_examples/flutter_gl/flutter_gl/example/lib/ExampleTriangle01.dart:110:15
When the exception was thrown, this was the stack: 
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 251:49  throw_
packages/flutter_gl_example/ExampleTriangle01.dart 22:15                                                                   get width
packages/flutter_gl_example/ExampleTriangle01.dart 130:20                                                                  [_build]
packages/flutter_gl_example/ExampleTriangle01.dart 113:49                                                                  <fn>
packages/flutter/src/widgets/basic.dart 7398:48                                                                            build
packages/flutter/src/widgets/framework.dart 4827:28                                                                        build
<FLUTTER INTERNAL STACK TRACE SKIPPED>
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/isolate_helper.dart 48:19       internalCallback
====================================================================================================
 click render ... 
 render n: 0 
 click render ... 
 render n: 0 

  • Windows desktop
Launching lib\main.dart on Windows in debug mode...
Building Windows application...
Debug service listening on ws://127.0.0.1:50588/1OBRUsWQ464=/ws
Syncing files to device Windows...
flutter:  init state..... 
flutter:  screenSize: Size(1265.6, 682.4) dpr: 1.25 

======== Exception caught by widgets library =======================================================
The following LateError was thrown building Builder(dirty, dependencies: [MediaQuery]):
LateInitializationError: Field 'width' has not been initialized.

The relevant error-causing widget was: 
  Builder Builder:file:///D:/Prog/Github_examples/flutter_gl/flutter_gl/example/lib/ExampleTriangle01.dart:110:15
When the exception was thrown, this was the stack: 
#0      _MyAppState.width (package:flutter_gl_example/ExampleTriangle01.dart)
#1      _MyAppState._build (package:flutter_gl_example/ExampleTriangle01.dart:130:20)
#2      _MyAppState.build.<anonymous closure> (package:flutter_gl_example/ExampleTriangle01.dart:113:49)
#3      Builder.build (package:flutter/src/widgets/basic.dart:7398:48)
#4      StatelessElement.build (package:flutter/src/widgets/framework.dart:4827:28)
#5      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4754:15)
#6      Element.rebuild (package:flutter/src/widgets/framework.dart:4477:5)
#7      ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4735:5)
#8      ComponentElement.mount (package:flutter/src/widgets/framework.dart:4729:5)
...     Normal element mounting (19 frames)
#27     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3790:14)
#28     MultiChildRenderObjectElement.inflateWidget (package:flutter/src/widgets/framework.dart:6422:36)
#29     MultiChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:6433:32)
...     Normal element mounting (255 frames)
#284    Element.inflateWidget (package:flutter/src/widgets/framework.dart:3790:14)
#285    MultiChildRenderObjectElement.inflateWidget (package:flutter/src/widgets/framework.dart:6422:36)
#286    MultiChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:6433:32)
...     Normal element mounting (387 frames)
#673    Element.inflateWidget (package:flutter/src/widgets/framework.dart:3790:14)
#674    Element.updateChild (package:flutter/src/widgets/framework.dart:3540:18)
#675    RenderObjectToWidgetElement._rebuild (package:flutter/src/widgets/binding.dart:1198:16)
#676    RenderObjectToWidgetElement.mount (package:flutter/src/widgets/binding.dart:1167:5)
#677    RenderObjectToWidgetAdapter.attachToRenderTree.<anonymous closure> (package:flutter/src/widgets/binding.dart:1112:18)
#678    BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2600:19)
#679    RenderObjectToWidgetAdapter.attachToRenderTree (package:flutter/src/widgets/binding.dart:1111:13)
#680    WidgetsBinding.attachRootWidget (package:flutter/src/widgets/binding.dart:944:7)
#681    WidgetsBinding.scheduleAttachRootWidget.<anonymous closure> (package:flutter/src/widgets/binding.dart:924:7)
(elided 11 frames from class _RawReceivePortImpl, class _Timer, dart:async, and dart:async-patch)
====================================================================================================
flutter:  flutterGlPlugin: textureid: 2755101658608 
flutter:  initShaders LINK_STATUS _res: 1 
flutter:  render n: 3 
flutter:  click render ... 
flutter:  render n: 3 

You need to add a depth Buffer in setupDefaultFBO method

I found an issue when I try to use the gl.DEPTH_BUFFER_BIT .

I found the issue on the Android device.

Example code

draw() {

// Tell WebGL how to convert from clip space to pixels
    gl.viewport(0, 0, (width * flgl.dpr).toInt(), (height * flgl.dpr).toInt());

    // Clear the canvas. sets the canvas background color.
    gl.clearColor(0, 0, 0, 1);

    // Clear the canvas.
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

    // Turn on culling. By default backfacing triangles will be culled.
    gl.enable(gl.CULL_FACE);

    // Enable the depth buffer
    gl.enable(gl.DEPTH_TEST);

    // print('CULL_FACE Enabled: ${gl.getParameter(gl.CULL_FACE)}');
    // print('DEPTH_TEST Enabled: ${gl.getParameter(gl.DEPTH_TEST)}');

    // Tell it to use our program (pair of shaders)
    gl.useProgram(program);

    // Turn on the attribute
    gl.enableVertexAttribArray(positionLocation);

    // Bind the position buffer.
    gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);

    // Tell the attribute how to get data out of positionBuffer (ARRAY_BUFFER)
    var size = 3; // 3 components per iteration
    var type = gl.FLOAT; // the data is 32bit floats
    var normalize = false; // don't normalize the data
    var stride = 0;
    var offset = 0; // start at the beginning of the buffer
    gl.vertexAttribPointer(positionLocation, size, type, normalize, stride, offset);
}

And I get this:

Screenshot 2021-09-24 191041

But I want this:

Screenshot 2021-09-24 191122

I found a workaround that fixes this issue but I am not sure if this produces any other issues

setupDefaultFBO() {

  int glWidth = (width * dpr).toInt();
  int glHeight = (height * dpr).toInt();

  dynamic defaultFramebuffer = _gl.createFramebuffer();
  dynamic defaultFramebufferTexture = _gl.createTexture();
  _gl.activeTexture(_gl.TEXTURE0);

  _gl.bindTexture(_gl.TEXTURE_2D, defaultFramebufferTexture);
  _gl.texImage2D(
  _gl.TEXTURE_2D, 0, _gl.RGBA, glWidth, glHeight, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null);
  _gl.texParameteri(_gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.LINEAR);
  _gl.texParameteri(_gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.LINEAR);

  _gl.bindFramebuffer(_gl.FRAMEBUFFER, defaultFramebuffer);
  _gl.framebufferTexture2D(
  _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, defaultFramebufferTexture, 0);

  Pointer<Int32> depthBuffer = calloc();
  _gl.gl.glGenRenderbuffers(1, depthBuffer.cast());
  _gl.gl.glBindRenderbuffer(_gl.RENDERBUFFER, depthBuffer.value);
  _gl.gl.glRenderbufferStorage(_gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, glWidth, glHeight);
  _gl.gl.glFramebufferRenderbuffer(
  _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, depthBuffer.value);

  return defaultFramebufferTexture;
}

Can't release memory After disposed the Texture

Hi, I have some problems when I tried to release memory. If I don't create a new textureId, the memory wouldn't be out of memory, but once I tried to dispose of one and create a new one, the memory will increase rapidly. After multiple operations, my app will crash...
My code like this:
`
@OverRide
void dispose() {
picList![0].dispose();
picList![1].dispose();

_gl.deleteTexture(frameTextureList[0]);
frameTextureList[0] = 0;

_gl.deleteTexture(frameTextureList[1]);
frameTextureList[1] = 0;

_gl.deleteFramebuffer(defaultFramebuffers);
defaultFramebuffers = 0;

_gl.deleteRenderbuffer(defaultRenderbuffer);
defaultRenderbuffer = 0;

_gl.deleteTexture(frameTexture);
frameTexture = 0;

_gl.deleteTexture(frameTexture2);
frameTexture2 = 0;

_gl.deleteTexture(defaultFramebufferTexturess);
defaultFramebufferTexturess = 0;

_gl.deleteTexture(sourceTexture);
sourceTexture = 0;

if (vao != 0 && vao != null) {
  _gl.deleteVertexArray(vao);
  vao = 0;
}
if (vertexBuffer != 0 && vertexBuffer != null) {
  _gl.deleteBuffer(vertexBuffer);
  vertexBuffer = 0;
}
if (vertexBuffer1 != 0 && vertexBuffer1 != null) {
  _gl.deleteBuffer(vertexBuffer1);
  vertexBuffer1 = 0;
}

_gl.deleteProgram(glProgram);
glProgram = 0;
_gl.useProgram(0);
_gl.finish();

flutterGlPlugin.dispose();

super.dispose();

}`

I change the NativeArray.app.dart file to:
`final freenalizer = NativeFinalizer(DynamicLibrary.executable().lookup('free'));

@OverRide
void dispose() {
if (!disposed) {
calloc.free(data);
freenalizer.detach(this);
disposed = true;
}
super.dispose();
}

NativeUint8Array(int size) : super(size) {
_list = calloc(size);
freenalizer.attach(this, _list.cast(), detach: this);
oneByteSize = sizeOf();
}
NativeUint8Array.from(List listData) : super.from(listData) {
_list = calloc(listData.length);
freenalizer.attach(this, _list.cast(), detach: this);
oneByteSize = sizeOf();
this.toDartList().setAll(0, listData);
}
`
can someone help me fix this bug? Thank you!!!!!!!

the textureid problem

the first one : how to view three js widget in android ๏ผŸ texture in flutter or other ?

second : where the textureid being set ? the example demo can't running ,

Cobe Problem

My Code
`
import 'dart:async';
import 'dart:io';
import 'dart:typed_data';

import 'dart:ui' as ui;
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import 'package:flutter_gl/flutter_gl.dart';
import 'package:flutter_gl/openGL/opengl/opengl_es_bindings/opengl_es_bindings.dart';
import 'package:vector_math/vector_math.dart' as math;

class ExampleCube extends StatefulWidget {
_MyAppState createState() => _MyAppState();
}

class _MyAppState extends State {
late FlutterGlPlugin flutterGlPlugin;

int? fboId;
num dpr = 1.0;
late double width;
late double height;

ui.Size? screenSize;

dynamic glProgram;
dynamic _vao;
dynamic _ebo;
dynamic _texture1;
dynamic _texture2;

dynamic sourceTexture;

dynamic defaultFramebuffer;
dynamic defaultFramebufferTexture;

int n = 0;

int t = DateTime.now().millisecondsSinceEpoch;

@OverRide
void initState() {
super.initState();

print(" init state..... ");

}

// Platform messages are asynchronous, so we initialize in an async method.
Future initPlatformState() async {
width = screenSize!.width;
height = width;

flutterGlPlugin = FlutterGlPlugin();

Map<String, dynamic> _options = {
  "antialias": true,
  "alpha": false,
  "width": width.toInt(),
  "height": height.toInt(),
  "dpr": dpr
};

await flutterGlPlugin.initialize(options: _options);

print(" flutterGlPlugin: textureid: ${flutterGlPlugin.textureId} ");

setState(() {});

// web need wait dom ok!!!
Future.delayed(Duration(milliseconds: 100), () {
  setup();
});

}

setup() async {
// web no need use fbo
if (!kIsWeb) {
await flutterGlPlugin.prepareContext();

  setupDefaultFBO();
  sourceTexture = defaultFramebufferTexture;
}

prepare();

}

initSize(BuildContext context) {
if (screenSize != null) {
return;
}

final mq = MediaQuery.of(context);

screenSize = mq.size;
dpr = mq.devicePixelRatio;

print(" screenSize: ${screenSize} dpr: ${dpr} ");

initPlatformState();

}

@OverRide
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Example app'),
),
body: Builder(
builder: (BuildContext context) {
initSize(context);
return SingleChildScrollView(child: _build(context));
},
),
floatingActionButton: FloatingActionButton(
onPressed: () {
clickRender();
},
child: Text("Render"),
),
),
);
}

Widget _build(BuildContext context) {
return Column(
children: [
Container(
width: width,
height: width,
color: Colors.black,
child: Builder(builder: (BuildContext context) {
if (kIsWeb) {
return flutterGlPlugin.isInitialized
? HtmlElementView(
viewType: flutterGlPlugin.textureId!.toString())
: Container();
} else {
return flutterGlPlugin.isInitialized
? Texture(textureId: flutterGlPlugin.textureId!)
: Container();
}
})),
],
);
}

setupDefaultFBO() {
final _gl = flutterGlPlugin.gl;
int glWidth = (width * dpr).toInt();
int glHeight = (height * dpr).toInt();

print("glWidth: ${glWidth} glHeight: ${glHeight} ");

defaultFramebuffer = _gl.createFramebuffer();
defaultFramebufferTexture = _gl.createTexture();
_gl.activeTexture(_gl.TEXTURE0);

_gl.bindTexture(_gl.TEXTURE_2D, defaultFramebufferTexture);
_gl.texImage2D(_gl.TEXTURE_2D, 0, _gl.RGBA, glWidth, glHeight, 0, _gl.RGBA,
    _gl.UNSIGNED_BYTE, null);
_gl.texParameteri(_gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.LINEAR);
_gl.texParameteri(_gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.LINEAR);

_gl.bindFramebuffer(_gl.FRAMEBUFFER, defaultFramebuffer);
_gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0,
    _gl.TEXTURE_2D, defaultFramebufferTexture, 0);

}

clickRender() {
print(" click render ... ");
render();
}

render() {
final _gl = flutterGlPlugin.gl;

_gl.viewport(0, 0, (width * dpr).toInt(), (height * dpr).toInt());

// Clear canvas
_gl.clearColor(0.2, 0.3, 0.3, 1.0);
_gl.clear(_gl.COLOR_BUFFER_BIT|_gl.DEPTH_BUFFER_BIT);

_gl.drawArrays(_gl.TRIANGLES, 0, 36);

print(" render n: $n ");

_gl.finish();

if (!kIsWeb) {
  flutterGlPlugin.updateTexture(sourceTexture);
}

}

prepare() {
final _gl = flutterGlPlugin.gl;

String _version = "300 es";

if(!kIsWeb) {
  if (Platform.isMacOS || Platform.isWindows) {
    _version = "150";
  }
}

var vs = """#version ${_version}

precision mediump float; // add a precision qualifier

layout (location = 0) in vec3 a_Position;
layout (location = 1) in vec2 a_TexCoord;

out vec2 TexCoord;

uniform mat4 mvp;

void main() {
gl_Position = mvp * vec4(a_Position, 1.0);
TexCoord = vec2(a_TexCoord.x,a_TexCoord.y);
}
""";

var fs = """#version ${_version}

precision mediump float;

out vec4 pc_fragColor;
#define gl_FragColor pc_fragColor

in vec2 TexCoord;

uniform sampler2D texture1;
uniform sampler2D texture2;

void main() {
gl_FragColor = mix(texture(texture1, TexCoord), texture(texture2, TexCoord), 0.2);
}
""";

if (!initShaders(_gl, vs, fs)) {
  print('Failed to intialize shaders.');
  return;
}

// Write the positions of vertices to a vertex shader
n = initVertexBuffers(_gl);
if (n < 0) {
  print('Failed to set the positions of the vertices');
  return;
}

}

initVertexBuffers(gl) {
// Vertices
var dim = 3;

gl.enable(GL_DEPTH_TEST);

var vertices = Float32Array.fromList([
  // position       // texture coords
  -0.5, -0.5, -0.5,  0.0, 0.0,
  0.5, -0.5, -0.5,  1.0, 0.0,
  0.5,  0.5, -0.5,  1.0, 1.0,
  0.5,  0.5, -0.5,  1.0, 1.0,
  -0.5,  0.5, -0.5,  0.0, 1.0,
  -0.5, -0.5, -0.5,  0.0, 0.0,
  -0.5, -0.5,  0.5,  0.0, 0.0,
  0.5, -0.5,  0.5,  1.0, 0.0,
  0.5,  0.5,  0.5,  1.0, 1.0,
  0.5,  0.5,  0.5,  1.0, 1.0,
  -0.5,  0.5,  0.5,  0.0, 1.0,
  -0.5, -0.5,  0.5,  0.0, 0.0,
  -0.5,  0.5,  0.5,  1.0, 0.0,
  -0.5,  0.5, -0.5,  1.0, 1.0,
  -0.5, -0.5, -0.5,  0.0, 1.0,
  -0.5, -0.5, -0.5,  0.0, 1.0,
  -0.5, -0.5,  0.5,  0.0, 0.0,
  -0.5,  0.5,  0.5,  1.0, 0.0,
  0.5,  0.5,  0.5,  1.0, 0.0,
  0.5,  0.5, -0.5,  1.0, 1.0,
  0.5, -0.5, -0.5,  0.0, 1.0,
  0.5, -0.5, -0.5,  0.0, 1.0,
  0.5, -0.5,  0.5,  0.0, 0.0,
  0.5,  0.5,  0.5,  1.0, 0.0,
  -0.5, -0.5, -0.5,  0.0, 1.0,
  0.5, -0.5, -0.5,  1.0, 1.0,
  0.5, -0.5,  0.5,  1.0, 0.0,
  0.5, -0.5,  0.5,  1.0, 0.0,
  -0.5, -0.5,  0.5,  0.0, 0.0,
  -0.5, -0.5, -0.5,  0.0, 1.0,
  -0.5,  0.5, -0.5,  0.0, 1.0,
  0.5,  0.5, -0.5,  1.0, 1.0,
  0.5,  0.5,  0.5,  1.0, 0.0,
  0.5,  0.5,  0.5,  1.0, 0.0,
  -0.5,  0.5,  0.5,  0.0, 0.0,
  -0.5,  0.5, -0.5,  0.0, 1.0,
]);

_vao = gl.createVertexArray();
gl.bindVertexArray(_vao);

// Create a buffer object
var vertexBuffer = gl.createBuffer();
if (vertexBuffer == null) {
  print('Failed to create the buffer object');
  return -1;
}
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);

if(kIsWeb) {
  gl.bufferData(gl.ARRAY_BUFFER, vertices.length, vertices, gl.STATIC_DRAW);
} else {
  gl.bufferData(gl.ARRAY_BUFFER, vertices.lengthInBytes, vertices, gl.STATIC_DRAW);
}

// Assign the vertices in buffer object to a_Position variable
var a_Position = gl.getAttribLocation(glProgram, 'a_Position');
if (a_Position < 0) {
  print('Failed to get the storage location of a_Position');
  return -1;
}

var c_Position = gl.getAttribLocation(glProgram, 'a_TexCoord');
if(c_Position < 0){
  print('Failed to get the storage location of a_TexCoord');
  return -1;
}

gl.vertexAttribPointer(
    a_Position, dim, gl.FLOAT, false, Float32List.bytesPerElement * 5, 0);
gl.enableVertexAttribArray(a_Position);

gl.vertexAttribPointer(
    c_Position, 2, gl.FLOAT, false, Float32List.bytesPerElement * 5, Float32List.bytesPerElement * 3);
gl.enableVertexAttribArray(c_Position);

_texture1 = gl.createTexture();
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(GL_TEXTURE_2D, _texture1);
// set the texture wrapping parameters
gl.texParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
gl.texParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
// set texture filtering parameters
gl.texParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
gl.texParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
gl.uniform1i(gl.getUniformLocation(glProgram,'texture1'),0);

// load image, create texture and generate mipmaps
loadImage('assets/images/flutter540.jpg').then((bytes) {
  gl.texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 540, 540, 0, GL_RGBA, GL_UNSIGNED_BYTE, Uint8Array.from(bytes.toList()));
  gl.generateMipmap(GL_TEXTURE_2D);

  _texture2 = gl.createTexture();
  gl.activeTexture(gl.TEXTURE1);
  gl.bindTexture(GL_TEXTURE_2D, _texture2);
  // set the texture wrapping parameters
  gl.texParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
  gl.texParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
  // set texture filtering parameters
  gl.texParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
  gl.texParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  gl.uniform1i(gl.getUniformLocation(glProgram,'texture2'),1);

  // load image, create texture and generate mipmaps
  loadImage('assets/images/awesomeface.png').then((bytes) {
    gl.texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 476, 476, 0, GL_RGBA, GL_UNSIGNED_BYTE, Uint8Array.from(bytes.toList()));
    gl.generateMipmap(GL_TEXTURE_2D);
  });
});

int _current = DateTime.now().millisecondsSinceEpoch;
math.Vector3 axis = math.Vector3(0.5, 1.0, 0.0);
final model = math.Matrix4.identity()..rotate(axis, _current.toDouble());
final view = math.Matrix4.identity()..translate(math.Vector3(0.0,0.0,-3.0));
math.Matrix4 projection = math.makePerspectiveMatrix(45.0,1.0, 0.1, 100.0);
math.Matrix4 MVP = projection * view * model;

var mvpPosition = gl.getUniformLocation(glProgram, 'mvp');
if(mvpPosition < 0){
  print('Failed to get the storage location of MVP');
  return -1;
}
gl.uniformMatrix4fv(mvpPosition, true, MVP.storage);

// Return number of vertices
return (vertices.length / dim).toInt();

}

initShaders(gl, vs_source, fs_source) {
// Compile shaders
var vertexShader = makeShader(gl, vs_source, gl.VERTEX_SHADER);
var fragmentShader = makeShader(gl, fs_source, gl.FRAGMENT_SHADER);

// Create program
glProgram = gl.createProgram();

// Attach and link shaders to the program
gl.attachShader(glProgram, vertexShader);
gl.attachShader(glProgram, fragmentShader);
gl.linkProgram(glProgram);
var _res = gl.getProgramParameter(glProgram, gl.LINK_STATUS);
print(" initShaders LINK_STATUS _res: ${_res} ");
if (_res == false || _res == 0) {
  print("Unable to initialize the shader program");
  return false;
}

// Use program
gl.useProgram(glProgram);

return true;

}

makeShader(gl, src, type) {
var shader = gl.createShader(type);
gl.shaderSource(shader, src);
gl.compileShader(shader);
var _res = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
if (_res == 0 || _res == false) {
print("Error compiling shader: ${gl.getShaderInfoLog(shader)}");
return;
}
return shader;
}

Future loadImage(String imgPath) async{
final ByteData imageData = await rootBundle.load(imgPath);
final Uint8List bytes = imageData.buffer.asUint8List();

// Decode the image
final ui.Codec codec = await ui.instantiateImageCodec(bytes);
final ui.Image image = (await codec.getNextFrame()).image;

// Flip the image vertically
final Uint8List pixelData = await _flipImageVertically(image);

return pixelData;

}

Future _flipImageVertically(ui.Image image) async {
final int width = image.width;
final int height = image.height;

final ByteData? byteData = await image.toByteData();
final Uint8List pixels = Uint8List.fromList(byteData?.buffer.asUint8List() ?? []);

for (int y = 0; y < height ~/ 2; y++) {
  final int topOffset = y * width * 4;
  final int bottomOffset = (height - y - 1) * width * 4;
  for (int x = 0; x < width; x++) {
    final int topIndex = topOffset + x * 4;
    final int bottomIndex = bottomOffset + x * 4;
    final int r = pixels[topIndex];
    final int g = pixels[topIndex + 1];
    final int b = pixels[topIndex + 2];
    final int a = pixels[topIndex + 3];
    pixels[topIndex] = pixels[bottomIndex];
    pixels[topIndex + 1] = pixels[bottomIndex + 1];
    pixels[topIndex + 2] = pixels[bottomIndex + 2];
    pixels[topIndex + 3] = pixels[bottomIndex + 3];
    pixels[bottomIndex] = r;
    pixels[bottomIndex + 1] = g;
    pixels[bottomIndex + 2] = b;
    pixels[bottomIndex + 3] = a;
  }
}

return pixels;

}
}
`
When I render on Android mobile. It's not showing as a 3D cube, but as a 2D square.
Screenshot_20230330_143643
My image
flutter540

awesomeface
Can anyone help guide me?

Cannot compile Android app with `flutter_gl` dependency

Getting an error why compiling the Android app.

  • Added flutter_gl to my pubspec.yaml as a dependency
  • Ran flutter build apk

Error message:

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:checkReleaseAarMetadata'.
> Could not resolve all files for configuration ':app:releaseRuntimeClasspath'.
   > Could not find :threeegl:.
     Searched in the following locations:
       - file:<redacted>/Samples/test3d/android/app/libs/aars/threeegl.aar
     Required by:
         project :app > project :flutter_gl

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.

* Get more help at https://help.gradle.org

Any ideas what might fix this?

Interoperability with Native Flutter Context

Love this project and was able to get some nice multi-pass shaders going with it.
One issue I don't understand is how to set up a shared context properly.
Specifically, let's say I want to process frames from the video_player plugin.
The video_player keeps a textureId that holds the content of the current frame, which can then be rendered onto a Texture Widget.
However, when I try to use that textureId in flutter_gl it doesn't work. And, in fact, the same textureId is handed out by flutter_gl, which indicates that they are not using the same context.
I am assuming that video_player uses some sort of "standard" fluter context since it doesn't have to do any magic with flutterGlPlugin.updateTexture() in the end.
So then, how would I make flutter_gl leverage that same, shared context?
Thanks for your help!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.