optimization of the detection algorithem.

BOOK update.
This commit is contained in:
Jan Pleterski
2026-11-27 09:43:25 +01:00
parent b22d7987e3
commit 5f9e2a3b86
11 changed files with 1209 additions and 542 deletions
+438 -177
View File
@@ -12,13 +12,20 @@ import '../widgets/section.dart';
import 'session_screen.dart'; import 'session_screen.dart';
import 'target_view.dart'; import 'target_view.dart';
enum _View { stats, history }
enum _Filter { training, tournament } enum _Filter { training, tournament }
enum _HistoryFilter { all, training, tournament }
enum _Period { month, threeMonths, year, all, custom } enum _Period { month, threeMonths, year, all, custom }
/// Knjiga: one summary card with the shooter's form, records and progress graph, /// Knjiga, two screens:
/// then their sessions. One period filter drives the card and the list, so they /// * Statistika: the summary card (form, records) and the progress graph for
/// always agree; the graph has its own month/year navigation. /// one kind of session and one number of shots per target, so averages
/// compare like with like. The graph has its own month/year navigation.
/// * Zgodovina: every session of the chosen kind, whatever its shot count.
/// One period filter drives the card and the list, so they always agree.
class BookScreen extends StatefulWidget { class BookScreen extends StatefulWidget {
const BookScreen({super.key}); const BookScreen({super.key});
@@ -31,7 +38,9 @@ class _BookScreenState extends State<BookScreen> with WidgetsBindingObserver {
List<Session>? _sessions; // all sessions; null while loading List<Session>? _sessions; // all sessions; null while loading
List<int> _years = []; // years with sessions, newest first List<int> _years = []; // years with sessions, newest first
_Filter _filter = _Filter.training; _View _view = _View.stats;
_Filter _filter = _Filter.training; // Statistika: trainings or tournaments
_HistoryFilter _historyFilter = _HistoryFilter.all; // Zgodovina
int? _shots; // shots per target shown; null = pick the most common one int? _shots; // shots per target shown; null = pick the most common one
bool _sortByScore = false; bool _sortByScore = false;
_Period _period = _Period.year; _Period _period = _Period.year;
@@ -63,7 +72,9 @@ class _BookScreenState extends State<BookScreen> with WidgetsBindingObserver {
final end = p.getInt('${_prefix}customEnd'); final end = p.getInt('${_prefix}customEnd');
if (!mounted) return; if (!mounted) return;
setState(() { setState(() {
_view = pick(_View.values, 'view', _view);
_filter = pick(_Filter.values, 'filter', _filter); _filter = pick(_Filter.values, 'filter', _filter);
_historyFilter = pick(_HistoryFilter.values, 'historyFilter', _historyFilter);
_period = pick(_Period.values, 'period', _period); _period = pick(_Period.values, 'period', _period);
_shots = p.getInt('${_prefix}shots'); _shots = p.getInt('${_prefix}shots');
_sortByScore = p.getBool('${_prefix}sortByScore') ?? _sortByScore; _sortByScore = p.getBool('${_prefix}sortByScore') ?? _sortByScore;
@@ -80,7 +91,9 @@ class _BookScreenState extends State<BookScreen> with WidgetsBindingObserver {
Future<void> _saveSettings() async { Future<void> _saveSettings() async {
final p = await SharedPreferences.getInstance(); final p = await SharedPreferences.getInstance();
await p.setInt('${_prefix}view', _view.index);
await p.setInt('${_prefix}filter', _filter.index); await p.setInt('${_prefix}filter', _filter.index);
await p.setInt('${_prefix}historyFilter', _historyFilter.index);
await p.setInt('${_prefix}period', _period.index); await p.setInt('${_prefix}period', _period.index);
if (_shots == null) { if (_shots == null) {
await p.remove('${_prefix}shots'); await p.remove('${_prefix}shots');
@@ -262,8 +275,17 @@ class _BookScreenState extends State<BookScreen> with WidgetsBindingObserver {
]); ]);
} }
// Statistics only compare like with like: one tab, one shots-per-target if (_view == _View.history) {
// format. The card and the list use the period; the graph its own month/year. return Column(children: [
_buildTabs(),
_buildHistoryBar(),
Expanded(child: _buildHistoryScreen()),
]);
}
// Statistics only compare like with like: one kind of session, one
// shots-per-target format. The card uses the period; the graph its own
// month/year.
final typed = _filtered; final typed = _filtered;
final formats = _formats(typed.where(_inPeriod).toList()); final formats = _formats(typed.where(_inPeriod).toList());
final shots = formats.contains(_shots) final shots = formats.contains(_shots)
@@ -280,23 +302,18 @@ class _BookScreenState extends State<BookScreen> with WidgetsBindingObserver {
return Column( return Column(
children: [ children: [
_buildTabs(), _buildTabs(),
_buildFilterBar(formats, shots), _buildStatsBar(formats, shots),
Expanded( Expanded(
child: RefreshIndicator( child: _years.isEmpty
onRefresh: _load, ? _centered(_buildEmpty())
child: ListView( : stats.targets == 0
padding: const EdgeInsets.fromLTRB(16, 16, 16, 32), ? Column(children: [
children: [ Padding(
if (_years.isEmpty) padding: const EdgeInsets.fromLTRB(16, 8, 16, 0),
_buildEmpty() child: _periodRow()),
else ...[ Expanded(child: _centered(_noSessions())),
if (stats.targets > 0) _buildSummary(format, stats), ])
..._buildHistory(sessions, : _buildStats(format, stats),
stats.sessions > 1 ? stats.averagePerShot : null),
],
],
),
),
), ),
], ],
); );
@@ -304,43 +321,205 @@ class _BookScreenState extends State<BookScreen> with WidgetsBindingObserver {
); );
} }
// Filters continue the dark app bar, like Koledar/Stiki // An empty state in the middle of the free space; pull-to-refresh still works
Widget _centered(Widget child) {
return RefreshIndicator(
onRefresh: _load,
child: CustomScrollView(
physics: const AlwaysScrollableScrollPhysics(),
slivers: [
SliverFillRemaining(
hasScrollBody: false,
child: Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: child,
),
),
),
],
),
);
}
// Nothing in the chosen period or filter (there are sessions elsewhere)
Widget _noSessions() {
final s = AppSettings.instance;
final surf = Surfaces.current;
return Padding(
padding: const EdgeInsets.only(bottom: 48), // a little above the middle
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.event_busy_rounded, size: 40, color: surf.textSecondary),
const SizedBox(height: 10),
Text(s.t('No sessions in this period'),
textAlign: TextAlign.center,
style: TextStyle(fontSize: 15, color: surf.textSecondary)),
],
),
);
}
// Full-width "Obdobje … To leto ▾" button: says what it changes and that it
// can be tapped. Opens the period sheet; Statistika and Zgodovina share it.
Widget _periodRow() {
final s = AppSettings.instance;
final surf = Surfaces.current;
return Material(
color: surf.card,
borderRadius: BorderRadius.circular(14),
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: _pickPeriod,
child: Padding(
padding: const EdgeInsets.fromLTRB(14, 10, 8, 10),
child: Row(
children: [
Icon(Icons.date_range_rounded, size: 20, color: s.bulletColor),
const SizedBox(width: 10),
Text(s.t('Period'),
style: TextStyle(fontSize: 13, color: surf.textSecondary)),
const SizedBox(width: 12),
Expanded(
child: Text(
_periodLabel(_period),
textAlign: TextAlign.right,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w700,
color: surf.textPrimary),
),
),
Icon(Icons.expand_more_rounded, color: surf.textSecondary),
],
),
),
),
);
}
// Zgodovina: every session of the chosen kind in the period, any shot count
Widget _buildHistoryScreen() {
if (_years.isEmpty) return _centered(_buildEmpty());
final sessions = [
for (final x in _sessions!)
if (_inPeriod(x) &&
switch (_historyFilter) {
_HistoryFilter.all => true,
_HistoryFilter.training => !x.isTournament,
_HistoryFilter.tournament => x.isTournament,
})
x,
];
// Average per shot over the listed sessions, for each card's difference
final shots = sessions.fold(0, (a, x) => a + x.shots);
final average = sessions.length > 1 && shots > 0
? sessions.fold(0, (a, x) => a + x.totalScore) / shots
: null;
if (sessions.isEmpty) {
return Column(children: [
Padding(
padding: const EdgeInsets.fromLTRB(16, 4, 16, 0),
child: _historyHeader()),
Expanded(child: _centered(_noSessions())),
]);
}
return RefreshIndicator(
onRefresh: _load,
child: ListView(
padding: const EdgeInsets.fromLTRB(16, 4, 16, 32),
children: _buildHistory(sessions, average),
),
);
}
// The two screens; filters continue the dark app bar, like Koledar/Stiki
Widget _buildTabs() { Widget _buildTabs() {
final s = AppSettings.instance; final s = AppSettings.instance;
return BarTabs( return BarTabs(
tabs: [ tabs: [
BarTab(s.t('Trainings'), Icons.track_changes_rounded), BarTab(s.t('Statistics'), Icons.insights_rounded),
BarTab(s.t('Tournaments'), Icons.emoji_events_rounded), BarTab(s.t('History'), Icons.history_rounded),
], ],
selected: _filter.index, selected: _view.index,
onSelect: (i) => _change(() { onSelect: (i) => _change(() => _view = _View.values[i]),
_filter = _Filter.values[i];
_shots = null;
_chartAt = null;
}),
); );
} }
// Second dark row under the tabs: shots-per-target pills across the width // Zgodovina's dark row: which sessions to list
// Always 1–5 (the capture limit); older saves above 5 keep their own pill. Widget _buildHistoryBar() {
// Formats with no targets yet are dimmed and can't be picked. final s = AppSettings.instance;
Widget _buildFilterBar(List<int> formats, int? selected) { final labels = {
_HistoryFilter.all: s.t('All'),
_HistoryFilter.training: s.t('Trainings'),
_HistoryFilter.tournament: s.t('Tournaments'),
};
return Container(
color: AppTheme.bar,
padding: const EdgeInsets.fromLTRB(12, 4, 12, 10),
child: Row(
children: [
for (final f in _HistoryFilter.values) ...[
if (f.index > 0) const SizedBox(width: 6),
Expanded(
child: _BarPill(
label: labels[f]!,
selected: f == _historyFilter,
empty: false,
onTap: () => _change(() => _historyFilter = f),
),
),
],
],
),
);
}
// Statistika's dark row: trainings or tournaments, then shots per target.
// Shots are always 1–5 (the capture limit); older saves above 5 keep their
// own pill. Formats with no targets yet are dimmed and can't be picked.
Widget _buildStatsBar(List<int> formats, int? selected) {
final s = AppSettings.instance;
final sorted = { final sorted = {
for (int n = AppSettings.minBullets; n <= AppSettings.maxBullets; n++) n, for (int n = AppSettings.minBullets; n <= AppSettings.maxBullets; n++) n,
...formats, ...formats,
}.toList() }.toList()
..sort(); ..sort();
Widget kind(_Filter f, String label) => Expanded(
flex: 5,
child: _BarPill(
label: s.t(label),
selected: f == _filter,
empty: false,
onTap: () => _change(() {
_filter = f;
_shots = null;
_chartAt = null;
}),
),
);
return Container( return Container(
color: AppTheme.bar, color: AppTheme.bar,
padding: const EdgeInsets.fromLTRB(12, 4, 12, 10), padding: const EdgeInsets.fromLTRB(12, 4, 12, 10),
// Pills share the full width equally
child: Row( child: Row(
children: [ children: [
Text(AppSettings.instance.t('Shots'), kind(_Filter.training, 'Trainings'),
style: const TextStyle(fontSize: 12, color: Colors.white60)),
for (final n in sorted) ...[
const SizedBox(width: 6), const SizedBox(width: 6),
kind(_Filter.tournament, 'Tournaments'),
// Divider between the two groups
Container(
width: 1,
height: 22,
margin: const EdgeInsets.symmetric(horizontal: 8),
color: Colors.white24),
for (final n in sorted) ...[
if (n != sorted.first) const SizedBox(width: 4),
Expanded( Expanded(
flex: 2,
child: _BarPill( child: _BarPill(
label: '$n', label: '$n',
selected: n == selected, selected: n == selected,
@@ -355,6 +534,7 @@ class _BookScreenState extends State<BookScreen> with WidgetsBindingObserver {
); );
} }
// Monday–Sunday week of [date], cut to its month: "6.–12. 10.", "27.–31. 10." // Monday–Sunday week of [date], cut to its month: "6.–12. 10.", "27.–31. 10."
static String _weekLabel(DateTime date) { static String _weekLabel(DateTime date) {
final day = DateTime(date.year, date.month, date.day); final day = DateTime(date.year, date.month, date.day);
@@ -427,54 +607,130 @@ class _BookScreenState extends State<BookScreen> with WidgetsBindingObserver {
s.isLightBackground ? Colors.black : Colors.white, amount)!; s.isLightBackground ? Colors.black : Colors.white, amount)!;
} }
// Hero on the card surface (follows light/dark like the rest of Knjiga): the // Statistika as cards: one with the period's average per shot and its trend
// period's average per shot with its trend, counts and best session. // beside three counts; the graph; the best session. It fits
// The graph below gets every loaded session of the format, [all], and picks // the screen without scrolling, the graph taking the height that is left;
// its own month or year. // on a screen too small for that it scrolls with a fixed-height graph.
Widget _buildSummary(List<Session> all, ShooterStats stats) { // The graph gets every loaded session of the format, [all], and picks its
// own month or year.
Widget _buildStats(List<Session> all, ShooterStats stats) {
final s = AppSettings.instance;
final bestSession = stats.bestSession;
final tournaments = _filter == _Filter.tournament;
const gap = SizedBox(height: 12);
// One card: the average on the left, the three counts on the right
final surf = Surfaces.current;
final top = _BookCard(
padding: const EdgeInsets.symmetric(vertical: 14),
child: IntrinsicHeight(
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(flex: 11, child: _averageContent(stats)),
VerticalDivider(width: 1, thickness: 1, color: surf.divider),
Expanded(
flex: 9,
child: Padding(
padding: const EdgeInsets.only(left: 14, right: 12),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
_CountLine(
value: '${stats.sessions}',
label: s.t(tournaments ? 'Tournaments' : 'Trainings')),
_CountLine(
value: '${stats.targets}', label: s.t('Targets')),
_CountLine(
value: stats.averageTarget!.toStringAsFixed(1),
label: s.t('Average target')),
],
),
),
),
],
),
),
);
// Best session; tap to see its targets
final best = bestSession != null && stats.sessions > 1
? _HeroRecord(
label: s.t(tournaments ? 'Best tournament' : 'Best training'),
value: bestSession.averagePerShot!.toStringAsFixed(2),
caption:
'${DateFormat('d. M.').format(bestSession.date)} · ${bestSession.name}',
onTap: () => _openTargets(bestSession),
)
: null;
return LayoutBuilder(builder: (context, box) {
// Room for the cards above plus a graph that is still worth reading
if (box.maxHeight >= 560) {
return Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 16),
child: Column(
children: [
_periodRow(),
const SizedBox(height: 8),
top,
gap,
Expanded(child: _BookCard(child: _buildChart(all, stats, fill: true))),
if (best != null) ...[gap, best],
],
),
);
}
return RefreshIndicator(
onRefresh: _load,
child: ListView(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 32),
children: [
_periodRow(),
const SizedBox(height: 8),
top,
gap,
_BookCard(child: _buildChart(all, stats)),
if (best != null) ...[gap, best],
],
),
);
});
}
Widget _averageContent(ShooterStats stats) {
final s = AppSettings.instance; final s = AppSettings.instance;
final surf = Surfaces.current; final surf = Surfaces.current;
final trend = stats.trend; final trend = stats.trend;
final bestSession = stats.bestSession; return Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
return ClipRRect(
borderRadius: BorderRadius.circular(20),
child: ColoredBox(
color: surf.card,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(18, 16, 18, 14),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Expanded(
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [ children: [
Text(s.t('Average per shot').toUpperCase(), Text(s.t('Average per shot').toUpperCase(),
maxLines: 1, maxLines: 2,
overflow: TextOverflow.ellipsis,
style: TextStyle( style: TextStyle(
fontSize: 11, fontSize: 11,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
letterSpacing: 1.2, letterSpacing: 1.2,
color: surf.textSecondary)), color: surf.textSecondary)),
Text( FittedBox(
fit: BoxFit.scaleDown,
alignment: Alignment.centerLeft,
child: Text(
stats.averagePerShot?.toStringAsFixed(2) ?? '–', stats.averagePerShot?.toStringAsFixed(2) ?? '–',
style: TextStyle( style: TextStyle(
fontSize: 44, fontSize: 48,
fontWeight: FontWeight.w800, fontWeight: FontWeight.w800,
color: surf.textPrimary, color: surf.textPrimary,
height: 1.1), height: 1.1),
), ),
),
if (trend != null) if (trend != null)
Text( Text(
'${trend >= 0 ? '▲' : '▼'} ${trend.abs().toStringAsFixed(2)} ${s.t('vs earlier')}', '${trend >= 0 ? '▲' : '▼'} ${trend.abs().toStringAsFixed(2)} ${s.t('vs earlier')}',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle( style: TextStyle(
fontSize: 12, fontSize: 12,
fontWeight: FontWeight.w600, fontWeight: FontWeight.w600,
@@ -482,50 +738,12 @@ class _BookScreenState extends State<BookScreen> with WidgetsBindingObserver {
), ),
], ],
), ),
),
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
_HeroCount(
value: '${stats.sessions}',
label: s.t(_filter == _Filter.tournament
? 'Tournaments'
: 'Trainings')),
_HeroCount(
value: '${stats.targets}', label: s.t('Targets')),
_HeroCount(
value: stats.averageTarget!.toStringAsFixed(1),
label: s.t('Average target')),
],
),
],
),
// Best session; tap to see its targets
if (bestSession != null && stats.sessions > 1) ...[
const SizedBox(height: 14),
_HeroRecord(
label: s.t(_filter == _Filter.tournament
? 'Best tournament'
: 'Best training'),
value: bestSession.averagePerShot!.toStringAsFixed(2),
caption:
'${DateFormat('d. M.').format(bestSession.date)} · ${bestSession.name}',
onTap: () => _openTargets(bestSession),
),
],
],
),
),
Divider(height: 1, thickness: 1, color: surf.divider),
_buildChart(all, stats),
],
),
),
); );
} }
// Shot average and points per session, each on its own scale. // Shot average and points per session, each on its own scale.
Widget _buildChart(List<Session> all, ShooterStats stats) { // [fill]: the graph takes all the height the card gets (inside an Expanded)
Widget _buildChart(List<Session> all, ShooterStats stats, {bool fill = false}) {
final s = AppSettings.instance; final s = AppSettings.instance;
final surf = Surfaces.current; final surf = Surfaces.current;
final scored = all.where((x) => x.shots > 0).toList(); final scored = all.where((x) => x.shots > 0).toList();
@@ -594,14 +812,22 @@ class _BookScreenState extends State<BookScreen> with WidgetsBindingObserver {
], ],
), ),
if (shown.isEmpty) if (shown.isEmpty)
_fillIf(
fill,
Padding( Padding(
padding: const EdgeInsets.symmetric(vertical: 40), padding: const EdgeInsets.symmetric(vertical: 40),
child: Center(
child: Text(s.t('No sessions in this period'), child: Text(s.t('No sessions in this period'),
style: TextStyle(color: surf.textSecondary)), style: TextStyle(color: surf.textSecondary)),
),
),
) )
else ...[ else ...[
const SizedBox(height: 4), const SizedBox(height: 4),
_fillIf(
fill,
ProgressChart( ProgressChart(
expand: fill,
labels: data.labels, labels: data.labels,
series: [ series: [
ChartSeries(s.t('Shot average'), s.bulletColor, data.perShot, ChartSeries(s.t('Shot average'), s.bulletColor, data.perShot,
@@ -612,12 +838,16 @@ class _BookScreenState extends State<BookScreen> with WidgetsBindingObserver {
textColor: surf.textSecondary, textColor: surf.textSecondary,
gridColor: surf.divider, gridColor: surf.divider,
), ),
),
], ],
], ],
), ),
); );
} }
static Widget _fillIf(bool fill, Widget child) =>
fill ? Expanded(child: child) : child;
List<Widget> _buildHistory(List<Session> sessions, double? average) { List<Widget> _buildHistory(List<Session> sessions, double? average) {
// Average per shot, so sessions with more targets don't win by volume // Average per shot, so sessions with more targets don't win by volume
final ordered = _sortByScore final ordered = _sortByScore
@@ -627,60 +857,54 @@ class _BookScreenState extends State<BookScreen> with WidgetsBindingObserver {
return [ return [
_historyHeader(), _historyHeader(),
for (final x in ordered) _sessionCard(x, average), for (final x in ordered) _sessionCard(x, average),
if (sessions.isEmpty)
Padding(
padding: const EdgeInsets.all(24),
child: Center(
child: Text(AppSettings.instance.t('No sessions in this period'),
style: TextStyle(color: Surfaces.current.textSecondary)),
),
),
]; ];
} }
// Section title, then the period chip (drives the card above too) and the sort toggle // Period selector (shared with Statistika) and the sort order, both labelled
Widget _historyHeader() { Widget _historyHeader() {
final s = AppSettings.instance; final s = AppSettings.instance;
final surf = Surfaces.current; final surf = Surfaces.current;
return Padding( return Padding(
padding: const EdgeInsets.fromLTRB(4, 12, 0, 4), // With the list's 4 px this starts 8 px under the bar, like Statistika
padding: const EdgeInsets.only(top: 4, bottom: 8),
// Same height for both buttons
child: IntrinsicHeight(
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(child: _periodRow()),
const SizedBox(width: 8),
// Each tap switches between date and score order
Material(
color: surf.card,
borderRadius: BorderRadius.circular(14),
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: () => _change(() => _sortByScore = !_sortByScore),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
child: Row( child: Row(
children: [ children: [
Expanded( Icon(
child: Text( _sortByScore
s.t(_sortByScore ? 'Best results' : 'History').toUpperCase(), ? Icons.leaderboard_rounded
: Icons.event_rounded,
size: 20,
color: s.bulletColor),
const SizedBox(width: 6),
Text(s.t(_sortByScore ? 'Sort by Score' : 'Sort by Date'),
style: TextStyle( style: TextStyle(
fontSize: 12, fontSize: 13,
fontWeight: FontWeight.bold,
letterSpacing: 1.4,
color: surf.textSecondary,
),
),
),
ActionChip(
avatar: Icon(Icons.date_range_rounded,
size: 16, color: surf.textSecondary),
label: Text(_periodLabel(_period)),
labelStyle: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w600, fontWeight: FontWeight.w600,
color: surf.textPrimary), color: surf.textPrimary)),
backgroundColor: surf.card, ],
side: BorderSide.none, ),
shape: const StadiumBorder(), ),
visualDensity: VisualDensity.compact,
onPressed: _pickPeriod,
), ),
// Each tap switches between date and score order
IconButton(
tooltip: s.t(_sortByScore ? 'Sort by Score' : 'Sort by Date'),
icon: Icon(
_sortByScore ? Icons.leaderboard_rounded : Icons.event_rounded,
color: surf.textSecondary),
onPressed: () => _change(() => _sortByScore = !_sortByScore),
), ),
], ],
), ),
),
); );
} }
@@ -789,14 +1013,24 @@ class _BookScreenState extends State<BookScreen> with WidgetsBindingObserver {
final s = AppSettings.instance; final s = AppSettings.instance;
final surf = Surfaces.current; final surf = Surfaces.current;
return Container( return Container(
padding: const EdgeInsets.symmetric(vertical: 48, horizontal: 24), width: double.infinity,
margin: const EdgeInsets.only(bottom: 48), // a little above the middle
padding: const EdgeInsets.symmetric(vertical: 36, horizontal: 24),
decoration: BoxDecoration( decoration: BoxDecoration(
color: surf.card, borderRadius: BorderRadius.circular(20)), color: surf.card, borderRadius: BorderRadius.circular(24)),
child: Column( child: Column(
mainAxisSize: MainAxisSize.min,
children: [ children: [
Icon(Icons.track_changes_rounded, Container(
size: 48, color: surf.textSecondary), padding: const EdgeInsets.all(18),
const SizedBox(height: 12), decoration: BoxDecoration(
color: s.bulletColor.withValues(alpha: 0.15),
shape: BoxShape.circle,
),
child: Icon(Icons.track_changes_rounded,
size: 44, color: s.bulletColor),
),
const SizedBox(height: 16),
Text( Text(
s.t('No saved target data found'), s.t('No saved target data found'),
textAlign: TextAlign.center, textAlign: TextAlign.center,
@@ -821,6 +1055,10 @@ class _BookScreenState extends State<BookScreen> with WidgetsBindingObserver {
void showBookHelp(BuildContext context) { void showBookHelp(BuildContext context) {
final s = AppSettings.instance; final s = AppSettings.instance;
showHelpSheet(context, accent: s.bulletColor, t: s.t, items: const [ showHelpSheet(context, accent: s.bulletColor, t: s.t, items: const [
(
Icons.insights_rounded,
'Statistics / History: your form and progress graph, or the list of all your sessions.'
),
( (
Icons.emoji_events_rounded, Icons.emoji_events_rounded,
'Trainings / Tournaments: choose which sessions the statistics count.' 'Trainings / Tournaments: choose which sessions the statistics count.'
@@ -843,7 +1081,11 @@ void showBookHelp(BuildContext context) {
), ),
( (
Icons.date_range_rounded, Icons.date_range_rounded,
'Period (next to History): this month, last 3 months, this year, all or your own dates. The top card and the list both use it.' 'Period: this month, last 3 months, this year, all or your own dates. Statistics and History both use it.'
),
(
Icons.filter_list_rounded,
'History: All / Trainings / Tournaments chooses which sessions are listed, with any number of shots.'
), ),
( (
Icons.sort_rounded, Icons.sort_rounded,
@@ -851,7 +1093,7 @@ void showBookHelp(BuildContext context) {
), ),
( (
Icons.touch_app_rounded, Icons.touch_app_rounded,
'Tap a session to see all its targets with the selected number of shots on one target.' 'Tap a session to see all its targets on one target.'
), ),
( (
Icons.more_vert_rounded, Icons.more_vert_rounded,
@@ -860,36 +1102,55 @@ void showBookHelp(BuildContext context) {
]); ]);
} }
/// "12 Trainings" line on the hero, value first. /// A rounded card on the page, the same surface as the history cards.
class _HeroCount extends StatelessWidget { class _BookCard extends StatelessWidget {
final String value; final Widget child;
final String label; final EdgeInsetsGeometry padding;
const _HeroCount({required this.value, required this.label}); const _BookCard({required this.child, this.padding = EdgeInsets.zero});
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final surf = Surfaces.current; return Container(
return Padding( padding: padding,
padding: const EdgeInsets.only(top: 2), decoration: BoxDecoration(
child: Text.rich( color: Surfaces.current.card,
TextSpan(children: [ borderRadius: BorderRadius.circular(20)),
TextSpan( child: child,
text: value,
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.w800,
color: surf.textPrimary)),
TextSpan(
text: ' $label',
style: TextStyle(fontSize: 12, color: surf.textSecondary)),
]),
),
); );
} }
} }
/// Record on the hero: label and date left, value right. Tappable. /// One count in the summary card: number, then its label, on one line.
class _CountLine extends StatelessWidget {
final String value;
final String label;
const _CountLine({required this.value, required this.label});
@override
Widget build(BuildContext context) {
final surf = Surfaces.current;
return Row(
children: [
Text(value,
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w800,
color: surf.textPrimary)),
const SizedBox(width: 8),
Expanded(
child: Text(label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 12, color: surf.textSecondary)),
),
],
);
}
}
/// Best-session card: label and date left, value right. Tappable.
class _HeroRecord extends StatelessWidget { class _HeroRecord extends StatelessWidget {
final String label; final String label;
final String value; final String value;
@@ -906,13 +1167,13 @@ class _HeroRecord extends StatelessWidget {
Widget build(BuildContext context) { Widget build(BuildContext context) {
final surf = Surfaces.current; final surf = Surfaces.current;
return Material( return Material(
color: surf.textPrimary.withValues(alpha: 0.06), color: surf.card,
borderRadius: BorderRadius.circular(12), borderRadius: BorderRadius.circular(20),
clipBehavior: Clip.antiAlias, clipBehavior: Clip.antiAlias,
child: InkWell( child: InkWell(
onTap: onTap, onTap: onTap,
child: Padding( child: Padding(
padding: const EdgeInsets.fromLTRB(12, 8, 6, 8), padding: const EdgeInsets.fromLTRB(16, 14, 10, 14),
child: Row( child: Row(
children: [ children: [
Icon(Icons.emoji_events_rounded, Icon(Icons.emoji_events_rounded,
+70 -30
View File
@@ -1,7 +1,9 @@
import 'dart:io'; import 'dart:io';
import 'dart:isolate';
import 'dart:math';
import 'package:flutter/foundation.dart' show kReleaseMode, Uint8List;
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:camera/camera.dart'; import 'package:camera/camera.dart';
import 'package:image/image.dart' as img;
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
import 'yolo_detector.dart'; import 'yolo_detector.dart';
import 'preview_screen.dart'; import 'preview_screen.dart';
@@ -21,7 +23,8 @@ class CameraScreen extends StatefulWidget {
class _CameraScreenState extends State<CameraScreen> { class _CameraScreenState extends State<CameraScreen> {
CameraController? _controller; CameraController? _controller;
Future<void>? _initializeControllerFuture; Future<void>? _initializeControllerFuture;
late YOLODetector _yoloDetector; YOLODetector? _yoloDetector; // null until the model has loaded
bool _processing = false; // a photo is being analysed
Color _bulletColor = Colors.blue; // default fallback Color _bulletColor = Colors.blue; // default fallback
// The variable to hold the number of bullets entered by the user (default set to 5) // The variable to hold the number of bullets entered by the user (default set to 5)
@@ -44,7 +47,13 @@ class _CameraScreenState extends State<CameraScreen> {
_loadBulletColor(); // 👈 _loadBulletColor(); // 👈
_loadLanguage(); _loadLanguage();
_loadSelectedTargetColor(); _loadSelectedTargetColor();
YOLODetector.create().then((detector) => _yoloDetector = detector); YOLODetector.create().then((detector) {
if (mounted) {
_yoloDetector = detector;
} else {
detector.close(); // screen closed while the model was loading
}
});
} }
String _t(String key) { String _t(String key) {
@@ -149,45 +158,44 @@ class _CameraScreenState extends State<CameraScreen> {
@override @override
void dispose() { void dispose() {
_controller?.dispose(); _controller?.dispose();
_yoloDetector.close(); _yoloDetector?.close();
super.dispose(); super.dispose();
} }
Future<void> _takePicture() async { Future<void> _takePicture() async {
final detector = _yoloDetector;
if (_processing || detector == null) return; // busy, or model still loading
setState(() => _processing = true);
try { try {
await _initializeControllerFuture; await _initializeControllerFuture;
final clock = Stopwatch()..start();
final file = await _controller!.takePicture(); final file = await _controller!.takePicture();
final imageFile = File(file.path); final shot = clock.elapsedMilliseconds;
final imageBytes = await imageFile.readAsBytes();
final decodedImage = img.decodeImage(imageBytes)!;
// Crop center square from full image // Platform JPEG decoder (off the UI thread); the model input is built in
final width = decodedImage.width; // the background straight from the photo's centre square
final height = decodedImage.height; final bytes = await File(file.path).readAsBytes();
final size = width < height ? width : height; final photo = await decodePhoto(bytes);
final offsetX = (width - size) ~/ 2; final decoded = clock.elapsedMilliseconds;
final offsetY = (height - size) ~/ 2;
final cropped = img.copyCrop( // Save the square for the preview while the model runs
decodedImage, final squarePath = '${file.path}_square.jpg';
x: offsetX, final (_, detections) = await (
y: offsetY, saveSquareInBackground(photo, squarePath),
width: size, detector.detectPhoto(photo),
height: size, ).wait;
); debugPrint('⏱ detection: photo $shot ms, decode ${decoded - shot} ms '
'(${photo.channels == 4 ? 'platform' : 'Dart'}), '
final croppedFile = File('${file.path}_square.jpg') 'model + save ${clock.elapsedMilliseconds - decoded} ms, '
..writeAsBytesSync(img.encodeJpg(cropped)); 'total ${clock.elapsedMilliseconds} ms');
if (!kReleaseMode) await _compareWithDartDecoder(detector, bytes, detections);
final detections = await _yoloDetector.detect(croppedFile);
if (!mounted) return; if (!mounted) return;
await Navigator.push(
Navigator.push(
context, context,
MaterialPageRoute( MaterialPageRoute(
builder: (context) => PreviewScreen( builder: (context) => PreviewScreen(
imagePath: croppedFile.path, imagePath: squarePath,
detections: detections, detections: detections,
bulletCount: _numberOfBullets, // Pass the bullet count bulletCount: _numberOfBullets, // Pass the bullet count
), ),
@@ -195,9 +203,34 @@ class _CameraScreenState extends State<CameraScreen> {
); );
} catch (e) { } catch (e) {
debugPrint('Error taking picture: $e'); debugPrint('Error taking picture: $e');
} finally {
if (mounted) setState(() => _processing = false);
} }
} }
// Debug and profile builds only: detect again on the pure-Dart decode of the same photo
// and log how far the results are apart (the platform decoder may round a
// few pixel values differently).
Future<void> _compareWithDartDecoder(YOLODetector detector, Uint8List bytes,
List<DetectionResult> platform) async {
final dart = await detector
.detectPhoto(await Isolate.run(() => decodePhotoDart(bytes)));
String count(List<DetectionResult> r, int c) =>
'${r.where((d) => d.classId == c).length}';
var maxShift = 0.0;
for (final a in platform) {
var nearest = double.infinity;
for (final b in dart.where((b) => b.classId == a.classId)) {
nearest = min(nearest,
sqrt(pow((a.x1 + a.x2 - b.x1 - b.x2) / 2, 2) + pow((a.y1 + a.y2 - b.y1 - b.y2) / 2, 2)));
}
maxShift = max(maxShift, nearest);
}
debugPrint('🔍 decoder check: bullets ${count(platform, 0)} vs ${count(dart, 0)}, '
'rings ${count(platform, 2)} vs ${count(dart, 2)} (platform vs Dart), '
'largest position difference ${maxShift.isFinite ? maxShift.toStringAsFixed(1) : '–'} px');
}
void _showBulletDialog() { void _showBulletDialog() {
showCameraSheet( showCameraSheet(
context, context,
@@ -411,8 +444,15 @@ class _CameraScreenState extends State<CameraScreen> {
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked, floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
floatingActionButton: FloatingActionButton( floatingActionButton: FloatingActionButton(
backgroundColor: Colors.white, backgroundColor: Colors.white,
onPressed: _takePicture, onPressed: _processing ? null : _takePicture,
child: const Icon(Icons.camera_alt, color: Colors.black), child: _processing
? const SizedBox(
width: 24,
height: 24,
child: CircularProgressIndicator(
strokeWidth: 3, color: Colors.black),
)
: const Icon(Icons.camera_alt, color: Colors.black),
), ),
body: FutureBuilder( body: FutureBuilder(
future: _initializeControllerFuture, future: _initializeControllerFuture,
+58 -90
View File
@@ -1,16 +1,17 @@
import 'dart:io'; import 'dart:io';
import 'dart:typed_data'; import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../utils/target_colors.dart'; import '../utils/target_colors.dart';
import '../theme/app_theme.dart'; import '../theme/app_theme.dart';
import 'package:flutter/services.dart' show rootBundle, HapticFeedback; import 'package:flutter/services.dart' show rootBundle, HapticFeedback;
import 'package:image/image.dart' as img;
import 'package:path_provider/path_provider.dart'; import 'package:path_provider/path_provider.dart';
import 'yolo_detector.dart'; import 'yolo_detector.dart';
import 'dart:convert'; // For JSON encoding import 'dart:convert'; // For JSON encoding
import 'dart:math'; import 'dart:math';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
import '../utils/translations.dart'; import '../utils/translations.dart';
import '../utils/target_scoring.dart';
class PreviewScreen extends StatefulWidget { class PreviewScreen extends StatefulWidget {
final String imagePath; final String imagePath;
@@ -36,22 +37,22 @@ class _PreviewScreenState extends State<PreviewScreen> {
List<Offset> _mappedBullets = []; List<Offset> _mappedBullets = [];
late List<DetectionResult> _realImageDetections; late List<DetectionResult> _realImageDetections;
img.Image? _realImageDecoded; Size? _realImageSize; // the photo; shown from its original bytes
img.Image? _targetImageDecoded; Size? _targetImageSize; // the selected target skin
Future<img.Image?>? _targetImageFuture; Future<Size?>? _targetImageFuture;
Uint8List? _cachedTargetImage; Uint8List? _cachedTargetImage;
Uint8List? _cachedRealImage; Uint8List? _cachedRealImage;
late String targetAssetPath; late String targetAssetPath;
final Offset fixedRingTargetCenter = const Offset(601, 598); final Offset fixedRingTargetCenter = TargetScoring.center;
final Size fixedRingTargetSize = const Size(355.94, 359.27); final Size fixedRingTargetSize = const Size(355.94, 359.27);
// Scale factors for different target image dimensions // Scale factors for different target image dimensions
double _scaleFactorX = 1.0; double _scaleFactorX = 1.0;
double _scaleFactorY = 1.0; double _scaleFactorY = 1.0;
img.Image? _defaultTargetDecoded; // Default target for reference dimensions Size? _defaultTargetSize; // Default target for reference dimensions
int? _highlightedBulletIndex; int? _highlightedBulletIndex;
@@ -144,8 +145,7 @@ class _PreviewScreenState extends State<PreviewScreen> {
Future<void> _loadDefaultTarget() async { Future<void> _loadDefaultTarget() async {
try { try {
final byteData = await rootBundle.load('assets/target.png'); final byteData = await rootBundle.load('assets/target.png');
final bytes = byteData.buffer.asUint8List(); _defaultTargetSize = await _imageSize(byteData.buffer.asUint8List());
_defaultTargetDecoded = img.decodeImage(bytes);
} catch (e) { } catch (e) {
debugPrint("❌ Error loading default target: $e"); debugPrint("❌ Error loading default target: $e");
} }
@@ -164,10 +164,8 @@ class _PreviewScreenState extends State<PreviewScreen> {
_backgroundColor = _getBackgroundColorForTarget(selectedTarget); _backgroundColor = _getBackgroundColorForTarget(selectedTarget);
// Await the image decoding to ensure it's populated before rebuilding // Await the image decoding to ensure it's populated before rebuilding
_targetImageDecoded = await _targetImageFuture; _targetImageSize = await _targetImageFuture;
if (_targetImageDecoded != null) { if (_targetImageSize != null) {
_cachedTargetImage =
Uint8List.fromList(img.encodePng(_targetImageDecoded!));
// Calculate scale factors based on target dimensions // Calculate scale factors based on target dimensions
_calculateScaleFactors(); _calculateScaleFactors();
} }
@@ -178,13 +176,13 @@ class _PreviewScreenState extends State<PreviewScreen> {
} }
void _calculateScaleFactors() { void _calculateScaleFactors() {
if (_defaultTargetDecoded == null || _targetImageDecoded == null) { if (_defaultTargetSize == null || _targetImageSize == null) {
_scaleFactorX = 1.0; _scaleFactorX = 1.0;
_scaleFactorY = 1.0; _scaleFactorY = 1.0;
return; return;
} }
_scaleFactorX = _targetImageDecoded!.width / _defaultTargetDecoded!.width; _scaleFactorX = _targetImageSize!.width / _defaultTargetSize!.width;
_scaleFactorY = _targetImageDecoded!.height / _defaultTargetDecoded!.height; _scaleFactorY = _targetImageSize!.height / _defaultTargetSize!.height;
debugPrint( debugPrint(
"📏 Scale factors calculated: X=$_scaleFactorX, Y=$_scaleFactorY"); "📏 Scale factors calculated: X=$_scaleFactorX, Y=$_scaleFactorY");
@@ -240,29 +238,9 @@ class _PreviewScreenState extends State<PreviewScreen> {
} }
} }
// Default-target position for a shot scored by hand. TargetScoring puts it
// where it scores exactly [score]; the angle spreads the hand-entered shots.
Offset _generatePositionForScore(int score) { Offset _generatePositionForScore(int score) {
const double bulletRadius = 25;
final List<double> rings = [14, 68, 123, 177, 232, 286, 342, 397, 455, 510];
// Always generate positions in the default 1200x1200 coordinate system
final center = fixedRingTargetCenter;
final rng = score.clamp(0, 10);
final double distance;
if (rng == 0) {
// Score 0: place outside all rings (bullet center beyond the outermost ring)
distance = rings.last + bulletRadius;
} else if (rng == 10) {
// Score 10: place in the center ring (0-14)
distance = rings[0] / 2;
} else {
// Scores 1-9: place in the middle of the ring
final outerRadius = rings[10 - rng];
final innerRadius = rng < 10 ? rings[10 - rng - 1] : 0;
distance = (outerRadius + innerRadius) / 2;
}
// Calculate angle based on which manual bullet this will be (add randomness for distribution) // Calculate angle based on which manual bullet this will be (add randomness for distribution)
final bulletIndex = _manualBulletScores.length; final bulletIndex = _manualBulletScores.length;
final angleIncrement = 360.0 / widget.bulletCount; final angleIncrement = 360.0 / widget.bulletCount;
@@ -270,27 +248,37 @@ class _PreviewScreenState extends State<PreviewScreen> {
// Add random offset within the angle increment to vary positioning // Add random offset within the angle increment to vary positioning
final randomOffset = (Random().nextDouble() - 0.5) * angleIncrement * 0.5; final randomOffset = (Random().nextDouble() - 0.5) * angleIncrement * 0.5;
final angle = baseAngle + randomOffset; final angle = baseAngle + randomOffset;
final radians = angle * 3.14159 / 180; return TargetScoring.positionFor(score, angle * pi / 180);
return Offset(
center.dx + distance * cos(radians),
center.dy + distance * sin(radians),
);
} }
Future<img.Image?> _loadAndDecodeTargetImage() async { // Shown from the asset's own bytes; only its size is read
Future<Size?> _loadAndDecodeTargetImage() async {
final byteData = await rootBundle.load(targetAssetPath); final byteData = await rootBundle.load(targetAssetPath);
final bytes = byteData.buffer.asUint8List(); final bytes = byteData.buffer.asUint8List();
return img.decodeImage(bytes); _cachedTargetImage = bytes;
return _imageSize(bytes);
}
// Width and height from the image header, without decoding the pixels
static Future<Size?> _imageSize(Uint8List bytes) async {
try {
final buffer = await ui.ImmutableBuffer.fromUint8List(bytes);
final descriptor = await ui.ImageDescriptor.encoded(buffer);
final size =
Size(descriptor.width.toDouble(), descriptor.height.toDouble());
descriptor.dispose();
buffer.dispose();
return size;
} catch (_) {
return null;
}
} }
Future<void> _runDetectionAndMapping() async { Future<void> _runDetectionAndMapping() async {
try { try {
// 1. Load target background image FIRST to calculate scale factors // 1. Load target background image FIRST to calculate scale factors
_targetImageDecoded = await _targetImageFuture; _targetImageSize = await _targetImageFuture;
if (_targetImageDecoded != null) { if (_targetImageSize != null) {
_cachedTargetImage =
Uint8List.fromList(img.encodePng(_targetImageDecoded!));
// Calculate scale factors based on target image dimensions // Calculate scale factors based on target image dimensions
_calculateScaleFactors(); _calculateScaleFactors();
} }
@@ -299,16 +287,16 @@ class _PreviewScreenState extends State<PreviewScreen> {
final File realImageFile = File(widget.imagePath); final File realImageFile = File(widget.imagePath);
final realBytes = await realImageFile.readAsBytes(); final realBytes = await realImageFile.readAsBytes();
// 3. Decode the real image (ensure it's valid) // 3. Read its size (the header is enough; the pixels are shown as they are)
_realImageDecoded = img.decodeImage(realBytes); _realImageSize = await _imageSize(realBytes);
if (_realImageDecoded == null) { if (_realImageSize == null) {
debugPrint("❌ Failed to decode image from path: ${widget.imagePath}"); debugPrint("❌ Failed to decode image from path: ${widget.imagePath}");
setState(() => _isLoading = false); setState(() => _isLoading = false);
return; return;
} }
// 4. Cache decoded image as PNG for rendering // 4. Shown from the saved JPEG itself
_cachedRealImage = Uint8List.fromList(img.encodePng(_realImageDecoded!)); _cachedRealImage = realBytes;
// 5. Find the detected ring center and size // 5. Find the detected ring center and size
final ringCamData = _getRingCenterSize(_realImageDetections); final ringCamData = _getRingCenterSize(_realImageDetections);
@@ -336,10 +324,7 @@ class _PreviewScreenState extends State<PreviewScreen> {
sizeCam, sizeCam,
fixedRingTargetSize, fixedRingTargetSize,
); );
final score = _scoreForBullet( final score = _scoreForBullet(mappedToDefaultTarget);
mappedToDefaultTarget,
fixedRingTargetCenter, // Always score relative to default target center
);
return {'bullet': mappedToDefaultTarget, 'score': score}; return {'bullet': mappedToDefaultTarget, 'score': score};
}).toList(); }).toList();
@@ -631,12 +616,17 @@ class _PreviewScreenState extends State<PreviewScreen> {
}; };
}).toList(); }).toList();
// Score of every saved bullet, in the same order: hand-entered shots
// keep the score that was entered. The target view shows these as saved.
final scores = [for (int i = 0; i < _mappedBullets.length; i++) _scoreAt(i)];
final targetData = { final targetData = {
'date': dateString, 'date': dateString,
'totalScore': _totalScore, 'totalScore': scores.fold(0, (a, b) => a + b),
'bulletCount': widget 'bulletCount': widget
.bulletCount, // shots fired; missed ones are absent from 'bullets' .bulletCount, // shots fired; missed ones are absent from 'bullets'
'bullets': bulletsInDefaultCoordinates, 'bullets': bulletsInDefaultCoordinates,
'scores': scores,
}; };
// Write file // Write file
@@ -658,10 +648,7 @@ class _PreviewScreenState extends State<PreviewScreen> {
return _manualBulletScores[index - manualStart]; return _manualBulletScores[index - manualStart];
} }
final b = _mappedBullets[index]; final b = _mappedBullets[index];
return _scoreForBullet( return _scoreForBullet(Offset(b.dx / _scaleFactorX, b.dy / _scaleFactorY));
Offset(b.dx / _scaleFactorX, b.dy / _scaleFactorY),
fixedRingTargetCenter,
);
} }
Widget _buildEditController() { Widget _buildEditController() {
@@ -887,10 +874,7 @@ class _PreviewScreenState extends State<PreviewScreen> {
updated.dx / _scaleFactorX, updated.dx / _scaleFactorX,
updated.dy / _scaleFactorY, updated.dy / _scaleFactorY,
); );
final updatedScore = _scoreForBullet( final updatedScore = _scoreForBullet(defaultTargetBullet);
defaultTargetBullet,
fixedRingTargetCenter,
);
_manualBulletScores[index - manualStartIndex] = updatedScore; _manualBulletScores[index - manualStartIndex] = updatedScore;
} }
}); });
@@ -1097,21 +1081,8 @@ class _PreviewScreenState extends State<PreviewScreen> {
return Offset(mappedX, mappedY); return Offset(mappedX, mappedY);
} }
int _scoreForBullet(Offset bullet, Offset centerOverride) { // Bullet in default target coordinates
const double bulletRadius = 25; int _scoreForBullet(Offset bullet) => TargetScoring.scoreAt(bullet);
final double distanceToEdge =
(bullet - centerOverride).distance - bulletRadius;
final List<double> rings = [14, 70, 125, 180, 235, 290, 345, 400, 455, 510];
for (int i = 0; i < rings.length; i++) {
if (distanceToEdge <= rings[i]) {
return 10 - i;
}
}
return 0;
}
int get _totalScore { int get _totalScore {
// Score is based on the default target coordinate system (1200x1200) // Score is based on the default target coordinate system (1200x1200)
@@ -1127,7 +1098,7 @@ class _PreviewScreenState extends State<PreviewScreen> {
b.dx / _scaleFactorX, b.dx / _scaleFactorX,
b.dy / _scaleFactorY, b.dy / _scaleFactorY,
); );
return _scoreForBullet(defaultTargetBullet, fixedRingTargetCenter); return _scoreForBullet(defaultTargetBullet);
}).fold(0, (sum, score) => sum + score); }).fold(0, (sum, score) => sum + score);
final manualScore = _manualBulletScores.fold(0, (a, b) => a + b); final manualScore = _manualBulletScores.fold(0, (a, b) => a + b);
@@ -1236,8 +1207,8 @@ class _PreviewScreenState extends State<PreviewScreen> {
: _cachedRealImage; : _cachedRealImage;
final imgData = _mode == PreviewMode.mappedTarget final imgData = _mode == PreviewMode.mappedTarget
? _targetImageDecoded ? _targetImageSize
: _realImageDecoded; : _realImageSize;
if (displayImage == null || imgData == null) { if (displayImage == null || imgData == null) {
return const Center( return const Center(
@@ -1418,14 +1389,11 @@ class _PreviewScreenState extends State<PreviewScreen> {
? _manualBulletScores[index - ? _manualBulletScores[index -
(_mappedBullets.length - (_mappedBullets.length -
_manualBulletScores.length)] _manualBulletScores.length)]
: _scoreForBullet(
// Convert bullet back to default coordinate system for scoring // Convert bullet back to default coordinate system for scoring
Offset( : _scoreForBullet(Offset(
bullet.dx / _scaleFactorX, bullet.dx / _scaleFactorX,
bullet.dy / _scaleFactorY, bullet.dy / _scaleFactorY,
), ));
fixedRingTargetCenter,
);
return Expanded( return Expanded(
child: Padding( child: Padding(
+43 -58
View File
@@ -7,6 +7,7 @@ import 'dart:convert';
import 'package:image/image.dart' as img; import 'package:image/image.dart' as img;
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
import '../utils/translations.dart'; import '../utils/translations.dart';
import '../utils/target_scoring.dart';
import '../utils/target_colors.dart'; import '../utils/target_colors.dart';
import '../widgets/result_share.dart'; import '../widgets/result_share.dart';
import 'session_screen.dart' show targetCount, shotCount; import 'session_screen.dart' show targetCount, shotCount;
@@ -30,11 +31,11 @@ class TargetViewScreen extends StatefulWidget {
class _TargetViewScreenState extends State<TargetViewScreen> { class _TargetViewScreenState extends State<TargetViewScreen> {
final int _currentIndex = 0; final int _currentIndex = 0;
List<Offset> _bullets = []; List<Offset> _bullets = [];
List<int> _scores = []; // score of each bullet, same order as _bullets
List<Offset> _scaledBullets = []; // Bullets scaled to display target size List<Offset> _scaledBullets = []; // Bullets scaled to display target size
int _totalScore = 0; int _totalScore = 0;
int _shotCount = 0; // shots fired, misses included (bulletCount) int _shotCount = 0; // shots fired, misses included (bulletCount)
Map<int, int> _folderChartScores = {}; Map<int, int> _folderChartScores = {};
Offset? _targetCenter;
Uint8List? _targetImageBytes; Uint8List? _targetImageBytes;
img.Image? _targetImageDecoded; img.Image? _targetImageDecoded;
String _date = ''; String _date = '';
@@ -139,6 +140,25 @@ class _TargetViewScreenState extends State<TargetViewScreen> {
} }
} }
// Bullets, their scores and the total of one saved target. Newer saves store
// each shot's score (hand-entered shots keep the score that was entered);
// older ones are scored from the positions, by the same rule as saving.
static ({List<Offset> bullets, List<int> scores, int total}) _readTarget(
Map<String, dynamic> data) {
final bullets = [
for (final b in (data['bullets'] as List?) ?? const [])
Offset((b['x'] as num).toDouble(), (b['y'] as num).toDouble())
];
final saved = data['scores'];
final scores = saved is List && saved.length == bullets.length
? [for (final x in saved) (x as num).toInt()]
: [for (final b in bullets) TargetScoring.scoreAt(b)];
final total = data['totalScore'] is int
? data['totalScore'] as int
: scores.fold(0, (a, b) => a + b);
return (bullets: bullets, scores: scores, total: total);
}
Future<void> _loadJsonAndImage() async { Future<void> _loadJsonAndImage() async {
try { try {
// Load default target for bullet positioning reference // Load default target for bullet positioning reference
@@ -151,12 +171,6 @@ class _TargetViewScreenState extends State<TargetViewScreen> {
return; return;
} }
// Calculate target center from default target (for bullet positioning)
_targetCenter = Offset(
defaultTargetDecoded.width / 2,
defaultTargetDecoded.height / 2 - 1,
);
// Load selected target for display // Load selected target for display
final displayByteData = await rootBundle.load(_selectedTargetPath); final displayByteData = await rootBundle.load(_selectedTargetPath);
final displayBytes = displayByteData.buffer.asUint8List(); final displayBytes = displayByteData.buffer.asUint8List();
@@ -173,20 +187,22 @@ class _TargetViewScreenState extends State<TargetViewScreen> {
if (widget.isCombinedView) { if (widget.isCombinedView) {
// In combined view, collect all bullets from all files // In combined view, collect all bullets from all files
final allBullets = <Offset>[]; final allBullets = <Offset>[];
final allScores = <int>[];
final chartScores = <int, int>{};
var total = 0;
String latestDate = 'Unknown Date'; String latestDate = 'Unknown Date';
var shots = 0; var shots = 0;
for (var file in widget.jsonFiles) { for (var file in widget.jsonFiles) {
final jsonString = await file.readAsString(); final jsonString = await file.readAsString();
final data = jsonDecode(jsonString); final data = jsonDecode(jsonString) as Map<String, dynamic>;
final target = _readTarget(data);
final bulletsJson = data['bullets'] as List?; shots += (data['bulletCount'] as int?) ?? target.bullets.length;
shots += (data['bulletCount'] as int?) ?? bulletsJson?.length ?? 0; allBullets.addAll(target.bullets);
if (bulletsJson != null) { allScores.addAll(target.scores);
allBullets.addAll( total += target.total;
bulletsJson.map((b) => Offset(b['x'].toDouble(), b['y'].toDouble())).toList(), chartScores[chartScores.length + 1] = target.total;
);
}
if (data['date'] != null) { if (data['date'] != null) {
latestDate = data['date']; latestDate = data['date'];
@@ -214,6 +230,9 @@ class _TargetViewScreenState extends State<TargetViewScreen> {
} }
_bullets = allBullets; _bullets = allBullets;
_scores = allScores;
_totalScore = total;
_folderChartScores = chartScores;
_shotCount = shots; _shotCount = shots;
} else { } else {
// Single file view - load from current file // Single file view - load from current file
@@ -240,8 +259,10 @@ class _TargetViewScreenState extends State<TargetViewScreen> {
} else { } else {
_date = rawDate; _date = rawDate;
} }
final bulletsJson = data['bullets'] as List; final target = _readTarget(data as Map<String, dynamic>);
_bullets = bulletsJson.map((b) => Offset(b['x'].toDouble(), b['y'].toDouble())).toList(); _bullets = target.bullets;
_scores = target.scores;
_totalScore = target.total;
_shotCount = (data['bulletCount'] as int?) ?? _bullets.length; _shotCount = (data['bulletCount'] as int?) ?? _bullets.length;
} }
@@ -261,41 +282,12 @@ class _TargetViewScreenState extends State<TargetViewScreen> {
); );
}).toList(); }).toList();
_totalScore = _bullets
.map((b) => _scoreForBullet(b, _targetCenter!))
.fold(0, (sum, score) => sum + score);
// Pre-compute folder chart scores to avoid sync file reads in build
if (widget.isCombinedView) {
final chartScores = <int, int>{};
for (int i = 0; i < widget.jsonFiles.length; i++) {
final data = jsonDecode(await widget.jsonFiles[i].readAsString());
final bullets = (data['bullets'] as List?) ?? [];
int s = 0;
for (final b in bullets) {
s += _scoreForBullet(Offset(b['x'].toDouble(), b['y'].toDouble()), _targetCenter!);
}
chartScores[i + 1] = s;
}
_folderChartScores = chartScores;
}
setState(() {}); setState(() {});
} catch (e) { } catch (e) {
debugPrint("Error loading JSON or image: $e"); debugPrint("Error loading JSON or image: $e");
} }
} }
int _scoreForBullet(Offset bullet, Offset center) {
const bulletRadius = 25;
final distance = (bullet - center).distance - bulletRadius;
final rings = [14, 70, 125, 180, 235, 290, 345, 400, 455, 510];
for (int i = 0; i < rings.length; i++) {
if (distance <= rings[i]) return 10 - i;
}
return 0;
}
Future<void> _deleteTarget() async { Future<void> _deleteTarget() async {
try { try {
final file = File(_targetFilePath); final file = File(_targetFilePath);
@@ -317,8 +309,7 @@ class _TargetViewScreenState extends State<TargetViewScreen> {
// What the screen shows, as one image: target and tiles left, chart right // What the screen shows, as one image: target and tiles left, chart right
void _share() { void _share() {
final center = _targetCenter ?? Offset.zero; final scores = _scores;
final scores = [for (final b in _bullets) _scoreForBullet(b, center)];
final List<(String, String)> tiles; final List<(String, String)> tiles;
final List<MapEntry<int, int>> chart; final List<MapEntry<int, int>> chart;
@@ -543,10 +534,7 @@ class _TargetViewScreenState extends State<TargetViewScreen> {
// Scaled bullets are already scaled to display target dimensions // Scaled bullets are already scaled to display target dimensions
final dx = scaledBullet.dx * scaleX + offsetX; final dx = scaledBullet.dx * scaleX + offsetX;
final dy = scaledBullet.dy * scaleY + offsetY; final dy = scaledBullet.dy * scaleY + offsetY;
// Score is calculated using original bullet position and default target center final score = _scores[i];
final originalBullet = _bullets[i];
final score = _scoreForBullet(
originalBullet, _targetCenter ?? Offset.zero);
final isHighlighted = widget.isCombinedView final isHighlighted = widget.isCombinedView
? (_pressedScoreGroup == score) ? (_pressedScoreGroup == score)
: (i == _highlightedBulletIndex); : (i == _highlightedBulletIndex);
@@ -695,8 +683,7 @@ class _TargetViewScreenState extends State<TargetViewScreen> {
// Single file view: each shot as a bar // Single file view: each shot as a bar
final Map<int, int> shotScores = {}; final Map<int, int> shotScores = {};
for (int i = 0; i < _bullets.length; i++) { for (int i = 0; i < _bullets.length; i++) {
final score = _scoreForBullet(_bullets[i], _targetCenter ?? Offset.zero); shotScores[i + 1] = _scores[i]; // Shot number starts at 1
shotScores[i + 1] = score; // Shot number starts at 1
} }
if (shotScores.isEmpty) { if (shotScores.isEmpty) {
@@ -741,8 +728,7 @@ class _TargetViewScreenState extends State<TargetViewScreen> {
List<Widget> _buildGroupedScoreButtons() { List<Widget> _buildGroupedScoreButtons() {
final Map<int, int> scoreGroups = {}; final Map<int, int> scoreGroups = {};
for (final bullet in _bullets) { for (final score in _scores) {
final score = _scoreForBullet(bullet, _targetCenter!);
scoreGroups[score] = (scoreGroups[score] ?? 0) + 1; scoreGroups[score] = (scoreGroups[score] ?? 0) + 1;
} }
@@ -835,8 +821,7 @@ class _TargetViewScreenState extends State<TargetViewScreen> {
final scoredBullets = _bullets.asMap().entries.map((entry) { final scoredBullets = _bullets.asMap().entries.map((entry) {
final index = entry.key; final index = entry.key;
final bullet = entry.value; final bullet = entry.value;
final score = _scoreForBullet(bullet, _targetCenter ?? Offset.zero); return {'index': index, 'score': _scores[index], 'bullet': bullet};
return {'index': index, 'score': score, 'bullet': bullet};
}).toList(); }).toList();
// Sort descending by score // Sort descending by score
+116 -115
View File
@@ -1,6 +1,8 @@
// ======= yolo_detector.dart (updated with imageToInputTensor helper) =======
import 'dart:io'; import 'dart:io';
import 'dart:isolate';
import 'dart:math';
import 'dart:typed_data'; import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:tflite_flutter/tflite_flutter.dart'; import 'package:tflite_flutter/tflite_flutter.dart';
import 'package:image/image.dart' as img; import 'package:image/image.dart' as img;
@@ -12,154 +14,153 @@ class DetectionResult {
DetectionResult(this.x1, this.y1, this.x2, this.y2, this.confidence, this.classId); DetectionResult(this.x1, this.y1, this.x2, this.y2, this.confidence, this.classId);
} }
class CroppedImageResult { /// A decoded camera photo, upright: [channels] bytes per pixel (RGBA from the
final img.Image image; /// platform decoder, RGB from the Dart one), row by row.
final int offsetX; class Photo {
final int offsetY; final Uint8List pixels;
final int cropWidth; final int width, height, channels;
final int cropHeight;
CroppedImageResult(this.image, this.offsetX, this.offsetY, this.cropWidth, this.cropHeight); Photo(this.pixels, this.width, this.height, this.channels);
/// The centre square: what detection looks at, the preview shows and gets saved.
int get side => min(width, height);
int get squareX => (width - side) ~/ 2;
int get squareY => (height - side) ~/ 2;
} }
/// Decodes a camera JPEG with the platform's decoder, several times faster
/// than the pure-Dart one; falls back to that if it fails. Both apply the
/// photo's EXIF rotation, so the result is upright.
Future<Photo> decodePhoto(Uint8List jpeg) async =>
await decodePhotoNative(jpeg) ?? await Isolate.run(() => decodePhotoDart(jpeg));
Future<Photo?> decodePhotoNative(Uint8List jpeg) async {
try {
final codec = await ui.instantiateImageCodec(jpeg);
final frame = await codec.getNextFrame();
final image = frame.image;
final data = await image.toByteData(format: ui.ImageByteFormat.rawStraightRgba);
final photo = data == null
? null
: Photo(data.buffer.asUint8List(), image.width, image.height, 4);
image.dispose();
codec.dispose();
return photo;
} catch (_) {
return null;
}
}
Photo decodePhotoDart(Uint8List jpeg) {
final decoded = img.decodeImage(jpeg);
if (decoded == null) throw Exception('Could not decode image.');
return Photo(decoded.getBytes(order: img.ChannelOrder.rgb), decoded.width,
decoded.height, 3);
}
/// Model input from the photo's centre square: RGB floats 0..1, row by row,
/// [width] x [height]. Samples the same pixels as copyResize (nearest) of the
/// cropped square, without copying the square first.
Float32List inputFromPhoto(Photo photo, int width, int height) {
final side = photo.side, ox = photo.squareX, oy = photo.squareY;
final ch = photo.channels, rowBytes = photo.width * ch, px = photo.pixels;
final dx = side / width, dy = side / height;
final cols = Int32List(width);
for (int x = 0; x < width; x++) {
cols[x] = (ox + (x * dx).toInt()) * ch;
}
final input = Float32List(width * height * 3);
int i = 0;
for (int y = 0; y < height; y++) {
final row = (oy + (y * dy).toInt()) * rowBytes;
for (int x = 0; x < width; x++) {
final p = row + cols[x];
input[i++] = px[p] / 255.0;
input[i++] = px[p + 1] / 255.0;
input[i++] = px[p + 2] / 255.0;
}
}
return input;
}
/// The centre square as an image, for saving.
img.Image squareOf(Photo photo) {
final full = img.Image.fromBytes(
width: photo.width,
height: photo.height,
bytes: photo.pixels.buffer,
bytesOffset: photo.pixels.offsetInBytes,
numChannels: photo.channels);
return img.copyCrop(full,
x: photo.squareX, y: photo.squareY, width: photo.side, height: photo.side);
}
/// Save the centre square as JPEG in a background isolate.
Future<void> saveSquareInBackground(Photo photo, String path) =>
Isolate.run(() => File(path).writeAsBytesSync(img.encodeJpg(squareOf(photo))));
class YOLODetector { class YOLODetector {
late Interpreter _interpreter; late Interpreter _interpreter;
late IsolateInterpreter _background; // runs the model off the UI thread
late int inputWidth, inputHeight; late int inputWidth, inputHeight;
final double confidenceThreshold = 0.4; final double confidenceThreshold = 0.4;
YOLODetector._create(); YOLODetector._create();
/// Loads the model and runs it once, so the first real photo doesn't pay
/// for the interpreter's one-time setup.
static Future<YOLODetector> create() async { static Future<YOLODetector> create() async {
final detector = YOLODetector._create(); final detector = YOLODetector._create();
await detector._loadModel(); await detector._loadModel();
await detector._run(Float32List(detector.inputWidth * detector.inputHeight * 3));
return detector; return detector;
} }
Future<void> _loadModel() async { Future<void> _loadModel() async {
final options = InterpreterOptions()..threads = 2; final options = InterpreterOptions()..threads = 4;
_interpreter = await Interpreter.fromAsset('assets/best_float32_nms.tflite', options: options); _interpreter = await Interpreter.fromAsset('assets/best_float32_nms.tflite', options: options);
_background = await IsolateInterpreter.create(address: _interpreter.address);
final inputTensor = _interpreter.getInputTensor(0); final inputShape = _interpreter.getInputTensor(0).shape;
final inputShape = inputTensor.shape;
inputHeight = inputShape[1]; inputHeight = inputShape[1];
inputWidth = inputShape[2]; inputWidth = inputShape[2];
} }
Future<List<DetectionResult>> detect(File imageFile) async { // One model run; each row of the result is x1, y1, x2, y2, score, class
final bytes = await imageFile.readAsBytes(); Future<List<List<double>>> _run(Float32List input) async {
final decodedImage = img.decodeImage(bytes); final numDetections = _interpreter.getOutputTensor(0).shape[1];
if (decodedImage == null) throw Exception("Could not decode image."); final output = [List.generate(numDetections, (_) => List.filled(6, 0.0))];
return detectFromImage(decodedImage); await _background.run(input.buffer, output);
return output[0];
} }
Future<List<DetectionResult>> detectFromImage(img.Image originalImage) async { /// Whole pipeline for a photo file. Coordinates are in pixels of the
final croppedResult = cropToModelAspectRatio(originalImage, inputWidth, inputHeight); /// photo's centre square.
final fixedImage = img.bakeOrientation(croppedResult.image); Future<List<DetectionResult>> detect(File imageFile) async =>
final inputTensor = imageToInputTensor(fixedImage, inputWidth, inputHeight); detectPhoto(await decodePhoto(await imageFile.readAsBytes()));
final inputBuffer = reshapeFloat(inputTensor.toList(), [1, inputHeight, inputWidth, 3]); /// Runs the model on [photo]'s centre square; coordinates are in pixels of
/// that square. Not re-entrant: wait for one call to finish before the next.
Future<List<DetectionResult>> detectPhoto(Photo photo) async {
final w = inputWidth, h = inputHeight;
final input = await Isolate.run(() => inputFromPhoto(photo, w, h));
final rows = await _run(input);
final outputShape = _interpreter.getOutputTensor(0).shape; final side = photo.side.toDouble();
final numDetections = outputShape[1];
final outputBuffer = List.generate(1, (_) =>
List.generate(numDetections, (_) => List.filled(6, 0.0)));
_interpreter.run(inputBuffer, outputBuffer);
final rawDetections = outputBuffer[0];
final results = <DetectionResult>[]; final results = <DetectionResult>[];
for (final d in rows) {
for (var detection in rawDetections) { final score = d[4];
final x1 = detection[0];
final y1 = detection[1];
final x2 = detection[2];
final y2 = detection[3];
final score = detection[4];
final classId = detection[5].toInt();
if (score < confidenceThreshold) continue; if (score < confidenceThreshold) continue;
// Corners come normalized to [0, 1] of the model input, which is the
// The model outputs coordinates normalized to [0, 1] relative to the input tensor (inputWidth x inputHeight) // whole square scaled down
// We need to scale back to the original cropped image coordinates results.add(DetectionResult(d[0] * side, d[1] * side, d[2] * side,
// The cropped image (cropWidth x cropHeight) was resized to (inputWidth x inputHeight) d[3] * side, score, d[5].toInt()));
final scaledX1 = x1 * croppedResult.cropWidth;
final scaledY1 = y1 * croppedResult.cropHeight;
final scaledX2 = x2 * croppedResult.cropWidth;
final scaledY2 = y2 * croppedResult.cropHeight;
// Add offset to get coordinates in the original image space
results.add(DetectionResult(
scaledX1 + croppedResult.offsetX,
scaledY1 + croppedResult.offsetY,
scaledX2 + croppedResult.offsetX,
scaledY2 + croppedResult.offsetY,
score,
classId,
));
} }
return results; return results;
} }
void close() { void close() {
_background.close();
_interpreter.close(); _interpreter.close();
} }
List<List<List<List<double>>>> reshapeFloat(List<double> flat, List<int> dims) {
final d0 = dims[0], d1 = dims[1], d2 = dims[2], d3 = dims[3];
final reshaped = List.generate(d0, (_) =>
List.generate(d1, (_) =>
List.generate(d2, (_) => List.filled(d3, 0.0))));
int index = 0;
for (int i = 0; i < d0; i++) {
for (int j = 0; j < d1; j++) {
for (int k = 0; k < d2; k++) {
for (int l = 0; l < d3; l++) {
reshaped[i][j][k][l] = flat[index++];
}
}
}
}
return reshaped;
}
CroppedImageResult cropToModelAspectRatio(img.Image image, int targetWidth, int targetHeight) {
final targetAspectRatio = targetWidth / targetHeight;
final originalAspectRatio = image.width / image.height;
int cropWidth = image.width;
int cropHeight = image.height;
if (originalAspectRatio > targetAspectRatio) {
cropWidth = (image.height * targetAspectRatio).toInt();
} else {
cropHeight = (image.width / targetAspectRatio).toInt();
}
final offsetX = ((image.width - cropWidth) / 2).toInt();
final offsetY = ((image.height - cropHeight) / 2).toInt();
final croppedImage = img.copyCrop(image, x: offsetX, y: offsetY, width: cropWidth, height: cropHeight);
return CroppedImageResult(croppedImage, offsetX, offsetY, cropWidth, cropHeight);
}
Float32List imageToInputTensor(img.Image inputImage, int width, int height) {
final resized = img.copyResize(inputImage, width: width, height: height);
final Float32List input = Float32List(width * height * 3);
int index = 0;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
final pixel = resized.getPixel(x, y);
final r = pixel.r / 255.0;
final g = pixel.g / 255.0;
final b = pixel.b / 255.0;
input[index++] = r;
input[index++] = g;
input[index++] = b;
}
}
return input;
}
} }
+48
View File
@@ -0,0 +1,48 @@
import 'dart:math';
import 'dart:ui';
/// The one scoring rule for a shot on the default target (assets/target.png,
/// 1200x1200). Saving, the preview and the target view all use it, so a shot
/// scores the same everywhere.
///
/// A shot counts for the best ring its edge touches: the distance from the
/// centre to the bullet's centre, minus the bullet's radius, is compared with
/// the outer edge of each ring.
class TargetScoring {
TargetScoring._();
static const Offset center = Offset(601, 598);
static const double bulletRadius = 25;
/// Outer edge of ring 10, 9, ... 1, measured from [center].
static const List<double> rings = [
14, 70, 125, 180, 235, 290, 345, 400, 455, 510,
];
/// Score of a shot whose centre is at [bullet] (default target coordinates).
static int scoreAt(Offset bullet) {
final edge = (bullet - center).distance - bulletRadius;
for (int i = 0; i < rings.length; i++) {
if (edge <= rings[i]) return 10 - i;
}
return 0;
}
/// Where to draw a shot that was scored by hand, in direction [angle]
/// (radians): the middle of the band of positions [scoreAt] gives [score]
/// for, so the dot always scores what was entered.
static Offset positionFor(int score, double angle) {
final s = score.clamp(0, 10);
// Distance of the bullet's edge from the centre, middle of the band
final double edge;
if (s == 10) {
edge = (-bulletRadius + rings[0]) / 2; // bullet over the centre
} else if (s == 0) {
edge = rings.last + 30; // just outside the target
} else {
edge = (rings[9 - s] + rings[10 - s]) / 2;
}
final distance = edge + bulletRadius;
return center + Offset(cos(angle), sin(angle)) * distance;
}
}
+20 -10
View File
@@ -1029,6 +1029,26 @@ class AppTranslations {
'Slovenian': 'Tukaj se bodo prikazale shranjene tarče in tvoja statistika', 'Slovenian': 'Tukaj se bodo prikazale shranjene tarče in tvoja statistika',
'German': 'Hier erscheinen gespeicherte Scheiben und deine Statistik', 'German': 'Hier erscheinen gespeicherte Scheiben und deine Statistik',
}, },
'Statistics / History: your form and progress graph, or the list of all your sessions.': {
'English': 'Statistics / History: your form and progress graph, or the list of all your sessions.',
'Slovenian': 'Statistika / Zgodovina: tvoja forma in graf napredka ali seznam vseh tvojih sej.',
'German': 'Statistik / Verlauf: deine Form und der Fortschrittsgraf oder die Liste aller Einheiten.',
},
'History: All / Trainings / Tournaments chooses which sessions are listed, with any number of shots.': {
'English': 'History: All / Trainings / Tournaments chooses which sessions are listed, with any number of shots.',
'Slovenian': 'Zgodovina: Vse / Treningi / Tekmovanja izbere, katere seje so na seznamu, ne glede na število strelov.',
'German': 'Verlauf: Alle / Trainings / Wettkämpfe wählt, welche Einheiten gelistet werden, mit beliebiger Schusszahl.',
},
'Period: this month, last 3 months, this year, all or your own dates. Statistics and History both use it.': {
'English': 'Period: this month, last 3 months, this year, all or your own dates. Statistics and History both use it.',
'Slovenian': 'Obdobje: ta mesec, zadnji 3 meseci, to leto, vse ali tvoji datumi. Uporabljata ga Statistika in Zgodovina.',
'German': 'Zeitraum: dieser Monat, letzte 3 Monate, dieses Jahr, alle oder eigene Daten. Statistik und Verlauf nutzen ihn beide.',
},
'Tap a session to see all its targets on one target.': {
'English': 'Tap a session to see all its targets on one target.',
'Slovenian': 'Tapni sejo, da vidiš vse njene tarče na eni tarči.',
'German': 'Tippe auf eine Einheit, um alle ihre Scheiben auf einer Scheibe zu sehen.',
},
'Trainings / Tournaments: choose which sessions the statistics count.': { 'Trainings / Tournaments: choose which sessions the statistics count.': {
'English': 'Trainings / Tournaments: choose which sessions the statistics count.', 'English': 'Trainings / Tournaments: choose which sessions the statistics count.',
'Slovenian': 'Treningi / Tekmovanja: izberi, katere seje šteje statistika.', 'Slovenian': 'Treningi / Tekmovanja: izberi, katere seje šteje statistika.',
@@ -1039,11 +1059,6 @@ class AppTranslations {
'Slovenian': 'Streli 1–5: statistika primerja le tarče z enakim številom strelov. Sive številke še nimajo tarč.', 'Slovenian': 'Streli 1–5: statistika primerja le tarče z enakim številom strelov. Sive številke še nimajo tarč.',
'German': 'Schüsse 1–5: Die Statistik vergleicht nur Scheiben mit gleicher Schusszahl. Graue Zahlen haben noch keine Scheiben.', 'German': 'Schüsse 1–5: Die Statistik vergleicht nur Scheiben mit gleicher Schusszahl. Graue Zahlen haben noch keine Scheiben.',
}, },
'Tap a session to see all its targets with the selected number of shots on one target.': {
'English': 'Tap a session to see all its targets with the selected number of shots on one target.',
'Slovenian': 'Tapni sejo za prikaz vseh njenih tarč z izbranim številom strelov na eni tarči.',
'German': 'Tippe auf eine Einheit, um alle ihre Scheiben mit der gewählten Schusszahl auf einer Scheibe zu sehen.',
},
'Three dots on the right or long press: session details, single targets, rename and delete.': { 'Three dots on the right or long press: session details, single targets, rename and delete.': {
'English': 'Three dots on the right or long press: session details, single targets, rename and delete.', 'English': 'Three dots on the right or long press: session details, single targets, rename and delete.',
'Slovenian': 'Tri pike na desni ali dolg pritisk: podrobnosti seje, posamezne tarče, preimenovanje in brisanje.', 'Slovenian': 'Tri pike na desni ali dolg pritisk: podrobnosti seje, posamezne tarče, preimenovanje in brisanje.',
@@ -1065,11 +1080,6 @@ class AppTranslations {
'Slovenian': 'Graf: povprečje strela (leva os) in število točk (desna os). Mesec prikaže vsako sejo meseca, Leto eno točko na mesec; s puščicami greš nazaj po mesecih ali letih. Tapni ali povleci po njem za vrednosti.', 'Slovenian': 'Graf: povprečje strela (leva os) in število točk (desna os). Mesec prikaže vsako sejo meseca, Leto eno točko na mesec; s puščicami greš nazaj po mesecih ali letih. Tapni ali povleci po njem za vrednosti.',
'German': 'Diagramm: Schussdurchschnitt (linke Achse) und Punktzahl (rechte Achse). Monat zeigt jede Einheit eines Monats, Jahr einen Punkt pro Monat; mit den Pfeilen gehst du zu früheren Monaten oder Jahren. Tippe oder ziehe darauf, um die Werte zu sehen.', 'German': 'Diagramm: Schussdurchschnitt (linke Achse) und Punktzahl (rechte Achse). Monat zeigt jede Einheit eines Monats, Jahr einen Punkt pro Monat; mit den Pfeilen gehst du zu früheren Monaten oder Jahren. Tippe oder ziehe darauf, um die Werte zu sehen.',
}, },
'Period (next to History): this month, last 3 months, this year, all or your own dates. The top card and the list both use it.': {
'English': 'Period (next to History): this month, last 3 months, this year, all or your own dates. The top card and the list both use it.',
'Slovenian': 'Obdobje (zraven Zgodovine): ta mesec, zadnji 3 meseci, to leto, vse ali svoji datumi. Uporabljata ga zgornja kartica in seznam.',
'German': 'Zeitraum (neben Verlauf): dieser Monat, letzte 3 Monate, dieses Jahr, alles oder eigene Daten. Die obere Karte und die Liste verwenden ihn beide.',
},
'Period': { 'Period': {
'English': 'Period', 'English': 'Period',
'Slovenian': 'Obdobje', 'Slovenian': 'Obdobje',
+13 -6
View File
@@ -27,6 +27,9 @@ class ProgressChart extends StatefulWidget {
final List<ChartSeries> series; // legend and tooltip order final List<ChartSeries> series; // legend and tooltip order
final Color textColor; final Color textColor;
final Color gridColor; final Color gridColor;
// true: the graph takes all the height its parent gives it (inside an
// Expanded); false: a fixed 190 px
final bool expand;
const ProgressChart({ const ProgressChart({
super.key, super.key,
@@ -34,6 +37,7 @@ class ProgressChart extends StatefulWidget {
required this.series, required this.series,
required this.textColor, required this.textColor,
required this.gridColor, required this.gridColor,
this.expand = false,
}); });
@override @override
@@ -78,12 +82,10 @@ class _ProgressChartState extends State<ProgressChart> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Column( final graph = LayoutBuilder(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
LayoutBuilder(
builder: (context, constraints) { builder: (context, constraints) {
final size = Size(constraints.maxWidth, 190); final size = Size(
constraints.maxWidth, widget.expand ? constraints.maxHeight : 190);
return GestureDetector( return GestureDetector(
behavior: HitTestBehavior.opaque, behavior: HitTestBehavior.opaque,
onTapDown: (d) => _toggle(d.localPosition, size), onTapDown: (d) => _toggle(d.localPosition, size),
@@ -100,7 +102,12 @@ class _ProgressChartState extends State<ProgressChart> {
), ),
); );
}, },
), );
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: widget.expand ? MainAxisSize.max : MainAxisSize.min,
children: [
widget.expand ? Expanded(child: graph) : graph,
const SizedBox(height: 8), const SizedBox(height: 8),
// Legend, centred under the graph // Legend, centred under the graph
Wrap( Wrap(
+46
View File
@@ -0,0 +1,46 @@
import 'dart:math';
import 'package:flutter_test/flutter_test.dart';
import 'package:sd_kovinar/utils/target_scoring.dart';
void main() {
group('TargetScoring', () {
test('a hand-entered shot scores what was entered, in every direction', () {
for (int score = 0; score <= 10; score++) {
for (int deg = 0; deg < 360; deg += 5) {
final p = TargetScoring.positionFor(score, deg * pi / 180);
expect(TargetScoring.scoreAt(p), score,
reason: 'score $score placed at $deg°');
}
}
});
test('hand-entered shots are not placed on a ring line', () {
// Moving a dot by a couple of pixels (rounding, editing) must not
// change its score
for (int score = 0; score <= 10; score++) {
final p = TargetScoring.positionFor(score, 0.7);
for (final d in [const Offset(2, 0), const Offset(-2, 0), const Offset(0, 2), const Offset(0, -2)]) {
expect(TargetScoring.scoreAt(p + d), score, reason: 'score $score nudged by $d');
}
}
});
test('ring edges count the bullet radius', () {
const c = TargetScoring.center;
// Bullet edge exactly on the outer edge of ring 10
expect(TargetScoring.scoreAt(c + const Offset(14 + 25, 0)), 10);
expect(TargetScoring.scoreAt(c + const Offset(14 + 25 + 0.5, 0)), 9);
// Outside the last ring
expect(TargetScoring.scoreAt(c + const Offset(510 + 25 + 0.5, 0)), 0);
});
test('hand-entered shots stay on the 1200x1200 target', () {
for (int deg = 0; deg < 360; deg += 15) {
final p = TargetScoring.positionFor(0, deg * pi / 180);
expect(p.dx, inInclusiveRange(0, 1200));
expect(p.dy, inInclusiveRange(0, 1200));
}
});
});
}
+107
View File
@@ -0,0 +1,107 @@
import 'dart:math';
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:image/image.dart' as img;
import 'package:sd_kovinar/screens/yolo_detector.dart';
/// The model input as it was built before the speed-up: decode, crop the
/// centre square, resize (nearest), then pixel by pixel.
Float32List oldInput(Uint8List jpeg, int width, int height) {
final decoded = img.decodeImage(jpeg)!;
final size = min(decoded.width, decoded.height);
final square = img.copyCrop(decoded,
x: (decoded.width - size) ~/ 2,
y: (decoded.height - size) ~/ 2,
width: size,
height: size);
final resized = img.copyResize(square, width: width, height: height);
final input = Float32List(width * height * 3);
int i = 0;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
final p = resized.getPixel(x, y);
input[i++] = p.r / 255.0;
input[i++] = p.g / 255.0;
input[i++] = p.b / 255.0;
}
}
return input;
}
/// A photo-like JPEG: smooth shapes plus sensor noise, so it compresses like
/// a camera picture rather than pure noise.
Uint8List cameraLikeJpeg(int width, int height, {int seed = 1, int? orientation}) {
final rng = Random(seed);
final image = img.Image(width: width, height: height);
for (final p in image) {
final d = sqrt(pow(p.x - width / 2, 2) + pow(p.y - height / 2, 2));
final ring = (d ~/ 40).isEven ? 230 : 40;
p.setRgb((ring + rng.nextInt(20)).clamp(0, 255),
(ring * 0.9 + rng.nextInt(20)).clamp(0, 255), (p.x * 255 ~/ width));
}
img.fillRect(image, x1: 0, y1: 0, x2: 80, y2: 40, color: img.ColorRgb8(255, 0, 0));
if (orientation != null) image.exif.imageIfd.orientation = orientation;
return img.encodeJpg(image, quality: 92);
}
void main() {
group('model input with the Dart decoder is bit-identical to before', () {
for (final (w, h) in [(1280, 720), (720, 1280), (720, 720), (640, 640), (1000, 700)]) {
test('${w}x$h photo', () {
final jpeg = cameraLikeJpeg(w, h);
final now = inputFromPhoto(decodePhotoDart(jpeg), 640, 640);
expect(now, orderedEquals(oldInput(jpeg, 640, 640)));
});
}
});
test('saved square is the same as cropping the decoded photo', () {
final jpeg = cameraLikeJpeg(1280, 720);
final decoded = img.decodeImage(jpeg)!;
final expected = img.copyCrop(decoded, x: 280, y: 0, width: 720, height: 720);
final square = squareOf(decodePhotoDart(jpeg));
expect(square.width, 720);
expect(square.height, 720);
for (final (x, y) in [(0, 0), (359, 359), (719, 719), (100, 600)]) {
final a = square.getPixel(x, y), b = expected.getPixel(x, y);
expect([a.r, a.g, a.b], [b.r, b.g, b.b], reason: 'pixel $x,$y');
}
});
group('platform decoder', () {
testWidgets('applies the EXIF rotation like the Dart decoder', (tester) async {
// Stored 1280x720 with "rotate 90°": both decoders must give 720x1280
// with the red corner in the same place
final jpeg = cameraLikeJpeg(1280, 720, orientation: 6);
final dart = decodePhotoDart(jpeg);
final native = (await tester.runAsync(() => decodePhotoNative(jpeg)))!;
expect([native.width, native.height], [dart.width, dart.height]);
expect([native.width, native.height], [720, 1280]);
int red(Photo p, int x, int y) => p.pixels[(y * p.width + x) * p.channels];
// Red block was top-left before rotating 90° clockwise: now top-right
expect(red(native, native.width - 10, 10), greaterThan(200));
expect(red(dart, dart.width - 10, 10), greaterThan(200));
});
testWidgets('gives practically the same model input', (tester) async {
final jpeg = cameraLikeJpeg(1280, 720, seed: 7);
final dart = inputFromPhoto(decodePhotoDart(jpeg), 640, 640);
final decoded = await tester.runAsync(() => decodePhotoNative(jpeg));
final native = inputFromPhoto(decoded!, 640, 640);
var maxDiff = 0.0, sum = 0.0, differing = 0;
for (int i = 0; i < dart.length; i++) {
final d = (dart[i] - native[i]).abs();
if (d > 0) differing++;
sum += d;
maxDiff = max(maxDiff, d);
}
// ignore: avoid_print
print('platform vs Dart decoder: ${(differing / dart.length * 100).toStringAsFixed(1)}% '
'of values differ, mean ${(sum / dart.length * 255).toStringAsFixed(3)} / 255, '
'max ${(maxDiff * 255).round()} / 255');
// JPEG decoders may round a few values differently; nothing visible
expect(sum / dart.length * 255, lessThan(1.0));
});
});
}
+194
View File
@@ -0,0 +1,194 @@
#!/usr/bin/env python3
"""Fill the debug app on an emulator with realistic saved targets.
python3 tool/seed_debug_data.py # add the debug sessions
python3 tool/seed_debug_data.py --remove # remove them again
PACKAGE=si.sdkkovinar.app.test ANDROID_SERIAL=<device> python3 tool/seed_debug_data.py
Writes trainings and tournaments over 2025-2026 into the app's
app_flutter/saved_images/, in the same format preview_screen saves:
<session>/metadata.json {"isTournament", "createdAt"}
<session>/target_<y>-<m>-<d>_<h>-<m>-<s>.json {"date", "totalScore", "bulletCount", "bullets", "scores"}
Bullets are in the default target's 1200x1200 coordinates. Scoring and the
placement of hand-entered shots follow lib/utils/target_scoring.dart, so the
saved scores, the totals in Knjiga and the dots in the preview all agree.
camera - scattered around the centre, as detection finds them
manual - in the middle of the ring that gives the entered score, as the
missing-bullet dialog places them
mix - some of each; some targets also have a missed (unscored) shot
Needs a debug build (run-as) on the device adb talks to. Only touches the
session folders listed below; your other sessions stay as they are.
"""
import io
import json
import math
import os
import shlex
import random
import subprocess
import sys
import tarfile
import time
from datetime import datetime
# PACKAGE=si.sdkkovinar.app.test for the side-by-side test install;
# ANDROID_SERIAL=<id> picks the device when several are connected (adb reads it)
PACKAGE = os.environ.get('PACKAGE', 'si.sdkkovinar.app')
ADB = os.environ.get('ADB', os.path.expanduser('~/Android/Sdk/platform-tools/adb'))
ROOT = 'app_flutter/saved_images'
# Same geometry as lib/utils/target_scoring.dart (TargetScoring)
CENTER = (601, 598)
BULLET_RADIUS = 25
RINGS = [14, 70, 125, 180, 235, 290, 345, 400, 455, 510]
# (date, name, tournament, shots per target, targets, mode, spread)
# spread = how far camera shots scatter (px); it shrinks over time, so the
# graph shows a shooter getting better.
SESSIONS = [
('2025-06-12 18:10', 'Trening 2', False, 5, 3, 'camera', 190),
('2025-09-20 09:30', 'Liga – 1. krog', True, 5, 4, 'mix', 175),
('2025-12-05 18:40', 'Trening 3', False, 3, 2, 'manual', 170),
('2026-01-15 18:05', 'Trening 4', False, 5, 3, 'camera', 165),
('2026-02-22 10:00', 'Liga – 2. krog', True, 5, 6, 'mix', 160),
('2026-03-18 18:20', 'Trening 5', False, 5, 2, 'manual', 155),
('2026-04-09 17:45', 'Trening 6', False, 1, 5, 'camera', 150),
('2026-05-30 09:15', 'Regijsko prvenstvo', True, 5, 4, 'camera', 140),
('2026-07-04 18:30', 'Trening 7', False, 5, 3, 'mix', 135),
('2026-08-21 18:00', 'Trening 8', False, 3, 3, 'camera', 130),
('2026-09-13 09:45', 'Liga – 3. krog', True, 5, 5, 'mix', 125),
('2026-10-02 18:15', 'Trening 9', False, 5, 3, 'camera', 120),
('2026-10-16 18:25', 'Trening 10', False, 5, 4, 'manual', 115),
('2026-10-29 18:05', 'Trening 11', False, 5, 3, 'mix', 110),
('2026-11-05 18:10', 'Trening 12', False, 5, 3, 'camera', 105),
('2026-11-19 18:35', 'Trening 13', False, 5, 4, 'mix', 100),
('2026-11-22 09:30', 'Liga – 4. krog', True, 5, 5, 'camera', 95),
('2026-11-24 18:20', 'Trening 14', False, 5, 3, 'manual', 90),
]
def score(x, y):
edge = math.dist((x, y), CENTER) - BULLET_RADIUS
for i, r in enumerate(RINGS):
if edge <= r:
return 10 - i
return 0
def camera_bullet(rng, spread):
# Gaussian scatter, kept on the 1200x1200 target
while True:
x = rng.gauss(CENTER[0], spread)
y = rng.gauss(CENTER[1], spread)
if 30 < x < 1170 and 30 < y < 1170:
return x, y
def manual_bullet(rng, index, shots, value):
# Same placement as TargetScoring.positionFor: middle of the band that
# scores [value], measured to the bullet's edge
if value == 10:
edge = (-BULLET_RADIUS + RINGS[0]) / 2
elif value == 0:
edge = RINGS[-1] + 30
else:
edge = (RINGS[9 - value] + RINGS[10 - value]) / 2
distance = edge + BULLET_RADIUS
step = 360 / shots
angle = math.radians(step * index + (rng.random() - 0.5) * step * 0.5)
return CENTER[0] + distance * math.cos(angle), CENTER[1] + distance * math.sin(angle)
def target(rng, shots, mode, spread):
bullets, scores = [], []
# A missed shot now and then: counted in bulletCount, absent from bullets
missed = 1 if mode == 'mix' and shots > 1 and rng.random() < 0.35 else 0
for i in range(shots - missed):
manual = mode == 'manual' or (mode == 'mix' and rng.random() < 0.4)
if manual:
value = max(4, min(10, round(rng.gauss(10 - spread / 35, 1.5))))
x, y = manual_bullet(rng, i, shots, value)
else:
x, y = camera_bullet(rng, spread)
# Round first, then score what is actually saved
x, y = round(x, 2), round(y, 2)
s = score(x, y)
if manual:
assert s == value, f'hand-entered {value} placed where it scores {s}'
bullets.append({'x': x, 'y': y})
scores.append(s)
return {'bullets': bullets, 'scores': scores, 'totalScore': sum(scores),
'bulletCount': shots}
def build_tar():
rng = random.Random(2026) # same data every run
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode='w') as tar:
def add(path, data):
raw = json.dumps(data).encode()
info = tarfile.TarInfo(path)
info.size = len(raw)
info.mtime = time.time()
tar.addfile(info, io.BytesIO(raw))
for when, name, tournament, shots, count, mode, spread in SESSIONS:
start = datetime.strptime(when, '%Y-%m-%d %H:%M')
add(f'{name}/metadata.json',
{'isTournament': tournament, 'createdAt': start.isoformat()})
for n in range(count):
t = datetime.fromtimestamp(start.timestamp() + n * 7 * 60 + rng.randint(0, 120))
data = target(rng, shots, mode, spread)
# File name and date exactly as preview_screen _performSave writes them
file = f'target_{t.year}-{t.month}-{t.day}_{t.hour}-{t.minute}-{t.second}.json'
add(f'{name}/{file}', {'date': t.strftime('%d/%m/%Y'), **data})
print(f'{name:22} {file:40} {data["totalScore"]:3} / {shots} shots'
f' ({len(data["bullets"])} bullets, {mode})')
return buf.getvalue()
DEVICE_TAR = '/data/local/tmp/kovinar_seed.tar'
def run_as(command):
# adb joins the arguments into one device command line, so quote the script
return subprocess.run([ADB, 'shell', 'run-as', PACKAGE, 'sh', '-c', shlex.quote(command)],
capture_output=True, check=True)
def main():
names = ' '.join(f"'{s[1]}'" for s in SESSIONS)
if '--remove' in sys.argv:
run_as(f'cd {ROOT} && rm -rf {names}')
print('Removed the debug sessions.')
return
archive = build_tar()
# Data piped into run-as does not arrive, so go through the shared temp
# folder: adb pushes the archive there and the app unpacks it.
local = os.path.join(os.path.dirname(os.path.abspath(__file__)), '.seed.tar')
try:
with open(local, 'wb') as f:
f.write(archive)
subprocess.run([ADB, 'push', local, DEVICE_TAR], capture_output=True, check=True)
finally:
os.remove(local)
subprocess.run([ADB, 'shell', 'chmod', '644', DEVICE_TAR], check=True)
try:
# Replace earlier copies so re-running gives the same data
run_as(f'mkdir -p {ROOT} && cd {ROOT} && rm -rf {names} && tar xf {DEVICE_TAR}')
finally:
subprocess.run([ADB, 'shell', 'rm', '-f', DEVICE_TAR], check=True)
# adb does not always pass the device's exit code back: check the result
listing = run_as(f'ls {ROOT}').stdout.decode()
missing = [s[1] for s in SESSIONS if s[1] not in listing.splitlines()]
if missing:
sys.exit(f'\nPush failed, missing on the device: {", ".join(missing)}\n'
f'Is the debug build of {PACKAGE} installed?\n{listing.strip()}')
print(f'\nWrote {len(SESSIONS)} sessions. Reopen Knjiga (or pull to refresh) to see them.')
if __name__ == '__main__':
main()