sprite_box.dart 15.7 KB
Newer Older
1
part of flutter_sprites;
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30

/// 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;

31
  void set rootNode (NodeWithSize value) {
32
    if (value == _rootNode) return;
33

34
    // Ensure that the root node has a size
35 36 37 38
    assert(_transformMode == SpriteBoxTransformMode.nativePoints
      || value.size.width > 0);
    assert(_transformMode == SpriteBoxTransformMode.nativePoints
      || value.size.height > 0);
39

40 41 42 43 44
    // Remove sprite box references
    if (_rootNode != null) _removeSpriteBoxReference(_rootNode);

    // Update the value
    _rootNode = value;
45
    _actionControllers = null;
46 47 48

    // Add new references
    _addSpriteBoxReference(_rootNode);
49
    markNeedsLayout();
50 51
  }

52
  // Tracking of frame rate and updates
53
  Duration _lastTimeStamp;
54 55
  double _frameRate = 0.0;

56 57
  double get frameRate => _frameRate;

58 59 60
  // Transformation mode
  SpriteBoxTransformMode _transformMode;

61 62 63 64 65 66
  void set transformMode (SpriteBoxTransformMode value) {
    if (value == _transformMode)
      return;
    _transformMode = value;

    // Invalidate stuff
67
    markNeedsLayout();
68 69
  }

70 71 72 73 74 75 76 77
  /// The transform mode used by the [SpriteBox].
  SpriteBoxTransformMode get transformMode => _transformMode;

  // Cached transformation matrix
  Matrix4 _transformMatrix;

  List<Node> _eventTargets;

78 79
  List<ActionController> _actionControllers;

80 81
  List<Node> _constrainedNodes;

82
  List<PhysicsWorld> _physicsNodes;
83

84 85
  Rect _visibleArea;

86
  Rect get visibleArea {
87 88
    if (_visibleArea == null)
      _calcTransformMatrix();
89 90
    return _visibleArea;
  }
91

92 93
  bool _initialized = false;

94 95 96 97 98 99 100 101 102 103 104 105 106 107
  // 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 transform mode
108
    this.transformMode = mode;
109 110 111

    // Setup root node
    this.rootNode = rootNode;
112
  }
113

114 115 116 117 118
  void _removeSpriteBoxReference(Node node) {
    node._spriteBox = null;
    for (Node child in node._children) {
      _removeSpriteBoxReference(child);
    }
119 120 121 122 123 124 125 126 127
  }

  void _addSpriteBoxReference(Node node) {
    node._spriteBox = this;
    for (Node child in node._children) {
      _addSpriteBoxReference(child);
    }
  }

128 129 130 131 132
  void attach() {
    super.attach();
    _scheduleTick();
  }

133 134 135 136 137 138 139 140 141 142 143
  // 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);
144
    _initialized = true;
145 146
  }

147 148
  // Adding and removing nodes

149
  void _registerNode(Node node) {
150 151
    _actionControllers = null;
    _eventTargets = null;
152
    _physicsNodes = null;
153
    if (node == null || node.constraints != null) _constrainedNodes = null;
154 155
  }

156
  void _deregisterNode(Node node) {
157 158
    _actionControllers = null;
    _eventTargets = null;
159
    _physicsNodes = null;
160
    if (node == null || node.constraints != null) _constrainedNodes = null;
161 162
  }

163 164 165 166 167 168 169 170 171
  // 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];
172 173
      if (child.zPosition >= 0.0)
        break;
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
      _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++;
    }
  }

191
  void handleEvent(PointerEvent event, _SpriteBoxHitTestEntry entry) {
192
    if (!attached)
Adam Barth's avatar
Adam Barth committed
193
      return;
194

195 196 197 198 199 200
    if (event is PointerDownEvent) {
      // Build list of event targets
      if (_eventTargets == null) {
        _eventTargets = <Node>[];
        _addEventTargets(_rootNode, _eventTargets);
      }
201

202 203 204 205 206 207 208 209 210 211 212 213
      // Find the once that are hit by the pointer
      List<Node> nodeTargets = <Node>[];
      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;
214 215 216 217
          }
        }
      }

218 219
      entry.nodeTargets = nodeTargets;
    }
220

221 222 223 224 225 226
    // 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
227
        bool consumedEvent = node.handleEvent(new SpriteBoxEvent(event.position, event.runtimeType, event.pointer));
228 229
        if (consumedEvent == null || consumedEvent)
          break;
230 231
      }
    }
232 233 234 235 236 237

    // De-register pointer for nodes that doesn't handle multiple pointers
    for (Node node in targets) {
      if (event is PointerUpEvent || event is PointerCancelEvent)
        node._handlingPointer = null;
    }
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
  }

  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
254 255
    if (_transformMatrix == null) {
      _calcTransformMatrix();
256
    }
257 258
    return _transformMatrix;
  }
259

260
  void _calcTransformMatrix() {
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
    _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:
312 313
        systemWidth = size.width;
        systemHeight = size.height;
314 315 316 317 318 319
        break;
      default:
        assert(false);
        break;
    }

320 321 322 323 324
    _visibleArea = new Rect.fromLTRB(-offsetX / scaleX,
                                     -offsetY / scaleY,
                                     systemWidth + offsetX / scaleX,
                                     systemHeight + offsetY / scaleY);

