Skip to main content

flix3dengine 0.1.0 copy "flix3dengine: ^0.1.0" to clipboard
flix3dengine: ^0.1.0 copied to clipboard

A Flutter game engine package with a C++20 runtime and Dart FFI.

example/lib/main.dart

import 'dart:math' as math;

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

void main() {
  runApp(const Flix3DExampleApp());
}

class Flix3DExampleApp extends StatelessWidget {
  const Flix3DExampleApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flix3DEngine',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(
          seedColor: const Color(0xFF35D0BA),
          brightness: Brightness.dark,
        ),
        scaffoldBackgroundColor: const Color(0xFF101513),
        useMaterial3: true,
      ),
      home: const EngineExamplePage(),
    );
  }
}

class EngineExamplePage extends StatefulWidget {
  const EngineExamplePage({super.key});

  @override
  State<EngineExamplePage> createState() => _EngineExamplePageState();
}

class _EngineExamplePageState extends State<EngineExamplePage> {
  late final Flix3DEngine _engine;
  late final Flix3DController _viewportController;
  String? _selectedEntityId;
  int _nextEntityId = 1;

  @override
  void initState() {
    super.initState();
    _engine = Flix3DEngine(
      config: const Flix3DEngineConfig(name: 'Flix3DEngine Example'),
    );
    _viewportController = Flix3DController();
    _addEntity(name: 'Entity 1');
    _engine.initialize();
  }

  @override
  void dispose() {
    _viewportController.dispose();
    _engine.dispose();
    super.dispose();
  }

  void _addEntity({String? name}) {
    final id = 'entity-${_nextEntityId++}';
    final entity = _engine.scene.addEntity(
      id: id,
      name: name ?? 'Entity ${_nextEntityId - 1}',
    );
    setState(() => _selectedEntityId = entity.id);
  }

  void _removeSelectedEntity() {
    final id = _selectedEntityId;
    if (id == null) {
      return;
    }

    _engine.scene.removeEntity(id);
    final remaining = _engine.scene.entities;
    setState(
      () => _selectedEntityId = remaining.isEmpty ? null : remaining.last.id,
    );
  }

