Move example out of sky/packages to //examples

This commit is contained in:
Ian Fischer
2015-08-07 14:42:20 -07:00
parent 19fa9ae2d6
commit d44ed7dfc3
172 changed files with 51 additions and 51 deletions

17
examples/BUILD.gn Normal file
View File

@@ -0,0 +1,17 @@
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
group("examples") {
testonly = true
deps = [
"//examples/demo_launcher",
"//examples/fitness",
"//examples/game",
"//examples/mine_digger",
"//examples/rendering",
"//examples/stocks",
"//examples/widgets",
]
}

16
examples/README.md Normal file
View File

@@ -0,0 +1,16 @@
Sky Examples
============
This directory contains several examples of using Sky. Each of these is an
individual Dart application package. If you wish to run them with `sky_tool`
then you will want to run `pub get` inside their directory before running
`./packages/sky/sky_tool start`.
1. *Hello, world.* The [hello world app](hello_world) is a basic app that shows
the text "hello, world."
2. *Stocks.* The [stocks app](stocks) is an example of a typical mobile app
built using Sky. The app shows a list of all the stocks in the NASDAQ.
3. *Widgets.* The [widgets app](widgets) contains a number of Sky widgets so
you can experiment with them in a simple container.

View File

@@ -0,0 +1,149 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:sky/editing/input.dart';
import 'package:sky/theme/colors.dart' as colors;
import 'package:sky/theme/typography.dart' as typography;
import 'package:sky/widgets.dart';
class Field extends Component {
Field({
Key key,
this.inputKey,
this.icon,
this.placeholder
}): super(key: key);
final GlobalKey inputKey;
final String icon;
final String placeholder;
Widget build() {
return new Flex([
new Padding(
padding: const EdgeDims.symmetric(horizontal: 16.0),
child: new Icon(type: icon, size: 24)
),
new Flexible(
child: new Input(
key: inputKey,
placeholder: placeholder
)
)
],
direction: FlexDirection.horizontal
);
}
}
class AddressBookApp extends App {
Widget buildToolBar(Navigator navigator) {
return new ToolBar(
left: new IconButton(icon: "navigation/arrow_back"),
right: [new IconButton(icon: "navigation/check")]
);
}
Widget buildFloatingActionButton(Navigator navigator) {
return new FloatingActionButton(
child: new Icon(type: 'image/photo_camera', size: 24),
backgroundColor: Theme.of(this).accentColor,
onPressed: () {
showDialog(navigator, (navigator) {
return new Dialog(
title: new Text("Describe your picture"),
content: new ScrollableBlock([
new Field(inputKey: fillKey, icon: "editor/format_color_fill", placeholder: "Color"),
new Field(inputKey: emoticonKey, icon: "editor/insert_emoticon", placeholder: "Emotion"),
]),
onDismiss: navigator.pop,
actions: [
new FlatButton(
child: new Text('DISCARD'),
onPressed: navigator.pop
),
new FlatButton(
child: new Text('SAVE'),
onPressed: () {
navigator.pop();
}
),
]
);
});
}
);
}
static final GlobalKey nameKey = new GlobalKey();
static final GlobalKey phoneKey = new GlobalKey();
static final GlobalKey emailKey = new GlobalKey();
static final GlobalKey addressKey = new GlobalKey();
static final GlobalKey ringtoneKey = new GlobalKey();
static final GlobalKey noteKey = new GlobalKey();
static final GlobalKey fillKey = new GlobalKey();
static final GlobalKey emoticonKey = new GlobalKey();
Widget buildBody(Navigator navigator) {
return new Material(
child: new ScrollableBlock([
new AspectRatio(
aspectRatio: 16.0 / 9.0,
child: new Container(
decoration: new BoxDecoration(backgroundColor: colors.Purple[300])
)
),
new Field(inputKey: nameKey, icon: "social/person", placeholder: "Name"),
new Field(inputKey: phoneKey, icon: "communication/phone", placeholder: "Phone"),
new Field(inputKey: emailKey, icon: "communication/email", placeholder: "Email"),
new Field(inputKey: addressKey, icon: "maps/place", placeholder: "Address"),
new Field(inputKey: ringtoneKey, icon: "av/volume_up", placeholder: "Ringtone"),
new Field(inputKey: noteKey, icon: "content/add", placeholder: "Add note"),
])
);
}
Widget buildMain(Navigator navigator) {
return new Scaffold(
toolbar: buildToolBar(navigator),
body: buildBody(navigator),
floatingActionButton: buildFloatingActionButton(navigator)
);
}
NavigationState _navigationState;
void initState() {
_navigationState = new NavigationState([
new Route(
name: '/',
builder: (navigator, route) => buildMain(navigator)
),
]);
super.initState();
}
Widget build() {
ThemeData theme = new ThemeData(
brightness: ThemeBrightness.light,
primarySwatch: colors.Teal,
accentColor: colors.PinkAccent[100]
);
return new Theme(
data: theme,
child: new DefaultTextStyle(
style: typography.error, // if you see this, you've forgotten to correctly configure the text style!
child: new TaskDescription(
label: 'Address Book',
child: new Navigator(_navigationState)
)
)
);
}
}
void main() {
runApp(new AddressBookApp());
}

View File

@@ -0,0 +1,28 @@
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import("//sky/build/sky_app.gni")
sky_app("demo_launcher") {
main_dart = "lib/main.dart"
manifest = "sky.yaml"
if (is_android) {
apk_name = "SkyDemo"
bundles = [
"//examples/fitness",
"//examples/game",
"//examples/mine_digger",
"//examples/rendering:interactive_flex",
"//examples/stocks",
"//examples/widgets:cards",
]
deps = [
"//examples/demo_launcher/apk:java",
"//examples/demo_launcher/apk:resources",
]
}
}

View File

@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright 2015 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="org.domokit.sky.demo" android:versionCode="22" android:versionName="0.0.22">
<uses-sdk android:minSdkVersion="14" android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-feature android:name="android.hardware.sensor.accelerometer" android:required="true" />
<application android:icon="@mipmap/ic_launcher" android:label="Sky" android:name="SkyDemoApplication">
<activity android:configChanges="orientation|keyboardHidden|keyboard|screenSize" android:documentLaunchMode="always" android:hardwareAccelerated="true" android:launchMode="standard" android:name="SkyDemoActivity" android:theme="@android:style/Theme.Black.NoTitleBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

View File

@@ -0,0 +1,27 @@
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
assert(is_android)
import("//build/config/android/config.gni")
import("//build/config/android/rules.gni")
android_library("java") {
java_files = [
"org/domokit/sky/demo/SkyDemoActivity.java",
"org/domokit/sky/demo/SkyDemoApplication.java",
]
deps = [
"//base:base_java",
"//mojo/public/java:bindings",
"//mojo/public/java:system",
"//sky/shell:java",
]
}
android_resources("resources") {
resource_dirs = [ "res" ]
android_manifest = "AndroidManifest.xml"
}

View File

@@ -0,0 +1,8 @@
Icon image comes from:
https://openclipart.org/detail/30073/tango%20weather%20few%20clouds
and is public domain.
Icon resources were generated using:
http://romannurik.github.io/AndroidAssetStudio/icons-launcher.html
which produces art under CC 3.0:
http://creativecommons.org/licenses/by/3.0/

View File

@@ -0,0 +1,31 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.domokit.sky.demo;
import android.content.Intent;
import org.domokit.sky.shell.SkyActivity;
/**
* Main activity for SkyDemo.
*/
public class SkyDemoActivity extends SkyActivity {
@Override
protected void onSkyReady() {
Intent intent = getIntent();
String action = intent.getAction();
if (Intent.ACTION_VIEW.equals(action)) {
String bundleName = intent.getStringExtra("bundleName");
if (bundleName != null && loadBundleByName(bundleName)) {
return;
}
loadUrl(intent.getDataString());
return;
}
super.onSkyReady();
}
}

View File

@@ -0,0 +1,30 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.domokit.sky.demo;
import android.content.Context;
import org.domokit.sky.shell.ResourceExtractor;
import org.domokit.sky.shell.SkyApplication;
/**
* SkyDemo implementation of {@link android.app.Application}
*/
public class SkyDemoApplication extends SkyApplication {
private static final String[] DEMO_RESOURCES = {
"cards.skyx",
"fitness.skyx",
"game.skyx",
"interactive_flex.skyx",
"mine_digger.skyx",
"stocks.skyx",
};
@Override
protected void onBeforeResourceExtraction(ResourceExtractor extractor) {
super.onBeforeResourceExtraction(extractor);
extractor.addResources(DEMO_RESOURCES);
}
}

View File

@@ -0,0 +1 @@
First version published to production from our service account.

View File

@@ -0,0 +1,7 @@
Fixed a common startup crasher on Android systems before 5.0
Fixed to not draw behind the status bar on before Android 5.0
First release from new http://github.com/domokit/sky_engine repository.
I suspect there may still be some crashes we will be fixing
in the coming days as we set up systems to catch these crashes
before they are shipped to users.

View File

@@ -0,0 +1 @@
Fixes crash on Nexus 6

View File

@@ -0,0 +1,3 @@
Huge speed improvements in Asteroids.
Fixed startup crash on many devices.
Lots of various other widget fixes.

View File

@@ -0,0 +1,2 @@
- No longer crashes on Android M Developer Preview
- 3x scrolling speed improvement.

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 280 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

View File

@@ -0,0 +1,210 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:sky/mojo/activity.dart' as activity;
import 'package:sky/mojo/asset_bundle.dart';
import 'package:sky/painting/box_painter.dart';
import 'package:sky/theme/colors.dart' as colors;
import 'package:sky/theme/typography.dart' as typography;
import 'package:sky/widgets.dart';
AssetBundle _initBundle() {
if (rootBundle != null)
return rootBundle;
const String _kAssetBase = '..';
return new NetworkAssetBundle(Uri.base.resolve(_kAssetBase));
}
final AssetBundle _bundle = _initBundle();
EventDisposition launch(String relativeUrl, String bundle) {
// TODO(eseidel): This is a hack to keep non-skyx examples working for now:
Uri productionBase = Uri.parse(
'https://domokit.github.io/example/demo_launcher/lib/main.dart');
Uri base = rootBundle == null ? Uri.base : productionBase;
Uri url = base.resolve(relativeUrl);
activity.ComponentName component = new activity.ComponentName()
..packageName = 'org.domokit.sky.demo'
..className = 'org.domokit.sky.demo.SkyDemoActivity';
activity.Intent intent = new activity.Intent()
..action = 'android.intent.action.VIEW'
..component = component
..flags = activity.MULTIPLE_TASK | activity.NEW_DOCUMENT
..url = url.toString();
if (bundle != null) {
activity.StringExtra extra = new activity.StringExtra()
..name = 'bundleName'
..value = bundle;
intent.stringExtras = [extra];
}
activity.startActivity(intent);
return EventDisposition.processed;
}
class SkyDemo {
SkyDemo({
name,
this.href,
this.bundle,
this.description,
this.textTheme,
this.decoration
}) : name = name, key = new Key(name);
final String name;
final Key key;
final String href;
final String bundle;
final String description;
final typography.TextTheme textTheme;
final BoxDecoration decoration;
}
List<SkyDemo> demos = [
new SkyDemo(
name: 'Stocks',
href: '../../stocks/lib/main.dart',
bundle: 'stocks.skyx',
description: 'Multi-screen app with scrolling list',
textTheme: typography.black,
decoration: new BoxDecoration(
backgroundImage: new BackgroundImage(
image: _bundle.loadImage('assets/stocks_thumbnail.png'),
fit: BackgroundFit.cover
)
)
),
new SkyDemo(
name: 'Asteroids',
href: '../../game/main.dart',
bundle: 'game.skyx',
description: '2D game using sprite sheets',
textTheme: typography.white,
decoration: new BoxDecoration(
backgroundImage: new BackgroundImage(
image: _bundle.loadImage('assets/game_thumbnail.png'),
fit: BackgroundFit.cover
)
)
),
new SkyDemo(
name: 'Fitness',
href: '../../fitness/lib/main.dart',
bundle: 'fitness.skyx',
description: 'Track progress towards healthy goals',
textTheme: typography.white,
decoration: new BoxDecoration(
backgroundColor: colors.Indigo[500]
)
),
new SkyDemo(
name: 'Swipe Away',
href: '../../widgets/card_collection.dart',
bundle: 'cards.skyx',
description: 'Infinite list of swipeable cards',
textTheme: typography.white,
decoration: new BoxDecoration(
backgroundColor: colors.RedAccent[200]
)
),
new SkyDemo(
name: 'Interactive Text',
href: '../../rendering/interactive_flex.dart',
bundle: 'interactive_flex.skyx',
description: 'Swipe to reflow the app',
textTheme: typography.white,
decoration: new BoxDecoration(
backgroundColor: const Color(0xFF0081C6)
)
),
// new SkyDemo(
// 'Touch Demo', '../../rendering/touch_demo.dart', 'Simple example showing handling of touch events at a low level'),
new SkyDemo(
name: 'Minedigger Game',
href: '../../mine_digger/lib/main.dart',
bundle: 'mine_digger.skyx',
description: 'Clone of the classic Minesweeper game',
textTheme: typography.white,
decoration: new BoxDecoration(
backgroundColor: colors.black
)
),
// TODO(jackson): This doesn't seem to be working
// new SkyDemo('Licenses', 'LICENSES.sky'),
];
const double kCardHeight = 120.0;
const EdgeDims kListPadding = const EdgeDims.all(4.0);
class DemoList extends Component {
Widget buildCardContents(SkyDemo demo) {
return new Container(
decoration: demo.decoration,
child: new InkWell(
child: new Container(
margin: const EdgeDims.only(top: 24.0, left: 24.0),
child: new Flex([
new Text(demo.name, style: demo.textTheme.title),
new Flexible(
child: new Text(demo.description, style: demo.textTheme.subhead)
)
],
direction: FlexDirection.vertical,
alignItems: FlexAlignItems.start)
)
)
);
}
Widget buildDemo(SkyDemo demo) {
return new Listener(
key: demo.key,
onGestureTap: (_) => launch(demo.href, demo.bundle),
child: new Container(
height: kCardHeight,
child: new Card(
child: buildCardContents(demo)
)
)
);
}
Widget build() {
return new ScrollableList<SkyDemo>(
items: demos,
itemHeight: kCardHeight,
itemBuilder: buildDemo,
padding: kListPadding
);
}
}
class SkyHome extends App {
Widget build() {
return new Theme(
data: new ThemeData(
brightness: ThemeBrightness.light,
primarySwatch: colors.Teal
),
child: new TaskDescription(
label: 'Sky Demos',
child: new Scaffold(
toolbar: new ToolBar(center: new Text('Sky Demos')),
body: new Material(
type: MaterialType.canvas,
child: new DemoList()
)
)
)
);
}
}
void main() {
runApp(new SkyHome());
}

View File

@@ -0,0 +1,9 @@
name: demo_launcher
dependencies:
sky: any
sky_tools: any
dependency_overrides:
material_design_icons:
path: ../../sky/packages/material_design_icons
sky:
path: ../../sky/packages/sky

View File

@@ -0,0 +1,4 @@
assets:
- assets/game_thumbnail.png
- assets/sector_thumbnail.png
- assets/stocks_thumbnail.png

18
examples/fitness/BUILD.gn Normal file
View File

@@ -0,0 +1,18 @@
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import("//sky/build/sky_app.gni")
sky_app("fitness") {
main_dart = "lib/main.dart"
manifest = "sky.yaml"
if (is_android) {
apk_name = "Fitness"
deps = [
"//examples/fitness/apk:resources",
]
}
}

View File

@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright 2015 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.domokit.fitness" android:versionCode="1" android:versionName="0.0.1">
<uses-sdk android:minSdkVersion="14" android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET"/>
<application android:icon="@mipmap/ic_launcher" android:name="org.domokit.sky.shell.SkyApplication" android:label="Fitness">
<activity android:name="org.domokit.sky.shell.SkyActivity"
android:launchMode="singleTask"
android:theme="@android:style/Theme.Black.NoTitleBar"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize"
android:hardwareAccelerated="true">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>

View File

@@ -0,0 +1,14 @@
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
assert(is_android)
import("//build/config/android/config.gni")
import("//build/config/android/rules.gni")
android_resources("resources") {
resource_dirs = [ "res" ]
android_manifest = "AndroidManifest.xml"
}

View File

@@ -0,0 +1,10 @@
Icon image comes from:
https://openclipart.org/detail/22309/apple-icon
and is public domain.
Icon resources were generated using:
http://romannurik.github.io/AndroidAssetStudio/icons-launcher.html
with settings:
http://romannurik.github.io/AndroidAssetStudio/icons-launcher.html#foreground.type=image&foreground.space.trim=1&foreground.space.pad=0&foreColor=607d8b%2C0&crop=0&backgroundShape=none&backColor=ffffff%2C100&effects=none
which produces art under CC 3.0:
http://creativecommons.org/licenses/by/3.0/

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

View File

@@ -0,0 +1,296 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
part of fitness;
class FitnessItemList extends Component {
FitnessItemList({ Key key, this.items, this.onDismissed }) : super(key: key) {
assert(items != null);
assert(onDismissed != null);
}
final List<FitnessItem> items;
final FitnessItemHandler onDismissed;
Widget build() {
return new Material(
type: MaterialType.canvas,
child: new ScrollableList<FitnessItem>(
padding: const EdgeDims.all(4.0),
items: items,
itemHeight: kFitnessItemHeight,
itemBuilder: (item) => item.toRow(onDismissed: onDismissed)
)
);
}
}
class DialogMenuItem extends ButtonBase {
DialogMenuItem(this.children, { Key key, this.onPressed }) : super(key: key);
List<Widget> children;
Function onPressed;
void syncFields(DialogMenuItem source) {
children = source.children;
onPressed = source.onPressed;
super.syncFields(source);
}
Widget buildContent() {
return new Listener(
onGestureTap: (_) {
if (onPressed != null)
onPressed();
},
child: new Container(
height: 48.0,
child: new InkWell(
child: new Padding(
padding: const EdgeDims.symmetric(horizontal: 16.0),
child: new Flex(children)
)
)
)
);
}
}
class FeedFragment extends StatefulComponent {
FeedFragment({ this.navigator, this.userData, this.onItemCreated, this.onItemDeleted });
Navigator navigator;
List<FitnessItem> userData;
FitnessItemHandler onItemCreated;
FitnessItemHandler onItemDeleted;
FitnessMode _fitnessMode = FitnessMode.feed;
void initState() {
// if (debug)
// new Timer(new Duration(seconds: 1), dumpState);
super.initState();
}
void syncFields(FeedFragment source) {
navigator = source.navigator;
userData = source.userData;
onItemCreated = source.onItemCreated;
onItemDeleted = source.onItemDeleted;
}
bool _isShowingSnackBar = false;
EventDisposition _handleFitnessModeChange(FitnessMode value) {
setState(() {
_fitnessMode = value;
_drawerShowing = false;
});
return EventDisposition.processed;
}
Drawer buildDrawer() {
if (_drawerStatus == AnimationStatus.dismissed)
return null;
return new Drawer(
showing: _drawerShowing,
level: 3,
onDismissed: _handleDrawerDismissed,
navigator: navigator,
children: [
new DrawerHeader(children: [new Text('Fitness')]),
new DrawerItem(
icon: 'action/list',
onPressed: () => _handleFitnessModeChange(FitnessMode.feed),
selected: _fitnessMode == FitnessMode.feed,
children: [new Text('Feed')]),
new DrawerItem(
icon: 'action/assessment',
onPressed: () => _handleFitnessModeChange(FitnessMode.chart),
selected: _fitnessMode == FitnessMode.chart,
children: [new Text('Chart')]),
new DrawerDivider(),
new DrawerItem(
icon: 'action/settings',
onPressed: _handleShowSettings,
children: [new Text('Settings')]),
new DrawerItem(
icon: 'action/help',
children: [new Text('Help & Feedback')])
]
);
}
bool _drawerShowing = false;
AnimationStatus _drawerStatus = AnimationStatus.dismissed;
void _handleOpenDrawer() {
setState(() {
_drawerShowing = true;
_drawerStatus = AnimationStatus.forward;
});
}
void _handleDrawerDismissed() {
setState(() {
_drawerStatus = AnimationStatus.dismissed;
});
}
EventDisposition _handleShowSettings() {
navigator.pop();
navigator.pushNamed('/settings');
return EventDisposition.processed;
}
// TODO(jackson): We should be localizing
String get fitnessModeTitle {
switch(_fitnessMode) {
case FitnessMode.feed: return "Feed";
case FitnessMode.chart: return "Chart";
}
}
Widget buildToolBar() {
return new ToolBar(
left: new IconButton(
icon: "navigation/menu",
onPressed: _handleOpenDrawer),
center: new Text(fitnessModeTitle)
);
}
FitnessItem _undoItem;
void _handleItemDismissed(FitnessItem item) {
onItemDeleted(item);
setState(() {
_undoItem = item;
_isShowingSnackBar = true;
});
}
Widget buildBody() {
TextStyle style = Theme.of(this).text.title;
switch (_fitnessMode) {
case FitnessMode.feed:
if (userData.length > 0)
return new FitnessItemList(
items: userData,
onDismissed: _handleItemDismissed
);
return new Material(
type: MaterialType.canvas,
child: new Flex(
[new Text("No data yet.\nAdd some!", style: style)],
justifyContent: FlexJustifyContent.center
)
);
case FitnessMode.chart:
return new Material(
type: MaterialType.canvas,
child: new Flex([
new Text("Charts are coming soon!", style: style)
], justifyContent: FlexJustifyContent.center)
);
}
}
void _handleUndo() {
onItemCreated(_undoItem);
setState(() {
_undoItem = null;
_isShowingSnackBar = false;
});
}
Widget buildSnackBar() {
if (!_isShowingSnackBar)
return null;
return new SnackBar(
showing: _isShowingSnackBar,
content: new Text("Item deleted."),
actions: [new SnackBarAction(label: "UNDO", onPressed: _handleUndo)]
);
}
void _handleActionButtonPressed() {
showDialog(navigator, (navigator) => new AddItemDialog(navigator)).then((routeName) {
if (routeName != null)
navigator.pushNamed(routeName);
});
}
Widget buildFloatingActionButton() {
switch (_fitnessMode) {
case FitnessMode.feed:
return new FloatingActionButton(
child: new Icon(type: 'content/add', size: 24),
onPressed: _handleActionButtonPressed
);
case FitnessMode.chart:
return null;
}
}
Widget build() {
return new Scaffold(
toolbar: buildToolBar(),
body: buildBody(),
snackBar: buildSnackBar(),
floatingActionButton: buildFloatingActionButton(),
drawer: buildDrawer()
);
}
}
class AddItemDialog extends StatefulComponent {
AddItemDialog(this.navigator);
Navigator navigator;
void syncFields(AddItemDialog source) {
this.navigator = source.navigator;
}
String _addItemRoute;
void _handleAddItemRouteChanged(String routeName) {
setState(() {
_addItemRoute = routeName;
});
}
Widget build() {
// TODO(jackson): Internationalize
Map<String, String> labels = {
'/meals/new': 'Eat',
'/measurements/new': 'Measure',
};
List<Widget> menuItems = [];
for(String routeName in labels.keys) {
menuItems.add(new DialogMenuItem([
new Flexible(child: new Text(labels[routeName])),
new Radio(value: routeName, groupValue: _addItemRoute, onChanged: _handleAddItemRouteChanged),
], onPressed: () => _handleAddItemRouteChanged(routeName)));
}
return new Dialog(
title: new Text("What are you doing?"),
content: new ScrollableBlock(menuItems),
onDismiss: navigator.pop,
actions: [
new FlatButton(
child: new Text('CANCEL'),
onPressed: navigator.pop
),
new FlatButton(
child: new Text('ADD'),
onPressed: () {
navigator.pop(_addItemRoute);
}
),
]
);
}
}

View File

@@ -0,0 +1,48 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
part of fitness;
typedef void FitnessItemHandler(FitnessItem item);
const double kFitnessItemHeight = 79.0;
abstract class FitnessItem {
FitnessItem({ this.when }) {
assert(when != null);
}
final DateTime when;
// TODO(jackson): Internationalize
String get displayDate => "${when.year.toString()}-${when.month.toString().padLeft(2,'0')}-${when.day.toString().padLeft(2,'0')}";
FitnessItemRow toRow({ FitnessItemHandler onDismissed });
}
abstract class FitnessItemRow extends Component {
FitnessItemRow({ FitnessItem item, this.onDismissed })
: this.item = item,
super(key: new Key(item.when.toString())) {
assert(onDismissed != null);
}
final FitnessItem item;
final FitnessItemHandler onDismissed;
Widget buildContent();
Widget build() {
return new Dismissable(
onDismissed: () => onDismissed(item),
child: new Card(
child: new Container(
height: kFitnessItemHeight,
padding: const EdgeDims.all(8.0),
child: buildContent()
)
)
);
}
}

View File

@@ -0,0 +1,8 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
part of fitness;
enum FitnessMode { feed, chart }
enum BackupMode { enabled, disabled }

View File

@@ -0,0 +1,109 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
library fitness;
import 'package:sky/editing/input.dart';
import 'package:sky/painting/text_style.dart';
import 'package:sky/theme/colors.dart' as colors;
import 'package:sky/widgets.dart';
part 'feed.dart';
part 'fitness_item.dart';
part 'fitness_types.dart';
part 'meal.dart';
part 'measurement.dart';
part 'settings.dart';
class FitnessApp extends App {
NavigationState _navigationState;
final List<FitnessItem> _userData = [
new Measurement(weight: 180.0, when: new DateTime.now().add(const Duration(days: -1))),
new Measurement(weight: 160.0, when: new DateTime.now()),
];
void initState() {
_navigationState = new NavigationState([
new Route(
name: '/',
builder: (navigator, route) => new FeedFragment(
navigator: navigator,
userData: _userData,
onItemCreated: _handleItemCreated,
onItemDeleted: _handleItemDeleted
)
),
new Route(
name: '/meals/new',
builder: (navigator, route) => new MealFragment(
navigator: navigator,
onCreated: _handleItemCreated
)
),
new Route(
name: '/measurements/new',
builder: (navigator, route) => new MeasurementFragment(
navigator: navigator,
onCreated: _handleItemCreated
)
),
new Route(
name: '/settings',
builder: (navigator, route) => new SettingsFragment(navigator, backupSetting, settingsUpdater)
),
]);
super.initState();
}
void onBack() {
if (_navigationState.hasPrevious()) {
setState(() {
_navigationState.pop();
});
} else {
super.onBack();
}
}
void _handleItemCreated(FitnessItem item) {
setState(() {
_userData.add(item);
_userData.sort((a, b) => a.when.compareTo(b.when));
});
}
void _handleItemDeleted(FitnessItem item) {
setState(() {
_userData.remove(item);
});
}
BackupMode backupSetting = BackupMode.disabled;
void settingsUpdater({ BackupMode backup }) {
setState(() {
if (backup != null)
backupSetting = backup;
});
}
Widget build() {
return new Theme(
data: new ThemeData(
brightness: ThemeBrightness.light,
primarySwatch: colors.Indigo,
accentColor: colors.PinkAccent[200]
),
child: new TaskDescription(
label: 'Fitness',
child: new Navigator(_navigationState)
)
);
}
}
void main() {
runApp(new FitnessApp());
}

View File

