Newer
Older
Import / research / match3 / canvas.h
//  DescriptionHere - canvas.h
//  Created by John Ryland (jryland@xiaofrog.com), 29/10/2017
//  Copyright (c) 2017 InvertedLogic
//  All rights reserved.
#pragma once
#include "stdint.h"
#include <vector>

struct Image
{
  std::vector<uint32_t> pixels;
  uint32_t w, h;
};

struct Sprite
{
  const Image* image;
  uint32_t x, y, w, h;
};

struct SpriteSheet
{
  Image image;
  std::vector<Sprite> sprites;
};

struct CanvasItem
{
  bool visible;
  int32_t x, y;
  uint8_t alpha;
  int8_t mode; // 0 mask, 1 const alpha, 2 src alpha, 3 src*const alpha, 4 scaled
  uint32_t frame;
  float xScaling, yScaling;
  const Sprite* sprite;
};

// This is somewhat designed so that whilst the current implementation
// is just copying data around with the CPU, it could be switched to
// an implementation which uses the GPU instead. I imagine the canvas item
// list can be turned in to a vertex buffer, and the sprite sheet will
// be a texture which is uploaded
struct Canvas
{
  Image                    backgroundImage;
  std::vector<CanvasItem>  sprites;
  // Perhaps should hold the sprite sheet so lifetime matches
};

bool loadPngImage(Image& image, const char *pngFileName);
bool loadSpriteSheet(SpriteSheet& sheet, const char* fileName);
void drawTestGradient(Image& image);
void drawImage(Image& image, int x, int y, const Image& img);
void drawImageWithMask(Image& image, int x, int y, const Image& img);
void drawImageWithAlpha(Image& image, int x, int y, const Image& img);
void drawImageWithMaskWithConstantAlpha(Image& image, int x, int y, const Image& img, uint8_t alpha);
void drawSprite(Image& image, int x, int y, const Sprite& s, uint8_t alpha, int mode = 1, float xScaling = 1.0f, float yScaling = 1.0f);
void drawScaledSprite(Image& image, int x, int y, int w, int h, const Sprite& s);
void drawCanvas(Image& image, int x, int y, const Canvas& canvas);

void canvasAddSprite(Canvas& canvas, int x, int y, const Sprite& s);
// returns -1 for no hit, otherwise it is the index of the sprite
int canvasHitTest(const Canvas& canvas, int x, int y);
int canvasHitTestWithAlpha(const Canvas& canvas, int x, int y);

inline uint32_t pixelVal(uint8_t a, uint8_t r, uint8_t g, uint8_t b)
{
  return (uint32_t(a)<<24) | (uint32_t(b)<<16) | (uint32_t(g)<<8) | (uint32_t(r)<<0);
}