  void _updateSelectedTransform(
    Flix3DTransform Function(Flix3DTransform transform) update,
  ) {
    final id = _selectedEntityId;
    if (id == null) {
      return;
    }

    final entity = _engine.scene.entity(id);
    if (entity == null) {
      return;
    }
    _engine.scene.updateEntity(id, transform: update(entity.transform));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Flix3DEngineBuilder(
          engine: _engine,
          builder: (context, engine, _) {
            return LayoutBuilder(
              builder: (context, constraints) {
                final wide = constraints.maxWidth >= 920;
                final hierarchy = _buildHierarchy(engine);
                final details = Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    _Panel(
                      title: 'LIVE 3D VIEWPORT',
                      child: SizedBox(
                        height: 360,
                        child: Flix3DView(controller: _viewportController),
                      ),
                    ),
                    const SizedBox(height: 16),
                    _buildRuntime(engine),
                    const SizedBox(height: 16),
                    _buildInspector(engine),
                  ],
                );

                return SingleChildScrollView(
                  padding: const EdgeInsets.all(24),
                  child: Center(
                    child: ConstrainedBox(
                      constraints: const BoxConstraints(maxWidth: 1400),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.stretch,
                        children: [
                          _buildHeader(engine),
                          const SizedBox(height: 24),
                          if (wide)
                            Row(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                SizedBox(width: 320, child: hierarchy),
                                const SizedBox(width: 20),
                                Expanded(child: details),
                              ],
                            )
                          else ...[
                            hierarchy,
                            const SizedBox(height: 16),
                            details,
                          ],
                          const SizedBox(height: 16),
                          _buildRendererStatus(),
                        ],
                      ),
                    ),
                  ),
                );
              },
            );
          },
        ),
      ),
    );
  }

  Widget _buildHeader(Flix3DEngine engine) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final identity = Row(
          children: [
            Container(
              width: 44,
              height: 44,
              decoration: BoxDecoration(
                color: Theme.of(context).colorScheme.primaryContainer,
                borderRadius: BorderRadius.circular(14),
              ),
              child: Icon(
                Icons.view_in_ar_rounded,
                color: Theme.of(context).colorScheme.onPrimaryContainer,
              ),
            ),
            const SizedBox(width: 14),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    engine.config.name,
                    style: Theme.of(context).textTheme.titleLarge,
                  ),
                  Text(
                    'SCENE & ENGINE API EXAMPLE',
                    style: Theme.of(context).textTheme.labelSmall?.copyWith(
                      letterSpacing: 1.5,
                      color: Theme.of(context).colorScheme.onSurfaceVariant,
                    ),
                  ),
                ],
              ),
            ),
          ],
        );
        final actions = Wrap(
          spacing: 8,
          runSpacing: 8,
          alignment: WrapAlignment.end,
          children: [
            FilledButton.icon(
              onPressed: () {
                Navigator.of(context).push(
                  MaterialPageRoute<void>(
                    builder: (_) => Flix3DModelStudio(scene: engine.scene),
                  ),
                );
              },
              icon: const Icon(Icons.view_in_ar_outlined),
              label: const Text('Asset Studio'),
            ),
            FilledButton.icon(
              onPressed: () => _addEntity(),
              icon: const Icon(Icons.add),
              label: const Text('Add entity'),
            ),
          ],
        );
        if (constraints.maxWidth < 560) {
          return Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [identity, const SizedBox(height: 12), actions],
          );
        }
        return Row(
          children: [
            Expanded(child: identity),
            const SizedBox(width: 12),
            actions,
          ],
        );
      },
    );
  }

  Widget _buildRuntime(Flix3DEngine engine) {
    return _Panel(
      title: 'ENGINE RUNTIME',
      trailing: _StatusBadge(
        label: engine.state.name.toUpperCase(),
        running: engine.isRunning,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Text(
            'Dart-managed lifecycle and scene state',
            style: Theme.of(context).textTheme.bodyMedium,
          ),
          const SizedBox(height: 4),
          Text(
            '${engine.frameCount} frames · ${engine.scene.entities.length} entities',
            style: Theme.of(context).textTheme.bodySmall?.copyWith(
              color: Theme.of(context).colorScheme.onSurfaceVariant,
            ),
          ),
          const SizedBox(height: 16),
          Wrap(
            spacing: 8,
            runSpacing: 8,
            children: [
              if (!engine.isRunning)
                FilledButton.icon(
                  onPressed: engine.initialize,
                  icon: const Icon(Icons.play_arrow),
                  label: const Text('Start'),
                )
              else
                OutlinedButton.icon(
                  onPressed: engine.shutdown,
                  icon: const Icon(Icons.stop),
                  label: const Text('Stop'),
                ),
              OutlinedButton.icon(
                onPressed: engine.isRunning
                    ? () => engine.update(1 / 60)
                    : null,
                icon: const Icon(Icons.skip_next),
                label: const Text('Advance frame'),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildHierarchy(Flix3DEngine engine) {
    final entities = engine.scene.entities;
    return _Panel(
      title: 'SCENE HIERARCHY',
      trailing: Text(
        '${entities.length}',
        style: Theme.of(context).textTheme.labelLarge,
      ),
      child: entities.isEmpty
          ? Padding(
              padding: const EdgeInsets.symmetric(vertical: 24),
              child: Center(
                child: Text(
                  'The scene is empty.\nAdd an entity to get started.',
                  textAlign: TextAlign.center,
                  style: Theme.of(context).textTheme.bodyMedium,
                ),
              ),
            )
          : Column(
              children: [
                for (final entity in entities)
                  Padding(
                    padding: const EdgeInsets.only(bottom: 6),
                    child: Material(
                      color: entity.id == _selectedEntityId
                          ? Theme.of(context).colorScheme.secondaryContainer
                          : Colors.transparent,
                      borderRadius: BorderRadius.circular(10),
                      child: ListTile(
                        dense: true,
                        selected: entity.id == _selectedEntityId,
                        selectedTileColor: Colors.transparent,
                        leading: const Icon(Icons.view_in_ar, size: 20),
                        title: Text(entity.name),
                        subtitle: Text(entity.id),
                        onTap: () =>
                            setState(() => _selectedEntityId = entity.id),
                      ),
                    ),
                  ),
              ],
            ),
    );
  }

  Widget _buildInspector(Flix3DEngine engine) {
    final id = _selectedEntityId;
    final entity = id == null ? null : engine.scene.entity(id);
    if (entity == null) {
      return _Panel(
        title: 'INSPECTOR',
        child: Padding(
          padding: const EdgeInsets.symmetric(vertical: 24),
          child: Text(
            'Select an entity in the hierarchy to inspect its transform.',
            style: Theme.of(context).textTheme.bodyMedium,
          ),
        ),
      );
    }

    return _Panel(
      title: 'INSPECTOR',
      trailing: IconButton(
        tooltip: 'Remove selected entity',
        onPressed: _removeSelectedEntity,
        icon: const Icon(Icons.delete_outline),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Text(entity.name, style: Theme.of(context).textTheme.titleMedium),
          Text(
            'ID  ${entity.id}',
            style: Theme.of(context).textTheme.bodySmall?.copyWith(
              color: Theme.of(context).colorScheme.onSurfaceVariant,
            ),
          ),
          const SizedBox(height: 20),
          _buildVectorEditor(
            label: 'POSITION',
            values: entity.transform.position,
            suffix: 'u',
            step: 0.25,
            onChanged: (value) => _updateSelectedTransform(
              (transform) => transform.copyWith(position: value),
            ),
          ),
          const Divider(height: 28),
          _buildVectorEditor(
            label: 'ROTATION',
            values: Vector3(
              _toDegrees(entity.transform.rotationEuler.x),
              _toDegrees(entity.transform.rotationEuler.y),
              _toDegrees(entity.transform.rotationEuler.z),
            ),
            suffix: '°',
            step: 5,
            onChanged: (value) => _updateSelectedTransform(
              (transform) => transform.copyWith(
                rotationEuler: Vector3(
                  _toRadians(value.x),
                  _toRadians(value.y),
                  _toRadians(value.z),
                ),
              ),
            ),
          ),
          const Divider(height: 28),
          _buildVectorEditor(
            label: 'SCALE',
            values: entity.transform.scale,
            suffix: '',
            step: 0.1,
            onChanged: (value) => _updateSelectedTransform(
              (transform) => transform.copyWith(scale: value),
            ),
            minimum: 0.1,
          ),
        ],
      ),
    );
  }

  Widget _buildVectorEditor({
    required String label,
    required Vector3 values,
    required String suffix,
    required double step,
    required ValueChanged<Vector3> onChanged,
    double? minimum,
  }) {
    final components = <({String axis, double value})>[
      (axis: 'X', value: values.x),
      (axis: 'Y', value: values.y),
      (axis: 'Z', value: values.z),
    ];

    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        Text(label, style: Theme.of(context).textTheme.labelMedium),
        const SizedBox(height: 6),
        for (final (index, component) in components.indexed)
          Row(
            children: [
              SizedBox(
                width: 24,
                child: Text(
                  component.axis,
                  style: Theme.of(context).textTheme.labelMedium,
                ),
              ),
              Expanded(
                child: Text(
                  '${_formatValue(component.value)}$suffix',
                  textAlign: TextAlign.center,
                  style: Theme.of(context).textTheme.bodyMedium,
                ),
              ),
              IconButton(
                tooltip: 'Decrease ${component.axis}',
                visualDensity: VisualDensity.compact,
                onPressed: () => onChanged(
                  _replaceComponent(
                    values,
                    index,
                    component.value - step <
                            (minimum ?? double.negativeInfinity)
                        ? minimum!
                        : component.value - step,
                  ),
                ),
                icon: const Icon(Icons.remove, size: 18),
              ),
              IconButton(
                tooltip: 'Increase ${component.axis}',
                visualDensity: VisualDensity.compact,
                onPressed: () => onChanged(
                  _replaceComponent(values, index, component.value + step),
                ),
                icon: const Icon(Icons.add, size: 18),
              ),
            ],
          ),
      ],
    );
  }

  Widget _buildRendererStatus() {
    return _Panel(
      title: 'RENDERER STATUS',
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Icon(
            Icons.info_outline,
            size: 20,
            color: Theme.of(context).colorScheme.primary,
          ),
          const SizedBox(width: 10),
          Expanded(
            child: Text(
              'The viewport renders an orbitable cube mesh with a perspective '
              'camera and directional lighting using Flutter triangle '
              'painting. It is not the native Metal renderer; Shard Run uses '
              'Metal in its separate macOS SDL3 application.',
              style: Theme.of(context).textTheme.bodySmall,
            ),
          ),
        ],
      ),
    );
  }

  Vector3 _replaceComponent(Vector3 value, int index, double replacement) =>
      switch (index) {
        0 => Vector3(replacement, value.y, value.z),
        1 => Vector3(value.x, replacement, value.z),
        _ => Vector3(value.x, value.y, replacement),
      };

  double _toRadians(double degrees) => degrees * math.pi / 180;
  double _toDegrees(double radians) => radians * 180 / math.pi;

  String _formatValue(double value) => value.toStringAsFixed(2);
}