@@ -0,0 +1,114 @@
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
part of fitness;
class Meal extends FitnessItem {
Meal({ DateTime when, this.description }) : super(when: when);
final String description;
FitnessItemRow toRow({ FitnessItemHandler onDismissed }) {
return new MealRow(meal: this, onDismissed: onDismissed);
}
}
class MealRow extends FitnessItemRow {
MealRow({ Meal meal, FitnessItemHandler onDismissed })
: super(item: meal, onDismissed: onDismissed);
Widget buildContent() {
Meal meal = item;
List<Widget> children = [
new Flexible(
child: new Text(
meal.description,
style: const TextStyle(textAlign: TextAlign.right)
)
),
new Flexible(
child: new Text(
meal.displayDate,
style: Theme.of(this).text.caption.copyWith(textAlign: TextAlign.right)
)
)
];
return new Flex(
children,
alignItems: FlexAlignItems.baseline,
textBaseline: DefaultTextStyle.of(this).textBaseline
);
}
}
class MealFragment extends StatefulComponent {
MealFragment({ this.navigator, this.onCreated });
Navigator navigator;
FitnessItemHandler onCreated;
void syncFields(MealFragment source) {
navigator = source.navigator;
onCreated = source.onCreated;
}
String _description = "";
EventDisposition _handleSave() {
onCreated(new Meal(when: new DateTime.now(), description: _description));
navigator.pop();
return EventDisposition.processed;
}
Widget buildToolBar() {
return new ToolBar(
left: new IconButton(
icon: "navigation/close",
onPressed: navigator.pop),
center: new Text('New Meal'),
right: [new InkWell(
child: new Listener(
onGestureTap: (_) => _handleSave(),
child: new Text('SAVE')
)
)]
);
}
void _handleDescriptionChanged(String description) {
setState(() {
_description = description;
});
}
static final GlobalKey descriptionKey = new GlobalKey();
Widget buildBody() {
Meal meal = new Meal(when: new DateTime.now());
return new Material(
type: MaterialType.canvas,
child: new ScrollableViewport(
child: new Container(
padding: const EdgeDims.all(20.0),
child: new Block([
new Text(meal.displayDate),
new Input(
key: descriptionKey,
placeholder: 'Describe meal',
onChanged: _handleDescriptionChanged
),
])
)
)
);
}
Widget build() {
return new Scaffold(
toolbar: buildToolBar(),
body: buildBody()
);
}
}

View File

@@ -0,0 +1,135 @@
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
part of fitness;
class Measurement extends FitnessItem {
Measurement({ DateTime when, this.weight }) : super(when: when);
final double weight;
// TODO(jackson): Internationalize
String get displayWeight => "${weight.toStringAsFixed(2)} lbs";
FitnessItemRow toRow({ FitnessItemHandler onDismissed }) {
return new MeasurementRow(measurement: this, onDismissed: onDismissed);
}
}
class MeasurementRow extends FitnessItemRow {
MeasurementRow({ Measurement measurement, FitnessItemHandler onDismissed })
: super(item: measurement, onDismissed: onDismissed);
Widget buildContent() {
Measurement measurement = item;
List<Widget> children = [
new Flexible(
child: new Text(
measurement.displayWeight,
style: const TextStyle(textAlign: TextAlign.right)
)
),
new Flexible(
child: new Text(
measurement.displayDate,
style: Theme.of(this).text.caption.copyWith(textAlign: TextAlign.right)
)
)
];
return new Flex(
children,
alignItems: FlexAlignItems.baseline,
textBaseline: DefaultTextStyle.of(this).textBaseline
);
}
}
class MeasurementFragment extends StatefulComponent {
MeasurementFragment({ this.navigator, this.onCreated });
Navigator navigator;
FitnessItemHandler onCreated;
void syncFields(MeasurementFragment source) {
navigator = source.navigator;
onCreated = source.onCreated;
}
String _weight = "";
String _errorMessage = null;
EventDisposition _handleSave() {
double parsedWeight;
try {
parsedWeight = double.parse(_weight);
} on FormatException {
setState(() {
_errorMessage = "Save failed";
});
return EventDisposition.processed;
}
onCreated(new Measurement(when: new DateTime.now(), weight: parsedWeight));
navigator.pop();
return EventDisposition.processed;
}
Widget buildToolBar() {
return new ToolBar(
left: new IconButton(
icon: "navigation/close",
onPressed: navigator.pop),
center: new Text('New Measurement'),
right: [new InkWell(
child: new Listener(
onGestureTap: (_) => _handleSave(),
child: new Text('SAVE')
)
)]
);
}
void _handleWeightChanged(String weight) {
setState(() {
_weight = weight;
});
}
static final GlobalKey weightKey = new GlobalKey();
Widget buildBody() {
Measurement measurement = new Measurement(when: new DateTime.now());
return new Material(
type: MaterialType.canvas,
child: new ScrollableViewport(
child: new Container(
padding: const EdgeDims.all(20.0),
child: new Block([
new Text(measurement.displayDate),
new Input(
key: weightKey,
placeholder: 'Enter weight',
keyboardType: KeyboardType_NUMBER,
onChanged: _handleWeightChanged
),
])
)
)
);
}
Widget buildSnackBar() {
if (_errorMessage == null)
return null;
return new SnackBar(content: new Text(_errorMessage));
}
Widget build() {
return new Scaffold(
toolbar: buildToolBar(),
body: buildBody(),
snackBar: buildSnackBar()
);
}
}

View File

@@ -0,0 +1,67 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
part of fitness;
typedef void SettingsUpdater({
BackupMode backup
});
class SettingsFragment extends Component {
SettingsFragment(this.navigator, this.backup, this.updater);
final Navigator navigator;
final BackupMode backup;
final SettingsUpdater updater;
void _handleBackupChanged(bool value) {
if (updater != null)
updater(backup: value ? BackupMode.enabled : BackupMode.disabled);
}
Widget buildToolBar() {
return new ToolBar(
left: new IconButton(
icon: "navigation/arrow_back",
onPressed: navigator.pop),
center: new Text('Settings')
);
}
Widget buildSettingsPane() {
return new Material(
type: MaterialType.canvas,
child: new ScrollableViewport(
child: new Container(
padding: const EdgeDims.symmetric(vertical: 20.0),
child: new Block([
new DrawerItem(
onPressed: () { _handleBackupChanged(!(backup == BackupMode.enabled)); },
children: [
new Flexible(child: new Text('Back up data to the cloud')),
new Switch(value: backup == BackupMode.enabled, onChanged: _handleBackupChanged)
]
),
new DrawerItem(
children: [
new Flex([
new Text('Height'),
new Text("6'2\"", style: Theme.of(this).text.caption),
], direction: FlexDirection.vertical, alignItems: FlexAlignItems.start)
]
),
])
)
)
);
}
Widget build() {
return new Scaffold(
toolbar: buildToolBar(),
body: buildSettingsPane()
);
}
}

10
examples/fitness/sky.yaml Normal file
View File

@@ -0,0 +1,10 @@
material-design-icons:
- name: action/assessment
- name: action/help
- name: action/settings
- name: content/add
- name: maps/directions_run
- name: navigation/arrow_back
- name: navigation/menu
- name: navigation/more_vert
- name: av/stop

28
examples/game/BUILD.gn Normal file
View File

@@ -0,0 +1,28 @@
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import("//sky/build/sky_app.gni")
sky_app("game") {
main_dart = "main.dart"
manifest = "sky.yaml"
if (is_android) {
apk_name = "Asteroids"
deps = [
"//examples/game/apk:resources",
]
} else if (is_ios) {
info_plist = "ios/Info.plist"
launcher_resources = [
"assets/Icon.png",
"assets/Icon@2x.png",
"ios/LaunchScreen.storyboardc",
]
} else if (is_mac) {
info_plist = "mac/Info.plist"
xibs = [ "mac/sky_mac.xib" ]
}
}

2
examples/game/README.md Normal file
View File

@@ -0,0 +1,2 @@
Assets for this game are taken from Galactic Guardian:
https://github.com/slembcke/GalacticGuardian.spritebuilder

View File

@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright 2015 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.domokit.asteroids">
<uses-sdk android:minSdkVersion="14" android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET"/>
<application android:icon="@mipmap/ic_launcher" android:name="org.domokit.sky.shell.SkyApplication" android:label="Asteroids">
<activity android:name="org.domokit.sky.shell.SkyActivity"
android:launchMode="singleTask"
android:theme="@android:style/Theme.Black.NoTitleBar"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize"
android:hardwareAccelerated="true">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>

View File