325 326 327 328 329
    _transformMatrix.translate(offsetX, offsetY);
    _transformMatrix.scale(scaleX, scaleY);
  }

  void _invalidateTransformMatrix() {
330
    _visibleArea = null;
331 332 333 334
    _transformMatrix = null;
    _rootNode._invalidateToBoxTransformMatrix();
  }

335
  void paint(PaintingContext context, Offset offset) {
Adam Barth's avatar
Adam Barth committed
336
    final Canvas canvas = context.canvas;
337 338 339 340
    canvas.save();

    // Move to correct coordinate space before drawing
    canvas.translate(offset.dx, offset.dy);
341
    canvas.transform(transformMatrix.storage);
342 343

    // Draw the sprite tree
344
    Matrix4 totalMatrix = new Matrix4.fromFloat64List(canvas.getTotalMatrix());
345
    _rootNode._visit(canvas, totalMatrix);
346

347
    // Draw physics debug
348 349 350
    if (_physicsNodes == null)
      _rebuildActionControllersAndPhysicsNodes();

351 352 353 354 355 356 357
    for (PhysicsWorld world in _physicsNodes) {
      if (world.drawDebug) {
        canvas.setMatrix(world._debugDrawTransform.storage);
        world.paintDebug(canvas);
      }
    }

358 359 360 361 362 363
    canvas.restore();
  }

  // Updates

  void _scheduleTick() {
364
    Scheduler.instance.scheduleFrameCallback(_tick);
365 366
  }

367
  void _tick(Duration timeStamp) {
368 369
    if (!attached)
      return;
370

371
    // Calculate delta and frame rate
372 373 374
    if (_lastTimeStamp == null)
      _lastTimeStamp = timeStamp;
    double delta = (timeStamp - _lastTimeStamp).inMicroseconds.toDouble() / Duration.MICROSECONDS_PER_SECOND;
375 376 377 378
    _lastTimeStamp = timeStamp;

    _frameRate = 1.0/delta;

379 380 381 382 383 384 385
    if (_initialized) {
      _callConstraintsPreUpdate(delta);
      _runActions(delta);
      _callUpdate(_rootNode, delta);
      _callStepPhysics(delta);
      _callConstraintsConstrain(delta);
    }
386 387

    // Schedule next update
388
    _scheduleTick();
389 390

    // Make sure the node graph is redrawn
391 392 393
    markNeedsPaint();
  }

394 395
  void _runActions(double dt) {
    if (_actionControllers == null) {
396
      _rebuildActionControllersAndPhysicsNodes();
397 398 399
    }
    for (ActionController actions in _actionControllers) {
      actions.step(dt);
400
    }
401 402
  }

403
  void _rebuildActionControllersAndPhysicsNodes() {
Hixie's avatar
Hixie committed
404 405
    _actionControllers = <ActionController>[];
    _physicsNodes = <PhysicsWorld>[];
406 407 408 409 410
    _addActionControllersAndPhysicsNodes(_rootNode);
  }

  void _addActionControllersAndPhysicsNodes(Node node) {
    if (node._actions != null) _actionControllers.add(node._actions);
411
    if (node is PhysicsWorld) _physicsNodes.add(node);
412

413 414
    for (int i = node.children.length - 1; i >= 0; i--) {
      Node child = node.children[i];
415
      _addActionControllersAndPhysicsNodes(child);
416 417 418 419 420 421 422 423 424 425 426 427 428
    }
  }

  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);
      }
    }
  }

429 430 431 432
  void _callStepPhysics(double dt) {
    if (_physicsNodes == null)
      _rebuildActionControllersAndPhysicsNodes();

433
    for (PhysicsWorld physicsNode in _physicsNodes) {
434 435 436 437
      physicsNode._stepPhysics(dt);
    }
  }

438 439
  void _callConstraintsPreUpdate(double dt) {
    if (_constrainedNodes == null) {
Hixie's avatar
Hixie committed
440
      _constrainedNodes = <Node>[];
441 442 443 444 445 446 447 448 449 450 451 452
      _addConstrainedNodes(_rootNode, _constrainedNodes);
    }

    for (Node node in _constrainedNodes) {
      for (Constraint constraint in node.constraints) {
        constraint.preUpdate(node, dt);
      }
    }
  }

  void _callConstraintsConstrain(double dt) {
    if (_constrainedNodes == null) {
Hixie's avatar
Hixie committed
453
      _constrainedNodes = <Node>[];
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
      _addConstrainedNodes(_rootNode, _constrainedNodes);
    }

    for (Node node in _constrainedNodes) {
      for (Constraint constraint in node.constraints) {
        constraint.constrain(node, dt);
      }
    }
  }

  void _addConstrainedNodes(Node node, List<Node> nodes) {
    if (node._constraints != null && node._constraints.length > 0) {
      nodes.add(node);
    }

    for (Node child in node.children) {
      _addConstrainedNodes(child, nodes);
    }
  }

474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
  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);

Hixie's avatar
Hixie committed
492
    List<Node> nodes = <Node>[];
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533

    // 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;

534 535
  /// The type of event, there are currently four valid types, PointerDownEvent, PointerMoveEvent, PointerUpEvent, and
  /// PointerCancelEvent.
536
  ///
537
  ///     if (event.type == PointerDownEvent) {
538 539
  ///       // Do something!
  ///     }
540
  final Type type;
541 542 543 544 545 546 547 548 549 550 551 552 553

  /// 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);
}