class _Panel extends StatelessWidget {
  const _Panel({required this.title, required this.child, this.trailing});

  final String title;
  final Widget child;
  final Widget? trailing;

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(18),
      decoration: BoxDecoration(
        color: const Color(0xFF191F1C),
        border: Border.all(color: const Color(0xFF2A322E)),
        borderRadius: BorderRadius.circular(16),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Row(
            children: [
              Expanded(
                child: Text(
                  title,
                  style: Theme.of(context).textTheme.labelMedium?.copyWith(
                    letterSpacing: 1,
                    color: Theme.of(context).colorScheme.onSurfaceVariant,
                  ),
                ),
              ),
              ?trailing,
            ],
          ),
          const SizedBox(height: 16),
          child,
        ],
      ),
    );
  }
}

class _StatusBadge extends StatelessWidget {
  const _StatusBadge({required this.label, required this.running});

  final String label;
  final bool running;

  @override
  Widget build(BuildContext context) {
    final color = running ? const Color(0xFF35D0BA) : Colors.blueGrey;
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
      decoration: BoxDecoration(
        color: color.withAlpha(31),
        borderRadius: BorderRadius.circular(20),
      ),
      child: Text(
        label,
        style: Theme.of(context).textTheme.labelSmall?.copyWith(color: color),
      ),
    );
  }
}
0
likes
140
points
101
downloads

Documentation

API reference

Publisher

unverified uploader

Weekly Downloads

A Flutter game engine package with a C++20 runtime and Dart FFI.

License

MIT (license)

Dependencies

android_libcpp_shared, code_assets, ffi, file_picker, flutter, hooks, native_toolchain_c

More

Packages that depend on flix3dengine