@@ -0,0 +1,12 @@
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
assert(is_android)
import("//build/config/android/config.gni")
import("//build/config/android/rules.gni")
android_resources("resources") {
resource_dirs = [ "res" ]
android_manifest = "AndroidManifest.xml"
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

View File

@@ -0,0 +1,147 @@
{"frames": [
{
"filename": "bar_shield.png",
"frame": {"x":2,"y":954,"w":412,"h":100},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":412,"h":100},
"sourceSize": {"w":412,"h":100},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "bar_shield_fill.png",
"frame": {"x":2,"y":1156,"w":320,"h":72},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":320,"h":72},
"sourceSize": {"w":320,"h":72},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "btn_play_down.png",
"frame": {"x":2,"y":484,"w":468,"h":468},
"rotated": false,
"trimmed": true,
"spriteSourceSize": {"x":2,"y":16,"w":468,"h":468},
"sourceSize": {"w":472,"h":484},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "btn_play_up.png",
"frame": {"x":2,"y":2,"w":468,"h":480},
"rotated": false,
"trimmed": true,
"spriteSourceSize": {"x":2,"y":4,"w":468,"h":480},
"sourceSize": {"w":472,"h":484},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "number_0.png",
"frame": {"x":416,"y":954,"w":38,"h":63},
"rotated": false,
"trimmed": true,
"spriteSourceSize": {"x":23,"y":22,"w":38,"h":63},
"sourceSize": {"w":84,"h":107},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "number_1.png",
"frame": {"x":324,"y":1221,"w":16,"h":57},
"rotated": true,
"trimmed": true,
"spriteSourceSize": {"x":45,"y":25,"w":16,"h":57},
"sourceSize": {"w":84,"h":107},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "number_2.png",
"frame": {"x":366,"y":1056,"w":38,"h":63},
"rotated": false,
"trimmed": true,
"spriteSourceSize": {"x":23,"y":22,"w":38,"h":63},
"sourceSize": {"w":84,"h":107},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "number_3.png",
"frame": {"x":364,"y":1156,"w":35,"h":63},
"rotated": false,
"trimmed": true,
"spriteSourceSize": {"x":26,"y":22,"w":35,"h":63},
"sourceSize": {"w":84,"h":107},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "number_4.png",
"frame": {"x":416,"y":1019,"w":38,"h":57},
"rotated": false,
"trimmed": true,
"spriteSourceSize": {"x":23,"y":25,"w":38,"h":57},
"sourceSize": {"w":84,"h":107},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "number_5.png",
"frame": {"x":324,"y":1156,"w":38,"h":63},
"rotated": false,
"trimmed": true,
"spriteSourceSize": {"x":23,"y":22,"w":38,"h":63},
"sourceSize": {"w":84,"h":107},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "number_6.png",
"frame": {"x":406,"y":1078,"w":38,"h":63},
"rotated": true,
"trimmed": true,
"spriteSourceSize": {"x":23,"y":22,"w":38,"h":63},
"sourceSize": {"w":84,"h":107},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "number_7.png",
"frame": {"x":401,"y":1198,"w":35,"h":60},
"rotated": true,
"trimmed": true,
"spriteSourceSize": {"x":26,"y":22,"w":35,"h":60},
"sourceSize": {"w":84,"h":107},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "number_8.png",
"frame": {"x":406,"y":1118,"w":38,"h":63},
"rotated": true,
"trimmed": true,
"spriteSourceSize": {"x":23,"y":22,"w":38,"h":63},
"sourceSize": {"w":84,"h":107},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "number_9.png",
"frame": {"x":401,"y":1158,"w":38,"h":63},
"rotated": true,
"trimmed": true,
"spriteSourceSize": {"x":23,"y":22,"w":38,"h":63},
"sourceSize": {"w":84,"h":107},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "scoreboard.png",
"frame": {"x":2,"y":1056,"w":362,"h":98},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":362,"h":98},
"sourceSize": {"w":362,"h":98},
"pivot": {"x":0.5,"y":0.5}
}],
"meta": {
"app": "http://www.codeandweb.com/texturepacker",
"version": "1.0",
"image": "game_ui.png",
"format": "RGBA8888",
"size": {"w":472,"h":1239},
"scale": "1",
"smartupdate": "$TexturePacker:SmartUpdate:02d6676bdde949110cbdc9a2c385b33a:6b0974f94eba9593dd9636cc730412b8:10ac111e32c27e51f4e8444dbb39eff6$"
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 166 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 859 KiB

View File

@@ -0,0 +1,219 @@
{"frames": [
{
"filename": "asteroid_big_0.nrm.png",
"frame": {"x":2,"y":260,"w":200,"h":188},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":200,"h":188},
"sourceSize": {"w":200,"h":188},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "asteroid_big_0.png",
"frame": {"x":260,"y":193,"w":200,"h":167},
"rotated": false,
"trimmed": true,
"spriteSourceSize": {"x":0,"y":21,"w":200,"h":167},
"sourceSize": {"w":200,"h":188},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "asteroid_big_1.nrm.png",
"frame": {"x":451,"y":2,"w":204,"h":166},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":204,"h":166},
"sourceSize": {"w":204,"h":166},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "asteroid_big_1.png",
"frame": {"x":657,"y":2,"w":204,"h":166},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":204,"h":166},
"sourceSize": {"w":204,"h":166},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "asteroid_big_2.nrm.png",
"frame": {"x":462,"y":170,"w":194,"h":165},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":194,"h":165},
"sourceSize": {"w":194,"h":165},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "asteroid_big_2.png",
"frame": {"x":658,"y":170,"w":194,"h":165},
"rotated": false,
"trimmed": true,
"spriteSourceSize": {"x":0,"y":2,"w":194,"h":165},
"sourceSize": {"w":194,"h":167},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "asteroid_small_0.nrm.png",
"frame": {"x":204,"y":362,"w":102,"h":84},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":102,"h":84},
"sourceSize": {"w":102,"h":84},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "asteroid_small_0.png",
"frame": {"x":308,"y":362,"w":102,"h":84},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":102,"h":84},
"sourceSize": {"w":102,"h":84},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "asteroid_small_1.nrm.png",
"frame": {"x":854,"y":213,"w":96,"h":102},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":96,"h":102},
"sourceSize": {"w":96,"h":102},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "asteroid_small_1.png",
"frame": {"x":854,"y":317,"w":96,"h":102},
"rotated": false,
"trimmed": true,
"spriteSourceSize": {"x":0,"y":0,"w":96,"h":102},
"sourceSize": {"w":96,"h":106},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "asteroid_small_2.nrm.png",
"frame": {"x":740,"y":337,"w":109,"h":84},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":109,"h":84},
"sourceSize": {"w":109,"h":84},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "asteroid_small_2.png",
"frame": {"x":740,"y":423,"w":109,"h":84},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":109,"h":84},
"sourceSize": {"w":109,"h":84},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "explosion_flare.png",
"frame": {"x":863,"y":2,"w":56,"h":209},
"rotated": false,
"trimmed": true,
"spriteSourceSize": {"x":4,"y":0,"w":56,"h":209},
"sourceSize": {"w":64,"h":256},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "explosion_particle.png",
"frame": {"x":2,"y":450,"w":36,"h":60},
"rotated": false,
"trimmed": true,
"spriteSourceSize": {"x":14,"y":1,"w":36,"h":60},
"sourceSize": {"w":64,"h":64},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "explosion_ring.png",
"frame": {"x":2,"y":2,"w":256,"h":256},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":256,"h":256},
"sourceSize": {"w":256,"h":256},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "fire_particle.png",
"frame": {"x":40,"y":450,"w":55,"h":55},
"rotated": false,
"trimmed": true,
"spriteSourceSize": {"x":4,"y":4,"w":55,"h":55},
"sourceSize": {"w":64,"h":64},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "laser.png",
"frame": {"x":204,"y":260,"w":37,"h":76},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":37,"h":76},
"sourceSize": {"w":37,"h":76},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "shield.png",
"frame": {"x":260,"y":2,"w":189,"h":189},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":189,"h":189},
"sourceSize": {"w":189,"h":189},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "ship.nrm.png",
"frame": {"x":462,"y":337,"w":137,"h":167},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":137,"h":167},
"sourceSize": {"w":137,"h":167},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "ship.png",
"frame": {"x":601,"y":337,"w":137,"h":167},
"rotated": false,
"trimmed": true,
"spriteSourceSize": {"x":25,"y":10,"w":137,"h":167},
"sourceSize": {"w":188,"h":188},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "star_0.png",
"frame": {"x":204,"y":448,"w":62,"h":62},
"rotated": false,
"trimmed": true,
"spriteSourceSize": {"x":1,"y":1,"w":62,"h":62},
"sourceSize": {"w":64,"h":64},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "star_1.png",
"frame": {"x":268,"y":448,"w":62,"h":62},
"rotated": false,
"trimmed": true,
"spriteSourceSize": {"x":1,"y":1,"w":62,"h":62},
"sourceSize": {"w":64,"h":64},
"pivot": {"x":0.5,"y":0.5}
},
{
"filename": "star_2.png",
"frame": {"x":332,"y":448,"w":62,"h":62},
"rotated": false,
"trimmed": true,
"spriteSourceSize": {"x":1,"y":1,"w":62,"h":62},
"sourceSize": {"w":64,"h":64},
"pivot": {"x":0.5,"y":0.5}
}],
"meta": {
"app": "http://www.codeandweb.com/texturepacker",
"version": "1.0",
"image": "sprites.png",
"format": "RGBA8888",
"size": {"w":952,"h":512},
"scale": "1",
"smartupdate": "$TexturePacker:SmartUpdate:342fc72defddab59bb356b48894e2931:ecb4b4fa7772ea6a35788ebf670ca27c:1eabdf11f75e3a4fe3147baf7b5be24b$"
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 523 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

View File

@@ -0,0 +1,58 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<!--
This executable name must match the name of the app provided to the
ios_app GN template
-->
<key>CFBundleExecutable</key>
<string>game_app</string>
<key>CFBundleDisplayName</key>
<string>Asteroids</string>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>CFBundleIdentifier</key>
<string>com.google.sky.game</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>game_app</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>armv7</string>
</array>
<key>DTPlatformName</key>
<string>iphonesimulator</string>
<key>DTSDKName</key>
<string>iphonesimulator8.3</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>MinimumOSVersion</key>
<string>8.3</string>
<key>UIDeviceFamily</key>
<array>
<integer>1</integer>
<integer>2</integer>
</array>
<key>CFBundleSupportedPlatforms</key>
<array>
<string>iPhoneSimulator</string>
</array>
</dict>
</plist>

Binary file not shown.

View File

@@ -0,0 +1,470 @@
part of sprites;
typedef void ActionCallback();
abstract class Action {
Object _tag;
bool _finished = false;
bool _added = false;
void step(double dt);
void update(double t) {
}
void _reset() {
_finished = false;
}
double get duration => 0.0;
}
abstract class ActionInterval extends Action {
double _duration;
bool _firstTick = true;
double _elapsed = 0.0;
double get duration => _duration;
Curve curve;
ActionInterval([this._duration = 0.0, this.curve]);
void step(double dt) {
if (_firstTick) {
_firstTick = false;
} else {
_elapsed += dt;
}
double t;
if (this._duration == 0.0) {
t = 1.0;
} else {
t = (_elapsed / _duration).clamp(0.0, 1.0);
}
if (curve == null) {
update(t);
} else {
update(curve.transform(t));
}
if (t >= 1.0) _finished = true;
}
}
class ActionRepeat extends ActionInterval {
final int numRepeats;
final ActionInterval action;
int _lastFinishedRepeat = -1;
ActionRepeat(this.action, this.numRepeats) {
_duration = action.duration * numRepeats;
}
void update(double t) {
int currentRepeat = math.min((t * numRepeats.toDouble()).toInt(), numRepeats - 1);
for (int i = math.max(_lastFinishedRepeat, 0); i < currentRepeat; i++) {
if (!action._finished) action.update(1.0);
action._reset();
}
_lastFinishedRepeat = currentRepeat;
double ta = (t * numRepeats.toDouble()) % 1.0;
action.update(ta);
if (t >= 1.0) {
action.update(1.0);
action._finished = true;
}
}
}
class ActionRepeatForever extends Action {
final ActionInterval action;
double _elapsedInAction = 0.0;
ActionRepeatForever(this.action);
step(double dt) {
_elapsedInAction += dt;
while (_elapsedInAction > action.duration) {
_elapsedInAction -= action.duration;
if (!action._finished) action.update(1.0);
action._reset();
}
_elapsedInAction = math.max(_elapsedInAction, 0.0);
double t;
if (action._duration == 0.0) {
t = 1.0;
} else {
t = (_elapsedInAction / action._duration).clamp(0.0, 1.0);
}
action.update(t);
}
}
class ActionSequence extends ActionInterval {
Action _a;
Action _b;
double _split;
ActionSequence(List<Action> actions) {
assert(actions.length >= 2);
if (actions.length == 2) {
// Base case
_a = actions[0];
_b = actions[1];
} else {
_a = actions[0];
_b = new ActionSequence(actions.sublist(1));
}
// Calculate split and duration
_duration = _a.duration + _b.duration;
if (_duration > 0) {
_split = _a.duration / _duration;
} else {
_split = 1.0;
}
}
void update(double t) {
if (t < _split) {
// Play first action
double ta;
if (_split > 0.0) {
ta = (t / _split).clamp(0.0, 1.0);
} else {
ta = 1.0;
}
_updateWithCurve(_a, ta);
} else if (t >= 1.0) {
// Make sure everything is finished
if (!_a._finished) _finish(_a);
if (!_b._finished) _finish(_b);
} else {
// Play second action, but first make sure the first has finished
if (!_a._finished) _finish(_a);
double tb;
if (_split < 1.0) {
tb = (1.0 - (1.0 - t) / (1.0 - _split)).clamp(0.0, 1.0);
} else {
tb = 1.0;
}
_updateWithCurve(_b, tb);
}
}
void _updateWithCurve(Action action, double t) {
if (action is ActionInterval) {
ActionInterval actionInterval = action;
if (actionInterval.curve == null) {
action.update(t);
} else {
action.update(actionInterval.curve.transform(t));
}
} else {
action.update(t);
}
if (t >= 1.0) {
action._finished = true;
}
}
void _finish(Action action) {
action.update(1.0);
action._finished = true;
}
void _reset() {
super._reset();
_a._reset();
_b._reset();
}
}
class ActionGroup extends ActionInterval {
List<Action> _actions;
ActionGroup(this._actions) {
for (Action action in _actions) {
if (action.duration > _duration) {
_duration = action.duration;
}
}
}
void update(double t) {
if (t >= 1.0) {
// Finish all unfinished actions
for (Action action in _actions) {
if (!action._finished) {
action.update(1.0);
action._finished = true;
}
}
} else {
for (Action action in _actions) {
if (action.duration == 0.0) {
// Fire all instant actions immediately
if (!action._finished) {
action.update(1.0);
action._finished = true;
}
} else {
// Update child actions
double ta = (t / (action.duration / duration)).clamp(0.0, 1.0);
if (ta < 1.0) {
if (action is ActionInterval) {
ActionInterval actionInterval = action;
if (actionInterval.curve == null) {
action.update(ta);
} else {
action.update(actionInterval.curve.transform(ta));
}
} else {
action.update(ta);
}
} else if (!action._finished){
action.update(1.0);
action._finished = true;
}
}
}
}
}
void _reset() {
for (Action action in _actions) {
action._reset();
}
}
}
abstract class ActionInstant extends Action {
void step(double dt) {
}
void update(double t) {
fire();
_finished = true;
}
void fire();
}
class ActionCallFunction extends ActionInstant {
ActionCallback _function;
ActionCallFunction(this._function);
void fire() {
_function();
}
}
class ActionRemoveNode extends ActionInstant {
Node _node;
ActionRemoveNode(this._node);
void fire() {
_node.removeFromParent();
}
}
class ActionTween extends ActionInterval {
final Function setter;
final startVal;
final endVal;
var _delta;
ActionTween(this.setter, this.startVal, this.endVal, double duration, [Curve curve]) : super(duration, curve) {
_computeDelta();
}
void _computeDelta() {
if (startVal is Point) {
// Point
double xStart = startVal.x;
double yStart = startVal.y;
double xEnd = endVal.x;
double yEnd = endVal.y;
_delta = new Point(xEnd - xStart, yEnd - yStart);
} else if (startVal is Size) {
// Size
double wStart = startVal.width;
double hStart = startVal.height;
double wEnd = endVal.width;
double hEnd = endVal.height;
_delta = new Size(wEnd - wStart, hEnd - hStart);
} else if (startVal is Rect) {
// Rect
double lStart = startVal.left;
double tStart = startVal.top;
double rStart = startVal.right;
double bStart = startVal.bottom;
double lEnd = endVal.left;
double tEnd = endVal.top;
double rEnd = endVal.right;
double bEnd = endVal.bottom;
_delta = new Rect.fromLTRB(lEnd - lStart, tEnd - tStart, rEnd - rStart, bEnd - bStart);
} else if (startVal is double) {
// Double
_delta = endVal - startVal;
} else if (startVal is Color) {
// Color
int aDelta = endVal.alpha - startVal.alpha;
int rDelta = endVal.red - startVal.red;
int gDelta = endVal.green - startVal.green;
int bDelta = endVal.blue - startVal.blue;
_delta = new _ColorDiff(aDelta, rDelta, gDelta, bDelta);
} else {
assert(false);
}
}
void update(double t) {
var newVal;
if (startVal is Point) {
// Point
double xStart = startVal.x;
double yStart = startVal.y;
double xDelta = _delta.x;
double yDelta = _delta.y;
newVal = new Point(xStart + xDelta * t, yStart + yDelta * t);
} else if (startVal is Size) {
// Size
double wStart = startVal.width;
double hStart = startVal.height;
double wDelta = _delta.width;
double hDelta = _delta.height;
newVal = new Size(wStart + wDelta * t, hStart + hDelta * t);
} else if (startVal is Rect) {
// Rect
double lStart = startVal.left;
double tStart = startVal.top;
double rStart = startVal.right;
double bStart = startVal.bottom;
double lDelta = _delta.left;
double tDelta = _delta.top;
double rDelta = _delta.right;
double bDelta = _delta.bottom;
newVal = new Rect.fromLTRB(lStart + lDelta * t, tStart + tDelta * t, rStart + rDelta * t, bStart + bDelta * t);
} else if (startVal is double) {
// Doubles
newVal = startVal + _delta * t;
} else if (startVal is Color) {
// Colors
int aNew = (startVal.alpha + (_delta.alpha * t).toInt()).clamp(0, 255);
int rNew = (startVal.red + (_delta.red * t).toInt()).clamp(0, 255);
int gNew = (startVal.green + (_delta.green * t).toInt()).clamp(0, 255);
int bNew = (startVal.blue + (_delta.blue * t).toInt()).clamp(0, 255);
newVal = new Color.fromARGB(aNew, rNew, gNew, bNew);
} else {
// Oopses
assert(false);
}
setter(newVal);
}
}
class ActionController {
List<Action> _actions = [];
ActionController();
void run(Action action, [Object tag]) {
assert(!action._added);
action._tag = tag;
action._added = true;
action.update(0.0);
_actions.add(action);
}
void stop(Action action) {
if (_actions.remove(action)) {
action._added = false;
action._reset();
}
}
void _stopAtIndex(int i) {
Action action = _actions[i];
action._added = false;
action._reset();
_actions.removeAt(i);
}
void stopWithTag(Object tag) {
for (int i = _actions.length - 1; i >= 0; i--) {
Action action = _actions[i];
if (action._tag == tag) {
_stopAtIndex(i);
}
}
}
void stopAll() {
for (int i = _actions.length - 1; i >= 0; i--) {
_stopAtIndex(i);
}
}
void step(double dt) {
for (int i = _actions.length - 1; i >= 0; i--) {
Action action = _actions[i];
action.step(dt);
if (action._finished) {
action._added = false;
_actions.removeAt(i);
}
}
}
}
class _ColorDiff {
final int alpha;
final int red;
final int green;
final int blue;
_ColorDiff(this.alpha, this.red, this.green, this.blue);
}
double _bounce(double t)
{
if (t < 1.0 / 2.75) {
return 7.5625 * t * t;
} else if (t < 2 / 2.75) {
t -= 1.5 / 2.75;
return 7.5625 * t * t + 0.75;
} else if (t < 2.5 / 2.75) {
t -= 2.25 / 2.75;
return 7.5625 * t * t + 0.9375;
}
t -= 2.625 / 2.75;
return 7.5625 * t * t + 0.984375;
}
class BounceOutCurve implements Curve {
const BounceOutCurve();
double transform(double t) {
return _bounce(t);
}
}
const BounceOutCurve bounceOut = const BounceOutCurve();

View File

@@ -0,0 +1,61 @@
part of sprites;
class ColorSequence {
List<Color> colors;
List<double> colorStops;
ColorSequence(this.colors, this.colorStops) {
assert(colors != null);
assert(colorStops != null);
assert(colors.length == colorStops.length);
}
ColorSequence.fromStartAndEndColor(Color start, Color end) {
colors = [start, end];
colorStops = [0.0, 1.0];
}
ColorSequence.copy(ColorSequence sequence) {
colors = new List<Color>.from(sequence.colors);
colorStops = new List<double>.from(sequence.colorStops);
}
Color colorAtPosition(double pos) {
assert(pos >= 0.0 && pos <= 1.0);
double lastStop = colorStops[0];
Color lastColor = colors[0];
for (int i = 0; i < colors.length; i++) {
double currentStop = colorStops[i];
Color currentColor = colors[i];
if (pos <= currentStop) {
double blend = (pos - lastStop) / (currentStop - lastStop);
return _interpolateColor(lastColor, currentColor, blend);
}
lastStop = currentStop;
lastColor = currentColor;
}
return colors[colors.length-1];
}
}
Color _interpolateColor(Color a, Color b, double blend) {
double aa = a.alpha.toDouble();
double ar = a.red.toDouble();
double ag = a.green.toDouble();
double ab = a.blue.toDouble();
double ba = b.alpha.toDouble();
double br = b.red.toDouble();
double bg = b.green.toDouble();
double bb = b.blue.toDouble();
int na = (aa * (1.0 - blend) + ba * blend).toInt();
int nr = (ar * (1.0 - blend) + br * blend).toInt();
int ng = (ag * (1.0 - blend) + bg * blend).toInt();
int nb = (ab * (1.0 - blend) + bb * blend).toInt();
return new Color.fromARGB(na, nr, ng, nb);
}

View File

@@ -0,0 +1,12 @@
library game;
import 'dart:sky' as sky;
import 'dart:math' as Math;
import 'sprites.dart';
import 'package:sky/rendering/object.dart';
import 'package:sky/widgets/framework.dart';
import 'package:sky/widgets/navigator.dart';
import 'package:vector_math/vector_math_64.dart';
part 'game_demo_world.dart';

View File

@@ -0,0 +1,744 @@
part of game;
const double _steeringThreshold = 0.0;
const double _steeringMax = 150.0;
// Random generator
Math.Random _rand = new Math.Random();
const double _gameSizeWidth = 1024.0;
const double _gameSizeHeight = 1024.0;
const double _shipRadius = 30.0;
const double _lrgAsteroidRadius = 40.0;
const double _medAsteroidRadius = 20.0;
const double _smlAsteroidRadius = 10.0;
const double _maxAsteroidSpeed = 1.0;
const int _lifeTimeLaser = 50;
const int _numStarsInStarField = 150;
const int _numFramesShieldActive = 60 * 5;
const int _numFramesShieldFlickers = 60;
class GameDemoWorld extends NodeWithSize {
// Images
sky.Image _imgNebula;
SpriteSheet _spriteSheet;
SpriteSheet _spriteSheetUI;
Navigator _navigator;
// Inputs
double _joystickX = 0.0;
double _joystickY = 0.0;
Node _gameLayer;
Ship _ship;
Sprite _shield;
List<Asteroid> _asteroids = [];
List<Laser> _lasers = [];
StarField _starField;
Nebula _nebula;
// Game state
int _numFrames = 0;
bool _isGameOver = false;
int _gameOverFrame;
int _currentLevel = 0;
// Heads up display
Hud _hud;
Function _gameOverCallback;
GameDemoWorld(App app, this._navigator, ImageMap images, this._spriteSheet, this._spriteSheetUI, this._gameOverCallback) : super(new Size(_gameSizeWidth, _gameSizeHeight)) {
// Fetch images
_imgNebula = images["assets/nebula.png"];
_gameLayer = new Node();
this.addChild(_gameLayer);
// Add ship
addShip();
// Add background
Sprite sprtBackground = new Sprite.fromImage(images["assets/starfield.png"]);
sprtBackground.position = new Point(512.0, 512.0);
sprtBackground.zPosition = -3.0;
addChild(sprtBackground);
// Add starfield
_starField = new StarField(_spriteSheet, _numStarsInStarField);
_starField.zPosition = -2.0;
addChild(_starField);
// Add nebula
addNebula();
userInteractionEnabled = true;
handleMultiplePointers = true;
_hud = new Hud(_spriteSheetUI);
_hud.zPosition = 1000.0;
addChild(_hud);
// Setup level
setupLevel(0);
}
void setupLevel(int level) {
int numLargeAsteroids = 5 + level * 2;
int numMediumAsteroids = 5 + level * 2;
// Add some asteroids to the game world
for (int i = 0; i < numLargeAsteroids; i++) {
addAsteroid(AsteroidSize.large);
}
for (int i = 0; i < numMediumAsteroids; i++) {
addAsteroid(AsteroidSize.medium);
}
_numFrames = 0;
_shield.visible = true;
}
// Methods for adding game objects
void addAsteroid(AsteroidSize size, [Point pos]) {
Asteroid asteroid = new Asteroid(_spriteSheet, size);
asteroid.zPosition = 1.0;
if (pos != null) asteroid.position = pos;
_gameLayer.addChild(asteroid);
_asteroids.add(asteroid);
// Animate asteroid into the scene
Action action = new ActionTween((a) => asteroid.scale = a, 0.0, 1.0, 1.0, bounceOut);
_gameLayer.actions.run(action);
}
void addShip() {
Ship ship = new Ship(_spriteSheet["ship.png"]);
ship.zPosition = 10.0;
_gameLayer.addChild(ship);
_ship = ship;
_shield = new Sprite(_spriteSheet["shield.png"]);
_shield.zPosition = 11.0;
_shield.scale = 0.5;
_shield.transferMode = sky.TransferMode.plus;
_gameLayer.addChild(_shield);
Action rotate = new ActionRepeatForever(new ActionTween((a) => _shield.rotation = a, 0.0, 360.0, 1.0));
actions.run(rotate);
}
void addLaser() {
Laser laser = new Laser(_spriteSheet["laser.png"], _ship);
laser.zPosition = 8.0;
laser.constrainProportions = true;
_lasers.add(laser);
_gameLayer.addChild(laser);
}
void addNebula() {
_nebula = new Nebula.withImage(_imgNebula);
_gameLayer.addChild(_nebula);
}
void addExplosion(AsteroidSize asteroidSize, Point position) {
Node explosionNode = new Node();
// Add particles
ParticleSystem particlesDebris = new ParticleSystem(
_spriteSheet["explosion_particle.png"],
rotateToMovement: true,
startRotation:90.0,
startRotationVar: 0.0,
endRotation: 90.0,
startSize: 0.3,
startSizeVar: 0.1,
endSize: 0.3,
endSizeVar: 0.1,
numParticlesToEmit: 25,
emissionRate:1000.0,
greenVar: 127,
redVar: 127
);
particlesDebris.zPosition = 1010.0;
explosionNode.addChild(particlesDebris);
ParticleSystem particlesFire = new ParticleSystem(
_spriteSheet["fire_particle.png"],
colorSequence: new ColorSequence([new Color(0xffffff33), new Color(0xffff3333), new Color(0x00ff3333)], [0.0, 0.5, 1.0]),
numParticlesToEmit: 25,
emissionRate: 1000.0,
startSize: 0.5,
startSizeVar: 0.1,
endSize: 0.5,
endSizeVar: 0.1,
posVar: new Point(10.0, 10.0),
speed: 10.0,
speedVar: 5.0
);
particlesFire.zPosition = 1011.0;
explosionNode.addChild(particlesFire);
// Add ring
Sprite sprtRing = new Sprite(_spriteSheet["explosion_ring.png"]);
sprtRing.transferMode = sky.TransferMode.plus;
explosionNode.addChild(sprtRing);
Action scale = new ActionTween( (a) => sprtRing.scale = a, 0.2, 1.0, 1.5);
Action scaleAndRemove = new ActionSequence([scale, new ActionRemoveNode(sprtRing)]);
Action fade = new ActionTween( (a) => sprtRing.opacity = a, 1.0, 0.0, 1.5);
actions.run(scaleAndRemove);
actions.run(fade);
// Add streaks
for (int i = 0; i < 5; i++) {
Sprite sprtFlare = new Sprite(_spriteSheet["explosion_flare.png"]);
sprtFlare.pivot = new Point(0.3, 1.0);
sprtFlare.scaleX = 0.3;
sprtFlare.transferMode = sky.TransferMode.plus;
sprtFlare.rotation = _rand.nextDouble() * 360.0;
explosionNode.addChild(sprtFlare);
double multiplier = _rand.nextDouble() * 0.3 + 1.0;
Action scale = new ActionTween( (a) => sprtFlare.scaleY = a, 0.3 * multiplier, 0.8, 1.5 * multiplier);
Action scaleAndRemove = new ActionSequence([scale, new ActionRemoveNode(sprtFlare)]);
Action fadeIn = new ActionTween( (a) => sprtFlare.opacity = a, 0.0, 1.0, 0.5 * multiplier);
Action fadeOut = new ActionTween( (a) => sprtFlare.opacity = a, 1.0, 0.0, 1.0 * multiplier);
Action fadeInOut = new ActionSequence([fadeIn, fadeOut]);
actions.run(scaleAndRemove);
actions.run(fadeInOut);
}
explosionNode.position = position;
explosionNode.zPosition = 1010.0;
if (asteroidSize == AsteroidSize.large) {
explosionNode.scale = 1.5;
}
_gameLayer.addChild(explosionNode);
}
void update(double dt) {
// Move asteroids
for (Asteroid asteroid in _asteroids) {
asteroid.position = pointAdd(asteroid.position, asteroid._movementVector);
}
// Move lasers and remove expired lasers
for (int i = _lasers.length - 1; i >= 0; i--) {
Laser laser = _lasers[i];
laser.move();
if (laser._frameCount > _lifeTimeLaser) {
laser.removeFromParent();
_lasers.removeAt(i);
}
}
// Apply thrust to ship
if (_joystickX != 0.0 || _joystickY != 0.0) {
_ship.thrust(_joystickX, _joystickY);
}
// Move ship
_ship.move();
_shield.position = _ship.position;
// Check collisions between asteroids and lasers
for (int i = _lasers.length -1; i >= 0; i--) {
// Iterate over all the lasers
Laser laser = _lasers[i];
for (int j = _asteroids.length - 1; j >= 0; j--) {
// Iterate over all the asteroids
Asteroid asteroid = _asteroids[j];
// Check for collision
if (pointQuickDist(laser.position, asteroid.position) < laser.radius + asteroid.radius) {
// Remove laser
laser.removeFromParent();
_lasers.removeAt(i);
// Add asteroids and explosions
if (asteroid._asteroidSize == AsteroidSize.large) {
for (int a = 0; a < 3; a++) addAsteroid(AsteroidSize.medium, asteroid.position);
}
else if (asteroid._asteroidSize == AsteroidSize.medium) {
for (int a = 0; a < 5; a++) addAsteroid(AsteroidSize.small, asteroid.position);
}
addExplosion(asteroid._asteroidSize, asteroid.position);
// Remove asteroid
asteroid.removeFromParent();
_asteroids.removeAt(j);
// Scoring
if (asteroid._asteroidSize == AsteroidSize.large)
addScore(100);
else if (asteroid._asteroidSize == AsteroidSize.medium)
addScore(50);
else
addScore(10);
break;
}
}
}
// Check collisions between asteroids and ship
if (_numFrames > _numFramesShieldActive) {
// Shield is no longer active
for (int i = _asteroids.length - 1; i >= 0; i--) {
// Iterate over all the asteroids
Asteroid asteroid = _asteroids[i];
if (pointQuickDist(asteroid.position, _ship.position) < asteroid.radius + _ship.radius) {
killShip();
}
}
}
// Move objects to center camera and warp objects around the edges
centerCamera();
warpObjects();
// Check for level up
if (_asteroids.length == 0) {
_currentLevel++;
setupLevel(_currentLevel);
}
// Update shield
if (_numFrames > _numFramesShieldActive) _shield.visible = false;
else if (_numFrames > _numFramesShieldActive - _numFramesShieldFlickers) _shield.visible = !_shield.visible;
// Check for exit back to main screen
if (_isGameOver && _numFrames - _gameOverFrame == 60) {
_navigator.pop();
}
_numFrames++;
}
void centerCamera() {
const cameraDampening = 0.1;
Point delta = new Point(_gameSizeWidth/2 - _ship.position.x, _gameSizeHeight/2 - _ship.position.y);
delta = pointMult(delta, cameraDampening);
for (Node child in _gameLayer.children) {
child.position = pointAdd(child.position, delta);
}
// Update starfield
_starField.move(delta.x, delta.y);
}
void warpObjects() {
for (Node child in _gameLayer.children) {
if (child.position.x < 0) child.position = pointAdd(child.position, new Point(_gameSizeWidth, 0.0));
if (child.position.x >= _gameSizeWidth) child.position = pointAdd(child.position, new Point(-_gameSizeWidth, 0.0));
if (child.position.y < 0) child.position = pointAdd(child.position, new Point(0.0, _gameSizeHeight));
if (child.position.y >= _gameSizeHeight) child.position = pointAdd(child.position, new Point(0.0, -_gameSizeHeight));
}
}
void killShip() {
if (_isGameOver) return;
// Set game over
_isGameOver = true;
_gameOverFrame = _numFrames;
_gameOverCallback(_hud.score);
// Remove the ship
_ship.visible = false;
// Add an explosion
addExplosion(AsteroidSize.large, _ship.position);
}
// Handling controls
void controlSteering(double x, double y) {
// Reset controls if it's game over
if (_isGameOver) {
x = y = 0.0;
}
_joystickX = x;
_joystickY = y;
}
void controlFire() {
// Don't shoot if it's game over
if (_isGameOver) return;
addLaser();
}
// Handle pointer events
int _firstPointer = -1;
int _secondPointer = -1;
Point _firstPointerDownPos;
bool handleEvent(SpriteBoxEvent event) {
Point pointerPos = convertPointToNodeSpace(event.boxPosition);
int pointer = event.pointer;
switch (event.type) {
case 'pointerdown':
if (_firstPointer == -1) {
// Assign the first pointer
_firstPointer = pointer;
_firstPointerDownPos = pointerPos;
}
else if (_secondPointer == -1) {
// Assign second pointer
_secondPointer = pointer;
controlFire();
}
else {
// There is a pointer used for steering, let's fire instead
controlFire();
}
break;
case 'pointermove':
if (pointer == _firstPointer) {
// Handle turning control
double joystickX = 0.0;
double deltaX = pointerPos.x - _firstPointerDownPos.x;
if (deltaX > _steeringThreshold || deltaX < -_steeringThreshold) {
joystickX = (deltaX - _steeringThreshold)/(_steeringMax - _steeringThreshold);
if (joystickX > 1.0) joystickX = 1.0;
if (joystickX < -1.0) joystickX = -1.0;
}
double joystickY = 0.0;
double deltaY = pointerPos.y - _firstPointerDownPos.y;
if (deltaY > _steeringThreshold || deltaY < -_steeringThreshold) {
joystickY = (deltaY - _steeringThreshold)/(_steeringMax - _steeringThreshold);
if (joystickY > 1.0) joystickY = 1.0;
if (joystickY < -1.0) joystickY = -1.0;
}
controlSteering(joystickX, joystickY);
}
break;
case 'pointerup':
case 'pointercancel':
if (pointer == _firstPointer) {
// Un-assign the first pointer
_firstPointer = -1;
_firstPointerDownPos = null;
controlSteering(0.0, 0.0);
}
else if (pointer == _secondPointer) {
_secondPointer = -1;
}
break;
default:
break;
}
return true;
}
// Scoring and HUD
void addScore(int score) {
_hud.score += score;
}
}
// Game objects
enum AsteroidSize {
small,
medium,
large,
}
class Asteroid extends Sprite {
Point _movementVector;
AsteroidSize _asteroidSize;
double _radius;
double get radius {
if (_radius != null) return _radius;
if (_asteroidSize == AsteroidSize.small) _radius = _smlAsteroidRadius;
else if (_asteroidSize == AsteroidSize.medium) _radius = _medAsteroidRadius;
else if (_asteroidSize == AsteroidSize.large) _radius = _lrgAsteroidRadius;
return _radius;
}
Asteroid(SpriteSheet spriteSheet, AsteroidSize this._asteroidSize) {
size = new Size(radius * 2.0, radius * 2.0);
position = new Point(_gameSizeWidth * _rand.nextDouble(), _gameSizeHeight * _rand.nextDouble());
rotation = 360.0 * _rand.nextDouble();
if (_asteroidSize == AsteroidSize.small) {
texture = spriteSheet["asteroid_small_${_rand.nextInt(2)}.png"];
} else {
texture = spriteSheet["asteroid_big_${_rand.nextInt(2)}.png"];
}
_movementVector = new Point(_rand.nextDouble() * _maxAsteroidSpeed * 2 - _maxAsteroidSpeed,
_rand.nextDouble() * _maxAsteroidSpeed * 2 - _maxAsteroidSpeed);
userInteractionEnabled = true;
// Rotate forever
double direction = (_rand.nextBool()) ? 360.0 : -360.0;
ActionTween rot = new ActionTween( (a) => rotation = a, 0.0, direction, 2.0 * _rand.nextDouble() + 2.0);
ActionRepeatForever repeat = new ActionRepeatForever(rot);
actions.run(repeat);
}
bool handleEvent(SpriteBoxEvent event) {
if (event.type == "pointerdown") {
actions.stopWithTag("fade");
colorOverlay = new Color(0x99ffffff);
}
else if (event.type == "pointerup") {
// Fade out the color overlay
Action fadeOut = new ActionTween((a) => this.colorOverlay = a, new Color(0x99ffffff), new Color(0x00ffffff), 1.0);
Action fadeOutAndRemove = new ActionSequence([fadeOut, new ActionCallFunction(() => this.colorOverlay = null)]);
actions.run(fadeOutAndRemove, "fade");
}
return false;
}
}
class Ship extends Sprite {
Vector2 _movementVector;
double _rotationTarget;
double radius = _shipRadius;
Ship(Texture img) : super(img) {
_movementVector = new Vector2.zero();
rotation = _rotationTarget = 270.0;
// Create sprite
size = new Size(_shipRadius * 2.0, _shipRadius * 2.0);
position = new Point(_gameSizeWidth/2.0, _gameSizeHeight/2.0);
}
void thrust(double x, double y) {
_rotationTarget = convertRadians2Degrees(Math.atan2(y, x));
Vector2 directionVector = new Vector2(x, y).normalize();
_movementVector.addScaled(directionVector, 1.0);
}
void move() {
position = new Point(position.x + _movementVector[0], position.y + _movementVector[1]);
_movementVector.scale(0.9);
rotation = dampenRotation(rotation, _rotationTarget, 0.1);
}
}
class Laser extends Sprite {
int _frameCount = 0;
Point _movementVector;
double radius = 20.0;
Laser(Texture img, Ship ship) : super(img) {
size = new Size(30.0, 30.0);
position = ship.position;
rotation = ship.rotation + 90.0;
transferMode = sky.TransferMode.plus;
double rotRadians = convertDegrees2Radians(rotation);
_movementVector = pointMult(new Point(Math.sin(rotRadians), -Math.cos(rotRadians)), 10.0);
_movementVector = new Point(_movementVector.x + ship._movementVector[0], _movementVector.y + ship._movementVector[1]);
}
void move() {
position = pointAdd(position, _movementVector);
_frameCount++;
}
}
// Background starfield
class StarField extends NodeWithSize {
sky.Image _image;
int _numStars;
bool _autoScroll;
List<Point> _starPositions;
List<double> _starScales;
List<Rect> _rects;
List<Color> _colors;
Paint _paint = new Paint()
..setFilterQuality(sky.FilterQuality.low)
..isAntiAlias = false
..setTransferMode(sky.TransferMode.plus);
StarField(SpriteSheet spriteSheet, this._numStars, [this._autoScroll = false]) : super(new Size(1024.0, 1024.0)) {
_starPositions = [];
_starScales = [];
_colors = [];
_rects = [];
for (int i = 0; i < _numStars; i++) {
_starPositions.add(new Point(_rand.nextDouble() * _gameSizeWidth, _rand.nextDouble() * _gameSizeHeight));
_starScales.add(_rand.nextDouble());
_colors.add(new Color.fromARGB((255.0 * (_rand.nextDouble() * 0.5 + 0.5)).toInt(), 255, 255, 255));
_rects.add(spriteSheet["star_${_rand.nextInt(2)}.png"].frame);
}
_image = spriteSheet.image;
}
void paint(PaintingCanvas canvas) {
// Create a transform for each star
List<sky.RSTransform> transforms = [];
for (int i = 0; i < _numStars; i++) {
sky.RSTransform transform = new sky.RSTransform(_starScales[i], 0.0, _starPositions[i].x, _starPositions[i].y);
transforms.add(transform);
}
// Draw the stars
canvas.drawAtlas(_image, transforms, _rects, _colors, sky.TransferMode.modulate, null, _paint);
}
void move(double dx, double dy) {
for (int i = 0; i < _numStars; i++) {
double xPos = _starPositions[i].x;
double yPos = _starPositions[i].y;
double scale = _starScales[i];
xPos += dx * scale;
yPos += dy * scale;
if (xPos >= _gameSizeWidth) xPos -= _gameSizeWidth;
if (xPos < 0) xPos += _gameSizeWidth;
if (yPos >= _gameSizeHeight) yPos -= _gameSizeHeight;
if (yPos < 0) yPos += _gameSizeHeight;
_starPositions[i] = new Point(xPos, yPos);
}
}
void update(double dt) {
if (_autoScroll) {
move(dt * 100.0, 0.0);
}
}
}
class Hud extends NodeWithSize {
SpriteSheet spriteSheetUI;
Sprite sprtBgScore;
Sprite sprtBgShield;
bool _dirtyScore = true;
int _score = 0;
int get score => _score;
set score(int score) {
_score = score;
_dirtyScore = true;
}
Hud(this.spriteSheetUI) {
pivot = Point.origin;
sprtBgScore = new Sprite(spriteSheetUI["scoreboard.png"]);
sprtBgScore.pivot = new Point(1.0, 0.0);
sprtBgScore.scale = 0.6;
addChild(sprtBgScore);
sprtBgShield = new Sprite(spriteSheetUI["bar_shield.png"]);
sprtBgShield.pivot = Point.origin;
sprtBgShield.scale = 0.6;
// TODO: Add shield
//addChild(sprtBgShield);
}
void spriteBoxPerformedLayout() {
// Set the size and position of HUD display
position = spriteBox.visibleArea.topLeft;
size = spriteBox.visibleArea.size;
// Position hud objects
sprtBgShield.position = new Point(20.0, 20.0);
sprtBgScore.position = new Point(size.width - 20.0, 20.0);
}
void update(double dt) {
// Update score
if (_dirtyScore) {
sprtBgScore.removeAllChildren();
String scoreStr = _score.toString();
double xPos = -50.0;
for (int i = scoreStr.length - 1; i >= 0; i--) {
String numStr = scoreStr.substring(i, i + 1);
Sprite numSprt = new Sprite(spriteSheetUI["number_$numStr.png"]);
numSprt.position = new Point(xPos, 49.0);
sprtBgScore.addChild(numSprt);
xPos -= 37.0;
}
_dirtyScore = false;
}
// Update power bar
}
}
class Nebula extends Node {
Nebula.withImage(sky.Image img) {
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
Sprite sprt = new Sprite.fromImage(img);
sprt.transferMode = sky.TransferMode.plus;
sprt.pivot = Point.origin;
sprt.position = new Point(i * _gameSizeWidth - _gameSizeWidth, j * _gameSizeHeight - _gameSizeHeight);
addChild(sprt);
}
}
}
}
// Convenience methods
Point pointAdd(Point a, Point b) {
return new Point(a.x+ b.x, a.y + b.y);
}
Point pointMult(Point a, double multiplier) {
return new Point(a.x * multiplier, a.y * multiplier);
}
double dampenRotation(double src, double dst, double dampening) {
double delta = dst - src;
while (delta > 180.0) delta -= 360;
while (delta < -180) delta += 360;
delta *= dampening;
return src + delta;
}
double pointQuickDist(Point a, Point b) {
double dx = a.x - b.x;
double dy = a.y - b.y;
if (dx < 0.0) dx = -dx;
if (dy < 0.0) dy = -dy;
if (dx > dy) {
return dx + dy/2.0;
}
else {
return dy + dx/2.0;
}
}

View File

@@ -0,0 +1,25 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
part of sprites;
class ImageMap {
ImageMap(AssetBundle bundle) : _bundle = bundle;
final AssetBundle _bundle;
final Map<String, Image> _images = new Map<String, Image>();
Future<List<Image>> load(List<String> urls) {
return Future.wait(urls.map(_loadImage));
}
Future<Image> _loadImage(String url) async {
Image image = await _bundle.loadImage(url);
_images[url] = image;
return image;
}
Image getImage(String url) => _images[url];
Image operator [](String url) => _images[url];
}

573
examples/game/lib/node.dart Normal file
View File

@@ -0,0 +1,573 @@
part of sprites;
double convertDegrees2Radians(double degrees) => degrees * math.PI/180.8;
double convertRadians2Degrees(double radians) => radians * 180.0/math.PI;
/// A base class for all objects that can be added to the sprite node tree and rendered to screen using [SpriteBox] and
/// [SpriteWidget].
///
/// The [Node] class itself doesn't render any content, but provides the basic functions of any type of node, such as
/// handling transformations and user input. To render the node tree, a root node must be added to a [SpriteBox] or a
/// [SpriteWidget]. Commonly used sub-classes of [Node] are [Sprite], [NodeWithSize], and many more upcoming subclasses.
///
/// Nodes form a hierarchical tree. Each node can have a number of children, and the transformation (positioning,
/// rotation, and scaling) of a node also affects its children.
class Node {
// Member variables
SpriteBox _spriteBox;
Node _parent;
Point _position = Point.origin;
double _rotation = 0.0;
Matrix4 _transformMatrix = new Matrix4.identity();
Matrix4 _transformMatrixNodeToBox;
Matrix4 _transformMatrixBoxToNode;
double _scaleX = 1.0;
double _scaleY = 1.0;
double _skewX = 0.0;
double _skewY = 0.0;
/// The visibility of this node and its children.
bool visible = true;
double _zPosition = 0.0;
int _addedOrder;
int _childrenLastAddedOrder = 0;
bool _childrenNeedSorting = false;
Matrix4 _savedTotalMatrix;
/// Decides if the node and its children is currently paused.
///
/// A paused node will not receive any input events, update calls, or run any animations.
///
/// myNodeTree.paused = true;
bool paused = false;
bool _userInteractionEnabled = false;
/// If set to true the node will receive multiple pointers, otherwise it will only receive events the first pointer.
///
/// This property is only meaningful if [userInteractionEnabled] is set to true. Default value is false.
///
/// class MyCustomNode extends Node {
/// handleMultiplePointers = true;
/// }
bool handleMultiplePointers = false;
int _handlingPointer;
List<Node>_children = [];
ActionController _actions;
ActionController get actions {
if (_actions == null) {
_actions = new ActionController();
if (_spriteBox != null) _spriteBox._actionControllers = null;
}
return _actions;
}
// Constructors
/// Creates a new [Node] without any transformation.
///
/// var myNode = new Node();
Node() {
}
// Property setters and getters
/// The [SpriteBox] this node is added to, or null if it's not currently added to a [SpriteBox].
///
/// For most applications it's not necessary to access the [SpriteBox] directly.
///
/// // Get the transformMode of the sprite box
/// var transformMode = myNode.spriteBox.transformMode;
SpriteBox get spriteBox => _spriteBox;
/// The parent of this node, or null if it doesn't have a parent.
///
/// // Hide the parent
/// myNode.parent.visible = false;
Node get parent => _parent;
/// The rotation of this node in degrees.
///
/// myNode.rotation = 45.0;
double get rotation => _rotation;
void set rotation(double rotation) {
assert(rotation != null);
_rotation = rotation;
invalidateTransformMatrix();
}
/// The position of this node relative to its parent.
///
/// myNode.position = new Point(42.0, 42.0);
Point get position => _position;
void set position(Point position) {
assert(position != null);
_position = position;
invalidateTransformMatrix();
}
double get skewX => _skewX;
void set skewX (double skewX) {
assert(skewX != null);
_skewX = skewX;
invalidateTransformMatrix();
}
double get skewY => _skewY;
void set skewY (double skewY) {
assert(skewY != null);
_skewY = skewY;
invalidateTransformMatrix();
}
/// The draw order of this node compared to its parent and its siblings.
///
/// By default nodes are drawn in the order that they have been added to a parent. To override this behavior the
/// [zPosition] property can be used. A higher value of this property will force the node to be drawn in front of
/// siblings that have a lower value. If a negative value is used the node will be drawn behind its parent.
///
/// nodeInFront.zPosition = 1.0;
/// nodeBehind.zPosition = -1.0;
double get zPosition => _zPosition;
void set zPosition(double zPosition) {
assert(zPosition != null);
_zPosition = zPosition;
if (_parent != null) {
_parent._childrenNeedSorting = true;
}
}
/// The scale of this node relative its parent.
///
/// The [scale] property is only valid if [scaleX] and [scaleY] are equal values.
///
/// myNode.scale = 5.0;
double get scale {
assert(_scaleX == _scaleY);
return _scaleX;
}
void set scale(double scale) {
assert(scale != null);
_scaleX = _scaleY = scale;
invalidateTransformMatrix();
}
/// The horizontal scale of this node relative its parent.
///
/// myNode.scaleX = 5.0;
double get scaleX => _scaleX;
void set scaleX(double scaleX) {
assert(scaleX != null);
_scaleX = scaleX;
invalidateTransformMatrix();
}
/// The vertical scale of this node relative its parent.
///
/// myNode.scaleY = 5.0;
double get scaleY => _scaleY;
void set scaleY(double scaleY) {
assert(scaleY != null);
_scaleY = scaleY;
invalidateTransformMatrix();
}
/// A list of the children of this node.
///
/// This list should only be modified by using the [addChild] and [removeChild] methods.
///
/// // Iterate over a nodes children
/// for (Node child in myNode.children) {
/// // Do something with the child
/// }
List<Node> get children {
_sortChildren();
return _children;
}
// Adding and removing children
/// Adds a child to this node.
///
/// The same node cannot be added to multiple nodes.
///
/// addChild(new Sprite(myImage));
void addChild(Node child) {
assert(child != null);
assert(child._parent == null);
_childrenNeedSorting = true;
_children.add(child);
child._parent = this;
child._spriteBox = this._spriteBox;
_childrenLastAddedOrder += 1;
child._addedOrder = _childrenLastAddedOrder;
if (_spriteBox != null) _spriteBox._registerNode(child);
}
/// Removes a child from this node.
///
/// removeChild(myChildNode);
void removeChild(Node child) {
assert(child != null);
if (_children.remove(child)) {
child._parent = null;
child._spriteBox = null;
if (_spriteBox != null) _spriteBox._deregisterNode(child);
}
}
/// Removes this node from its parent node.
///
/// removeFromParent();
void removeFromParent() {
assert(_parent != null);
_parent.removeChild(this);
}
/// Removes all children of this node.
///
/// removeAllChildren();
void removeAllChildren() {
for (Node child in _children) {
child._parent = null;
child._spriteBox = null;
}
_children = [];
_childrenNeedSorting = false;
if (_spriteBox != null) _spriteBox._deregisterNode(null);
}
void _sortChildren() {
// Sort children primarily by zPosition, secondarily by added order
if (_childrenNeedSorting) {
_children.sort((Node a, Node b) {
if (a._zPosition == b._zPosition) {
return a._addedOrder - b._addedOrder;
}
else if (a._zPosition > b._zPosition) {
return 1;
}
else {
return -1;
}
});
_childrenNeedSorting = false;
}
}
// Calculating the transformation matrix
/// The transformMatrix describes the transformation from the node's parent.
///
/// You cannot set the transformMatrix directly, instead use the position, rotation and scale properties.
///
/// Matrix4 matrix = myNode.transformMatrix;
Matrix4 get transformMatrix {
if (_transformMatrix == null) {
_transformMatrix = computeTransformMatrix();
}
return _transformMatrix;
}
Matrix4 computeTransformMatrix() {
double cx, sx, cy, sy;
if (_rotation == 0.0) {
cx = 1.0;
sx = 0.0;
cy = 1.0;
sy = 0.0;
}
else {
double radiansX = convertDegrees2Radians(_rotation);
double radiansY = convertDegrees2Radians(_rotation);
cx = math.cos(radiansX);
sx = math.sin(radiansX);
cy = math.cos(radiansY);
sy = math.sin(radiansY);
}
// Create transformation matrix for scale, position and rotation
Matrix4 matrix = new Matrix4(cy * _scaleX, sy * _scaleX, 0.0, 0.0,
-sx * _scaleY, cx * _scaleY, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
_position.x, _position.y, 0.0, 1.0);
if (_skewX != 0.0 || _skewY != 0.0) {
// Needs skew transform
Matrix4 skew = new Matrix4(1.0, math.tan(radians(_skewX)), 0.0, 0.0,
math.tan(radians(_skewY)), 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0);
matrix.multiply(skew);
}
return matrix;
}
void invalidateTransformMatrix() {
_transformMatrix = null;
_invalidateToBoxTransformMatrix();
}
void _invalidateToBoxTransformMatrix () {
_transformMatrixNodeToBox = null;
_transformMatrixBoxToNode = null;
for (Node child in children) {
child._invalidateToBoxTransformMatrix();
}
}
// Transforms to other nodes
Matrix4 _nodeToBoxMatrix() {
assert(_spriteBox != null);
if (_transformMatrixNodeToBox != null) {
return _transformMatrixNodeToBox;
}
if (_parent == null) {
// Base case, we are at the top
assert(this == _spriteBox.rootNode);
_transformMatrixNodeToBox = new Matrix4.copy(_spriteBox.transformMatrix).multiply(transformMatrix);
}
else {
_transformMatrixNodeToBox = new Matrix4.copy(_parent._nodeToBoxMatrix()).multiply(transformMatrix);
}
return _transformMatrixNodeToBox;
}
Matrix4 _boxToNodeMatrix() {
assert(_spriteBox != null);
if (_transformMatrixBoxToNode != null) {
return _transformMatrixBoxToNode;
}
_transformMatrixBoxToNode = new Matrix4.copy(_nodeToBoxMatrix());
_transformMatrixBoxToNode.invert();
return _transformMatrixBoxToNode;
}
/// Converts a point from the coordinate system of the [SpriteBox] to the local coordinate system of the node.
///
/// This method is particularly useful when handling pointer events and need the pointers position in a local
/// coordinate space.
///
/// Point localPoint = myNode.convertPointToNodeSpace(pointInBoxCoordinates);
Point convertPointToNodeSpace(Point boxPoint) {
assert(boxPoint != null);
assert(_spriteBox != null);
Vector4 v =_boxToNodeMatrix().transform(new Vector4(boxPoint.x, boxPoint.y, 0.0, 1.0));
return new Point(v[0], v[1]);
}
/// Converts a point from the local coordinate system of the node to the coordinate system of the [SpriteBox].
///
/// Point pointInBoxCoordinates = myNode.convertPointToBoxSpace(localPoint);
Point convertPointToBoxSpace(Point nodePoint) {
assert(nodePoint != null);
assert(_spriteBox != null);
Vector4 v =_nodeToBoxMatrix().transform(new Vector4(nodePoint.x, nodePoint.y, 0.0, 1.0));
return new Point(v[0], v[1]);
}
/// Converts a [point] from another [node]s coordinate system into the local coordinate system of this node.
///
/// Point pointInNodeASpace = nodeA.convertPointFromNode(pointInNodeBSpace, nodeB);
Point convertPointFromNode(Point point, Node node) {
assert(node != null);
assert(point != null);
assert(_spriteBox != null);
assert(_spriteBox == node._spriteBox);
Point boxPoint = node.convertPointToBoxSpace(point);
Point localPoint = convertPointToNodeSpace(boxPoint);
return localPoint;
}
// Hit test
/// Returns true if the [point] is inside the node, the [point] is in the local coordinate system of the node.
///
/// myNode.isPointInside(localPoint);
///
/// [NodeWithSize] provides a basic bounding box check for this method, if you require a more detailed check this
/// method can be overridden.
///
/// bool isPointInside (Point nodePoint) {
/// double minX = -size.width * pivot.x;
/// double minY = -size.height * pivot.y;
/// double maxX = minX + size.width;
/// double maxY = minY + size.height;
/// return (nodePoint.x >= minX && nodePoint.x < maxX &&
/// nodePoint.y >= minY && nodePoint.y < maxY);
/// }
bool isPointInside(Point point) {
assert(point != null);
return false;
}
// Rendering
void _visit(PaintingCanvas canvas, Matrix4 totalMatrix) {
assert(canvas != null);
if (!visible) return;
_prePaint(canvas, totalMatrix);
_visitChildren(canvas, totalMatrix);
_postPaint(canvas, totalMatrix);
}
void _prePaint(PaintingCanvas canvas, Matrix4 matrix) {
_savedTotalMatrix = new Matrix4.copy(matrix);
// Get the transformation matrix and apply transform
matrix.multiply(transformMatrix);
}
/// Paints this node to the canvas.
///
/// Subclasses, such as [Sprite], override this method to do the actual painting of the node. To do custom
/// drawing override this method and make calls to the [canvas] object. All drawing is done in the node's local
/// coordinate system, relative to the node's position. If you want to make the drawing relative to the node's
/// bounding box's origin, override [NodeWithSize] and call the applyTransformForPivot method before making calls for
/// drawing.
///
/// void paint(PaintingCanvas canvas) {
/// canvas.save();
/// applyTransformForPivot(canvas);
///
/// // Do painting here
///
/// canvas.restore();
/// }
void paint(PaintingCanvas canvas) {
}
void _visitChildren(PaintingCanvas canvas, Matrix4 totalMatrix) {
// Sort children if needed
_sortChildren();
int i = 0;
// Visit children behind this node
while (i < _children.length) {
Node child = _children[i];
if (child.zPosition >= 0.0) break;
child._visit(canvas, totalMatrix);
i++;
}
// Paint this node
canvas.setMatrix(totalMatrix.storage);
paint(canvas);
// Visit children in front of this node
while (i < _children.length) {
Node child = _children[i];
child._visit(canvas, totalMatrix);
i++;
}
}
void _postPaint(PaintingCanvas canvas, Matrix4 totalMatrix) {
totalMatrix.setFrom(_savedTotalMatrix);
}
// Receiving update calls
/// Called before a frame is drawn.
///
/// Override this method to do any updates to the node or node tree before it's drawn to screen.
///
/// // Make the node rotate at a fixed speed
/// void update(double dt) {
/// rotation = rotation * 10.0 * dt;
/// }
void update(double dt) {
}
/// Called whenever the [SpriteBox] is modified or resized, or if the device is rotated.
///
/// Override this method to do any updates that may be necessary to correctly display the node or node tree with the
/// new layout of the [SpriteBox].
///
/// void spriteBoxPerformedLayout() {
/// // Move some stuff around here
/// }
void spriteBoxPerformedLayout() {
}
// Handling user interaction
/// The node will receive user interactions, such as pointer (touch or mouse) events.
///
/// class MyCustomNode extends NodeWithSize {
/// userInteractionEnabled = true;
/// }
bool get userInteractionEnabled => _userInteractionEnabled;
void set userInteractionEnabled(bool userInteractionEnabled) {
_userInteractionEnabled = userInteractionEnabled;
if (_spriteBox != null) _spriteBox._eventTargets = null;
}
/// Handles an event, such as a pointer (touch or mouse) event.
///
/// Override this method to handle events. The node will only receive events if the [userInteractionEnabled] property
/// is set to true and the [isPointInside] method returns true for the position of the pointer down event (default
/// behavior provided by [NodeWithSize]). Unless [handleMultiplePointers] is set to true, the node will only receive
/// events for the first pointer that is down.
///
/// Return true if the node has consumed the event, if an event is consumed it will not be passed on to nodes behind
/// the current node.
///
/// // MyTouchySprite gets transparent when we touch it
/// class MyTouchySprite extends Sprite {
///
/// MyTouchySprite(Image img) : super (img) {
/// userInteractionEnabled = true;
/// }
///
/// bool handleEvent(SpriteBoxEvent event) {
/// if (event.type == 'pointerdown) {
/// opacity = 0.5;
/// }
/// else if (event.type == 'pointerup') {
/// opacity = 1.0;
/// }
/// return true;
/// }
/// }
bool handleEvent(SpriteBoxEvent event) {
return false;
}
}

View File

@@ -0,0 +1,49 @@
part of sprites;
class Node3D extends Node {
double _rotationX = 0.0;
double get rotationX => _rotationX;
set rotationX(double rotationX) {
_rotationX = rotationX;
invalidateTransformMatrix();
}
double _rotationY = 0.0;
double get rotationY => _rotationY;
set rotationY(double rotationY) {
_rotationY = rotationY;
invalidateTransformMatrix();
}
double _projectionDepth = 500.0;
double get projectionDepth => _projectionDepth;
set projectionDepth(double projectionDepth) {
_projectionDepth = projectionDepth;
invalidateTransformMatrix();
}
Matrix4 computeTransformMatrix() {
// Apply normal 2d transforms
Matrix4 matrix = super.computeTransformMatrix();
// Apply perspective projection
Matrix4 projection = new Matrix4(1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, -1.0/_projectionDepth,
0.0, 0.0, 0.0, 1.0);
matrix = matrix.multiply(projection);
// Rotate around x and y axis
matrix.rotateY(radians(_rotationY));
matrix.rotateX(radians(_rotationX));
return matrix;
}
}

View File

@@ -0,0 +1,60 @@
part of sprites;
/// The super class of any [Node] that has a size.
///
/// NodeWithSize adds the ability for a node to have a size and a pivot point.
class NodeWithSize extends Node {
/// Changing the size will affect the size of the rendering of the node.
///
/// myNode.size = new Size(1024.0, 1024.0);
Size size;
/// The normalized point which the node is transformed around.
///
/// // Position myNode from is middle top
/// myNode.pivot = new Point(0.5, 0.0);
Point pivot;
/// Creates a new NodeWithSize.
///
/// The default [size] is zero and the default [pivot] point is the origin. Subclasses may change the default values.
///
/// var myNodeWithSize = new NodeWithSize(new Size(1024.0, 1024.0));
NodeWithSize([Size this.size, Point this.pivot]) {
if (size == null) size = Size.zero;
if (pivot == null) pivot = Point.origin;
}
/// Call this method in your [paint] method if you want the origin of your drawing to be the top left corner of the
/// node's bounding box.
///
/// If you use this method you will need to save and restore your canvas at the beginning and
/// end of your [paint] method.
///
/// void paint(PaintingCanvas canvas) {
/// canvas.save();
/// applyTransformForPivot(canvas);
///
/// // Do painting here
///
/// canvas.restore();
/// }
void applyTransformForPivot(PaintingCanvas canvas) {
if (pivot.x != 0 || pivot.y != 0) {
double pivotInPointsX = size.width * pivot.x;
double pivotInPointsY = size.height * pivot.y;
canvas.translate(-pivotInPointsX, -pivotInPointsY);
}
}
bool isPointInside (Point nodePoint) {
double minX = -size.width * pivot.x;
double minY = -size.height * pivot.y;
double maxX = minX + size.width;
double maxY = minY + size.height;
return (nodePoint.x >= minX && nodePoint.x < maxX &&
nodePoint.y >= minY && nodePoint.y < maxY);
}
}

View File

@@ -0,0 +1,380 @@
part of sprites;
class _Particle {
Vector2 pos;
Vector2 startPos;
double colorPos;
double deltaColorPos;
double size;
double deltaSize;
double rotation;
double deltaRotation;
double timeToLive;
Vector2 dir;
_ParticleAccelerations accelerations;
Float64List simpleColorSequence;
ColorSequence colorSequence;
}
class _ParticleAccelerations {
double radialAccel;
double tangentialAccel;
}
class ParticleSystem extends Node {
Texture texture;
double life;
double lifeVar;
Point posVar;
double startSize;
double startSizeVar;
double endSize;
double endSizeVar;
double startRotation;
double startRotationVar;
double endRotation;
double endRotationVar;
bool rotateToMovement;
double direction;
double directionVar;
double speed;
double speedVar;
double radialAcceleration;
double radialAccelerationVar;
double tangentialAcceleration;
double tangentialAccelerationVar;
Vector2 gravity;
int maxParticles;
int numParticlesToEmit;
double emissionRate;
bool autoRemoveOnFinish;
ColorSequence colorSequence;
int alphaVar;
int redVar;
int greenVar;
int blueVar;
TransferMode colorTransferMode;
TransferMode transferMode;
List<_Particle> _particles;
double _emitCounter;
int _numEmittedParticles = 0;
static Paint _paint = new Paint()
..setFilterQuality(FilterQuality.low)
..isAntiAlias = false;
ParticleSystem(this.texture,
{this.life: 1.5,
this.lifeVar: 1.0,
this.posVar: Point.origin,
this.startSize: 2.5,
this.startSizeVar: 0.5,
this.endSize: 0.0,
this.endSizeVar: 0.0,
this.startRotation: 0.0,
this.startRotationVar: 0.0,
this.endRotation: 0.0,
this.endRotationVar: 0.0,
this.rotateToMovement : false,
this.direction: 0.0,
this.directionVar: 360.0,
this.speed: 100.0,
this.speedVar: 50.0,
this.radialAcceleration: 0.0,
this.radialAccelerationVar: 0.0,
this.tangentialAcceleration: 0.0,
this.tangentialAccelerationVar: 0.0,
this.gravity,
this.maxParticles: 100,
this.emissionRate: 50.0,
this.colorSequence,
this.alphaVar: 0,
this.redVar: 0,
this.greenVar: 0,
this.blueVar: 0,
this.colorTransferMode: TransferMode.multiply,
this.transferMode: TransferMode.plus,
this.numParticlesToEmit: 0,
this.autoRemoveOnFinish: true}) {
_particles = new List<_Particle>();
_emitCounter = 0.0;
// _elapsedTime = 0.0;
if (gravity == null) gravity = new Vector2.zero();
if (colorSequence == null) colorSequence = new ColorSequence.fromStartAndEndColor(new Color(0xffffffff), new Color(0x00ffffff));
}
void update(double dt) {
// TODO: Fix this (it's a temp fix for low framerates)
if (dt > 0.1) dt = 0.1;
// Create new particles
double rate = 1.0 / emissionRate;
if (_particles.length < maxParticles) {
_emitCounter += dt;
}
while(_particles.length < maxParticles
&& _emitCounter > rate
&& (numParticlesToEmit == 0 || _numEmittedParticles < numParticlesToEmit)) {
// Add a new particle
_addParticle();
_emitCounter -= rate;
}
// _elapsedTime += dt;
// Iterate over all particles
for (int i = _particles.length -1; i >= 0; i--) {
_Particle particle = _particles[i];
// Manage life time
particle.timeToLive -= dt;
if (particle.timeToLive <= 0) {
_particles.removeAt(i);
continue;
}
// Update the particle
if (particle.accelerations != null) {
// Radial acceleration
Vector2 radial;
if (particle.pos[0] != 0 || particle.pos[1] != 0) {
radial = new Vector2.copy(particle.pos).normalize();
} else {
radial = new Vector2.zero();
}
Vector2 tangential = new Vector2.copy(radial);
radial.scale(particle.accelerations.radialAccel);
// Tangential acceleration
double newY = tangential.x;
tangential.x = -tangential.y;
tangential.y = newY;
tangential.scale(particle.accelerations.tangentialAccel);
// (gravity + radial + tangential) * dt
Vector2 accel = (gravity + radial + tangential).scale(dt);
particle.dir += accel;
} else if (gravity[0] != 0.0 || gravity[1] != 0) {
// gravity
Vector2 accel = gravity.scale(dt);
particle.dir += accel;
}
// Update particle position
particle.pos[0] += particle.dir[0] * dt;
particle.pos[1] += particle.dir[1] * dt;
// Size
particle.size = math.max(particle.size + particle.deltaSize * dt, 0.0);
// Angle
particle.rotation += particle.deltaRotation * dt;
// Color
if (particle.simpleColorSequence != null) {
for (int i = 0; i < 4; i++) {
particle.simpleColorSequence[i] += particle.simpleColorSequence[i + 4] * dt;
}
} else {
particle.colorPos = math.min(particle.colorPos + particle.deltaColorPos * dt, 1.0);
}
}
if (autoRemoveOnFinish && _particles.length == 0 && _numEmittedParticles > 0) {
if (parent != null) removeFromParent();
}
}
void _addParticle() {
_Particle particle = new _Particle();
// Time to live
particle.timeToLive = math.max(life + lifeVar * randomSignedDouble(), 0.0);
// Position
Point srcPos = Point.origin;
particle.pos = new Vector2(srcPos.x + posVar.x * randomSignedDouble(),
srcPos.y + posVar.y * randomSignedDouble());
// Size
particle.size = math.max(startSize + startSizeVar * randomSignedDouble(), 0.0);
double endSizeFinal = math.max(endSize + endSizeVar * randomSignedDouble(), 0.0);
particle.deltaSize = (endSizeFinal - particle.size) / particle.timeToLive;
// Rotation
particle.rotation = startRotation + startRotationVar * randomSignedDouble();
double endRotationFinal = endRotation + endRotationVar * randomSignedDouble();
particle.deltaRotation = (endRotationFinal - particle.rotation) / particle.timeToLive;
// Direction
double dirRadians = convertDegrees2Radians(direction + directionVar * randomSignedDouble());
Vector2 dirVector = new Vector2(math.cos(dirRadians), math.sin(dirRadians));
double speedFinal = speed + speedVar * randomSignedDouble();
particle.dir = dirVector.scale(speedFinal);
// Accelerations
if (radialAcceleration != 0.0 || radialAccelerationVar != 0.0 ||
tangentialAcceleration != 0.0 || tangentialAccelerationVar != 0.0) {
particle.accelerations = new _ParticleAccelerations();
// Radial acceleration
particle.accelerations.radialAccel = radialAcceleration + radialAccelerationVar * randomSignedDouble();
// Tangential acceleration
particle.accelerations.tangentialAccel = tangentialAcceleration + tangentialAccelerationVar * randomSignedDouble();
}
// Color
particle.colorPos = 0.0;
particle.deltaColorPos = 1.0 / particle.timeToLive;
if (alphaVar != 0 || redVar != 0 || greenVar != 0 || blueVar != 0) {
particle.colorSequence = _ColorSequenceUtil.copyWithVariance(colorSequence, alphaVar, redVar, greenVar, blueVar);
}
// Optimizes the case where there are only two colors in the sequence
if (colorSequence.colors.length == 2) {
Color startColor;
Color endColor;
if (particle.colorSequence != null) {
startColor = particle.colorSequence.colors[0];
endColor = particle.colorSequence.colors[1];
} else {
startColor = colorSequence.colors[0];
endColor = colorSequence.colors[1];
}
// First 4 elements are start ARGB, last 4 are delta ARGB
particle.simpleColorSequence = new Float64List(8);
particle.simpleColorSequence[0] = startColor.alpha.toDouble();
particle.simpleColorSequence[1] = startColor.red.toDouble();
particle.simpleColorSequence[2] = startColor.green.toDouble();
particle.simpleColorSequence[3] = startColor.blue.toDouble();
particle.simpleColorSequence[4] = (endColor.alpha.toDouble() - startColor.alpha.toDouble()) / particle.timeToLive;
particle.simpleColorSequence[5] = (endColor.red.toDouble() - startColor.red.toDouble()) / particle.timeToLive;
particle.simpleColorSequence[6] = (endColor.green.toDouble() - startColor.green.toDouble()) / particle.timeToLive;
particle.simpleColorSequence[7] = (endColor.blue.toDouble() - startColor.blue.toDouble()) / particle.timeToLive;
}
_particles.add(particle);
_numEmittedParticles++;
}
void paint(PaintingCanvas canvas) {
List<RSTransform> transforms = [];
List<Rect> rects = [];
List<Color> colors = [];
_paint.setTransferMode(transferMode);
for (_Particle particle in _particles) {
// Rect
Rect rect = texture.frame;
rects.add(rect);
// Transform
double scos;
double ssin;
if (rotateToMovement) {
double extraRotation = GameMath.atan2(particle.dir[1], particle.dir[0]);
scos = math.cos(convertDegrees2Radians(particle.rotation) + extraRotation) * particle.size;
ssin = math.sin(convertDegrees2Radians(particle.rotation) + extraRotation) * particle.size;
} else if (particle.rotation != 0.0) {
scos = math.cos(convertDegrees2Radians(particle.rotation)) * particle.size;
ssin = math.sin(convertDegrees2Radians(particle.rotation)) * particle.size;
} else {
scos = particle.size;
ssin = 0.0;
}
double ax = rect.width / 2;
double ay = rect.height / 2;
double tx = particle.pos[0] + -scos * ax + ssin * ay;
double ty = particle.pos[1] + -ssin * ax - scos * ay;
RSTransform transform = new RSTransform(scos, ssin, tx, ty);
transforms.add(transform);
// Color
if (particle.simpleColorSequence != null) {
Color particleColor = new Color.fromARGB(
particle.simpleColorSequence[0].toInt().clamp(0, 255),
particle.simpleColorSequence[1].toInt().clamp(0, 255),
particle.simpleColorSequence[2].toInt().clamp(0, 255),
particle.simpleColorSequence[3].toInt().clamp(0, 255));
colors.add(particleColor);
} else {
Color particleColor;
if (particle.colorSequence != null) {
particleColor = particle.colorSequence.colorAtPosition(particle.colorPos);
} else {
particleColor = colorSequence.colorAtPosition(particle.colorPos);
}
colors.add(particleColor);
}
}
canvas.drawAtlas(texture.image, transforms, rects, colors,
TransferMode.modulate, null, _paint);
}
}
class _ColorSequenceUtil {
static ColorSequence copyWithVariance(
ColorSequence sequence,
int alphaVar,
int redVar,
int greenVar,
int blueVar
) {
ColorSequence copy = new ColorSequence.copy(sequence);
int i = 0;
for (Color color in sequence.colors) {
int aDelta = ((randomDouble() * 2.0 - 1.0) * alphaVar).toInt();
int rDelta = ((randomDouble() * 2.0 - 1.0) * redVar).toInt();
int gDelta = ((randomDouble() * 2.0 - 1.0) * greenVar).toInt();
int bDelta = ((randomDouble() * 2.0 - 1.0) * blueVar).toInt();
int aNew = (color.alpha + aDelta).clamp(0, 255);
int rNew = (color.red + rDelta).clamp(0, 255);
int gNew = (color.green + gDelta).clamp(0, 255);
int bNew = (color.blue + bDelta).clamp(0, 255);
copy.colors[i] = new Color.fromARGB(aNew, rNew, gNew, bNew);
i++;
}
return copy;
}
}

View File

@@ -0,0 +1,114 @@
part of sprites;
/// A Sprite is a [Node] that renders a bitmap image to the screen.
class Sprite extends NodeWithSize {
/// The texture that the sprite will render to screen.
///
/// If the texture is null, the sprite will be rendered as a red square
/// marking the bounds of the sprite.
///
/// mySprite.texture = myTexture;
Texture texture;
/// If true, constrains the proportions of the image by scaling it down, if its proportions doesn't match the [size].
///
/// mySprite.constrainProportions = true;
bool constrainProportions = false;
double _opacity = 1.0;
/// The color to draw on top of the sprite, null if no color overlay is used.
///
/// // Color the sprite red
/// mySprite.colorOverlay = new Color(0x77ff0000);
Color colorOverlay;
/// The transfer mode used when drawing the sprite to screen.
///
/// // Add the colors of the sprite with the colors of the background
/// mySprite.transferMode = TransferMode.plusMode;
TransferMode transferMode;
Paint _cachedPaint = new Paint()
..setFilterQuality(FilterQuality.low)
..isAntiAlias = false;
/// Creates a new sprite from the provided [texture].
///
/// var mySprite = new Sprite(myTexture)
Sprite([this.texture]) {
if (texture != null) {
size = texture.size;
pivot = texture.pivot;
} else {
pivot = new Point(0.5, 0.5);
}
}
/// Creates a new sprite from the provided [image].
///
/// var mySprite = new Sprite.fromImage(myImage);
Sprite.fromImage(Image image) {
assert(image != null);
texture = new Texture(image);
size = texture.size;
pivot = new Point(0.5, 0.5);
}
/// The opacity of the sprite in the range 0.0 to 1.0.
///
/// mySprite.opacity = 0.5;
double get opacity => _opacity;
void set opacity(double opacity) {
assert(opacity != null);
assert(opacity >= 0.0 && opacity <= 1.0);
_opacity = opacity;
}
void paint(PaintingCanvas canvas) {
// Account for pivot point
applyTransformForPivot(canvas);
if (texture != null) {
double w = texture.size.width;
double h = texture.size.height;
if (w <= 0 || h <= 0) return;
double scaleX = size.width / w;
double scaleY = size.height / h;
if (constrainProportions) {
// Constrain proportions, using the smallest scale and by centering the image
if (scaleX < scaleY) {
canvas.translate(0.0, (size.height - scaleX * h) / 2.0);
scaleY = scaleX;
} else {
canvas.translate((size.width - scaleY * w) / 2.0, 0.0);
scaleX = scaleY;
}
}
canvas.scale(scaleX, scaleY);
// Setup paint object for opacity and transfer mode
_cachedPaint.color = new Color.fromARGB((255.0*_opacity).toInt(), 255, 255, 255);
if (colorOverlay != null) {
_cachedPaint.setColorFilter(new ColorFilter.mode(colorOverlay, TransferMode.srcATop));
}
if (transferMode != null) {
_cachedPaint.setTransferMode(transferMode);
}
// Do actual drawing of the sprite
texture.drawTexture(canvas, Point.origin, _cachedPaint);
} else {
// Paint a red square for missing texture
canvas.drawRect(new Rect.fromLTRB(0.0, 0.0, size.width, size.height),
new Paint()..color = new Color.fromARGB(255, 255, 0, 0));
}
}
}

View File

@@ -0,0 +1,473 @@
part of sprites;
/// Options for setting up a [SpriteBox].
///
/// * [nativePoints], use the same points as the parent [Widget].
/// * [letterbox], use the size of the root node for the coordinate system, constrain the aspect ratio and trim off
/// areas that end up outside the screen.
/// * [stretch], use the size of the root node for the coordinate system, scale it to fit the size of the box.
/// * [scaleToFit], similar to the letterbox option, but instead of trimming areas the sprite system will be scaled
/// down to fit the box.
/// * [fixedWidth], uses the width of the root node to set the size of the coordinate system, this option will change
/// the height of the root node to fit the box.
/// * [fixedHeight], uses the height of the root node to set the size of the coordinate system, this option will change
/// the width of the root node to fit the box.
enum SpriteBoxTransformMode {
nativePoints,
letterbox,
stretch,
scaleToFit,
fixedWidth,
fixedHeight,
}
class SpriteBox extends RenderBox {
// Member variables
// Root node for drawing
NodeWithSize _rootNode;
void set rootNode (NodeWithSize value) {
if (value == _rootNode) return;
// Ensure that the root node has a size
assert(value.size.width > 0);
assert(value.size.height > 0);
// Remove sprite box references
if (_rootNode != null) _removeSpriteBoxReference(_rootNode);
// Update the value
_rootNode = value;
// Add new references
_addSpriteBoxReference(_rootNode);
markNeedsLayout();
}
// Tracking of frame rate and updates
double _lastTimeStamp;
double _frameRate = 0.0;
double get frameRate => _frameRate;
// Transformation mode
SpriteBoxTransformMode _transformMode;
void set transformMode (SpriteBoxTransformMode value) {
if (value == _transformMode)
return;
_transformMode = value;
// Invalidate stuff
markNeedsLayout();
}
/// The transform mode used by the [SpriteBox].
SpriteBoxTransformMode get transformMode => _transformMode;
// Cached transformation matrix
Matrix4 _transformMatrix;
List<Node> _eventTargets;
List<ActionController> _actionControllers;
Rect _visibleArea;
Rect get visibleArea {
if (_visibleArea == null)
_calcTransformMatrix();
return _visibleArea;
}
// Setup
/// Creates a new SpriteBox with a node as its content, by default uses letterboxing.
///
/// The [rootNode] provides the content of the node tree, typically it's a custom subclass of [NodeWithSize]. The
/// [mode] provides different ways to scale the content to best fit it to the screen. In most cases it's preferred to
/// use a [SpriteWidget] that automatically wraps the SpriteBox.
///
/// var spriteBox = new SpriteBox(myNode, SpriteBoxTransformMode.fixedHeight);
SpriteBox(NodeWithSize rootNode, [SpriteBoxTransformMode mode = SpriteBoxTransformMode.letterbox]) {
assert(rootNode != null);
assert(rootNode._spriteBox == null);
// Setup root node
this.rootNode = rootNode;
// Setup transform mode
this.transformMode = mode;
}
void _removeSpriteBoxReference(Node node) {
node._spriteBox = null;
for (Node child in node._children) {
_removeSpriteBoxReference(child);
}
}
void _addSpriteBoxReference(Node node) {
node._spriteBox = this;
for (Node child in node._children) {
_addSpriteBoxReference(child);
}
}
void attach() {
super.attach();
_scheduleTick();
}
// Properties
/// The root node of the node tree that is rendered by this box.
///
/// var rootNode = mySpriteBox.rootNode;
NodeWithSize get rootNode => _rootNode;
void performLayout() {
size = constraints.biggest;
_invalidateTransformMatrix();
_callSpriteBoxPerformedLayout(_rootNode);
}
// Adding and removing nodes
_registerNode(Node node) {
_actionControllers = null;
_eventTargets = null;
}
_deregisterNode(Node node) {
_actionControllers = null;
_eventTargets = null;
}
// Event handling
void _addEventTargets(Node node, List<Node> eventTargets) {
List children = node.children;
int i = 0;
// Add childrens that are behind this node
while (i < children.length) {
Node child = children[i];
if (child.zPosition >= 0.0)
break;
_addEventTargets(child, eventTargets);
i++;
}
// Add this node
if (node.userInteractionEnabled) {
eventTargets.add(node);
}
// Add children in front of this node
while (i < children.length) {
Node child = children[i];
_addEventTargets(child, eventTargets);
i++;
}
}
EventDisposition handleEvent(Event event, _SpriteBoxHitTestEntry entry) {
if (!attached)
return EventDisposition.ignored;
if (event is PointerEvent) {
if (event.type == 'pointerdown') {
// Build list of event targets
if (_eventTargets == null) {
_eventTargets = [];
_addEventTargets(_rootNode, _eventTargets);
}
// Find the once that are hit by the pointer
List<Node> nodeTargets = [];
for (int i = _eventTargets.length - 1; i >= 0; i--) {
Node node = _eventTargets[i];
// Check if the node is ready to handle a pointer
if (node.handleMultiplePointers || node._handlingPointer == null) {
// Do the hit test
Point posInNodeSpace = node.convertPointToNodeSpace(entry.localPosition);
if (node.isPointInside(posInNodeSpace)) {
nodeTargets.add(node);
node._handlingPointer = event.pointer;
}
}
}
entry.nodeTargets = nodeTargets;
}
// Pass the event down to nodes that were hit by the pointerdown
List<Node> targets = entry.nodeTargets;
for (Node node in targets) {
// Check if this event should be dispatched
if (node.handleMultiplePointers || event.pointer == node._handlingPointer) {
// Dispatch event
bool consumedEvent = node.handleEvent(new SpriteBoxEvent(new Point(event.x, event.y), event.type, event.pointer));
if (consumedEvent == null || consumedEvent)
break;
}
}
// De-register pointer for nodes that doesn't handle multiple pointers
for (Node node in targets) {
if (event.type == 'pointerup' || event.type == 'pointercancel') {
node._handlingPointer = null;
}
}
}
return EventDisposition.ignored;
}
bool hitTest(HitTestResult result, { Point position }) {
result.add(new _SpriteBoxHitTestEntry(this, position));
return true;
}
// Rendering
/// The transformation matrix used to transform the root node to the space of the box.
///
/// It's uncommon to need access to this property.
///
/// var matrix = mySpriteBox.transformMatrix;
Matrix4 get transformMatrix {
// Get cached matrix if available
if (_transformMatrix == null) {
_calcTransformMatrix();
}
return _transformMatrix;
}
void _calcTransformMatrix() {
_transformMatrix = new Matrix4.identity();
// Calculate matrix
double scaleX = 1.0;
double scaleY = 1.0;
double offsetX = 0.0;
double offsetY = 0.0;
double systemWidth = rootNode.size.width;
double systemHeight = rootNode.size.height;
switch(_transformMode) {
case SpriteBoxTransformMode.stretch:
scaleX = size.width/systemWidth;
scaleY = size.height/systemHeight;
break;
case SpriteBoxTransformMode.letterbox:
scaleX = size.width/systemWidth;
scaleY = size.height/systemHeight;
if (scaleX > scaleY) {
scaleY = scaleX;
offsetY = (size.height - scaleY * systemHeight)/2.0;
} else {
scaleX = scaleY;
offsetX = (size.width - scaleX * systemWidth)/2.0;
}
break;
case SpriteBoxTransformMode.scaleToFit:
scaleX = size.width/systemWidth;
scaleY = size.height/systemHeight;
if (scaleX < scaleY) {
scaleY = scaleX;
offsetY = (size.height - scaleY * systemHeight)/2.0;
} else {
scaleX = scaleY;
offsetX = (size.width - scaleX * systemWidth)/2.0;
}
break;
case SpriteBoxTransformMode.fixedWidth:
scaleX = size.width/systemWidth;
scaleY = scaleX;
systemHeight = size.height/scaleX;
rootNode.size = new Size(systemWidth, systemHeight);
break;
case SpriteBoxTransformMode.fixedHeight:
scaleY = size.height/systemHeight;
scaleX = scaleY;
systemWidth = size.width/scaleY;
rootNode.size = new Size(systemWidth, systemHeight);
break;
case SpriteBoxTransformMode.nativePoints:
break;
default:
assert(false);
break;
}
_visibleArea = new Rect.fromLTRB(-offsetX / scaleX,
-offsetY / scaleY,
systemWidth + offsetX / scaleX,
systemHeight + offsetY / scaleY);
_transformMatrix.translate(offsetX, offsetY);
_transformMatrix.scale(scaleX, scaleY);
}
void _invalidateTransformMatrix() {
_visibleArea = null;
_transformMatrix = null;
_rootNode._invalidateToBoxTransformMatrix();
}
void paint(PaintingCanvas canvas, Offset offset) {
canvas.save();
// Move to correct coordinate space before drawing
canvas.translate(offset.dx, offset.dy);
canvas.concat(transformMatrix.storage);
// Draw the sprite tree
Matrix4 totalMatrix = new Matrix4.fromFloat32List(canvas.getTotalMatrix());
_rootNode._visit(canvas, totalMatrix);
canvas.restore();
}
// Updates
void _scheduleTick() {
scheduler.requestAnimationFrame(_tick);
}
void _tick(double timeStamp) {
if (!attached)
return;
// Calculate delta and frame rate
if (_lastTimeStamp == null) _lastTimeStamp = timeStamp;
double delta = (timeStamp - _lastTimeStamp) / 1000;
_lastTimeStamp = timeStamp;
_frameRate = 1.0/delta;
_runActions(delta);
_callUpdate(_rootNode, delta);
// Schedule next update
_scheduleTick();
// Make sure the node graph is redrawn
markNeedsPaint();
}
void _runActions(double dt) {
if (_actionControllers == null) {
_actionControllers = [];
_addActionControllers(_rootNode, _actionControllers);
}
for (ActionController actions in _actionControllers) {
actions.step(dt);
}
}
void _addActionControllers(Node node, List<ActionController> controllers) {
if (node._actions != null) controllers.add(node._actions);
for (int i = node.children.length - 1; i >= 0; i--) {
Node child = node.children[i];
_addActionControllers(child, controllers);
}
}
void _callUpdate(Node node, double dt) {
node.update(dt);
for (int i = node.children.length - 1; i >= 0; i--) {
Node child = node.children[i];
if (!child.paused) {
_callUpdate(child, dt);
}
}
}
void _callSpriteBoxPerformedLayout(Node node) {
node.spriteBoxPerformedLayout();
for (Node child in node.children) {
_callSpriteBoxPerformedLayout(child);
}
}
// Hit tests
/// Finds all nodes at a position defined in the box's coordinates.
///
/// Use this method with caution. It searches the complete node tree to locate the nodes, which can be slow if the
/// node tree is large.
///
/// List nodes = mySpriteBox.findNodesAtPosition(new Point(50.0, 50.0));
List<Node> findNodesAtPosition(Point position) {
assert(position != null);
List<Node> nodes = [];
// Traverse the render tree and find objects at the position
_addNodesAtPosition(_rootNode, position, nodes);
return nodes;
}
_addNodesAtPosition(Node node, Point position, List<Node> list) {
// Visit children first
for (Node child in node.children) {
_addNodesAtPosition(child, position, list);
}
// Do the hit test
Point posInNodeSpace = node.convertPointToNodeSpace(position);
if (node.isPointInside(posInNodeSpace)) {
list.add(node);
}
}
}
class _SpriteBoxHitTestEntry extends BoxHitTestEntry {
List<Node> nodeTargets;
_SpriteBoxHitTestEntry(RenderBox target, Point localPosition) : super(target, localPosition);
}
/// An event that is passed down the node tree when pointer events occur. The SpriteBoxEvent is typically handled in
/// the handleEvent method of [Node].
class SpriteBoxEvent {
/// The position of the event in box coordinates.
///
/// You can use the convertPointToNodeSpace of [Node] to convert the position to local coordinates.
///
/// bool handleEvent(SpriteBoxEvent event) {
/// Point localPosition = convertPointToNodeSpace(event.boxPosition);
/// if (event.type == 'pointerdown') {
/// // Do something!
/// }
/// }
final Point boxPosition;
/// The type of event, there are currently four valid types, 'pointerdown', 'pointermoved', 'pointerup', and
/// 'pointercancel'.
///
/// if (event.type == 'pointerdown') {
/// // Do something!
/// }
final String type;
/// The id of the pointer. Each pointer on the screen will have a unique pointer id.
///
/// if (event.pointer == firstPointerId) {
/// // Do something
/// }
final int pointer;
/// Creates a new SpriteBoxEvent, typically this is done internally inside the SpriteBox.
///
/// var event = new SpriteBoxEvent(new Point(50.0, 50.0), 'pointerdown', 0);
SpriteBoxEvent(this.boxPosition, this.type, this.pointer);
}

View File

@@ -0,0 +1,37 @@
part of sprites;
/// A widget that uses a [SpriteBox] to render a sprite node tree to the screen.
class SpriteWidget extends OneChildRenderObjectWrapper {
/// The rootNode of the sprite node tree.
///
/// var node = mySpriteWidget.rootNode;
final NodeWithSize rootNode;
/// The transform mode used to fit the sprite node tree to the size of the widget.
final SpriteBoxTransformMode transformMode;
/// Creates a new sprite widget with [rootNode] as its content.
///
/// The widget will setup the coordinate space for the sprite node tree using the size of the [rootNode] in
/// combination with the supplied [transformMode]. By default the letterbox transform mode is used. See
/// [SpriteBoxTransformMode] for more details on the different modes.
///
/// The most common way to setup the sprite node graph is to subclass [NodeWithSize] and pass it to the sprite widget.
/// In the custom subclass it's possible to build the node graph, do animations and handle user events.
///
/// var mySpriteTree = new MyCustomNodeWithSize();
/// var mySpriteWidget = new SpriteWidget(mySpriteTree, SpriteBoxTransformMode.fixedHeight);
SpriteWidget(this.rootNode, [this.transformMode = SpriteBoxTransformMode.letterbox]);
SpriteBox get root => super.root;
SpriteBox createNode() => new SpriteBox(rootNode, transformMode);
void syncRenderObject(SpriteWidget old) {
super.syncRenderObject(old);
root.rootNode = rootNode;
root.transformMode = transformMode;
}
}

View File

@@ -0,0 +1,33 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
library sprites;
import 'dart:async';
import 'dart:convert';
import 'dart:math' as math;
import 'dart:typed_data';
import 'dart:sky';
import 'package:sky/animation/curves.dart';
import 'package:sky/base/scheduler.dart' as scheduler;
import 'package:sky/mojo/asset_bundle.dart';
import 'package:sky/rendering/box.dart';
import 'package:sky/rendering/object.dart';
import 'package:sky/widgets/framework.dart';
import 'package:vector_math/vector_math.dart';
part 'action.dart';
part 'color_secuence.dart';
part 'image_map.dart';
part 'node.dart';
part 'node3d.dart';
part 'node_with_size.dart';
part 'particle_system.dart';
part 'sprite.dart';
part 'spritesheet.dart';
part 'sprite_box.dart';
part 'sprite_widget.dart';
part 'texture.dart';
part 'util.dart';

View File

@@ -0,0 +1,74 @@
part of sprites;
/// A sprite sheet packs a number of smaller images into a single large image.
///
/// The placement of the smaller images are defined by a json file. The larger image and json file is typically created
/// by a tool such as TexturePacker. The [SpriteSheet] class will take a reference to a larger image and a json string.
/// From the image and the string the [SpriteSheet] creates a number of [Texture] objects. The names of the frames in
/// the sprite sheet definition are used to reference the different textures.
class SpriteSheet {
Image _image;
Map<String, Texture> _textures = new Map();
/// Creates a new sprite sheet from an [_image] and a sprite sheet [jsonDefinition].
///
/// var mySpriteSheet = new SpriteSheet(myImage, jsonString);
SpriteSheet(this._image, String jsonDefinition) {
assert(_image != null);
assert(jsonDefinition != null);
JsonDecoder decoder = new JsonDecoder();
Map file = decoder.convert(jsonDefinition);
assert(file != null);
List frames = file["frames"];
for (Map frameInfo in frames) {
String fileName = frameInfo["filename"];
Rect frame = _readJsonRect(frameInfo["frame"]);
bool rotated = frameInfo["rotated"];
bool trimmed = frameInfo["trimmed"];
Rect spriteSourceSize = _readJsonRect(frameInfo["spriteSourceSize"]);
Size sourceSize = _readJsonSize(frameInfo["sourceSize"]);
Point pivot = _readJsonPoint(frameInfo["pivot"]);
var texture = new Texture._fromSpriteFrame(_image, fileName, sourceSize, rotated, trimmed, frame,
spriteSourceSize, pivot);
_textures[fileName] = texture;
}
}
Rect _readJsonRect(Map data) {
num x = data["x"];
num y = data["y"];
num w = data["w"];
num h = data["h"];
return new Rect.fromLTRB(x.toDouble(), y.toDouble(), (x + w).toDouble(), (y + h).toDouble());
}
Size _readJsonSize(Map data) {
num w = data["w"];
num h = data["h"];
return new Size(w.toDouble(), h.toDouble());
}
Point _readJsonPoint(Map data) {
num x = data["x"];
num y = data["y"];
return new Point(x.toDouble(), y.toDouble());
}
/// The image used by the sprite sheet.
///
/// var spriteSheetImage = mySpriteSheet.image;
Image get image => _image;
/// Returns a texture by its name.
///
/// var myTexture = mySpriteSheet["example.png"];
Texture operator [](String fileName) => _textures[fileName];
}

View File

@@ -0,0 +1,112 @@
part of sprites;
/// A texture represents a rectangular area of an image and is typically used to draw a sprite to the screen.
///
/// Normally you get a reference to a texture from a [SpriteSheet], but you can also create one from an [Image].
class Texture {
/// The image that this texture is a part of.
///
/// var textureImage = myTexture.image;
final Image image;
/// The logical size of the texture, before being trimmed by the texture packer.
///
/// var textureSize = myTexture.size;
final Size size;
/// The name of the image acts as a tag when acquiring a reference to it.
///
/// myTexture.name = "new_texture_name";
String name;
/// The texture was rotated 90 degrees when being packed into a sprite sheet.
///
/// if (myTexture.rotated) drawRotated();
final bool rotated;
/// The texture was trimmed when being packed into a sprite sheet.
///
/// bool trimmed = myTexture.trimmed
final bool trimmed;
/// The frame of the trimmed texture inside the image.
///
/// Rect frame = myTexture.frame;
final Rect frame;
/// The offset and size of the trimmed texture inside the image.
///
/// Position represents the offset from the logical [size], the size of the rect represents the size of the trimmed
/// texture.
///
/// Rect spriteSourceSize = myTexture.spriteSourceSize;
final Rect spriteSourceSize;
/// The default pivot point for this texture. When creating a [Sprite] from the texture, this is the pivot point that
/// will be used.
///
/// myTexture.pivot = new Point(0.5, 0.5);
Point pivot;
/// Creates a new texture from an [Image] object.
///
/// var myTexture = new Texture(myImage);
Texture(Image image) :
size = new Size(image.width.toDouble(), image.height.toDouble()),
image = image,
trimmed = false,
rotated = false,
frame = new Rect.fromLTRB(0.0, 0.0, image.width.toDouble(), image.height.toDouble()),
spriteSourceSize = new Rect.fromLTRB(0.0, 0.0, image.width.toDouble(), image.height.toDouble()),
pivot = new Point(0.5, 0.5);
Texture._fromSpriteFrame(this.image, this.name, this.size, this.rotated, this.trimmed, this.frame,
this.spriteSourceSize, this.pivot) {
}
Texture textureFromRect(Rect rect, [String name = null]) {
assert(rect != null);
assert(!rotated);
Rect srcFrame = new Rect.fromLTWH(rect.left + frame.left, rect.top + frame.top, rect.size.width, rect.size.height);
Rect dstFrame = new Rect.fromLTWH(0.0, 0.0, rect.size.width, rect.size.height);
return new Texture._fromSpriteFrame(image, name, rect.size, false, false, srcFrame, dstFrame, new Point(0.5, 0.5));
}
void drawTexture(PaintingCanvas canvas, Point position, Paint paint) {
// Get drawing position
double x = position.x;
double y = position.y;
// Draw the texture
if (rotated) {
// Account for position
bool translate = (x != 0 || y != 0);
if (translate) {
canvas.translate(x, y);
}
// Calculate the rotated frame and spriteSourceSize
Size originalFrameSize = frame.size;
Rect rotatedFrame = frame.topLeft & new Size(originalFrameSize.height, originalFrameSize.width);
Point rotatedSpriteSourcePoint = new Point(
-spriteSourceSize.top - (spriteSourceSize.bottom - spriteSourceSize.top),
spriteSourceSize.left);
Rect rotatedSpriteSourceSize = rotatedSpriteSourcePoint & new Size(originalFrameSize.height, originalFrameSize.width);
// Draw the rotated sprite
canvas.rotate(-math.PI/2.0);
canvas.drawImageRect(image, rotatedFrame, rotatedSpriteSourceSize, paint);
canvas.rotate(math.PI/2.0);
// Translate back
if (translate) {
canvas.translate(-x, -y);
}
} else {
// Draw the sprite
Rect dstRect = new Rect.fromLTWH(x + spriteSourceSize.left, y + spriteSourceSize.top, spriteSourceSize.width, spriteSourceSize.height);
canvas.drawImageRect(image, frame, dstRect, paint);
}
}
}

View File

@@ -0,0 +1,83 @@
part of sprites;
math.Random _random = new math.Random();
// Random methods
double randomDouble() {
return _random.nextDouble();
}
double randomSignedDouble() {
return _random.nextDouble() * 2.0 - 1.0;
}
int randomInt(int max) {
return _random.nextInt(max);
}
// atan2
class _Atan2Constants {
_Atan2Constants() {
for (int i = 0; i <= size; i++) {
double f = i.toDouble() / size.toDouble();
ppy[i] = math.atan(f) * stretch / math.PI;
ppx[i] = stretch * 0.5 - ppy[i];
pny[i] = -ppy[i];
pnx[i] = ppy[i] - stretch * 0.5;
npy[i] = stretch - ppy[i];
npx[i] = ppy[i] + stretch * 0.5;
nny[i] = ppy[i] - stretch;
nnx[i] = -stretch * 0.5 - ppy[i];
}
}
static const int size = 1024;
static const double stretch = math.PI;
static const int ezis = -size;
final Float64List ppy = new Float64List(size + 1);
final Float64List ppx = new Float64List(size + 1);
final Float64List pny = new Float64List(size + 1);
final Float64List pnx = new Float64List(size + 1);
final Float64List npy = new Float64List(size + 1);
final Float64List npx = new Float64List(size + 1);
final Float64List nny = new Float64List(size + 1);
final Float64List nnx = new Float64List(size + 1);
}
class GameMath {
static final _Atan2Constants _atan2 = new _Atan2Constants();
static double atan2(double y, double x) {
if (x >= 0) {
if (y >= 0) {
if (x >= y)
return _atan2.ppy[(_Atan2Constants.size * y / x + 0.5).toInt()];
else
return _atan2.ppx[(_Atan2Constants.size * x / y + 0.5).toInt()];
} else {
if (x >= -y)
return _atan2.pny[(_Atan2Constants.ezis * y / x + 0.5).toInt()];
else
return _atan2.pnx[(_Atan2Constants.ezis * x / y + 0.5).toInt()];
}
} else {
if (y >= 0) {
if (-x >= y)
return _atan2.npy[(_Atan2Constants.ezis * y / x + 0.5).toInt()];
else
return _atan2.npx[(_Atan2Constants.ezis * x / y + 0.5).toInt()];
} else {
if (x <= y)
return _atan2.nny[(_Atan2Constants.size * y / x + 0.5).toInt()];
else
return _atan2.nnx[(_Atan2Constants.size * x / y + 0.5).toInt()];
}
}
}
}

View File

@@ -0,0 +1,34 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>game_app</string>
<key>CFBundleIconFile</key>
<string></string>
<key>CFBundleIdentifier</key>
<string>org.domokit.sky.asteroids</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>Asteroids</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSMinimumSystemVersion</key>
<string>10.6</string>
<key>NSHumanReadableCopyright</key>
<string>Copyright © 2015 The Chromium Authors. All rights reserved.</string>
<key>NSMainNibFile</key>
<string>sky_mac</string>
<key>NSPrincipalClass</key>
<string>SkyApplication</string>
</dict>
</plist>

View File

@@ -0,0 +1,695 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="7702" systemVersion="14E46" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES" customObjectInstantitationMethod="direct">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="7702"/>
</dependencies>
<objects>
<customObject id="-2" userLabel="File's Owner" customClass="SkyApplication">
<connections>
<outlet property="delegate" destination="Voe-Tx-rLC" id="GzC-gU-4Uq"/>
</connections>
</customObject>
<customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/>
<customObject id="-3" userLabel="Application" customClass="NSObject"/>
<customObject id="Voe-Tx-rLC" customClass="SkyAppDelegate">
<connections>
<outlet property="window" destination="QvC-M9-y7g" id="gIp-Ho-8D9"/>
</connections>
</customObject>
<customObject id="YLy-65-1bz" customClass="NSFontManager"/>
<menu title="Main Menu" systemMenu="main" id="AYu-sK-qS6">
<items>
<menuItem title="Sky" id="1Xt-HY-uBw">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Sky" systemMenu="apple" id="uQy-DD-JDr">
<items>
<menuItem title="About Sky" id="5kV-Vb-QxS">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="orderFrontStandardAboutPanel:" target="-1" id="Exp-CZ-Vem"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="VOq-y0-SEH"/>
<menuItem title="Preferences…" keyEquivalent="," id="BOF-NM-1cW"/>
<menuItem isSeparatorItem="YES" id="wFC-TO-SCJ"/>
<menuItem title="Services" id="NMo-om-nkz">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Services" systemMenu="services" id="hz9-B4-Xy5"/>
</menuItem>
<menuItem isSeparatorItem="YES" id="4je-JR-u6R"/>
<menuItem title="Hide Sky" keyEquivalent="h" id="Olw-nP-bQN">
<connections>
<action selector="hide:" target="-1" id="PnN-Uc-m68"/>
</connections>
</menuItem>
<menuItem title="Hide Others" keyEquivalent="h" id="Vdr-fp-XzO">
<modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
<connections>
<action selector="hideOtherApplications:" target="-1" id="VT4-aY-XCT"/>
</connections>
</menuItem>
<menuItem title="Show All" id="Kd2-mp-pUS">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="unhideAllApplications:" target="-1" id="Dhg-Le-xox"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="kCx-OE-vgT"/>
<menuItem title="Quit Sky" keyEquivalent="q" id="4sb-4s-VLi">
<connections>
<action selector="terminate:" target="-1" id="Te7-pn-YzF"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="File" id="dMs-cI-mzQ">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="File" id="bib-Uj-vzu">
<items>
<menuItem title="New" keyEquivalent="n" id="Was-JA-tGl">
<connections>
<action selector="newDocument:" target="-1" id="4Si-XN-c54"/>
</connections>
</menuItem>
<menuItem title="Open…" keyEquivalent="o" id="IAo-SY-fd9">
<connections>
<action selector="openDocument:" target="-1" id="bVn-NM-KNZ"/>
</connections>
</menuItem>
<menuItem title="Open Recent" id="tXI-mr-wws">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Open Recent" systemMenu="recentDocuments" id="oas-Oc-fiZ">
<items>
<menuItem title="Clear Menu" id="vNY-rz-j42">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="clearRecentDocuments:" target="-1" id="Daa-9d-B3U"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem isSeparatorItem="YES" id="m54-Is-iLE"/>
<menuItem title="Close" keyEquivalent="w" id="DVo-aG-piG">
<connections>
<action selector="performClose:" target="-1" id="HmO-Ls-i7Q"/>
</connections>
</menuItem>
<menuItem title="Save…" keyEquivalent="s" id="pxx-59-PXV">
<connections>
<action selector="saveDocument:" target="-1" id="teZ-XB-qJY"/>
</connections>
</menuItem>
<menuItem title="Save As…" keyEquivalent="S" id="Bw7-FT-i3A">
<connections>
<action selector="saveDocumentAs:" target="-1" id="mDf-zr-I0C"/>
</connections>
</menuItem>
<menuItem title="Revert to Saved" id="KaW-ft-85H">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="revertDocumentToSaved:" target="-1" id="iJ3-Pv-kwq"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="aJh-i4-bef"/>
<menuItem title="Page Setup…" keyEquivalent="P" id="qIS-W8-SiK">
<modifierMask key="keyEquivalentModifierMask" shift="YES" command="YES"/>
<connections>
<action selector="runPageLayout:" target="-1" id="Din-rz-gC5"/>
</connections>
</menuItem>
<menuItem title="Print…" keyEquivalent="p" id="aTl-1u-JFS">
<connections>
<action selector="print:" target="-1" id="qaZ-4w-aoO"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Edit" id="5QF-Oa-p0T">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Edit" id="W48-6f-4Dl">
<items>
<menuItem title="Undo" keyEquivalent="z" id="dRJ-4n-Yzg">
<connections>
<action selector="undo:" target="-1" id="M6e-cu-g7V"/>
</connections>
</menuItem>
<menuItem title="Redo" keyEquivalent="Z" id="6dh-zS-Vam">
<connections>
<action selector="redo:" target="-1" id="oIA-Rs-6OD"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="WRV-NI-Exz"/>
<menuItem title="Cut" keyEquivalent="x" id="uRl-iY-unG">
<connections>
<action selector="cut:" target="-1" id="YJe-68-I9s"/>
</connections>
</menuItem>
<menuItem title="Copy" keyEquivalent="c" id="x3v-GG-iWU">
<connections>
<action selector="copy:" target="-1" id="G1f-GL-Joy"/>
</connections>
</menuItem>
<menuItem title="Paste" keyEquivalent="v" id="gVA-U4-sdL">
<connections>
<action selector="paste:" target="-1" id="UvS-8e-Qdg"/>
</connections>
</menuItem>
<menuItem title="Paste and Match Style" keyEquivalent="V" id="WeT-3V-zwk">
<modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
<connections>
<action selector="pasteAsPlainText:" target="-1" id="cEh-KX-wJQ"/>
</connections>
</menuItem>
<menuItem title="Delete" id="pa3-QI-u2k">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="delete:" target="-1" id="0Mk-Ml-PaM"/>
</connections>
</menuItem>
<menuItem title="Select All" keyEquivalent="a" id="Ruw-6m-B2m">
<connections>
<action selector="selectAll:" target="-1" id="VNm-Mi-diN"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="uyl-h8-XO2"/>
<menuItem title="Find" id="4EN-yA-p0u">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Find" id="1b7-l0-nxx">
<items>
<menuItem title="Find…" tag="1" keyEquivalent="f" id="Xz5-n4-O0W">
<connections>
<action selector="performFindPanelAction:" target="-1" id="cD7-Qs-BN4"/>
</connections>
</menuItem>
<menuItem title="Find and Replace…" tag="12" keyEquivalent="f" id="YEy-JH-Tfz">
<modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
<connections>
<action selector="performFindPanelAction:" target="-1" id="WD3-Gg-5AJ"/>
</connections>
</menuItem>
<menuItem title="Find Next" tag="2" keyEquivalent="g" id="q09-fT-Sye">
<connections>
<action selector="performFindPanelAction:" target="-1" id="NDo-RZ-v9R"/>
</connections>
</menuItem>
<menuItem title="Find Previous" tag="3" keyEquivalent="G" id="OwM-mh-QMV">
<connections>
<action selector="performFindPanelAction:" target="-1" id="HOh-sY-3ay"/>
</connections>
</menuItem>
<menuItem title="Use Selection for Find" tag="7" keyEquivalent="e" id="buJ-ug-pKt">
<connections>
<action selector="performFindPanelAction:" target="-1" id="U76-nv-p5D"/>
</connections>
</menuItem>
<menuItem title="Jump to Selection" keyEquivalent="j" id="S0p-oC-mLd">
<connections>
<action selector="centerSelectionInVisibleArea:" target="-1" id="IOG-6D-g5B"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Spelling and Grammar" id="Dv1-io-Yv7">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Spelling" id="3IN-sU-3Bg">
<items>
<menuItem title="Show Spelling and Grammar" keyEquivalent=":" id="HFo-cy-zxI">
<connections>
<action selector="showGuessPanel:" target="-1" id="vFj-Ks-hy3"/>
</connections>
</menuItem>
<menuItem title="Check Document Now" keyEquivalent=";" id="hz2-CU-CR7">
<connections>
<action selector="checkSpelling:" target="-1" id="fz7-VC-reM"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="bNw-od-mp5"/>
<menuItem title="Check Spelling While Typing" id="rbD-Rh-wIN">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleContinuousSpellChecking:" target="-1" id="7w6-Qz-0kB"/>
</connections>
</menuItem>
<menuItem title="Check Grammar With Spelling" id="mK6-2p-4JG">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleGrammarChecking:" target="-1" id="muD-Qn-j4w"/>
</connections>
</menuItem>
<menuItem title="Correct Spelling Automatically" id="78Y-hA-62v">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleAutomaticSpellingCorrection:" target="-1" id="2lM-Qi-WAP"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Substitutions" id="9ic-FL-obx">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Substitutions" id="FeM-D8-WVr">
<items>
<menuItem title="Show Substitutions" id="z6F-FW-3nz">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="orderFrontSubstitutionsPanel:" target="-1" id="oku-mr-iSq"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="gPx-C9-uUO"/>
<menuItem title="Smart Copy/Paste" id="9yt-4B-nSM">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleSmartInsertDelete:" target="-1" id="3IJ-Se-DZD"/>
</connections>
</menuItem>
<menuItem title="Smart Quotes" id="hQb-2v-fYv">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleAutomaticQuoteSubstitution:" target="-1" id="ptq-xd-QOA"/>
</connections>
</menuItem>
<menuItem title="Smart Dashes" id="rgM-f4-ycn">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleAutomaticDashSubstitution:" target="-1" id="oCt-pO-9gS"/>
</connections>
</menuItem>
<menuItem title="Smart Links" id="cwL-P1-jid">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleAutomaticLinkDetection:" target="-1" id="Gip-E3-Fov"/>
</connections>
</menuItem>
<menuItem title="Data Detectors" id="tRr-pd-1PS">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleAutomaticDataDetection:" target="-1" id="R1I-Nq-Kbl"/>
</connections>
</menuItem>
<menuItem title="Text Replacement" id="HFQ-gK-NFA">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleAutomaticTextReplacement:" target="-1" id="DvP-Fe-Py6"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Transformations" id="2oI-Rn-ZJC">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Transformations" id="c8a-y6-VQd">
<items>
<menuItem title="Make Upper Case" id="vmV-6d-7jI">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="uppercaseWord:" target="-1" id="sPh-Tk-edu"/>
</connections>
</menuItem>
<menuItem title="Make Lower Case" id="d9M-CD-aMd">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="lowercaseWord:" target="-1" id="iUZ-b5-hil"/>
</connections>
</menuItem>
<menuItem title="Capitalize" id="UEZ-Bs-lqG">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="capitalizeWord:" target="-1" id="26H-TL-nsh"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Speech" id="xrE-MZ-jX0">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Speech" id="3rS-ZA-NoH">
<items>
<menuItem title="Start Speaking" id="Ynk-f8-cLZ">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="startSpeaking:" target="-1" id="654-Ng-kyl"/>
</connections>
</menuItem>
<menuItem title="Stop Speaking" id="Oyz-dy-DGm">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="stopSpeaking:" target="-1" id="dX8-6p-jy9"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Format" id="jxT-CU-nIS">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Format" id="GEO-Iw-cKr">
<items>
<menuItem title="Font" id="Gi5-1S-RQB">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Font" systemMenu="font" id="aXa-aM-Jaq">
<items>
<menuItem title="Show Fonts" keyEquivalent="t" id="Q5e-8K-NDq">
<connections>
<action selector="orderFrontFontPanel:" target="YLy-65-1bz" id="WHr-nq-2xA"/>
</connections>
</menuItem>
<menuItem title="Bold" tag="2" keyEquivalent="b" id="GB9-OM-e27">
<connections>
<action selector="addFontTrait:" target="YLy-65-1bz" id="hqk-hr-sYV"/>
</connections>
</menuItem>
<menuItem title="Italic" tag="1" keyEquivalent="i" id="Vjx-xi-njq">
<connections>
<action selector="addFontTrait:" target="YLy-65-1bz" id="IHV-OB-c03"/>
</connections>
</menuItem>
<menuItem title="Underline" keyEquivalent="u" id="WRG-CD-K1S">
<connections>
<action selector="underline:" target="-1" id="FYS-2b-JAY"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="5gT-KC-WSO"/>
<menuItem title="Bigger" tag="3" keyEquivalent="+" id="Ptp-SP-VEL">
<connections>
<action selector="modifyFont:" target="YLy-65-1bz" id="Uc7-di-UnL"/>
</connections>
</menuItem>
<menuItem title="Smaller" tag="4" keyEquivalent="-" id="i1d-Er-qST">
<connections>
<action selector="modifyFont:" target="YLy-65-1bz" id="HcX-Lf-eNd"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="kx3-Dk-x3B"/>
<menuItem title="Kern" id="jBQ-r6-VK2">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Kern" id="tlD-Oa-oAM">
<items>
<menuItem title="Use Default" id="GUa-eO-cwY">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="useStandardKerning:" target="-1" id="6dk-9l-Ckg"/>
</connections>
</menuItem>
<menuItem title="Use None" id="cDB-IK-hbR">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="turnOffKerning:" target="-1" id="U8a-gz-Maa"/>
</connections>
</menuItem>
<menuItem title="Tighten" id="46P-cB-AYj">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="tightenKerning:" target="-1" id="hr7-Nz-8ro"/>
</connections>
</menuItem>
<menuItem title="Loosen" id="ogc-rX-tC1">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="loosenKerning:" target="-1" id="8i4-f9-FKE"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Ligatures" id="o6e-r0-MWq">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Ligatures" id="w0m-vy-SC9">
<items>
<menuItem title="Use Default" id="agt-UL-0e3">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="useStandardLigatures:" target="-1" id="7uR-wd-Dx6"/>
</connections>
</menuItem>
<menuItem title="Use None" id="J7y-lM-qPV">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="turnOffLigatures:" target="-1" id="iX2-gA-Ilz"/>
</connections>
</menuItem>
<menuItem title="Use All" id="xQD-1f-W4t">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="useAllLigatures:" target="-1" id="KcB-kA-TuK"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Baseline" id="OaQ-X3-Vso">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Baseline" id="ijk-EB-dga">
<items>
<menuItem title="Use Default" id="3Om-Ey-2VK">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="unscript:" target="-1" id="0vZ-95-Ywn"/>
</connections>
</menuItem>
<menuItem title="Superscript" id="Rqc-34-cIF">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="superscript:" target="-1" id="3qV-fo-wpU"/>
</connections>
</menuItem>
<menuItem title="Subscript" id="I0S-gh-46l">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="subscript:" target="-1" id="Q6W-4W-IGz"/>
</connections>
</menuItem>
<menuItem title="Raise" id="2h7-ER-AoG">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="raiseBaseline:" target="-1" id="4sk-31-7Q9"/>
</connections>
</menuItem>
<menuItem title="Lower" id="1tx-W0-xDw">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="lowerBaseline:" target="-1" id="OF1-bc-KW4"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem isSeparatorItem="YES" id="Ndw-q3-faq"/>
<menuItem title="Show Colors" keyEquivalent="C" id="bgn-CT-cEk">
<connections>
<action selector="orderFrontColorPanel:" target="-1" id="mSX-Xz-DV3"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="iMs-zA-UFJ"/>
<menuItem title="Copy Style" keyEquivalent="c" id="5Vv-lz-BsD">
<modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
<connections>
<action selector="copyFont:" target="-1" id="GJO-xA-L4q"/>
</connections>
</menuItem>
<menuItem title="Paste Style" keyEquivalent="v" id="vKC-jM-MkH">
<modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
<connections>
<action selector="pasteFont:" target="-1" id="JfD-CL-leO"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Text" id="Fal-I4-PZk">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Text" id="d9c-me-L2H">
<items>
<menuItem title="Align Left" keyEquivalent="{" id="ZM1-6Q-yy1">
<connections>
<action selector="alignLeft:" target="-1" id="zUv-R1-uAa"/>
</connections>
</menuItem>
<menuItem title="Center" keyEquivalent="|" id="VIY-Ag-zcb">
<connections>
<action selector="alignCenter:" target="-1" id="spX-mk-kcS"/>
</connections>
</menuItem>
<menuItem title="Justify" id="J5U-5w-g23">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="alignJustified:" target="-1" id="ljL-7U-jND"/>
</connections>
</menuItem>
<menuItem title="Align Right" keyEquivalent="}" id="wb2-vD-lq4">
<connections>
<action selector="alignRight:" target="-1" id="r48-bG-YeY"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="4s2-GY-VfK"/>
<menuItem title="Writing Direction" id="H1b-Si-o9J">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Writing Direction" id="8mr-sm-Yjd">
<items>
<menuItem title="Paragraph" enabled="NO" id="ZvO-Gk-QUH">
<modifierMask key="keyEquivalentModifierMask"/>
</menuItem>
<menuItem id="YGs-j5-SAR">
<string key="title"> Default</string>
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="makeBaseWritingDirectionNatural:" target="-1" id="qtV-5e-UBP"/>
</connections>
</menuItem>
<menuItem id="Lbh-J2-qVU">
<string key="title"> Left to Right</string>
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="makeBaseWritingDirectionLeftToRight:" target="-1" id="S0X-9S-QSf"/>
</connections>
</menuItem>
<menuItem id="jFq-tB-4Kx">
<string key="title"> Right to Left</string>
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="makeBaseWritingDirectionRightToLeft:" target="-1" id="5fk-qB-AqJ"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="swp-gr-a21"/>
<menuItem title="Selection" enabled="NO" id="cqv-fj-IhA">
<modifierMask key="keyEquivalentModifierMask"/>
</menuItem>
<menuItem id="Nop-cj-93Q">
<string key="title"> Default</string>
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="makeTextWritingDirectionNatural:" target="-1" id="lPI-Se-ZHp"/>
</connections>
</menuItem>
<menuItem id="BgM-ve-c93">
<string key="title"> Left to Right</string>
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="makeTextWritingDirectionLeftToRight:" target="-1" id="caW-Bv-w94"/>
</connections>
</menuItem>
<menuItem id="RB4-Sm-HuC">
<string key="title"> Right to Left</string>
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="makeTextWritingDirectionRightToLeft:" target="-1" id="EXD-6r-ZUu"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem isSeparatorItem="YES" id="fKy-g9-1gm"/>
<menuItem title="Show Ruler" id="vLm-3I-IUL">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleRuler:" target="-1" id="FOx-HJ-KwY"/>
</connections>
</menuItem>
<menuItem title="Copy Ruler" keyEquivalent="c" id="MkV-Pr-PK5">
<modifierMask key="keyEquivalentModifierMask" control="YES" command="YES"/>
<connections>
<action selector="copyRuler:" target="-1" id="71i-fW-3W2"/>
</connections>
</menuItem>
<menuItem title="Paste Ruler" keyEquivalent="v" id="LVM-kO-fVI">
<modifierMask key="keyEquivalentModifierMask" control="YES" command="YES"/>
<connections>
<action selector="pasteRuler:" target="-1" id="cSh-wd-qM2"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="View" id="H8h-7b-M4v">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="View" id="HyV-fh-RgO">
<items>
<menuItem title="Show Toolbar" keyEquivalent="t" id="snW-S8-Cw5">
<modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
<connections>
<action selector="toggleToolbarShown:" target="-1" id="BXY-wc-z0C"/>
</connections>
</menuItem>
<menuItem title="Customize Toolbar…" id="1UK-8n-QPP">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="runToolbarCustomizationPalette:" target="-1" id="pQI-g3-MTW"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Window" id="aUF-d1-5bR">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Window" systemMenu="window" id="Td7-aD-5lo">
<items>
<menuItem title="Minimize" keyEquivalent="m" id="OY7-WF-poV">
<connections>
<action selector="performMiniaturize:" target="-1" id="VwT-WD-YPe"/>
</connections>
</menuItem>
<menuItem title="Zoom" id="R4o-n2-Eq4">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="performZoom:" target="-1" id="DIl-cC-cCs"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="eu3-7i-yIM"/>
<menuItem title="Bring All to Front" id="LE2-aR-0XJ">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="arrangeInFront:" target="-1" id="DRN-fu-gQh"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Help" id="wpr-3q-Mcd">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Help" systemMenu="help" id="F2S-fz-NVQ">
<items>
<menuItem title="Sky Help" keyEquivalent="?" id="FKE-Sm-Kum">
<connections>
<action selector="showHelp:" target="-1" id="y7X-2Q-9no"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
</items>
</menu>
<window title="Sky" allowsToolTipsWhenApplicationIsInactive="NO" autorecalculatesKeyViewLoop="NO" releasedWhenClosed="NO" animationBehavior="default" id="QvC-M9-y7g" customClass="SkyWindow">
<windowStyleMask key="styleMask" titled="YES" closable="YES" miniaturizable="YES" resizable="YES"/>
<windowPositionMask key="initialPositionMask" leftStrut="YES" rightStrut="YES" topStrut="YES" bottomStrut="YES"/>
<rect key="contentRect" x="335" y="390" width="480" height="360"/>
<rect key="screenRect" x="0.0" y="0.0" width="1920" height="1177"/>
<view key="contentView" id="EiT-Mj-1SZ">
<rect key="frame" x="0.0" y="0.0" width="480" height="360"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<openGLView autoresizesSubviews="NO" useAuxiliaryDepthBufferStencil="NO" useDoubleBufferingEnabled="YES" allowOffline="YES" translatesAutoresizingMaskIntoConstraints="NO" id="AUD-Hu-um3">
<rect key="frame" x="0.0" y="0.0" width="480" height="360"/>
</openGLView>
</subviews>
<constraints>
<constraint firstAttribute="trailing" secondItem="AUD-Hu-um3" secondAttribute="trailing" id="9W1-4Z-nsQ"/>
<constraint firstItem="AUD-Hu-um3" firstAttribute="top" secondItem="EiT-Mj-1SZ" secondAttribute="top" id="KpO-qK-Zhv"/>
<constraint firstAttribute="bottom" secondItem="AUD-Hu-um3" secondAttribute="bottom" id="Myy-UN-4eQ"/>
<constraint firstItem="AUD-Hu-um3" firstAttribute="leading" secondItem="EiT-Mj-1SZ" secondAttribute="leading" id="gf3-3r-c0N"/>
</constraints>
</view>
<connections>
<outlet property="renderSurface" destination="AUD-Hu-um3" id="0jv-sx-91g"/>
</connections>
<point key="canvasLocation" x="128" y="455"/>
</window>
</objects>
</document>

229
examples/game/main.dart Normal file
View File

@@ -0,0 +1,229 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:sky/mojo/asset_bundle.dart';
import 'package:sky/theme/colors.dart' as colors;
import 'package:sky/rendering/object.dart';
import 'package:sky/painting/text_style.dart';
import 'package:sky/widgets/basic.dart';
import 'package:sky/widgets/button_base.dart';
import 'package:sky/widgets/navigator.dart';
import 'package:sky/widgets/framework.dart';
import 'package:sky/widgets/task_description.dart';
import 'package:sky/widgets/theme.dart';
import 'lib/game_demo.dart';
import 'lib/sprites.dart';
AssetBundle _initBundle() {
if (rootBundle != null)
return rootBundle;
return new NetworkAssetBundle(Uri.base);
}
final AssetBundle _bundle = _initBundle();
ImageMap _loader;
SpriteSheet _spriteSheet;
SpriteSheet _spriteSheetUI;
GameDemoApp _app;
main() async {
_loader = new ImageMap(_bundle);
await _loader.load([
'assets/nebula.png',
'assets/sprites.png',
'assets/starfield.png',
'assets/game_ui.png',
]);
String json = await _bundle.loadString('assets/sprites.json');
_spriteSheet = new SpriteSheet(_loader['assets/sprites.png'], json);
json = await _bundle.loadString('assets/game_ui.json');
_spriteSheetUI = new SpriteSheet(_loader["assets/game_ui.png"], json);
_app = new GameDemoApp();
runApp(_app);
}
class GameDemoApp extends App {
NavigationState _navigationState;
GameDemoWorld _game;
int _lastScore = 0;
void initState() {
_navigationState = new NavigationState([
new Route(
name: '/',
builder: _buildMainScene
),
new Route(
name: '/game',
builder: _buildGameScene
),
]);
super.initState();
}
Widget build() {
// TODO(viktork): The task bar purple is the wrong purple, we may need
// a custom theme swatch to match the purples in the sprites.
ThemeData theme = new ThemeData(
brightness: ThemeBrightness.light,
primarySwatch: colors.Purple
);
return new Theme(
data: theme,
child: new TaskDescription(
label: 'Asteroids',
child: new Navigator(_navigationState)
)
);
}
Widget _buildGameScene(navigator, route) {
return new SpriteWidget(_game);
}
Widget _buildMainScene(navigator, route) {
return new Stack([
new SpriteWidget(new MainScreenBackground()),
new Flex([
new TextureButton(
onPressed: () {
_game = new GameDemoWorld(
_app,
navigator,
_loader,
_spriteSheet,
_spriteSheetUI,
(lastScore) {
setState(() {_lastScore = lastScore;});
}
);
navigator.pushNamed('/game');
},
texture: _spriteSheetUI["btn_play_up.png"],
textureDown: _spriteSheetUI["btn_play_down.png"],
width: 128.0,
height: 128.0
),
new Text(
"Last Score: $_lastScore",
style: new TextStyle(fontSize:20.0)
)
],
direction: FlexDirection.vertical,
justifyContent: FlexJustifyContent.center)
]);
}
}
class TextureButton extends ButtonBase {
TextureButton({
Key key,
this.onPressed,
this.texture,
this.textureDown,
this.width: 128.0,
this.height: 128.0
}) : super(key: key);
final Function onPressed;
final Texture texture;
final Texture textureDown;
final double width;
final double height;
Widget buildContent() {
return new Listener(
child: new Container(
width: width,
height: height,
child: new CustomPaint(
callback: paintCallback,
token: new _TextureButtonToken(
highlight,
texture,
textureDown,
width,
height
)
)
),
onPointerUp: (_) {
if (onPressed != null) onPressed();
}
);
}
void paintCallback(PaintingCanvas canvas, Size size) {
if (texture == null)
return;
canvas.save();
if (highlight && textureDown != null) {
// Draw down state
canvas.scale(size.width / textureDown.size.width, size.height / textureDown.size.height);
textureDown.drawTexture(canvas, Point.origin, new Paint());
} else {
// Draw up state
canvas.scale(size.width / texture.size.width, size.height / texture.size.height);
texture.drawTexture(canvas, Point.origin, new Paint());
}
canvas.restore();
}
}
class _TextureButtonToken {
_TextureButtonToken(
this._highlight,
this._texture,
this._textureDown,
this._width,
this._height
);
final bool _highlight;
final Texture _texture;
final Texture _textureDown;
final double _width;
final double _height;
bool operator== (other) {
return
other is _TextureButtonToken &&
_highlight == other._highlight &&
_texture == other._texture &&
_textureDown == other._textureDown &&
_width == other._width &&
_height == other._height;
}
int get hashCode {
int value = 373;
value = 37 * value * _highlight.hashCode;
value = 37 * value * _texture.hashCode;
value = 37 * value * _textureDown.hashCode;
value = 37 * value * _width.hashCode;
value = 37 * value * _height.hashCode;
return value;
}
}
class MainScreenBackground extends NodeWithSize {
MainScreenBackground() : super(new Size(1024.0, 1024.0)) {
Sprite sprtBackground = new Sprite.fromImage(_loader["assets/starfield.png"]);
sprtBackground.position = new Point(512.0, 512.0);
addChild(sprtBackground);
StarField starField = new StarField(_spriteSheet, 200, true);
addChild(starField);
}
}

7
examples/game/sky.yaml Normal file
View File

@@ -0,0 +1,7 @@
assets:
- assets/nebula.png
- assets/sprites.json
- assets/sprites.png
- assets/starfield.png
- assets/game_ui.png
- assets/game_ui.json

View File

@@ -0,0 +1,84 @@
import 'lib/sprites.dart';
import 'dart:sky';
import 'package:sky/mojo/asset_bundle.dart';
import 'package:sky/rendering/object.dart';
import 'package:sky/theme/colors.dart' as colors;
import 'package:sky/widgets/basic.dart';
import 'package:sky/widgets/task_description.dart';
import 'package:sky/widgets/theme.dart';
AssetBundle _initBundle() {
if (rootBundle != null)
return rootBundle;
return new NetworkAssetBundle(Uri.base);
}
final AssetBundle _bundle = _initBundle();
ImageMap _images;
SpriteSheet _spriteSheet;
TestDrawAtlasApp _app;
main() async {
_images = new ImageMap(_bundle);
await _images.load([
'assets/sprites.png'
]);
String json = await _bundle.loadString('assets/sprites.json');
_spriteSheet = new SpriteSheet(_images['assets/sprites.png'], json);
_app = new TestDrawAtlasApp();
runApp(_app);
}
class TestDrawAtlasApp extends App {
Widget build() {
ThemeData theme = new ThemeData(
brightness: ThemeBrightness.light,
primarySwatch: colors.Purple
);
return new Theme(
data: theme,
child: new TaskDescription(
label: 'Test drawAtlas',
child: new SpriteWidget(
new TestDrawAtlas(),
SpriteBoxTransformMode.fixedWidth
)
)
);
}
}
class TestDrawAtlas extends NodeWithSize {
TestDrawAtlas() : super(new Size(1024.0, 1024.0)) {
}
void paint(PaintingCanvas canvas) {
List<RSTransform> transforms = [
new RSTransform(1.0, 0.0, 100.0, 100.0)
];
List<Rect> rects = [
_spriteSheet["ship.png"].frame
];
List<Color> colors = [
new Color(0xffffffff)
];
canvas.drawAtlas(
_spriteSheet.image,
transforms,
rects,
colors,
TransferMode.src,
null,
new Paint()..setFilterQuality(FilterQuality.low)..isAntiAlias=false
);
}
}

View File

@@ -0,0 +1,311 @@
import 'dart:sky' as sky;
import 'dart:math' as math;
import 'package:sky/mojo/asset_bundle.dart';
import 'package:sky/rendering/object.dart';
import 'package:sky/theme/colors.dart' as colors;
import 'package:sky/widgets/basic.dart';
import 'package:sky/widgets/task_description.dart';
import 'package:sky/widgets/theme.dart';
import 'lib/sprites.dart';
AssetBundle _initBundle() {
if (rootBundle != null)
return rootBundle;
return new NetworkAssetBundle(Uri.base);
}
final AssetBundle _bundle = _initBundle();
ImageMap _images;
SpriteSheet _spriteSheet;
TestApp _app;
main() async {
_images = new ImageMap(_bundle);
await _images.load([
'assets/sprites.png'
]);
String json = await _bundle.loadString('assets/sprites.json');
_spriteSheet = new SpriteSheet(_images['assets/sprites.png'], json);
_app = new TestApp();
runApp(_app);
}
class TestApp extends App {
Widget build() {
ThemeData theme = new ThemeData(
brightness: ThemeBrightness.light,
primarySwatch: colors.Purple
);
return new Theme(
data: theme,
child: new TaskDescription(
label: 'Test Sprite Performance',
child: new SpriteWidget(new TestPerformance())
)
);
}
}
class TestPerformance extends NodeWithSize {
final int numFramesPerTest = 100;
final int numTests = 5;
TestPerformance() : super(new Size(1024.0, 1024.0)) {
}
int test = 0;
int frame = 0;
int testStartTime;
void update(double dt) {
if (frame % numFramesPerTest == 0) {
if (test > 0 && test <= numTests) {
// End last test
int currentTime = new DateTime.now().millisecondsSinceEpoch;
int totalTestTime = currentTime - testStartTime;
double millisPerFrame =
totalTestTime.toDouble() / numFramesPerTest.toDouble();
print(" - RESULT fps: ${(1.0 / (millisPerFrame / 1000)).toStringAsFixed(1)} millis/frame: ${millisPerFrame.round()}");
// Clear test
removeAllChildren();
}
if (test < numTests) {
// Start new test
PerformanceTest perfTest = createTest(test);
addChild(perfTest);
print("TEST ${test + 1}/$numTests STARTING: ${perfTest.name}");
testStartTime = new DateTime.now().millisecondsSinceEpoch;
}
test++;
}
frame++;
}
PerformanceTest createTest(int n) {
if (test == 0) {
// Test atlas performance
return new TestPerformanceAtlas();
} else if (test == 1) {
// Test atlas performance
return new TestPerformanceAtlas2();
} else if (test == 2) {
// Test sprite performance
return new TestPerformanceSprites();
} else if (test == 3) {
// Test sprite performance
return new TestPerformanceSprites2();
} else if (test == 4) {
// Test particle performance
return new TestPerformanceParticles();
}
return null;
}
}
abstract class PerformanceTest extends Node {
String get name;
}
class TestPerformanceParticles extends PerformanceTest {
String get name => "64 particle systems";
final grid = 8;
TestPerformanceParticles() {
for (int x = 0; x < grid; x++) {
for (int y = 0; y < grid; y++) {
ParticleSystem particles = new ParticleSystem(
_spriteSheet["explosion_particle.png"],
rotateToMovement: true,
startRotation:90.0,
startRotationVar: 0.0,
endRotation: 90.0,
startSize: 0.3,
startSizeVar: 0.1,
endSize: 0.3,
endSizeVar: 0.1,
emissionRate:100.0,
greenVar: 127,
redVar: 127
);
particles.position = new Point(x * 1024.0 / (grid - 1), y * 1024.0 / (grid - 1));
addChild(particles);
}
}
}
}
class TestPerformanceSprites extends PerformanceTest {
String get name => "1001 sprites (24% offscreen)";
final int grid = 100;
TestPerformanceSprites() {
for (int x = 0; x < grid; x++) {
for (int y = 0; y < grid; y++) {
Sprite sprt = new Sprite(_spriteSheet["asteroid_big_1.png"]);
sprt.scale = 1.0;
sprt.position = new Point(x * 1024.0 / (grid - 1), y * 1024.0 / (grid - 1));
addChild(sprt);
//sprt.actions.run(new ActionRepeatForever(new ActionTween((a) => sprt.rotation = a, 0.0, 360.0, 1.0)));
}
}
Sprite sprt = new Sprite(_spriteSheet["asteroid_big_1.png"]);
sprt.position = new Point(512.0, 512.0);
addChild(sprt);
}
void update(double dt) {
for (Sprite sprt in children) {
sprt.rotation += 1;
}
}
}
class TestPerformanceSprites2 extends PerformanceTest {
String get name => "1001 sprites (24% offscreen never added)";
final int grid = 100;
TestPerformanceSprites2() {
for (int x = 12; x < grid - 12; x++) {
for (int y = 0; y < grid; y++) {
Sprite sprt = new Sprite(_spriteSheet["asteroid_big_1.png"]);
sprt.scale = 1.0;
sprt.position = new Point(x * 1024.0 / (grid - 1), y * 1024.0 / (grid - 1));
addChild(sprt);
//sprt.actions.run(new ActionRepeatForever(new ActionTween((a) => sprt.rotation = a, 0.0, 360.0, 1.0)));
}
}
Sprite sprt = new Sprite(_spriteSheet["asteroid_big_1.png"]);
sprt.position = new Point(512.0, 512.0);
addChild(sprt);
}
void update(double dt) {
for (Sprite sprt in children) {
sprt.rotation += 1;
}
}
}
class TestPerformanceAtlas extends PerformanceTest {
String get name => "1001 rects drawAtlas (24% offscreen)";
final int grid = 100;
double rotation = 0.0;
List<Rect> rects = [];
Paint cachedPaint = new Paint()
..setFilterQuality(sky.FilterQuality.low)
..isAntiAlias = false;
TestPerformanceAtlas() {
for (int x = 0; x < grid; x++) {
for (int y = 0; y < grid; y++) {
rects.add(_spriteSheet["asteroid_big_1.png"].frame);
}
}
rects.add(_spriteSheet["asteroid_big_1.png"].frame);
}
void paint(PaintingCanvas canvas) {
// Setup transforms
List<sky.RSTransform> transforms = [];
for (int x = 0; x < grid; x++) {
for (int y = 0; y < grid; y++) {
double xPos = x * 1024.0 / (grid - 1);
double yPos = y * 1024.0 / (grid - 1);
transforms.add(createTransform(xPos, yPos, rects[0].size.width / 2.0, rects[0].size.height / 2.0, rotation, 1.0));
}
}
transforms.add(createTransform(512.0, 512.0, rects[0].size.width / 2.0, rects[0].size.height / 2.0, rotation, 1.0));
// Draw atlas
Rect cullRect = spriteBox.visibleArea;
canvas.drawAtlas(_spriteSheet.image, transforms, rects, null, null, cullRect, cachedPaint);
}
void update(double dt) {
rotation += 1.0;
}
sky.RSTransform createTransform(double x, double y, double ax, double ay, double rot, double scale) {
double scos = math.cos(convertDegrees2Radians(rot)) * scale;
double ssin = math.sin(convertDegrees2Radians(rot)) * scale;
double tx = x + -scos * ax + ssin * ay;
double ty = y + -ssin * ax - scos * ay;
return new sky.RSTransform(scos, ssin, tx, ty);
}
}
class TestPerformanceAtlas2 extends PerformanceTest {
String get name => "1001 rects drawAtlas (24% offscreen never added)";
final int grid = 100;
double rotation = 0.0;
List<Rect> rects = [];
Paint cachedPaint = new Paint()
..setFilterQuality(sky.FilterQuality.low)
..isAntiAlias = false;
TestPerformanceAtlas2() {
for (int x = 12; x < grid - 12; x++) {
for (int y = 0; y < grid; y++) {
rects.add(_spriteSheet["asteroid_big_1.png"].frame);
}
}
rects.add(_spriteSheet["asteroid_big_1.png"].frame);
}
void paint(PaintingCanvas canvas) {
// Setup transforms
List<sky.RSTransform> transforms = [];
for (int x = 12; x < grid - 12; x++) {
for (int y = 0; y < grid; y++) {
double xPos = x * 1024.0 / (grid - 1);
double yPos = y * 1024.0 / (grid - 1);
transforms.add(createTransform(xPos, yPos, rects[0].size.width / 2.0, rects[0].size.height / 2.0, rotation, 1.0));
}
}
transforms.add(createTransform(512.0, 512.0, rects[0].size.width / 2.0, rects[0].size.height / 2.0, rotation, 1.0));
// Draw atlas
Rect cullRect = spriteBox.visibleArea;
canvas.drawAtlas(_spriteSheet.image, transforms, rects, null, null, cullRect, cachedPaint);
}
void update(double dt) {
rotation += 1.0;
}
sky.RSTransform createTransform(double x, double y, double ax, double ay, double rot, double scale) {
double scos = math.cos(convertDegrees2Radians(rot)) * scale;
double ssin = math.sin(convertDegrees2Radians(rot)) * scale;
double tx = x + -scos * ax + ssin * ay;
double ty = y + -ssin * ax - scos * ay;
return new sky.RSTransform(scos, ssin, tx, ty);
}
}

View File

@@ -0,0 +1,309 @@
import 'dart:math' as math;
import 'dart:typed_data';
import 'package:vector_math/vector_math.dart';
main() {
runTest();
}
const int numSystems = 1000;
const int numFrames = 1000;
void runTest() {
int timeStart;
timeStart = new DateTime.now().millisecondsSinceEpoch;
// Create systems
List<TestParticleSystem> systems = [];
for (int i = 0; i < numSystems; i++) {
systems.add(new TestParticleSystem());
}
int timeAfterCreate = new DateTime.now().millisecondsSinceEpoch;
print("TIME creation ${(timeAfterCreate - timeStart) / 1000.0}");
timeStart = new DateTime.now().millisecondsSinceEpoch;
// Update systems
for (int frame = 0; frame < numFrames; frame++) {
for (int i = 0; i < numSystems; i++) {
systems[i].update(1.0 / 60.0);
}
}
int timeAfterUpdates = new DateTime.now().millisecondsSinceEpoch;
print("TIME updates ${(timeAfterUpdates - timeStart) / 1000.0}");
timeStart = new DateTime.now().millisecondsSinceEpoch;
// Calculate matrices
for (int frame = 0; frame < numFrames; frame++) {
for (int i = 0; i < numSystems; i++) {
systems[i].paint();
}
}
int timeAfterMatrices = new DateTime.now().millisecondsSinceEpoch;
print("TIME matrices ${(timeAfterMatrices - timeStart) / 1000.0}");
}
class TestParticle {
Vector2 pos;
Vector2 startPos;
double colorPos;
double deltaColorPos;
double size;
double deltaSize;
double rotation;
double deltaRotation;
double timeToLive;
Vector2 dir;
double radialAccel;
double tangentialAccel;
Float64List simpleColorSequence;
Matrix4 transform;
}
class TestParticleSystem {
double life;
double lifeVar;
Vector2 posVar;
double startSize;
double startSizeVar;
double endSize;
double endSizeVar;
double startRotation;
double startRotationVar;
double endRotation;
double endRotationVar;
double direction;
double directionVar;
double speed;
double speedVar;
double radialAcceleration;
double radialAccelerationVar;
double tangentialAcceleration;
double tangentialAccelerationVar;
Vector2 gravity;
int maxParticles;
int numParticlesToEmit;
double emissionRate;
List<TestParticle> _particles;
double _emitCounter;
int _numEmittedParticles = 0;
TestParticleSystem({this.life: 1.5,
this.lifeVar: 0.0,
this.startSize: 2.5,
this.startSizeVar: 0.5,
this.endSize: 0.0,
this.endSizeVar: 0.0,
this.startRotation: 0.0,
this.startRotationVar: 0.0,
this.endRotation: 0.0,
this.endRotationVar: 0.0,
this.direction: 0.0,
this.directionVar: 360.0,
this.speed: 100.0,
this.speedVar: 50.0,
this.radialAcceleration: 0.0,
this.radialAccelerationVar: 0.0,
this.tangentialAcceleration: 0.0,
this.tangentialAccelerationVar: 0.0,
this.gravity,
this.maxParticles: 100,
this.emissionRate: 50.0,
this.numParticlesToEmit: 0}) {
posVar = new Vector2.zero();
_particles = new List<TestParticle>();
_emitCounter = 0.0;
gravity = new Vector2.zero();
}
void update(double dt) {
// Create new particles
double rate = 1.0 / emissionRate;
if (_particles.length < maxParticles) {
_emitCounter += dt;
}
while(_particles.length < maxParticles
&& _emitCounter > rate
&& (numParticlesToEmit == 0 || _numEmittedParticles < numParticlesToEmit)) {
// Add a new particle
_addParticle();
_emitCounter -= rate;
}
// Iterate over all particles
for (int i = _particles.length -1; i >= 0; i--) {
TestParticle particle = _particles[i];
// Manage life time
particle.timeToLive -= dt;
if (particle.timeToLive <= 0) {
_particles.removeAt(i);
continue;
}
// Update the particle
// Radial acceleration
Vector2 radial;
if (particle.pos[0] != 0 || particle.pos[1] != 0) {
radial = new Vector2.copy(particle.pos).normalize();
} else {
radial = new Vector2.zero();
}
Vector2 tangential = new Vector2.copy(radial);
radial.scale(particle.radialAccel);
// Tangential acceleration
double newY = tangential.x;
tangential.x = -tangential.y;
tangential.y = newY;
tangential.scale(particle.tangentialAccel);
// (gravity + radial + tangential) * dt
Vector2 accel = (gravity + radial + tangential).scale(dt);
particle.dir += accel;
// Update particle position
particle.pos[0] += particle.dir[0] * dt;
particle.pos[1] += particle.dir[1] * dt;
// Size
particle.size = math.max(particle.size + particle.deltaSize * dt, 0.0);
// Angle
particle.rotation += particle.deltaRotation * dt;
// Color
if (particle.simpleColorSequence != null) {
for (int i = 0; i < 4; i++) {
particle.simpleColorSequence[i] += particle.simpleColorSequence[i + 4] * dt;
}
} else {
particle.colorPos = math.min(particle.colorPos + particle.deltaColorPos * dt, 1.0);
}
}
}
void _addParticle() {
TestParticle particle = new TestParticle();
// Time to live
particle.timeToLive = math.max(life + lifeVar * randomSignedDouble(), 0.0);
// Position
Vector2 srcPos = new Vector2.zero();
particle.pos = new Vector2(srcPos.x + posVar.x * randomSignedDouble(),
srcPos.y + posVar.y * randomSignedDouble());
// Size
particle.size = math.max(startSize + startSizeVar * randomSignedDouble(), 0.0);
double endSizeFinal = math.max(endSize + endSizeVar * randomSignedDouble(), 0.0);
particle.deltaSize = (endSizeFinal - particle.size) / particle.timeToLive;
// Rotation
particle.rotation = startRotation + startRotationVar * randomSignedDouble();
double endRotationFinal = endRotation + endRotationVar * randomSignedDouble();
particle.deltaRotation = (endRotationFinal - particle.rotation) / particle.timeToLive;
// Direction
double dirRadians = radians(direction + directionVar * randomSignedDouble());
Vector2 dirVector = new Vector2(math.cos(dirRadians), math.sin(dirRadians));
double speedFinal = speed + speedVar * randomSignedDouble();
particle.dir = dirVector.scale(speedFinal);
// Radial acceleration
particle.radialAccel = radialAcceleration + radialAccelerationVar * randomSignedDouble();
// Tangential acceleration
particle.tangentialAccel = tangentialAcceleration + tangentialAccelerationVar * randomSignedDouble();
// Colors
particle.simpleColorSequence = new Float64List(8);
particle.simpleColorSequence[0] = 255.0;
particle.simpleColorSequence[1] = 255.0;
particle.simpleColorSequence[2] = 255.0;
particle.simpleColorSequence[3] = 255.0;
particle.simpleColorSequence[4] = 255.0;
particle.simpleColorSequence[5] = 0.0;
particle.simpleColorSequence[6] = 0.0;
particle.simpleColorSequence[7] = 0.0;
// Transform
particle.transform = new Matrix4.identity();
// Add particle
_particles.add(particle);
_numEmittedParticles++;
}
void paint() {
if (!printed) {
printed = true;
}
for (int i = _particles.length -1; i >= 0; i--) {
TestParticle particle = _particles[i];
particle.rotation + randomSignedDouble();
// Transform
double c = math.cos(radians(particle.rotation));
double s = math.sin(radians(particle.rotation));
// Create transformation matrix for scale, position and rotation
Matrix4 matrix = new Matrix4(c * particle.size, s * particle.size, 0.0, 0.0,
-s * particle.size, c * particle.size, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
particle.pos.x, particle.pos.y, 0.0, 1.0);
particle.transform.multiply(matrix);
}
}
}
math.Random _random = new math.Random();
bool printed = false;
// Random methods
double randomDouble() {
return _random.nextDouble();
}
double randomSignedDouble() {
return _random.nextDouble() * 2.0 - 1.0;
}
int randomInt(int max) {
return _random.nextInt(max);
}

View File

@@ -0,0 +1,15 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:sky/widgets.dart';
class HelloWorldApp extends App {
Widget build() {
return new Center(child: new Text('Hello, world!'));
}
}
void main() {
runApp(new HelloWorldApp());
}

View File

@@ -0,0 +1,13 @@
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import("//sky/build/sky_app.gni")
sky_app("mine_digger") {
main_dart = "lib/main.dart"
if (is_android) {
apk_name = "MineDigger"
}
}

View File

@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright 2015 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.domokit.mine_digger">
<uses-sdk android:minSdkVersion="14" android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET"/>
<application android:name="org.domokit.sky.shell.SkyApplication" android:label="Mine Digger">
<activity android:name="org.domokit.sky.shell.SkyActivity"
android:launchMode="singleTask"
android:theme="@android:style/Theme.Black.NoTitleBar"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize"
android:hardwareAccelerated="true">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>

View File

@@ -0,0 +1,365 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:sky' as sky;
import 'dart:math';
import 'package:sky/painting/text_style.dart';
import 'package:sky/rendering/flex.dart';
import 'package:sky/theme/colors.dart' as colors;
import 'package:sky/widgets.dart';
// Classic minesweeper-inspired game. The mouse controls are standard
// except for left + right combo which is not implemented. For touch,
// the duration of the pointer determines probing versus flagging.
//
// There are only 3 classes to understand. MineDiggerApp, which is
// contains all the logic and two classes that describe the mines:
// CoveredMineNode and ExposedMineNode, none of them holding state.
// Colors for each mine count (0-8):
const List<TextStyle> textStyles = const <TextStyle>[
const TextStyle(color: const Color(0xFF555555), fontWeight: bold),
const TextStyle(color: const Color(0xFF0094FF), fontWeight: bold), // blue
const TextStyle(color: const Color(0xFF13A023), fontWeight: bold), // green
const TextStyle(color: const Color(0xFFDA1414), fontWeight: bold), // red
const TextStyle(color: const Color(0xFF1E2347), fontWeight: bold), // black
const TextStyle(color: const Color(0xFF7F0037), fontWeight: bold), // dark red
const TextStyle(color: const Color(0xFF000000), fontWeight: bold),
const TextStyle(color: const Color(0xFF000000), fontWeight: bold),
const TextStyle(color: const Color(0xFF000000), fontWeight: bold),
];
enum CellState { covered, exploded, cleared, flagged, shown }
class MineDiggerApp extends App {
static const int rows = 9;
static const int cols = 9;
static const int totalMineCount = 11;
bool alive;
bool hasWon;
int detectedCount;
// |cells| keeps track of the positions of the mines.
List<List<bool>> cells;
// |uiState| keeps track of the visible player progess.
List<List<CellState>> uiState;
void initState() {
resetGame();
}
void resetGame() {
alive = true;
hasWon = false;
detectedCount = 0;
// Build the arrays.
cells = new List<List<bool>>();
uiState = new List<List<CellState>>();
for (int iy = 0; iy != rows; iy++) {
cells.add(new List<bool>());
uiState.add(new List<CellState>());
for (int ix = 0; ix != cols; ix++) {
cells[iy].add(false);
uiState[iy].add(CellState.covered);
}
}
// Place the mines.
Random random = new Random();
int cellsRemaining = rows * cols;
int minesRemaining = totalMineCount;
for (int x = 0; x < cols; x += 1) {
for (int y = 0; y < rows; y += 1) {
if (random.nextInt(cellsRemaining) < minesRemaining) {
cells[y][x] = true;
minesRemaining -= 1;
if (minesRemaining <= 0)
return;
}
cellsRemaining -= 1;
}
}
assert(false);
}
Stopwatch longPressStopwatch;
PointerEventListener _pointerDownHandlerFor(int posX, int posY) {
return (sky.PointerEvent event) {
if (event.buttons == 1) {
probe(posX, posY);
} else if (event.buttons == 2) {
flag(posX, posY);
} else {
// Touch event.
longPressStopwatch = new Stopwatch()..start();
}
};
}
PointerEventListener _pointerUpHandlerFor(int posX, int posY) {
return (sky.PointerEvent event) {
if (longPressStopwatch == null)
return;
// Pointer down was a touch event.
if (longPressStopwatch.elapsedMilliseconds < 250) {
probe(posX, posY);
} else {
// Long press flags.
flag(posX, posY);
}
longPressStopwatch = null;
};
}
Widget buildBoard() {
bool hasCoveredCell = false;
List<Flex> flexRows = <Flex>[];
for (int iy = 0; iy != 9; iy++) {
List<Widget> row = <Widget>[];
for (int ix = 0; ix != 9; ix++) {
CellState state = uiState[iy][ix];
int count = mineCount(ix, iy);
if (!alive) {
if (state != CellState.exploded)
state = cells[iy][ix] ? CellState.shown : state;
}
if (state == CellState.covered) {
row.add(new Listener(
onPointerDown: _pointerDownHandlerFor(ix, iy),
onPointerUp: _pointerUpHandlerFor(ix, iy),
child: new CoveredMineNode(
flagged: false,
posX: ix,
posY: iy
)
));
// Mutating |hasCoveredCell| here is hacky, but convenient, same
// goes for mutating |hasWon| below.
hasCoveredCell = true;
} else if (state == CellState.flagged) {
row.add(new CoveredMineNode(
flagged: true,
posX: ix,
posY: iy
));
} else {
row.add(new ExposedMineNode(
state: state,
count: count
));
}
}
flexRows.add(
new Flex(
row,
direction: FlexDirection.horizontal,
justifyContent: FlexJustifyContent.center,
key: new Key.stringify(iy)
)
);
}
if (!hasCoveredCell) {
// all cells uncovered. Are all mines flagged?
if ((detectedCount == totalMineCount) && alive) {
hasWon = true;
}
}
return new Container(
padding: new EdgeDims.all(10.0),
margin: new EdgeDims.all(10.0),
decoration: new BoxDecoration(backgroundColor: const Color(0xFF6B6B6B)),
child: new Flex(
flexRows,
direction: FlexDirection.vertical
)
);
}
Widget buildToolBar() {
String toolbarCaption = hasWon ?
'Awesome!!' : alive ?
'Mine Digger [$detectedCount-$totalMineCount]': 'Kaboom! [press here]';
return new ToolBar(
// FIXME: Strange to have the toolbar be tapable.
center: new Listener(
onPointerDown: handleToolbarPointerDown,
child: new Text(toolbarCaption, style: Theme.of(this).text.title)
)
);
}
Widget build() {
// We build the board before we build the toolbar because we compute the win state during build step.
Widget board = buildBoard();
return new TaskDescription(
label: 'Mine Digger',
child: new Scaffold(
toolbar: buildToolBar(),
body: new Container(
child: new Center(child: board),
decoration: new BoxDecoration(backgroundColor: colors.Grey[50])
)
)
);
}
EventDisposition handleToolbarPointerDown(sky.PointerEvent event) {
setState(() {
resetGame();
});
return EventDisposition.processed;
}
// User action. The user uncovers the cell which can cause losing the game.
void probe(int x, int y) {
if (!alive)
return;
if (uiState[y][x] == CellState.flagged)
return;
setState(() {
// Allowed to probe.
if (cells[y][x]) {
// Probed on a mine --> dead!!
uiState[y][x] = CellState.exploded;
alive = false;
} else {
// No mine, uncover nearby if possible.
cull(x, y);
}
});
}
// User action. The user is sure a mine is at this location.
void flag(int x, int y) {
setState(() {
if (uiState[y][x] == CellState.flagged) {
uiState[y][x] = CellState.covered;
--detectedCount;
} else {
uiState[y][x] = CellState.flagged;
++detectedCount;
}
});
}
// Recursively uncovers cells whose totalMineCount is zero.
void cull(int x, int y) {
if ((x < 0) || (x > rows - 1))
return;
if ((y < 0) || (y > cols - 1))
return;
if (uiState[y][x] == CellState.cleared)
return;
uiState[y][x] = CellState.cleared;
if (mineCount(x, y) > 0)
return;
cull(x - 1, y);
cull(x + 1, y);
cull(x, y - 1);
cull(x, y + 1 );
cull(x - 1, y - 1);
cull(x + 1, y + 1);
cull(x + 1, y - 1);
cull(x - 1, y + 1);
}
int mineCount(int x, int y) {
int count = 0;
int my = cols - 1;
int mx = rows - 1;
count += x > 0 ? bombs(x - 1, y) : 0;
count += x < mx ? bombs(x + 1, y) : 0;
count += y > 0 ? bombs(x, y - 1) : 0;
count += y < my ? bombs(x, y + 1 ) : 0;
count += (x > 0) && (y > 0) ? bombs(x - 1, y - 1) : 0;
count += (x < mx) && (y < my) ? bombs(x + 1, y + 1) : 0;
count += (x < mx) && (y > 0) ? bombs(x + 1, y - 1) : 0;
count += (x > 0) && (y < my) ? bombs(x - 1, y + 1) : 0;
return count;
}
int bombs(int x, int y) {
return cells[y][x] ? 1 : 0;
}
}
Widget buildCell(Widget child) {
return new Container(
padding: new EdgeDims.all(1.0),
height: 27.0, width: 27.0,
decoration: new BoxDecoration(backgroundColor: const Color(0xFFC0C0C0)),
margin: new EdgeDims.all(2.0),
child: child
);
}
Widget buildInnerCell(Widget child) {
return new Container(
padding: new EdgeDims.all(1.0),
margin: new EdgeDims.all(3.0),
height: 17.0, width: 17.0,
child: child
);
}
class CoveredMineNode extends Component {
CoveredMineNode({ this.flagged, this.posX, this.posY });
final bool flagged;
final int posX;
final int posY;
Widget build() {
Widget text;
if (flagged)
text = buildInnerCell(new StyledText(elements : [textStyles[5], '\u2691']));
Container inner = new Container(
margin: new EdgeDims.all(2.0),
height: 17.0, width: 17.0,
decoration: new BoxDecoration(backgroundColor: const Color(0xFFD9D9D9)),
child: text
);
return buildCell(inner);
}
}
class ExposedMineNode extends Component {
ExposedMineNode({ this.state, this.count });
final CellState state;
final int count;
Widget build() {
StyledText text;
if (state == CellState.cleared) {
// Uncovered cell with nearby mine count.
if (count != 0)
text = new StyledText(elements : [textStyles[count], '$count']);
} else {
// Exploded mine or shown mine for 'game over'.
int color = state == CellState.exploded ? 3 : 0;
text = new StyledText(elements : [textStyles[color], '\u2600']);
}
return buildCell(buildInnerCell(text));
}
}
void main() {
runApp(new MineDiggerApp());
}

View File

@@ -0,0 +1,65 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:sky' as sky;
void drawText(sky.Canvas canvas, String lh) {
sky.Paint paint = new sky.Paint();
// offset down
canvas.translate(0.0, 100.0);
// set up the text
sky.Document document = new sky.Document();
sky.Text arabic = document.createText("مرحبا");
sky.Text english = document.createText(" Hello");
sky.Element block = document.createElement('div');
block.style['display'] = 'paragraph';
block.style['font-family'] = 'monospace';
block.style['font-size'] = '50px';
block.style['line-height'] = lh;
block.style['color'] = '#0000A0';
block.appendChild(arabic);
block.appendChild(english);
sky.LayoutRoot layoutRoot = new sky.LayoutRoot();
layoutRoot.rootElement = block;
layoutRoot.maxWidth = sky.view.width - 20.0; // you need to set a width for this to paint
layoutRoot.layout();
// draw a line at the text's baseline
sky.Path path = new sky.Path();
path.moveTo(0.0, 0.0);
path.lineTo(block.maxContentWidth, 0.0);
path.moveTo(0.0, block.alphabeticBaseline);
path.lineTo(block.maxContentWidth, block.alphabeticBaseline);
path.moveTo(0.0, block.height);
path.lineTo(block.maxContentWidth, block.height);
paint.color = const sky.Color(0xFFFF9000);
paint.setStyle(sky.PaintingStyle.stroke);
paint.strokeWidth = 3.0;
canvas.drawPath(path, paint);
// paint the text
layoutRoot.paint(canvas);
}
void main() {
// prepare the rendering
sky.PictureRecorder recorder = new sky.PictureRecorder();
sky.Canvas canvas = new sky.Canvas(recorder, new sky.Rect.fromLTWH(0.0, 0.0, sky.view.width, sky.view.height));
// background
sky.Paint paint = new sky.Paint();
paint.color = const sky.Color(0xFFFFFFFF);
paint.setStyle(sky.PaintingStyle.fill);
canvas.drawRect(new sky.Rect.fromLTRB(0.0, 0.0, sky.view.width, sky.view.height), paint);
canvas.translate(10.0, 0.0);
drawText(canvas, '1.0');
drawText(canvas, 'lh');
// put it on the screen
sky.view.picture = recorder.endRecording();
sky.view.scheduleFrame();
}

View File

@@ -0,0 +1,46 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:sky';
Picture draw(int a, int r, int g, int b) {
Size size = new Size(view.width, view.height);
PictureRecorder recorder = new PictureRecorder();
Canvas canvas = new Canvas(recorder, Point.origin & size);
double radius = size.shortestSide * 0.45;
Paint paint = new Paint()..color = new Color.fromARGB(a, r, g, b);
canvas.drawCircle(size.center(Point.origin), radius, paint);
return recorder.endRecording();
}
bool handleEvent(Event event) {
if (event.type == "pointerdown") {
view.picture = draw(255, 0, 0, 255);
view.scheduleFrame();
return true;
}
if (event.type == "pointerup") {
view.picture = draw(255, 0, 255, 0);
view.scheduleFrame();
return true;
}
if (event.type == "back") {
print("Pressed back button.");
return true;
}
return false;
}
void main() {
print("Hello, world");
view.picture = draw(255, 0, 255, 0);
view.scheduleFrame();
view.setEventCallback(handleEvent);
}

View File

@@ -0,0 +1,221 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import "dart:math" as math;
import 'dart:sky' as sky;
const kMaxIterations = 100;
int peakCount = 1000; // this is the number that must be reached for us to start reporting the peak number of nodes in the tree each frame
void report(String s) {
// uncomment this if you want to see what the mutations are
// print("$s\n");
}
sky.LayoutRoot layoutRoot = new sky.LayoutRoot();
sky.Document document = new sky.Document();
sky.Element root;
math.Random random = new math.Random();
bool pickThis(double odds) {
return random.nextDouble() < odds;
}
String generateCharacter(int min, int max) {
String result = new String.fromCharCode(random.nextInt(max)+min);
report("generated character: '$result'");
return result;
}
String colorToCSSString(sky.Color color) {
return 'rgba(${color.red}, ${color.green}, ${color.blue}, ${color.alpha / 255.0})';
}
void doFrame(double timeStamp) {
// mutate the DOM randomly
int iterationsLeft = kMaxIterations;
sky.Node node = root;
sky.Node other = null;
while (node != null && iterationsLeft > 0) {
iterationsLeft -= 1;
if (node is sky.Element && pickThis(0.4)) {
node = (node as sky.Element).firstChild;
} else if (node.nextSibling != null && pickThis(0.5)) {
node = node.nextSibling;
} else if (other == null && node != root && pickThis(0.1)) {
other = node;
node = root;
} else if (node != root && other != null && pickThis(0.1)) {
report("insertBefore()");
try {
node.insertBefore([other]);
} catch (_) {
}
break;
} else if (node != root && pickThis(0.001)) {
report("remove()");
node.remove();
} else if (node is sky.Element) {
if (pickThis(0.1)) {
report("appending a new text node (ASCII)");
node.appendChild(document.createText(generateCharacter(0x20, 0x7F)));
break;
} else if (pickThis(0.05)) {
report("appending a new text node (Latin1)");
node.appendChild(document.createText(generateCharacter(0x20, 0xFF)));
break;
} else if (pickThis(0.025)) {
report("appending a new text node (BMP)");
node.appendChild(document.createText(generateCharacter(0x20, 0xFFFF)));
break;
} else if (pickThis(0.0125)) {
report("appending a new text node (Unicode)");
node.appendChild(document.createText(generateCharacter(0x20, 0x10FFFF)));
break;
} else if (pickThis(0.1)) {
report("appending a new Element");
node.appendChild(document.createElement('t'));
break;
} else if (pickThis(0.1)) {
report("styling: color");
node.style['color'] = colorToCSSString(new sky.Color(random.nextInt(0xFFFFFFFF) | 0xC0808080));
break;
} else if (pickThis(0.1)) {
report("styling: font-size");
node.style['font-size'] = "${random.nextDouble() * 48.0}px";
break;
} else if (pickThis(0.2)) {
report("styling: font-weight");
node.style['font-weight'] = "${random.nextInt(8)+1}00";
break;
} else if (pickThis(0.1)) {
report("styling: line-height, dynamic");
node.style['line-height'] = "${random.nextDouble()*1.5}";
break;
} else if (pickThis(0.001)) {
report("styling: line-height, fixed");
node.style['line-height'] = "${random.nextDouble()*1.5}px";
break;
} else if (pickThis(0.025)) {
report("styling: font-style italic");
node.style['font-style'] = "italic";
break;
} else if (pickThis(0.05)) {
report("styling: font-style normal");
node.style['font-style'] = "normal";
break;
} else if (pickThis(0.1)) {
report("styling: text-decoration");
node.style['text-decoration-line'] = "none";
break;
} else if (pickThis(0.01)) {
report("styling: text-decoration");
node.style['text-decoration-line'] = "underline";
break;
} else if (pickThis(0.01)) {
report("styling: text-decoration");
node.style['text-decoration-line'] = "overline";
break;
} else if (pickThis(0.01)) {
report("styling: text-decoration");
node.style['text-decoration-line'] = "underline overline";
break;
} else if (pickThis(0.1)) {
report("styling: text-decoration-style: inherit");
node.style['text-decoration-style'] = "inherit";
break;
} else if (pickThis(0.1)) {
report("styling: text-decoration-style: solid");
node.style['text-decoration-style'] = "solid";
break;
} else if (pickThis(0.1)) {
report("styling: text-decoration-style: double");
node.style['text-decoration-style'] = "double";
break;
} else if (pickThis(0.1)) {
report("styling: text-decoration-style: dotted");
node.style['text-decoration-style'] = "dotted";
break;
} else if (pickThis(0.1)) {
report("styling: text-decoration-style: dashed");
node.style['text-decoration-style'] = "dashed";
break;
} else if (pickThis(0.1)) {
report("styling: text-decoration-style: wavy");
node.style['text-decoration-style'] = "wavy";
break;
} else if (pickThis(0.1)) {
report("styling: text-decoration-color");
node.style['text-decoration-color'] = colorToCSSString(new sky.Color(random.nextInt(0xFFFFFFFF)));
break;
}
} else {
assert(node is sky.Text);
final sky.Text text = node;
if (pickThis(0.1)) {
report("appending a new text node (ASCII)");
text.appendData(generateCharacter(0x20, 0x7F));
break;
} else if (pickThis(0.05)) {
report("appending a new text node (Latin1)");
text.appendData(generateCharacter(0x20, 0xFF));
break;
} else if (pickThis(0.025)) {
report("appending a new text node (BMP)");
text.appendData(generateCharacter(0x20, 0xFFFF));
break;
} else if (pickThis(0.0125)) {
report("appending a new text node (Unicode)");
text.appendData(generateCharacter(0x20, 0x10FFFF));
break;
} else if (text.length > 1 && pickThis(0.1)) {
report("deleting character from Text node");
text.deleteData(random.nextInt(text.length), 1);
break;
}
}
}
report("counting...");
node = root;
int count = 1;
while (node != null) {
if (node is sky.Element && node.firstChild != null) {
node = (node as sky.Element).firstChild;
count += 1;
} else {
while (node != null && node.nextSibling == null)
node = node.parentNode;
if (node != null && node.nextSibling != null) {
node = node.nextSibling;
count += 1;
}
}
}
report("node count: $count\r");
if (count > peakCount) {
peakCount = count;
print("peak node count so far: $count\r");
}
// draw the result
report("recording...");
sky.PictureRecorder recorder = new sky.PictureRecorder();
sky.Canvas canvas = new sky.Canvas(recorder, new sky.Rect.fromLTWH(0.0, 0.0, sky.view.width, sky.view.height));
layoutRoot.maxWidth = sky.view.width;
layoutRoot.layout();
layoutRoot.paint(canvas);
report("painting...");
sky.view.picture = recorder.endRecording();
sky.view.scheduleFrame();
}
void main() {
root = document.createElement('p');
root.style['display'] = 'paragraph';
root.style['color'] = '#FFFFFF';
layoutRoot.rootElement = root;
sky.view.setFrameCallback(doFrame);
sky.view.scheduleFrame();
}

View File

@@ -0,0 +1,93 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:sky' as sky;
import 'dart:math' as math;
import 'dart:typed_data';
void beginFrame(double timeStamp) {
sky.Size size = new sky.Size(sky.view.width, sky.view.height);
sky.PictureRecorder recorder = new sky.PictureRecorder();
sky.Canvas canvas = new sky.Canvas(recorder, sky.Point.origin & size);
sky.Paint paint = new sky.Paint();
sky.Point mid = size.center(sky.Point.origin);
double radius = size.shortestSide / 2.0;
canvas.drawPaint(new sky.Paint()..color = const sky.Color(0xFFFFFFFF));
canvas.save();
canvas.translate(-mid.x/2.0, sky.view.height*2.0);
canvas.clipRect(
new sky.Rect.fromLTRB(0.0, -sky.view.height, sky.view.width, radius));
canvas.translate(mid.x, mid.y);
paint.color = const sky.Color.fromARGB(128, 255, 0, 255);
canvas.rotate(math.PI/4.0);
sky.Gradient yellowBlue = new sky.Gradient.linear(
[new sky.Point(-radius, -radius), new sky.Point(0.0, 0.0)],
[const sky.Color(0xFFFFFF00), const sky.Color(0xFF0000FF)]);
canvas.drawRect(new sky.Rect.fromLTRB(-radius, -radius, radius, radius),
new sky.Paint()..setShader(yellowBlue));
// Scale x and y by 0.5.
var scaleMatrix = new Float32List.fromList([
0.5, 0.0, 0.0, 0.0,
0.0, 0.5, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 1.0,
]);
canvas.concat(scaleMatrix);
paint.color = const sky.Color.fromARGB(128, 0, 255, 0);
canvas.drawCircle(sky.Point.origin, radius, paint);
canvas.restore();
canvas.translate(0.0, 50.0);
var builder = new sky.LayerDrawLooperBuilder()
..addLayerOnTop(
new sky.DrawLooperLayerInfo()
..setOffset(const sky.Offset(150.0, 0.0))
..setColorMode(sky.TransferMode.src)
..setPaintBits(sky.PaintBits.all),
(sky.Paint layerPaint) {
layerPaint.color = const sky.Color.fromARGB(128, 255, 255, 0);
layerPaint.setColorFilter(new sky.ColorFilter.mode(
const sky.Color.fromARGB(128, 0, 0, 255), sky.TransferMode.srcIn));
layerPaint.setMaskFilter(new sky.MaskFilter.blur(
sky.BlurStyle.normal, 3.0, highQuality: true));
})
..addLayerOnTop(
new sky.DrawLooperLayerInfo()
..setOffset(const sky.Offset(75.0, 75.0))
..setColorMode(sky.TransferMode.src)
..setPaintBits(sky.PaintBits.shader),
(sky.Paint layerPaint) {
sky.Gradient redYellow = new sky.Gradient.radial(
new sky.Point(0.0, 0.0), radius/3.0,
[const sky.Color(0xFFFFFF00), const sky.Color(0xFFFF0000)],
null, sky.TileMode.mirror);
layerPaint.setShader(redYellow);
// Since we're don't set sky.PaintBits.maskFilter, this has no effect.
layerPaint.setMaskFilter(new sky.MaskFilter.blur(
sky.BlurStyle.normal, 50.0, highQuality: true));
})
..addLayerOnTop(
new sky.DrawLooperLayerInfo()..setOffset(const sky.Offset(225.0, 75.0)),
(sky.Paint layerPaint) {
// Since this layer uses a DST color mode, this has no effect.
layerPaint.color = const sky.Color.fromARGB(128, 255, 0, 0);
});
paint.setDrawLooper(builder.build());
canvas.drawCircle(sky.Point.origin, radius, paint);
sky.view.picture = recorder.endRecording();
}
void main() {
sky.view.setFrameCallback(beginFrame);
sky.view.scheduleFrame();
}

View File

@@ -0,0 +1,54 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:sky';
PaintingNode paintingNode = null;
Picture draw(int a, int r, int g, int b) {
Rect bounds = new Rect.fromLTRB(0.0, 0.0, view.width, view.height);
Size size = new Size(view.width, view.height);
PictureRecorder recorder = new PictureRecorder();
Canvas canvas = new Canvas(recorder, bounds);
double radius = size.shortestSide * 0.45;
Paint paint = new Paint()..color = new Color.fromARGB(a, r, g, b);
canvas.drawCircle(size.center(Point.origin), radius, paint);
if (paintingNode == null) {
paintingNode = new PaintingNode();
Paint innerPaint = new Paint()..color = new Color.fromARGB(a, 255 - r, 255 - g, 255 - b);
PictureRecorder innerRecorder = new PictureRecorder();
Canvas innerCanvas = new Canvas(innerRecorder, bounds);
innerCanvas.drawCircle(size.center(Point.origin), radius * 0.5, innerPaint);
paintingNode.setBackingDrawable(innerRecorder.endRecordingAsDrawable());
}
canvas.drawPaintingNode(paintingNode, Point.origin);
return recorder.endRecording();
}
bool handleEvent(Event event) {
if (event.type == "pointerdown") {
view.picture = draw(255, 0, 0, 255);
view.scheduleFrame();
return true;
}
if (event.type == "pointerup") {
view.picture = draw(255, 0, 255, 0);
view.scheduleFrame();
return true;
}
return false;
}
void main() {
view.picture = draw(255, 0, 255, 0);
view.scheduleFrame();
view.setEventCallback(handleEvent);
}

40
examples/raw/shadow.dart Normal file
View File

@@ -0,0 +1,40 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:sky';
void beginFrame(double timeStamp) {
double size = 100.0;
PictureRecorder recorder = new PictureRecorder();
Canvas canvas = new Canvas(recorder, new Rect.fromLTWH(0.0, 0.0, view.width, view.height));
canvas.translate(size + 10.0, size + 10.0);
Paint paint = new Paint();
paint.color = const Color.fromARGB(255, 0, 255, 0);
var builder = new LayerDrawLooperBuilder()
// Shadow layer.
..addLayerOnTop(
new DrawLooperLayerInfo()
..setPaintBits(PaintBits.all)
..setOffset(const Offset(5.0, 5.0))
..setColorMode(TransferMode.src),
(Paint layerPaint) {
layerPaint.color = const Color.fromARGB(128, 55, 55, 55);
layerPaint.setMaskFilter(
new MaskFilter.blur(BlurStyle.normal, 5.0, highQuality: true));
})
// Main layer.
..addLayerOnTop(new DrawLooperLayerInfo(), (Paint) {});
paint.setDrawLooper(builder.build());
canvas.drawPaint(
new Paint()..color = const Color.fromARGB(255, 255, 255, 255));
canvas.drawRect(new Rect.fromLTRB(-size, -size, size, size), paint);
view.picture = recorder.endRecording();
}
void main() {
view.setFrameCallback(beginFrame);
view.scheduleFrame();
}

View File

@@ -0,0 +1,48 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import "dart:math" as math;
import 'dart:sky';
double timeBase = null;
LayoutRoot layoutRoot = new LayoutRoot();
void beginFrame(double timeStamp) {
if (timeBase == null)
timeBase = timeStamp;
double delta = timeStamp - timeBase;
PictureRecorder recorder = new PictureRecorder();
Canvas canvas = new Canvas(recorder, new Rect.fromLTWH(0.0, 0.0, view.width, view.height));
canvas.translate(view.width / 2.0, view.height / 2.0);
canvas.rotate(math.PI * delta / 1800);
canvas.drawRect(new Rect.fromLTRB(-100.0, -100.0, 100.0, 100.0),
new Paint()..color = const Color.fromARGB(255, 0, 255, 0));
double sin = math.sin(delta / 200);
layoutRoot.maxWidth = 150.0 + (50 * sin);
layoutRoot.layout();
canvas.translate(layoutRoot.maxWidth / -2.0, (layoutRoot.maxWidth / 2.0) - 125);
layoutRoot.paint(canvas);
view.picture = recorder.endRecording();
view.scheduleFrame();
}
void main() {
var document = new Document();
var arabic = document.createText("هذا هو قليلا طويلة من النص الذي يجب التفاف .");
var more = document.createText(" و أكثر قليلا لجعله أطول. ");
var block = document.createElement('p');
block.style['display'] = 'paragraph';
block.style['direction'] = 'rtl';
block.style['unicode-bidi'] = 'plaintext';
block.appendChild(arabic);
block.appendChild(more);
layoutRoot.rootElement = block;
view.setFrameCallback(beginFrame);
view.scheduleFrame();
}

View File

@@ -0,0 +1,73 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math' as math;
import 'dart:sky';
import 'package:sky/mojo/net/image_cache.dart' as image_cache;
double timeBase = null;
Image image = null;
String url1 = "https://www.dartlang.org/logos/dart-logo.png";
String url2 = "http://i2.kym-cdn.com/photos/images/facebook/000/581/296/c09.jpg";
void beginFrame(double timeStamp) {
if (timeBase == null)
timeBase = timeStamp;
double delta = timeStamp - timeBase;
PictureRecorder recorder = new PictureRecorder();
Canvas canvas = new Canvas(recorder, Point.origin & new Size(view.width, view.height));
canvas.translate(view.width / 2.0, view.height / 2.0);
canvas.rotate(math.PI * delta / 1800);
canvas.scale(0.2, 0.2);
Paint paint = new Paint()..color = const Color.fromARGB(255, 0, 255, 0);
// Draw image
if (image != null)
canvas.drawImage(image, new Point(-image.width / 2.0, -image.height / 2.0), paint);
// Draw cut out of image
canvas.rotate(math.PI * delta / 1800);
if (image != null) {
var w = image.width.toDouble();
var h = image.width.toDouble();
canvas.drawImageRect(image,
new Rect.fromLTRB(w * 0.25, h * 0.25, w * 0.75, h * 0.75),
new Rect.fromLTRB(-w / 4.0, -h / 4.0, w / 4.0, h / 4.0),
paint);
}
view.picture = recorder.endRecording();
view.scheduleFrame();
}
void handleImageLoad(result) {
if (result != image) {
print("${result.width}x${result.width} image loaded!");
image = result;
view.scheduleFrame();
} else {
print("Existing image was loaded again");
}
}
bool handleEvent(Event event) {
if (event.type == "pointerdown") {
return true;
}
if (event.type == "pointerup") {
image_cache.load(url2).then(handleImageLoad);
return true;
}
return false;
}
void main() {
image_cache.load(url1).then(handleImageLoad);
view.setEventCallback(handleEvent);
view.setFrameCallback(beginFrame);
}

View File

@@ -0,0 +1,29 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:sky';
import 'dart:math' as math;
double timeBase = null;
void beginFrame(double timeStamp) {
tracing.begin('beginFrame');
if (timeBase == null)
timeBase = timeStamp;
double delta = timeStamp - timeBase;
PictureRecorder recorder = new PictureRecorder();
Canvas canvas = new Canvas(recorder, new Rect.fromLTWH(0.0, 0.0, view.width, view.height));
canvas.translate(view.width / 2.0, view.height / 2.0);
canvas.rotate(math.PI * delta / 1800);
canvas.drawRect(new Rect.fromLTRB(-100.0, -100.0, 100.0, 100.0),
new Paint()..color = const Color.fromARGB(255, 0, 255, 0));
view.picture = recorder.endRecording();
view.scheduleFrame();
tracing.end('beginFrame');
}
void main() {
view.setFrameCallback(beginFrame);
view.scheduleFrame();
}

View File

@@ -0,0 +1,17 @@
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import("//sky/build/skyx.gni")
skyx("interactive_flex") {
main_dart = "interactive_flex.dart"
}
group("rendering") {
testonly = true
deps = [
":interactive_flex",
]
}

Some files were not shown because too many files have changed in this diff Show More