<commit_before>#include "actor.h"
#include "gamelevel.h"
#include "modules.h"
#include "util.h"
#include "assets.h"

// === Submarine ===

void Submarine::initialize() {
  x = W << 8;
  y = (SCREEN_HEIGHT / 2) << 8;
  extraLives = START_LIVES;
  armor      = ARMOR_FRAMES;
}

void Submarine::move(GameLevel& context) {
  if(context.isGameover()) { return; }

  // control
  static const int SPD = 1 << 7;
  static const int R2  = 90;  // 0.5/sqrt(2) / (1/256)
  if(context.core.pressed(BTN_U) && context.core.pressed(BTN_L)) {
    x -= R2;
    y -= R2;
  }
  else if(context.core.pressed(BTN_U) && context.core.pressed(BTN_R)) {
    x += R2;
    y -= R2;
  }
  else if(context.core.pressed(BTN_D) && context.core.pressed(BTN_L)) {
    x -= R2;
    y += R2;
  }
  else if(context.core.pressed(BTN_D) && context.core.pressed(BTN_R)) {
    x += R2;
    y += R2;
  }
  else if(context.core.pressed(BTN_U)) {
    y -= SPD;
  }
  else if(context.core.pressed(BTN_L)) {
    x -= SPD;
  }
  else if(context.core.pressed(BTN_R)) {
    x += SPD;
  }
  else if(context.core.pressed(BTN_D)) {
    y += SPD;
  }

  // clamping into field
  static const fixed MARGIN = 6;
  x = Clamp(x, 0, (SCREEN_WIDTH - MARGIN) << 8);
  y = Clamp(y, (MARGIN - H) << 8, (SCREEN_HEIGHT - MARGIN) << 8);

  // launching torpedo
  if(extraLives >= 0 && (context.core.pushed(BTN_A) || context.core.pushed(BTN_B))) {
    context.launchTorpedo(fieldX() + 10, fieldY() + 1);
  }

  //firing auto shot
#ifdef LOW_FLASH_MEMORY
  if(context.frameCount() % 5 == 0) {
    context.fireAutoShot(fieldX() + 3, fieldY() - 3);
  }
#else
  if(context.lookForEnemy() && context.frameCount() % 5 == 0) {
    context.fireAutoShot(fieldX() + 3, fieldY() - 3);
  }
#endif

  // updating armor timer
  if(armor > 0) { --armor; }
}

void Submarine::draw(GameLevel& context) const {
  if(armor == 0 || (extraLives >= 0 && context.frameCount() / 3 % 2 == 0)) {
    context.core.drawBitmap(fieldX() - 1, fieldY() - 2, bitmapSubmarine, 2);
    if(context.frameCount() % ECHO_CYCLE > 30) {  // sustain: 30 frames
      context.core.drawPixel(fieldX() + 6, fieldY() - 1, 1);
    }
  }
  //context.getArduboy().drawRect(x, y, W, H, 0);
}

void Submarine::onHit(GameLevel& context) {
  if(armor <= 0) {
    if(extraLives >= 0) {
      context.spawnParticle(fieldX() - 2, fieldY() - 4, PARTICLE_EXPLOSION);
      context.core.tone(185, 250);
    }
    --extraLives;
    if(extraLives < 0) {
      context.setGameover();
      // ToDo: add gameover sfx
      inactivate();
    }
    armor = ARMOR_FRAMES;
  }
}

// === Torpedo ===

bool Torpedo::launch(const char x, const char y) {
  if(!exist()) {
    this->x = x;
    this->y = y;
    vx = 0;
    return true;
  }
  return false;
}

void Torpedo::move() {
  static const fixed ACC = 1 << 7;  // 0.5
  if(!exist()) { return; }
  vx += ACC - (vx >> 4);
  x  += vx >> 8;
  if(x >= FIELD_WIDTH) {
    inactivate();
  }
}

void Torpedo::draw(GameLevel& context) const {
  if(!exist()) { return; }
  // body
  context.core.drawBitmap(x, y - 1, bitmapTorpedo, 2);
  // shockwave
  if(vx > 4 << 8) { // well accelerated
    const byte h = bitmapShockwave0[1];
    context.core.drawBitmap(x -  8, y - h/2, bitmapShockwave0, 2);
    context.core.drawBitmap(x - 16, y - h/2, bitmapShockwave1, 2);
    context.core.drawBitmap(x - 24, y - h/2, bitmapShockwave2, 2);
  }
  //context.getArduboy.drawFastHLine(x, y, W, 0);
}

// === AutoShot ===

void AutoShot::initialize(const char x, const char y) {
  this->x = x;
  this->y = y;
}

void AutoShot::move() {
  // moving
  x += 8;

  // frame out
  if(x > SCREEN_WIDTH) {
    inactivate();
  }
}

void AutoShot::draw(GameLevel& context) const {
  context.core.drawBitmap((int)x + 2, (int)y + 3, bitmapAutoShot, 2);
  //context.core.getArduboy().drawRect(x, y, W, H, 1);
}

// === BigEnemy ===

void BigEnemy::initialize(const char y) {
  this->x = FIELD_WIDTH;
  this->y = y;
  state   = 0;
  timer   = 0;
}

void BigEnemy::move(GameLevel& context) {
  // moving
  if(grazed() && x > SCREEN_WIDTH - 5) {
    x += -3; // submarine found
  }
  else if(timer % 5 == 0) { // -0.2
    --x;
  }

  // frame out
  if(x + bitmapCruEnemy0[0] < 0) {
    inactivate();
  }

  // setting sonar reaction
  context.echo.add(x, y, y+H);

  // firing bullet
  if(x < SCREEN_WIDTH - W / 2) {
    if(!onScreen()) {
      timer = 0;  // in order to sync fire cycle
      state |= ON_SCREEN_MASK;
    }
    const byte d = context.difficulty();
    if(timer == 0 || (d >= 60 && timer == 40)) {  // freq up when 60 and over
      const char bulletY     = y + bitmapCruEnemy0[1] / 2;
      const char bulletSpeed = (d >= 80) ? BULLET_TYPE2_SPD : BULLET_TYPE0_SPD;
      const char bulletType  = (d >= 80) ? 2 : 0;
      context.fireBullet(x, bulletY, context.getFutureSubmarineAngle(x, bulletY, bulletSpeed), bulletType);
    }
  }

  // updating timer
  static const byte PERIOD = 150;
  timer = (timer + 1) % PERIOD;
}

void BigEnemy::draw(GameLevel& context) const {
  if(x - 3 > SCREEN_WIDTH) { return; }
  context.core.drawBitmap(x - 3, y - 2, bitmapCruEnemy0, 2);
}

void BigEnemy::onHit(GameLevel& context) {
  // add score
  context.addScore(10);
  if(x > SCREEN_WIDTH) {  // far bonus
    context.addScore((x - SCREEN_WIDTH) * 10 / (FIELD_WIDTH - SCREEN_WIDTH));
  }
  // near
  if(x < SCREEN_WIDTH + 20) {
    context.core.tone(1047, 250);
    context.spawnParticle(x + random(-2,  8), y + random(-4, 4), PARTICLE_EXPLOSION);
    context.spawnParticle(x + random( 8, 18), y + random(-4, 4), PARTICLE_EXPLOSION);
#ifndef LOW_FLASH_MEMORY
    context.removeAllBullets();
    context.core.setQuake();
#endif
  }
  // reset
  inactivate();
}

// === SmallEnemy ===

void SmallEnemy::initialize(const char y, const byte type) {
  this->x    = FIELD_WIDTH;
  this->y    = y;
  this->type = type;
  timer      = 0;
}

void SmallEnemy::move(GameLevel& context) {
  const byte period = (getType() == 0) ? ZIG_PERIOD : TRI_PERIOD;

  switch(getType()) {
    // zigzag
    case 0: {
      // moving
      // x -= 1.5, y -= 0.5
      if(timer % 2 == 0) {
        x -= 2;
        y += (timer / (ZIG_PERIOD / 4) % 2 == 0) ? 1 : -1;
      }
      else {
        --x;
      }

      // firing bullet
      const byte d = context.difficulty();
      const byte typeCond = canFire() ||
        (d >= 70 && d < 80) || d >= 100;  // [70,80) or 100
      if(
        timer == 80 && typeCond &&    // time / type
        x < SCREEN_WIDTH - W / 2 &&   // position
        d >= 20                       // dont fire less than 20
      ) {
        const byte  bulletType = (d >= 80) ? 3 : 1;  // rapid when 80 and over
        const float subAngle   = context.getSubmarineAngle(x, y);
        context.fireBullet(x, y, subAngle, bulletType);
        // 3way
        if((d >= 50 && d < 70) || d >= 90) {
          context.fireBullet(x, y, subAngle - radians(10), 1);
          context.fireBullet(x, y, subAngle + radians(10), 1);
        }
      }
    } break;

    // triangle
    default: {
      // moving
      if(timer % 6 == 0) { --x; }
      const int half = period / 2;
      int tmp = half - timer % half;
      tmp = tmp*tmp / (half*half/4) - 1;
      if(tmp < 0) { tmp = 0; }
      x -= tmp;

      // firing bullet
      const bool timeCond = timer == 64 ||
        (context.difficulty() >= 25 && timer == 32) ||
        (context.difficulty() >= 75 && timer == 96);
      if(
        timeCond && canFire() &&                    // time / type
        x < SCREEN_WIDTH && x > SCREEN_WIDTH / 2 && // position
        context.difficulty() >= 20                  // difficulty
      ) {
        context.fireBullet(x, y, context.getSubmarineAngle(x, y), 1);
      }
    } break;
  }

  // frame out
  if(x + 12 < 0) {
    context.platoons.checkBonus(getPlatoon(), false);
    inactivate();
  }

  // setting sonar reaction
  context.echo.add(x, y, y+H);

  // updating timer
  timer = (timer + 1) % period;
}

void SmallEnemy::draw(GameLevel& context) const {
  if(x - 4 > SCREEN_WIDTH) { return; }
  switch(getType()) {
    // zigzag
    case 0: {
      const byte* bitmaps[] = {bitmapZigEnemy0, bitmapZigEnemy1};
      const byte frame = timer / (ZIG_PERIOD / 4) % 2;
      context.core.drawBitmap(x - 3, y - 3, bitmaps[frame], 2);
    } break;

    // triangle
    default: {
      const byte* bitmaps[] = {bitmapTriEnemy0, bitmapTriEnemy1};
      const byte frame = (timer % (TRI_PERIOD / 2) < 24) ? 1 : 0;
      context.core.drawBitmap(x - 3, y - 4, bitmaps[frame], 2);
      if(frame == 1) {
        context.core.drawBitmap(x + 7, y - 2, bitmapBoostEffect, 2);
      }
    } break;
  }
  //context.core.getArduboy().drawRect(x, y, W, H, 0);
}

void SmallEnemy::onHit(GameLevel& context) {
  context.addScore(1);
  if(x < SCREEN_WIDTH + 20) { // near
    context.spawnParticle(round(x) - 5, round(y) - 4, PARTICLE_EXPLOSION);
    context.core.tone(880, 62);
  }
  // platoon elimination
  if(context.platoons.checkBonus(getPlatoon(), true)) {
    if(x < SCREEN_WIDTH + 20) { // near
      context.spawnParticle(round(x) - 2, round(y) - 2, PARTICLE_TEN_POINT);
    }
    context.addScore(10);
  }
  inactivate();
}

// === Bullet ===

void Bullet::initialize(const char x, const char y, const float radian, const byte type) {
  this->x    = x << 8;
  this->y    = y << 8;
  this->type = type;

  const byte SPEEDS[] = {BULLET_TYPE0_SPD, BULLET_TYPE1_SPD, BULLET_TYPE2_SPD, BULLET_TYPE3_SPD};
  byte speed = SPEEDS[type];
  vx = round(cos(radian) * speed / (1.f / 256));
  vy = round(sin(radian) * speed / (1.f / 256));
}

void Bullet::move() {
  x += vx;
  y += vy;

  // frame out
  static const char MARGIN = 4;
  if(
    fieldX() < -MARGIN || fieldX() > SCREEN_WIDTH  + MARGIN ||
    fieldY() < -MARGIN || fieldY() > SCREEN_HEIGHT + MARGIN
  ) {
    inactivate();
  }
}

void Bullet::draw(GameLevel& context) const {
  // ToDo: async animation (if there are enough memories)
  const byte frame = context.frameCount() / 3 % 2;

  if(type % 2 == 0) {
    const byte* bitmaps[] = {bitmapMbullet0, bitmapMbullet1};
    context.core.drawBitmap(fieldX() - bitmapMbullet0[0]/2, fieldY() - bitmapMbullet0[1]/2, bitmaps[frame], 2);
  }
  else {
    const byte* bitmaps[] = {bitmapSbullet0, bitmapSbullet1};
    context.core.drawBitmap(fieldX() - bitmapSbullet0[0]/2, fieldY() - bitmapSbullet0[1]/2, bitmaps[frame], 2);
  }
  //arduboy.drawPixel(x, y, 0);
}

void Bullet::onHit(GameLevel& context) {
  context.core.drawCircle(fieldX(), fieldY(), 6, 1);
  inactivate();
}

// === Particle ===

void Particle::move() {
  --limit;
  if(limit <= 0) {
    inactivate();
  }
}

void Particle::draw(GameLevel& context) const {
  switch(type) {
    case 0: {
      if(limit > 8) {
        context.core.drawBitmap(x, y, bitmapExplosion0, 2);
      }
      else if(limit > 4) {
        context.core.drawBitmap(x, y, bitmapExplosion1, 2);
      }
      else {
        context.core.drawBitmap(x, y, bitmapExplosion2, 2);
      }
    } break;

    default: {
      context.core.drawBitmap(x, y, bitmapTen, 2);
    } break;
  }
}

<commit_msg>[fix] invalid comparisons because of the data type<commit_after>#include "actor.h"
#include "gamelevel.h"
#include "modules.h"
#include "util.h"
#include "assets.h"

// === Submarine ===

void Submarine::initialize() {
  x = W << 8;
  y = (SCREEN_HEIGHT / 2) << 8;
  extraLives = START_LIVES;
  armor      = ARMOR_FRAMES;
}

void Submarine::move(GameLevel& context) {
  if(context.isGameover()) { return; }

  // control
  static const int SPD = 1 << 7;
  static const int R2  = 90;  // 0.5/sqrt(2) / (1/256)
  if(context.core.pressed(BTN_U) && context.core.pressed(BTN_L)) {
    x -= R2;
    y -= R2;
  }
  else if(context.core.pressed(BTN_U) && context.core.pressed(BTN_R)) {
    x += R2;
    y -= R2;
  }
  else if(context.core.pressed(BTN_D) && context.core.pressed(BTN_L)) {
    x -= R2;
    y += R2;
  }
  else if(context.core.pressed(BTN_D) && context.core.pressed(BTN_R)) {
    x += R2;
    y += R2;
  }
  else if(context.core.pressed(BTN_U)) {
    y -= SPD;
  }
  else if(context.core.pressed(BTN_L)) {
    x -= SPD;
  }
  else if(context.core.pressed(BTN_R)) {
    x += SPD;
  }
  else if(context.core.pressed(BTN_D)) {
    y += SPD;
  }

  // clamping into field
  static const fixed MARGIN = 6;
  x = Clamp(x, 0, (SCREEN_WIDTH - MARGIN) << 8);
  y = Clamp(y, (MARGIN - H) << 8, (SCREEN_HEIGHT - MARGIN) << 8);

  // launching torpedo
  if(extraLives >= 0 && (context.core.pushed(BTN_A) || context.core.pushed(BTN_B))) {
    context.launchTorpedo(fieldX() + 10, fieldY() + 1);
  }

  //firing auto shot
#ifdef LOW_FLASH_MEMORY
  if(context.frameCount() % 5 == 0) {
    context.fireAutoShot(fieldX() + 3, fieldY() - 3);
  }
#else
  if(context.lookForEnemy() && context.frameCount() % 5 == 0) {
    context.fireAutoShot(fieldX() + 3, fieldY() - 3);
  }
#endif

  // updating armor timer
  if(armor > 0) { --armor; }
}

void Submarine::draw(GameLevel& context) const {
  if(armor == 0 || (extraLives >= 0 && context.frameCount() / 3 % 2 == 0)) {
    context.core.drawBitmap(fieldX() - 1, fieldY() - 2, bitmapSubmarine, 2);
    if(context.frameCount() % ECHO_CYCLE > 30) {  // sustain: 30 frames
      context.core.drawPixel(fieldX() + 6, fieldY() - 1, 1);
    }
  }
  //context.getArduboy().drawRect(x, y, W, H, 0);
}

void Submarine::onHit(GameLevel& context) {
  if(armor <= 0) {
    if(extraLives >= 0) {
      context.spawnParticle(fieldX() - 2, fieldY() - 4, PARTICLE_EXPLOSION);
      context.core.tone(185, 250);
    }
    --extraLives;
    if(extraLives < 0) {
      context.setGameover();
      // ToDo: add gameover sfx
      inactivate();
    }
    armor = ARMOR_FRAMES;
  }
}

// === Torpedo ===

bool Torpedo::launch(const char x, const char y) {
  if(!exist()) {
    this->x = x;
    this->y = y;
    vx = 0;
    return true;
  }
  return false;
}

void Torpedo::move() {
  static const fixed ACC = 1 << 7;  // 0.5
  if(!exist()) { return; }
  vx += ACC - (vx >> 4);
  x  += vx >> 8;
  if(x >= FIELD_WIDTH) {
    inactivate();
  }
}

void Torpedo::draw(GameLevel& context) const {
  if(!exist()) { return; }
  // body
  context.core.drawBitmap(x, y - 1, bitmapTorpedo, 2);
  // shockwave
  if(vx > 4 << 8) { // well accelerated
    const byte h = bitmapShockwave0[1];
    context.core.drawBitmap(x -  8, y - h/2, bitmapShockwave0, 2);
    context.core.drawBitmap(x - 16, y - h/2, bitmapShockwave1, 2);
    context.core.drawBitmap(x - 24, y - h/2, bitmapShockwave2, 2);
  }
  //context.getArduboy.drawFastHLine(x, y, W, 0);
}

// === AutoShot ===

void AutoShot::initialize(const char x, const char y) {
  this->x = x;
  this->y = y;
}

void AutoShot::move() {
  // moving
  x += 8;

  // frame out
  if((byte)x > SCREEN_WIDTH) {
    inactivate();
  }
}

void AutoShot::draw(GameLevel& context) const {
  context.core.drawBitmap((int)x + 2, (int)y + 3, bitmapAutoShot, 2);
  //context.core.getArduboy().drawRect(x, y, W, H, 1);
}

// === BigEnemy ===

void BigEnemy::initialize(const char y) {
  this->x = FIELD_WIDTH;
  this->y = y;
  state   = 0;
  timer   = 0;
}

void BigEnemy::move(GameLevel& context) {
  // moving
  if(grazed() && x > SCREEN_WIDTH - 5) {
    x += -3; // submarine found
  }
  else if(timer % 5 == 0) { // -0.2
    --x;
  }

  // frame out
  if(x + bitmapCruEnemy0[0] < 0) {
    inactivate();
  }

  // setting sonar reaction
  context.echo.add(x, y, y+H);

  // firing bullet
  if(x < SCREEN_WIDTH - W / 2) {
    if(!onScreen()) {
      timer = 0;  // in order to sync fire cycle
      state |= ON_SCREEN_MASK;
    }
    const byte d = context.difficulty();
    if(timer == 0 || (d >= 60 && timer == 40)) {  // freq up when 60 and over
      const char bulletY     = y + bitmapCruEnemy0[1] / 2;
      const char bulletSpeed = (d >= 80) ? BULLET_TYPE2_SPD : BULLET_TYPE0_SPD;
      const char bulletType  = (d >= 80) ? 2 : 0;
      context.fireBullet(x, bulletY, context.getFutureSubmarineAngle(x, bulletY, bulletSpeed), bulletType);
    }
  }

  // updating timer
  static const byte PERIOD = 150;
  timer = (timer + 1) % PERIOD;
}

void BigEnemy::draw(GameLevel& context) const {
  if(x - 3 > SCREEN_WIDTH) { return; }
  context.core.drawBitmap(x - 3, y - 2, bitmapCruEnemy0, 2);
}

void BigEnemy::onHit(GameLevel& context) {
  // add score
  context.addScore(10);
  if(x > SCREEN_WIDTH) {  // far bonus
    context.addScore((x - SCREEN_WIDTH) * 10 / (FIELD_WIDTH - SCREEN_WIDTH));
  }
  // near
  if(x < SCREEN_WIDTH + 20) {
    context.core.tone(1047, 250);
    context.spawnParticle(x + random(-2,  8), y + random(-4, 4), PARTICLE_EXPLOSION);
    context.spawnParticle(x + random( 8, 18), y + random(-4, 4), PARTICLE_EXPLOSION);
#ifndef LOW_FLASH_MEMORY
    context.removeAllBullets();
    context.core.setQuake();
#endif
  }
  // reset
  inactivate();
}

// === SmallEnemy ===

void SmallEnemy::initialize(const char y, const byte type) {
  this->x    = FIELD_WIDTH;
  this->y    = y;
  this->type = type;
  timer      = 0;
}

void SmallEnemy::move(GameLevel& context) {
  const byte period = (getType() == 0) ? ZIG_PERIOD : TRI_PERIOD;

  switch(getType()) {
    // zigzag
    case 0: {
      // moving
      // x -= 1.5, y -= 0.5
      if(timer % 2 == 0) {
        x -= 2;
        y += (timer / (ZIG_PERIOD / 4) % 2 == 0) ? 1 : -1;
      }
      else {
        --x;
      }

      // firing bullet
      const byte d = context.difficulty();
      const byte typeCond = canFire() ||
        (d >= 70 && d < 80) || d >= 100;  // [70,80) or 100
      if(
        timer == 80 && typeCond &&    // time / type
        x < SCREEN_WIDTH - W / 2 &&   // position
        d >= 20                       // dont fire less than 20
      ) {
        const byte  bulletType = (d >= 80) ? 3 : 1;  // rapid when 80 and over
        const float subAngle   = context.getSubmarineAngle(x, y);
        context.fireBullet(x, y, subAngle, bulletType);
        // 3way
        if((d >= 50 && d < 70) || d >= 90) {
          context.fireBullet(x, y, subAngle - radians(10), 1);
          context.fireBullet(x, y, subAngle + radians(10), 1);
        }
      }
    } break;

    // triangle
    default: {
      // moving
      if(timer % 6 == 0) { --x; }
      const int half = period / 2;
      int tmp = half - timer % half;
      tmp = tmp*tmp / (half*half/4) - 1;
      if(tmp < 0) { tmp = 0; }
      x -= tmp;

      // firing bullet
      const bool timeCond = timer == 64 ||
        (context.difficulty() >= 25 && timer == 32) ||
        (context.difficulty() >= 75 && timer == 96);
      if(
        timeCond && canFire() &&                    // time / type
        x < SCREEN_WIDTH && x > SCREEN_WIDTH / 2 && // position
        context.difficulty() >= 20                  // difficulty
      ) {
        context.fireBullet(x, y, context.getSubmarineAngle(x, y), 1);
      }
    } break;
  }

  // frame out
  if(x + 12 < 0) {
    context.platoons.checkBonus(getPlatoon(), false);
    inactivate();
  }

  // setting sonar reaction
  context.echo.add(x, y, y+H);

  // updating timer
  timer = (timer + 1) % period;
}

void SmallEnemy::draw(GameLevel& context) const {
  if(x - 4 > SCREEN_WIDTH) { return; }
  switch(getType()) {
    // zigzag
    case 0: {
      const byte* bitmaps[] = {bitmapZigEnemy0, bitmapZigEnemy1};
      const byte frame = timer / (ZIG_PERIOD / 4) % 2;
      context.core.drawBitmap(x - 3, y - 3, bitmaps[frame], 2);
    } break;

    // triangle
    default: {
      const byte* bitmaps[] = {bitmapTriEnemy0, bitmapTriEnemy1};
      const byte frame = (timer % (TRI_PERIOD / 2) < 24) ? 1 : 0;
      context.core.drawBitmap(x - 3, y - 4, bitmaps[frame], 2);
      if(frame == 1) {
        context.core.drawBitmap(x + 7, y - 2, bitmapBoostEffect, 2);
      }
    } break;
  }
  //context.core.getArduboy().drawRect(x, y, W, H, 0);
}

void SmallEnemy::onHit(GameLevel& context) {
  context.addScore(1);
  if(x < SCREEN_WIDTH + 20) { // near
    context.spawnParticle(round(x) - 5, round(y) - 4, PARTICLE_EXPLOSION);
    context.core.tone(880, 62);
  }
  // platoon elimination
  if(context.platoons.checkBonus(getPlatoon(), true)) {
    if(x < SCREEN_WIDTH + 20) { // near
      context.spawnParticle(round(x) - 2, round(y) - 2, PARTICLE_TEN_POINT);
    }
    context.addScore(10);
  }
  inactivate();
}

// === Bullet ===

void Bullet::initialize(const char x, const char y, const float radian, const byte type) {
  this->x    = x << 8;
  this->y    = y << 8;
  this->type = type;

  const byte SPEEDS[] = {BULLET_TYPE0_SPD, BULLET_TYPE1_SPD, BULLET_TYPE2_SPD, BULLET_TYPE3_SPD};
  byte speed = SPEEDS[type];
  vx = round(cos(radian) * speed / (1.f / 256));
  vy = round(sin(radian) * speed / (1.f / 256));
}

void Bullet::move() {
  x += vx;
  y += vy;

  // frame out
  static const char MARGIN = 4;
  if(
    fieldX() < -MARGIN || (byte)fieldX() > SCREEN_WIDTH  + MARGIN ||
    fieldY() < -MARGIN || (byte)fieldY() > SCREEN_HEIGHT + MARGIN
  ) {
    inactivate();
  }
}

void Bullet::draw(GameLevel& context) const {
  // ToDo: async animation (if there are enough memories)
  const byte frame = context.frameCount() / 3 % 2;

  if(type % 2 == 0) {
    const byte* bitmaps[] = {bitmapMbullet0, bitmapMbullet1};
    context.core.drawBitmap(fieldX() - bitmapMbullet0[0]/2, fieldY() - bitmapMbullet0[1]/2, bitmaps[frame], 2);
  }
  else {
    const byte* bitmaps[] = {bitmapSbullet0, bitmapSbullet1};
    context.core.drawBitmap(fieldX() - bitmapSbullet0[0]/2, fieldY() - bitmapSbullet0[1]/2, bitmaps[frame], 2);
  }
  //arduboy.drawPixel(x, y, 0);
}

void Bullet::onHit(GameLevel& context) {
  context.core.drawCircle(fieldX(), fieldY(), 6, 1);
  inactivate();
}

// === Particle ===

void Particle::move() {
  --limit;
  if(limit <= 0) {
    inactivate();
  }
}

void Particle::draw(GameLevel& context) const {
  switch(type) {
    case 0: {
      if(limit > 8) {
        context.core.drawBitmap(x, y, bitmapExplosion0, 2);
      }
      else if(limit > 4) {
        context.core.drawBitmap(x, y, bitmapExplosion1, 2);
      }
      else {
        context.core.drawBitmap(x, y, bitmapExplosion2, 2);
      }
    } break;

    default: {
      context.core.drawBitmap(x, y, bitmapTen, 2);
    } break;
  }
}

<|endoftext|>


<commit_before>// Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0

#include <openvdb/openvdb.h>
#include <openvdb/tools/LevelSetPlatonic.h>
#include <openvdb/tools/NodeVisitor.h>
#include <openvdb/tools/Prune.h>
#include "gtest/gtest.h"

class TestNodeVisitor: public ::testing::Test
{
};

struct NodeCountOp
{
    template <typename NodeT>
    void operator()(const NodeT&, size_t)
    {
        const openvdb::Index level = NodeT::LEVEL;
        while (level >= counts.size())     counts.emplace_back(0);
        counts[level]++;
    }

    std::vector<openvdb::Index32> counts;
}; // struct NodeCountOp

TEST_F(TestNodeVisitor, testNodeCount)
{
    using namespace openvdb;

    auto grid = tools::createLevelSetCube<FloatGrid>(/*scale=*/10.0f);

    NodeCountOp nodeCountOp;
    tools::visitNodesDepthFirst(grid->tree(), nodeCountOp);

    std::vector<Index32> nodeCount1 = nodeCountOp.counts;
    std::vector<Index32> nodeCount2 = grid->tree().nodeCount();

    EXPECT_EQ(nodeCount1.size(), nodeCount2.size());

    for (size_t i = 0; i < nodeCount1.size(); i++) {
        EXPECT_EQ(nodeCount1[i], nodeCount2[i]);
    }
}

template <typename TreeT>
struct LeafCountOp
{
    using LeafT = typename TreeT::LeafNodeType;

    template <typename NodeT>
    void operator()(const NodeT&, size_t) { }
    void operator()(const LeafT&, size_t) { count++; }

    openvdb::Index32 count{0};
}; // struct LeafCountOp

TEST_F(TestNodeVisitor, testLeafCount)
{
    using namespace openvdb;

    FloatGrid::Ptr grid = tools::createLevelSetCube<FloatGrid>(/*scale=*/10.0f);

    LeafCountOp<FloatTree> leafCountOp;
    tools::visitNodesDepthFirst(grid->tree(), leafCountOp);

    EXPECT_EQ(grid->tree().leafCount(), leafCountOp.count);
}

struct DescendOp
{
    template <typename NodeT>
    void operator()(const NodeT&, size_t)
    {
        const openvdb::Index level = NodeT::LEVEL;
        // count the number of times the operator descends
        // from a higher-level node to a lower-level node
        if (NodeT::LEVEL < previousLevel)   count++;
        previousLevel = level;
    }

    openvdb::Index32 previousLevel{0};
    openvdb::Index32 count{0};
}; // struct DescendOp

TEST_F(TestNodeVisitor, testDepthFirst)
{
    using namespace openvdb;

    FloatGrid::Ptr grid = tools::createLevelSetCube<FloatGrid>(/*scale=*/10.0f);

    DescendOp descendOp;
    tools::visitNodesDepthFirst(grid->tree(), descendOp);

    // this confirms that the visit pattern is depth-first
    EXPECT_EQ(descendOp.count, grid->tree().nonLeafCount());
}

template <typename TreeT>
struct StoreOriginsOp
{
    using RootT = typename TreeT::RootNodeType;

    StoreOriginsOp(std::vector<openvdb::Coord>& _origins)
        : origins(_origins) { }

    void operator()(const RootT&, size_t idx)
    {
        // root node has no origin
        origins[idx] = openvdb::Coord::max();
    }

    template <typename NodeT>
    void operator()(const NodeT& node, size_t idx)
    {
        origins[idx] = node.origin();
    }

    std::vector<openvdb::Coord>& origins;
}; // struct StoreOriginsOp

TEST_F(TestNodeVisitor, testOriginArray)
{
    using namespace openvdb;

    FloatGrid::Ptr grid = tools::createLevelSetCube<FloatGrid>(/*scale=*/10.0f);

    std::vector<Index32> nodeCount = grid->tree().nodeCount();
    Index32 totalNodeCount(0);
    for (Index32 count : nodeCount)     totalNodeCount += count;

    // use an offset
    size_t offset = 10;

    std::vector<Coord> origins;
    origins.resize(totalNodeCount + offset);

    StoreOriginsOp<FloatTree> storeOriginsOp(origins);
    tools::visitNodesDepthFirst(grid->tree(), storeOriginsOp, offset);

    size_t idx = offset;

    // root node
    EXPECT_EQ(origins[idx++], Coord::max());

    const auto& root = grid->tree().root();
    for (auto internal1Iter = root.cbeginChildOn(); internal1Iter; ++internal1Iter) {
        EXPECT_EQ(origins[idx++], internal1Iter->origin());
        for (auto internal2Iter = internal1Iter->cbeginChildOn(); internal2Iter; ++internal2Iter) {
            EXPECT_EQ(origins[idx++], internal2Iter->origin());
            for (auto leafIter = internal2Iter->cbeginChildOn(); leafIter; ++leafIter) {
                EXPECT_EQ(origins[idx++], leafIter->origin());
            }
        }
    }

    EXPECT_EQ(idx, origins.size());
}

template <typename TreeType>
struct DeactivateOp
{
    using LeafT = typename TreeType::LeafNodeType;

    template <typename NodeT>
    void operator()(NodeT&, size_t) { }

    void operator()(LeafT& leaf, size_t)
    {
        leaf.setValuesOff();
    }
}; // struct DeactivateOp

TEST_F(TestNodeVisitor, testPartialDeactivate)
{
    using namespace openvdb;

    FloatGrid::Ptr grid = tools::createLevelSetCube<FloatGrid>(/*scale=*/10.0f);

    using NodeT = FloatTree::RootNodeType::ChildNodeType::ChildNodeType;

    auto iter = grid->tree().root().beginChildOn()->beginChildOn();

    DeactivateOp<FloatTree> deactivateOp;
    tools::DepthFirstNodeVisitor<NodeT>::visit(*iter, deactivateOp);

    EXPECT_EQ(Index32(1413), grid->tree().leafCount());

    tools::pruneInactive(grid->tree());

    // a subset of the leaf nodes have now been deactivated and removed
    EXPECT_EQ(Index32(1195), grid->tree().leafCount());
}

// Functor to offset all the active values of a tree.
struct OffsetOp
{
    OffsetOp(float v): mOffset(v) { }

    template<typename NodeT>
    void operator()(NodeT& node, size_t) const
    {
        for (auto iter = node.beginValueOn(); iter; ++iter) {
            iter.setValue(iter.getValue() + mOffset);
        }
    }
private:
    const float mOffset;
};

// Functor to offset all the active values of a tree. Note
// this implementation also illustrates how different
// computation can be applied to the different node types.
template<typename TreeT>
struct OffsetByLevelOp
{
    using ValueT = typename TreeT::ValueType;
    using RootT = typename TreeT::RootNodeType;
    using LeafT = typename TreeT::LeafNodeType;
    OffsetByLevelOp(const ValueT& v) : mOffset(v) {}
    // Processes the root node.
    void operator()(RootT& root, size_t) const
    {
        for (auto iter = root.beginValueOn(); iter; ++iter) {
            iter.setValue(iter.getValue() + mOffset);
        }
    }
    // Processes the leaf nodes.
    void operator()(LeafT& leaf, size_t) const
    {
        for (auto iter = leaf.beginValueOn(); iter; ++iter) {
            iter.setValue(iter.getValue() + mOffset);
        }
    }
    // Processes the internal nodes.
    template<typename NodeT>
    void operator()(NodeT& node, size_t) const
    {
        for (auto iter = node.beginValueOn(); iter; ++iter) {
            iter.setValue(iter.getValue() + mOffset);
        }
    }
private:
    const ValueT mOffset;
};

// this is the example from the documentation
TEST_F(TestNodeVisitor, testOffset)
{
    using namespace openvdb;

    FloatGrid::Ptr grid = tools::createLevelSetCube<FloatGrid>(/*scale=*/10.0f);

    OffsetOp op(3.0f);
    tools::visitNodesDepthFirst(grid->tree(), op);

    OffsetByLevelOp<FloatTree> byLevelOp(3.0f);
    tools::visitNodesDepthFirst(grid->tree(), byLevelOp);
}
<commit_msg>Add ABI=7 guard to nodeCount unit tests<commit_after>// Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0

#include <openvdb/openvdb.h>
#include <openvdb/tools/LevelSetPlatonic.h>
#include <openvdb/tools/NodeVisitor.h>
#include <openvdb/tools/Prune.h>
#include "gtest/gtest.h"

class TestNodeVisitor: public ::testing::Test
{
};

#if OPENVDB_ABI_VERSION_NUMBER >= 7
struct NodeCountOp
{
    template <typename NodeT>
    void operator()(const NodeT&, size_t)
    {
        const openvdb::Index level = NodeT::LEVEL;
        while (level >= counts.size())     counts.emplace_back(0);
        counts[level]++;
    }

    std::vector<openvdb::Index32> counts;
}; // struct NodeCountOp

TEST_F(TestNodeVisitor, testNodeCount)
{
    using namespace openvdb;

    auto grid = tools::createLevelSetCube<FloatGrid>(/*scale=*/10.0f);

    NodeCountOp nodeCountOp;
    tools::visitNodesDepthFirst(grid->tree(), nodeCountOp);

    std::vector<Index32> nodeCount1 = nodeCountOp.counts;
    std::vector<Index32> nodeCount2 = grid->tree().nodeCount();

    EXPECT_EQ(nodeCount1.size(), nodeCount2.size());

    for (size_t i = 0; i < nodeCount1.size(); i++) {
        EXPECT_EQ(nodeCount1[i], nodeCount2[i]);
    }
}
#endif // OPENVDB_ABI_VERSION_NUMBER >= 7

template <typename TreeT>
struct LeafCountOp
{
    using LeafT = typename TreeT::LeafNodeType;

    template <typename NodeT>
    void operator()(const NodeT&, size_t) { }
    void operator()(const LeafT&, size_t) { count++; }

    openvdb::Index32 count{0};
}; // struct LeafCountOp

TEST_F(TestNodeVisitor, testLeafCount)
{
    using namespace openvdb;

    FloatGrid::Ptr grid = tools::createLevelSetCube<FloatGrid>(/*scale=*/10.0f);

    LeafCountOp<FloatTree> leafCountOp;
    tools::visitNodesDepthFirst(grid->tree(), leafCountOp);

    EXPECT_EQ(grid->tree().leafCount(), leafCountOp.count);
}

struct DescendOp
{
    template <typename NodeT>
    void operator()(const NodeT&, size_t)
    {
        const openvdb::Index level = NodeT::LEVEL;
        // count the number of times the operator descends
        // from a higher-level node to a lower-level node
        if (NodeT::LEVEL < previousLevel)   count++;
        previousLevel = level;
    }

    openvdb::Index32 previousLevel{0};
    openvdb::Index32 count{0};
}; // struct DescendOp

TEST_F(TestNodeVisitor, testDepthFirst)
{
    using namespace openvdb;

    FloatGrid::Ptr grid = tools::createLevelSetCube<FloatGrid>(/*scale=*/10.0f);

    DescendOp descendOp;
    tools::visitNodesDepthFirst(grid->tree(), descendOp);

    // this confirms that the visit pattern is depth-first
    EXPECT_EQ(descendOp.count, grid->tree().nonLeafCount());
}

#if OPENVDB_ABI_VERSION_NUMBER >= 7
template <typename TreeT>
struct StoreOriginsOp
{
    using RootT = typename TreeT::RootNodeType;

    StoreOriginsOp(std::vector<openvdb::Coord>& _origins)
        : origins(_origins) { }

    void operator()(const RootT&, size_t idx)
    {
        // root node has no origin
        origins[idx] = openvdb::Coord::max();
    }

    template <typename NodeT>
    void operator()(const NodeT& node, size_t idx)
    {
        origins[idx] = node.origin();
    }

    std::vector<openvdb::Coord>& origins;
}; // struct StoreOriginsOp

TEST_F(TestNodeVisitor, testOriginArray)
{
    using namespace openvdb;

    FloatGrid::Ptr grid = tools::createLevelSetCube<FloatGrid>(/*scale=*/10.0f);

    std::vector<Index32> nodeCount = grid->tree().nodeCount();
    Index32 totalNodeCount(0);
    for (Index32 count : nodeCount)     totalNodeCount += count;

    // use an offset
    size_t offset = 10;

    std::vector<Coord> origins;
    origins.resize(totalNodeCount + offset);

    StoreOriginsOp<FloatTree> storeOriginsOp(origins);
    tools::visitNodesDepthFirst(grid->tree(), storeOriginsOp, offset);

    size_t idx = offset;

    // root node
    EXPECT_EQ(origins[idx++], Coord::max());

    const auto& root = grid->tree().root();
    for (auto internal1Iter = root.cbeginChildOn(); internal1Iter; ++internal1Iter) {
        EXPECT_EQ(origins[idx++], internal1Iter->origin());
        for (auto internal2Iter = internal1Iter->cbeginChildOn(); internal2Iter; ++internal2Iter) {
            EXPECT_EQ(origins[idx++], internal2Iter->origin());
            for (auto leafIter = internal2Iter->cbeginChildOn(); leafIter; ++leafIter) {
                EXPECT_EQ(origins[idx++], leafIter->origin());
            }
        }
    }

    EXPECT_EQ(idx, origins.size());
}
#endif // OPENVDB_ABI_VERSION_NUMBER >= 7

template <typename TreeType>
struct DeactivateOp
{
    using LeafT = typename TreeType::LeafNodeType;

    template <typename NodeT>
    void operator()(NodeT&, size_t) { }

    void operator()(LeafT& leaf, size_t)
    {
        leaf.setValuesOff();
    }
}; // struct DeactivateOp

TEST_F(TestNodeVisitor, testPartialDeactivate)
{
    using namespace openvdb;

    FloatGrid::Ptr grid = tools::createLevelSetCube<FloatGrid>(/*scale=*/10.0f);

    using NodeT = FloatTree::RootNodeType::ChildNodeType::ChildNodeType;

    auto iter = grid->tree().root().beginChildOn()->beginChildOn();

    DeactivateOp<FloatTree> deactivateOp;
    tools::DepthFirstNodeVisitor<NodeT>::visit(*iter, deactivateOp);

    EXPECT_EQ(Index32(1413), grid->tree().leafCount());

    tools::pruneInactive(grid->tree());

    // a subset of the leaf nodes have now been deactivated and removed
    EXPECT_EQ(Index32(1195), grid->tree().leafCount());
}

// Functor to offset all the active values of a tree.
struct OffsetOp
{
    OffsetOp(float v): mOffset(v) { }

    template<typename NodeT>
    void operator()(NodeT& node, size_t) const
    {
        for (auto iter = node.beginValueOn(); iter; ++iter) {
            iter.setValue(iter.getValue() + mOffset);
        }
    }
private:
    const float mOffset;
};

// Functor to offset all the active values of a tree. Note
// this implementation also illustrates how different
// computation can be applied to the different node types.
template<typename TreeT>
struct OffsetByLevelOp
{
    using ValueT = typename TreeT::ValueType;
    using RootT = typename TreeT::RootNodeType;
    using LeafT = typename TreeT::LeafNodeType;
    OffsetByLevelOp(const ValueT& v) : mOffset(v) {}
    // Processes the root node.
    void operator()(RootT& root, size_t) const
    {
        for (auto iter = root.beginValueOn(); iter; ++iter) {
            iter.setValue(iter.getValue() + mOffset);
        }
    }
    // Processes the leaf nodes.
    void operator()(LeafT& leaf, size_t) const
    {
        for (auto iter = leaf.beginValueOn(); iter; ++iter) {
            iter.setValue(iter.getValue() + mOffset);
        }
    }
    // Processes the internal nodes.
    template<typename NodeT>
    void operator()(NodeT& node, size_t) const
    {
        for (auto iter = node.beginValueOn(); iter; ++iter) {
            iter.setValue(iter.getValue() + mOffset);
        }
    }
private:
    const ValueT mOffset;
};

// this is the example from the documentation
TEST_F(TestNodeVisitor, testOffset)
{
    using namespace openvdb;

    FloatGrid::Ptr grid = tools::createLevelSetCube<FloatGrid>(/*scale=*/10.0f);

    OffsetOp op(3.0f);
    tools::visitNodesDepthFirst(grid->tree(), op);

    OffsetByLevelOp<FloatTree> byLevelOp(3.0f);
    tools::visitNodesDepthFirst(grid->tree(), byLevelOp);
}
<|endoftext|>


<commit_before>//#include "OpenCLHelper.h"
//#include "ClConvolve.h"

#include <iostream>

#include "Timer.h"
#include "NeuralNet.h"
#include "AccuracyHelper.h"

using namespace std;

void test1() {
    Timer timer;
    float *data = new float[2];
    data[0] = 0.5;
    data[1] = -0.5;
    int *labels = new int[2];
    labels[0] = 0;
    labels[1] = 1;
    float *expectedResults = new float[4];
    expectedResults[0] = 0.5;
    expectedResults[1] = -0.5;
    expectedResults[2] = -0.5;
    expectedResults[3] = 0.5;
    NeuralNet *net = NeuralNet::maker()->planes(1)->boardSize(1)->instance();
    net->convolutionalMaker()->numFilters(2)->filterSize(1)->biased()->insert();
    for( int epoch = 0; epoch < 100; epoch++ ) {
        net->epochMaker()
            ->learningRate(1)
            ->batchSize(2)
            ->numExamples(2)
            ->inputData(data)
            ->expectedOutputs(expectedResults)
            ->run();
        cout << "loss, E, " << net->calcLoss(expectedResults) << endl;
        net->print();
        float const*results = net->getResults();
        AccuracyHelper::printAccuracy( 2, 2, labels, results );
    }
    net->print();
    float const*results = net->getResults();
    AccuracyHelper::printAccuracy( 2, 2, labels, results );

    delete net;
}

void test2() {
    Timer timer;
    float data[] = { 0.5, 0.5, 0.5,
                    -0.5, 0.5, 0.5,
                    0.5, 0.5, 0.5,

                   0.5, 0.5, 0.5,
                   0.5, -0.5, 0.5,
                   0.5, 0.5, 0.5,

                    -0.5, -0.5, -0.5,
                    -0.5, 0.5, -0.5,
                    -0.5, -0.5, -0.5,

                   -0.5, -0.5, -0.5,
                   0.5, -0.5, -0.5,
                   -0.5, -0.5, -0.5
 };

    int *labels = new int[4];
    labels[0] = 0;
    labels[1] = 1;
    labels[2] = 0;
    labels[3] = 1;
    float *expectedResults = new float[8];
    expectedResults[0] = 0.5;
    expectedResults[1] = -0.5;
    expectedResults[2] = -0.5;
    expectedResults[3] = 0.5;
    expectedResults[4] = 0.5;
    expectedResults[5] = -0.5;
    expectedResults[6] = -0.5;
    expectedResults[7] = 0.5;
    NeuralNet *net = NeuralNet::maker()->planes(1)->boardSize(3)->instance();
    net->convolutionalMaker()->numFilters(2)->filterSize(3)->biased()->insert();
    float const*results = 0;
    for( int epoch = 0; epoch < 20; epoch++ ) {
        net->epochMaker()
            ->learningRate(1)
            ->batchSize(4)
            ->numExamples(4)
            ->inputData(data)
            ->expectedOutputs(expectedResults)
            ->run();
        cout << "loss, E, " << net->calcLoss(expectedResults) << endl;
        results = net->getResults();
        AccuracyHelper::printAccuracy( 4, 2, labels, results );
    }
    net->print();
    AccuracyHelper::printAccuracy( 4, 2, labels, results );

    delete net;
}

int main( int argc, char *argv[] ) {
    int testNum = -1;
    if( argc == 2 ) {
        testNum = atoi( argv[1] );
    }
    if( testNum == -1 || testNum == 1 ) test1();
    if( testNum == -1 || testNum == 2 ) test2();

    return 0;
}

<commit_msg>automate testsimpleconvolvenet a bit<commit_after>//#include "OpenCLHelper.h"
//#include "ClConvolve.h"

#include <iostream>

#include "Timer.h"
#include "NeuralNet.h"
#include "AccuracyHelper.h"
#include "test/asserts.h"

using namespace std;

void test1() {
    Timer timer;
    float *data = new float[2];
    data[0] = 0.5;
    data[1] = -0.5;
    int *labels = new int[2];
    labels[0] = 0;
    labels[1] = 1;
    float *expectedResults = new float[4];
    expectedResults[0] = 0.5;
    expectedResults[1] = -0.5;
    expectedResults[2] = -0.5;
    expectedResults[3] = 0.5;
    NeuralNet *net = NeuralNet::maker()->planes(1)->boardSize(1)->instance();
    net->convolutionalMaker()->numFilters(2)->filterSize(1)->biased()->insert();
    for( int epoch = 0; epoch < 100; epoch++ ) {
        net->epochMaker()
            ->learningRate(1)
            ->batchSize(2)
            ->numExamples(2)
            ->inputData(data)
            ->expectedOutputs(expectedResults)
            ->run();
//        cout << "loss, E, " << net->calcLoss(expectedResults) << endl;
//        net->print();
        float const*results = net->getResults();
//        AccuracyHelper::printAccuracy( 2, 2, labels, results );
    }
//    net->print();
    cout << "loss, E, " << net->calcLoss(expectedResults) << endl;
    float const*results = net->getResults();
    AccuracyHelper::printAccuracy( 2, 2, labels, results );

    int numCorrect = AccuracyHelper::calcNumRight( 2, 2, labels, net->getResults() );
    cout << "accuracy: " << numCorrect << "/" << 2 << endl;
    assertEquals( numCorrect, 2 );

    delete net;
}

void test2() {
    Timer timer;
    float data[] = { 0.5, 0.5, 0.5,
                    -0.5, 0.5, 0.5,
                    0.5, 0.5, 0.5,

                   0.5, 0.5, 0.5,
                   0.5, -0.5, 0.5,
                   0.5, 0.5, 0.5,

                    -0.5, -0.5, -0.5,
                    -0.5, 0.5, -0.5,
                    -0.5, -0.5, -0.5,

                   -0.5, -0.5, -0.5,
                   0.5, -0.5, -0.5,
                   -0.5, -0.5, -0.5
 };

    int *labels = new int[4];
    labels[0] = 0;
    labels[1] = 1;
    labels[2] = 0;
    labels[3] = 1;
    float *expectedResults = new float[8];
    expectedResults[0] = 0.5;
    expectedResults[1] = -0.5;
    expectedResults[2] = -0.5;
    expectedResults[3] = 0.5;
    expectedResults[4] = 0.5;
    expectedResults[5] = -0.5;
    expectedResults[6] = -0.5;
    expectedResults[7] = 0.5;
    NeuralNet *net = NeuralNet::maker()->planes(1)->boardSize(3)->instance();
    net->convolutionalMaker()->numFilters(2)->filterSize(3)->biased()->insert();
    float const*results = 0;
    for( int epoch = 0; epoch < 20; epoch++ ) {
        net->epochMaker()
            ->learningRate(1)
            ->batchSize(4)
            ->numExamples(4)
            ->inputData(data)
            ->expectedOutputs(expectedResults)
            ->run();
        results = net->getResults();
        AccuracyHelper::printAccuracy( 4, 2, labels, results );
    }
//    net->print();
    cout << "loss, E, " << net->calcLoss(expectedResults) << endl;
    AccuracyHelper::printAccuracy( 4, 2, labels, results );
    int numCorrect = AccuracyHelper::calcNumRight( 4, 2, labels, net->getResults() );
    cout << "accuracy: " << numCorrect << "/" << 4 << endl;
    assertEquals( numCorrect, 4 );

    delete net;
}

int main( int argc, char *argv[] ) {
    int testNum = -1;
    if( argc == 2 ) {
        testNum = atoi( argv[1] );
    }

    if( testNum == -1 ) {
        for( int i = 0; i < 10; i++ ) {
            test1();
            test2();
        }
    }

    if( testNum == -1 || testNum == 1 ) test1();
    if( testNum == -1 || testNum == 2 ) test2();

    return 0;
}

<|endoftext|>


<commit_before>#include "include/http_server.h"

HttpServer::HttpServer()
{
  base = NULL;
  base = event_init();
}

HttpServer::~HttpServer()
{
  // if (base != NULL) delete base;
}

bool HttpServer::bind_callback(std::string url, int port, HttpCallback func)
{
  struct evhttp *httpd;
  httpd = evhttp_new(base);
  if (httpd == NULL) return -1;
  if (evhttp_bind_socket(httpd, url, port) != 0) return -1;
  evhttp_set_gencb(httpd, func, NULL);
}

std::string HttpServer::recv()
{
  event_base_dispatch(base);
}
<commit_msg>HTTP Server fixes<commit_after>#include "include/http_server.h"

HttpServer::HttpServer()
{
  base = NULL;
  base = event_init();
}

HttpServer::~HttpServer()
{
  // if (base != NULL) delete base;
}

bool HttpServer::bind_callback(std::string url, int port, HttpCallback func)
{
  struct evhttp *httpd;
  httpd = evhttp_new(base);
  if (httpd == NULL) return -1;
  if (evhttp_bind_socket(httpd, url.c_str(), port) != 0) return -1;
  evhttp_set_gencb(httpd, func, NULL);
}

std::string HttpServer::recv()
{
  event_base_dispatch(base);
}
<|endoftext|>


<commit_before>#include "table.h"
#include "libtext/align.hpp"
#include "libtext/from_string.hpp"
#include <cassert>
#include <numeric>
#include <iostream>
#include <algorithm>

namespace ncv
{
        table_t::table_t(const string_t& title)
                :       m_title(title)
        {
        }

        table_header_t& table_t::header()
        {
                clear();
                return m_header;
        }

        void table_t::clear()
        {
                m_rows.clear();
        }

        table_row_t& table_t::append(const string_t& name)
        {
                m_rows.emplace_back(name);
                return *m_rows.rbegin();
        }

        bool table_t::sort(size_t col, const comparator_t& comp)
        {
                if (col < cols())
                {
                        std::stable_sort(m_rows.begin(), m_rows.end(), [&] (const auto& row1, const auto& row2)
                        {
                                assert(col < row1.size());
                                assert(row1.size() == cols());

                                assert(col < row2.size());
                                assert(row2.size() == cols());

                                return comp(row1.values()[col], row2.values()[col]);
                        });

                        return true;
                }

                else
                {
                        // invalid index
                        return false;
                }
        }

        bool table_t::sort_as_number(size_t col, sorting mode)
        {
                switch (mode)
                {
                case sorting::ascending:
                        return sort(col, [] (const string_t& value1, const string_t& value2)
                        {
                                return text::from_string<double>(value1) < text::from_string<double>(value2);
                        });

                case sorting::descending:
                        return sort(col, [] (const string_t& value1, const string_t& value2)
                        {
                                return text::from_string<double>(value1) > text::from_string<double>(value2);
                        });

                default:
                        return false;
                }
        }

        bool table_t::mark(const marker_t& op, const char* marker_string)
        {
                for (auto& row : m_rows)
                {
                        const auto col = op(row.values());
                        if (col < cols())
                        {
                                row[col] += marker_string;
                        }
                }

                return true;
        }

        namespace
        {
                const auto op_comp = [] (const string_t& value1, const string_t& value2)
                {
                        return text::from_string<double>(value1) < text::from_string<double>(value2);
                };

                const auto op_marker = [] (const strings_t& values)
                {
                        return std::min_element(values.begin(), values.end(), op_comp) - values.begin();
                };
        }

        bool table_t::mark_min_number(const char* marker_string)
        {
                return mark(op_marker, marker_string);
        }

        std::size_t table_t::border() const
        {
                return 4;
        }

        size_t table_t::name_colsize() const
        {
                size_t colsize = 0;
                for (const auto& row : m_rows)
                {
                        colsize = std::max(colsize, row.name().size());
                }
                colsize = std::max(colsize, m_title.size()) + border();

                return colsize;
        }

        std::vector<std::size_t> table_t::value_colsizes() const
        {
                std::vector<std::size_t> colsizes(cols(), 0);
                for (size_t c = 0; c < cols(); c ++)
                {
                        colsizes[c] = std::max(colsizes[c], m_header[c].size());
                }
                for (const auto& row : m_rows)
                {
                        for (size_t c = 0; c < std::min(cols(), row.size()); c ++)
                        {
                                colsizes[c] = std::max(colsizes[c], row[c].size());
                        }
                }
                for (size_t& colsize : colsizes)
                {
                        colsize += border();
                }

                return colsizes;
        }

        bool table_t::print(std::ostream& os,
                const char table_delim,
                const char row_delim, bool use_row_delim) const
        {
                const char col_delim = ' ';

                // size of name & value columns (in characters)
                const auto ncolsize = this->name_colsize();
                const auto vcolsizes = this->value_colsizes();

                const auto rowsize = ncolsize + std::accumulate(vcolsizes.begin(), vcolsizes.end(), size_t(0));

                // display header
                os << string_t(rowsize, table_delim) << std::endl;

                os << text::align(m_title, ncolsize);
                for (size_t c = 0; c < cols(); c ++)
                {
                        os << text::align(col_delim + m_header[c], vcolsizes[c]);
                }
                os << std::endl;

                os << string_t(rowsize, row_delim) << std::endl;

                // display rows
                for (size_t r = 0; r < m_rows.size(); r ++)
                {
                        const auto& row = m_rows[r];

                        if (r > 0 && r < m_rows.size() && use_row_delim)
                        {
                                os << string_t(rowsize, row_delim) << std::endl;
                        }

                        os << text::align(row.name(), ncolsize);
                        for (size_t c = 0; c < std::min(cols(), row.size()); c ++)
                        {
                                os << text::align(col_delim + row[c], vcolsizes[c]);
                        }
                        os << std::endl;
                }

                os << string_t(rowsize, table_delim) << std::endl;

                return true;
        }
}
<commit_msg>fix compilation (debug)<commit_after>#include "table.h"
#include "libtext/align.hpp"
#include "libtext/from_string.hpp"
#include <cassert>
#include <numeric>
#include <iostream>
#include <algorithm>

namespace ncv
{
        table_t::table_t(const string_t& title)
                :       m_title(title)
        {
        }

        table_header_t& table_t::header()
        {
                clear();
                return m_header;
        }

        void table_t::clear()
        {
                m_rows.clear();
        }

        table_row_t& table_t::append(const string_t& name)
        {
                m_rows.emplace_back(name);
                return *m_rows.rbegin();
        }

        bool table_t::sort(size_t col, const comparator_t& comp)
        {
                if (col < cols())
                {
                        std::stable_sort(m_rows.begin(), m_rows.end(), [&] (const auto& row1, const auto& row2)
                        {
                                assert(col < row1.size());
                                assert(row1.size() == this->cols());

                                assert(col < row2.size());
                                assert(row2.size() == this->cols());

                                return comp(row1.values()[col], row2.values()[col]);
                        });

                        return true;
                }

                else
                {
                        // invalid index
                        return false;
                }
        }

        bool table_t::sort_as_number(size_t col, sorting mode)
        {
                switch (mode)
                {
                case sorting::ascending:
                        return sort(col, [] (const string_t& value1, const string_t& value2)
                        {
                                return text::from_string<double>(value1) < text::from_string<double>(value2);
                        });

                case sorting::descending:
                        return sort(col, [] (const string_t& value1, const string_t& value2)
                        {
                                return text::from_string<double>(value1) > text::from_string<double>(value2);
                        });

                default:
                        return false;
                }
        }

        bool table_t::mark(const marker_t& op, const char* marker_string)
        {
                for (auto& row : m_rows)
                {
                        const auto col = op(row.values());
                        if (col < cols())
                        {
                                row[col] += marker_string;
                        }
                }

                return true;
        }

        namespace
        {
                const auto op_comp = [] (const string_t& value1, const string_t& value2)
                {
                        return text::from_string<double>(value1) < text::from_string<double>(value2);
                };

                const auto op_marker = [] (const strings_t& values)
                {
                        return std::min_element(values.begin(), values.end(), op_comp) - values.begin();
                };
        }

        bool table_t::mark_min_number(const char* marker_string)
        {
                return mark(op_marker, marker_string);
        }

        std::size_t table_t::border() const
        {
                return 4;
        }

        size_t table_t::name_colsize() const
        {
                size_t colsize = 0;
                for (const auto& row : m_rows)
                {
                        colsize = std::max(colsize, row.name().size());
                }
                colsize = std::max(colsize, m_title.size()) + border();

                return colsize;
        }

        std::vector<std::size_t> table_t::value_colsizes() const
        {
                std::vector<std::size_t> colsizes(cols(), 0);
                for (size_t c = 0; c < cols(); c ++)
                {
                        colsizes[c] = std::max(colsizes[c], m_header[c].size());
                }
                for (const auto& row : m_rows)
                {
                        for (size_t c = 0; c < std::min(cols(), row.size()); c ++)
                        {
                                colsizes[c] = std::max(colsizes[c], row[c].size());
                        }
                }
                for (size_t& colsize : colsizes)
                {
                        colsize += border();
                }

                return colsizes;
        }

        bool table_t::print(std::ostream& os,
                const char table_delim,
                const char row_delim, bool use_row_delim) const
        {
                const char col_delim = ' ';

                // size of name & value columns (in characters)
                const auto ncolsize = this->name_colsize();
                const auto vcolsizes = this->value_colsizes();

                const auto rowsize = ncolsize + std::accumulate(vcolsizes.begin(), vcolsizes.end(), size_t(0));

                // display header
                os << string_t(rowsize, table_delim) << std::endl;

                os << text::align(m_title, ncolsize);
                for (size_t c = 0; c < cols(); c ++)
                {
                        os << text::align(col_delim + m_header[c], vcolsizes[c]);
                }
                os << std::endl;

                os << string_t(rowsize, row_delim) << std::endl;

                // display rows
                for (size_t r = 0; r < m_rows.size(); r ++)
                {
                        const auto& row = m_rows[r];

                        if (r > 0 && r < m_rows.size() && use_row_delim)
                        {
                                os << string_t(rowsize, row_delim) << std::endl;
                        }

                        os << text::align(row.name(), ncolsize);
                        for (size_t c = 0; c < std::min(cols(), row.size()); c ++)
                        {
                                os << text::align(col_delim + row[c], vcolsizes[c]);
                        }
                        os << std::endl;
                }

                os << string_t(rowsize, table_delim) << std::endl;

                return true;
        }
}
<|endoftext|>


<commit_before>//$Id$

//#include <QtGui/QFileDialog>
//#include <QtCore/QTextStream>
//#include <QDebug>
//
//#include <QtGui/QMainWindow>
//#include <QtGui/QWidget>
//#include <QtGui/QGridLayout>
//#include <QtGui/QTabWidget>
//#include <QtGui/QTreeWidget>
//#include <QtGui/QTreeWidgetItem>
//#include <QtGui/QMenuBar>
//#include <QtGui/QMenu>
//#include <QtGui/QStatusBar>
//#include <QtGui/QAction>
//#include <QtCore/QMetaObject>
//#include <QtCore/QString>
//#include <QtCore/QDir>
//#include <QtCore/QStringList>
//#include <QtCore/QIODevice>
//#include <QListWidgetItem>
//#include <QStringList>
//#include <QDockWidget>

#include <iostream>
#include <QtGui>

#include "mainwindow.h"
#include "treewidget.h"
#include "treewidgetitem.h"
#include "listwidget.h"
#include "listwidgetitem.h"
#include "ProjectTabWidget.h"
#include "LibraryWidget.h"
#include "SimulationSetupWidget.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    //Set the name and size of the main window
    this->setObjectName("MainWindow");
    this->resize(1024,768);
    this->setWindowTitle("HOPSAN NG");

    //Create a centralwidget for the main window
    mpCentralwidget = new QWidget(this);
    mpCentralwidget->setObjectName("centralwidget");

    //Create a grid on the centralwidget
    mpCentralgrid = new QGridLayout(mpCentralwidget);
    mpCentralgrid->setSpacing(10);

    //Create a dock for the MessageWidget
    QDockWidget *messagedock = new QDockWidget(tr("Messages"), this);
    messagedock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
    mpMessageWidget = new MessageWidget(this);
    mpMessageWidget->setReadOnly(true);
    messagedock->setWidget(mpMessageWidget);
    addDockWidget(Qt::BottomDockWidgetArea, messagedock);

    //Create a SimulationSetupWidget
    mpSimulationSetupWidget = new SimulationSetupWidget(tr("Simulation setup"), this);

    //Create the main tab container, need at least one tab
    mpProjectTabs = new ProjectTabWidget(this);
    mpProjectTabs->setObjectName("projectTabs");

    //Create a dock for the componentslibrary
    QDockWidget *libdock = new QDockWidget(tr("Components"), this);
    libdock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
    mpLibrary = new LibraryWidget(this);
    libdock->setWidget(mpLibrary);
    addDockWidget(Qt::LeftDockWidgetArea, libdock);

    mpCentralgrid->addWidget(mpSimulationSetupWidget,0,0);
    mpCentralgrid->addWidget(mpProjectTabs,1,0);

    mpCentralwidget->setLayout(mpCentralgrid);

    //Set the centralwidget
    this->setCentralWidget(mpCentralwidget);

    mpProjectTabs->addNewProjectTab();

    //Create the menubar
    menubar = new QMenuBar();
    menubar->setGeometry(QRect(0,0,800,25));
    menubar->setObjectName("menubar");

    //Create the menues
    menuFile = new QMenu(menubar);
    menuFile->setObjectName("menuFile");
    menuFile->setTitle("&File");

    menuNew = new QMenu(menubar);
    menuNew->setObjectName("menuNew");
    menuNew->setTitle("New");

    menuLibs = new QMenu(menubar);
    menuLibs->setObjectName("menuLibs");
    menuLibs->setTitle("&Libraries");

    menuSimulation = new QMenu(menubar);
    menuSimulation->setObjectName("menuSimulation");
    menuSimulation->setTitle("&Simulation");

    menuView = new QMenu(menubar);
    menuView->setTitle("&View");

    menuPlot = new QMenu(menubar);
    menuPlot->setTitle("&Plot");

    this->setMenuBar(menubar);

    //Create the Statusbar
    statusBar = new QStatusBar();
    statusBar->setObjectName("statusBar");
    this->setStatusBar(statusBar);

    //Create the actionsbuttons
    actionOpen = new QAction(this);
    actionOpen->setText("Open");
    actionOpen->setShortcut(QKeySequence("Ctrl+o"));

    actionClose = new QAction(this);
    actionClose->setText("Close");
    actionClose->setShortcut(QKeySequence("Ctrl+c"));

    actionSave = new QAction(this);
    actionSave->setText("Save");
    actionSave->setShortcut(QKeySequence("Ctrl+s"));

    actionSaveAs = new QAction(this);
    actionSaveAs->setText("Save As");

    actionProject = new QAction(this);
    actionProject->setText("Project");

    actionLoadLibs = new QAction(this);
    actionLoadLibs->setText("Load Libraries");

    actionSimulate = new QAction(this);
    actionSimulate->setText("Simulate");
    actionSimulate->setShortcut(Qt::Key_F9);

    actionPlot = new QAction(this);
    actionPlot->setText("Plot");

    this->createActions();
    this->createToolbars();

    //Add the actionbuttons to the menues
    menuNew->addAction(actionProject);

    menuFile->addAction(menuNew->menuAction());
    menuFile->addAction(actionOpen);
    menuFile->addAction(actionSave);
    menuFile->addAction(actionSaveAs);
    menuFile->addSeparator();
    menuFile->addAction(actionClose);

    menuLibs->addAction(actionLoadLibs);
    //menuLibs->addAction(actionOpen);

    menuSimulation->addAction(actionSimulate);

    menuView->addAction(libdock->toggleViewAction());
    menuView->addAction(messagedock->toggleViewAction());
    menuView->addAction(fileToolBar->toggleViewAction());
    menuView->addAction(clipboardToolBar->toggleViewAction());
    menuView->addAction(simToolBar->toggleViewAction());

    menuPlot->addAction(actionPlot);

    menubar->addAction(menuFile->menuAction());
    menubar->addAction(menuLibs->menuAction());
    menubar->addAction(menuSimulation->menuAction());
    menubar->addAction(menuView->menuAction());
    menubar->addAction(menuPlot->menuAction());

    //Load default libraries
    mpLibrary->addEmptyLibrary("User defined libraries");

    mpLibrary->addEmptyLibrary("Hydraulic");
    mpLibrary->addLibrary("../../HopsanGUI/componentData/hydraulic/sources","Hydraulic");
    mpLibrary->addLibrary("../../HopsanGUI/componentData/hydraulic/restrictors","Hydraulic");
    mpLibrary->addLibrary("../../HopsanGUI/componentData/hydraulic/volumes","Hydraulic");
    mpLibrary->addLibrary("../../HopsanGUI/componentData/hydraulic/actuators","Hydraulic");
    mpLibrary->addLibrary("../../HopsanGUI/componentData/hydraulic/valves","Hydraulic");
    mpLibrary->addLibrary("../../HopsanGUI/componentData/hydraulic/pumps","Hydraulic");

    mpLibrary->addLibrary("../../HopsanGUI/componentData/signal");

    mpLibrary->addLibrary("../../HopsanGUI/componentData/mechanic");

    QMetaObject::connectSlotsByName(this);

    //Establish connections
    this->connect(this->actionSave,SIGNAL(triggered()),mpProjectTabs,SLOT(saveProjectTab()));
    this->connect(this->actionSaveAs,SIGNAL(triggered()),mpProjectTabs,SLOT(saveProjectTabAs()));
    this->connect(this->actionClose,SIGNAL(triggered()),SLOT(close()));
    this->connect(this->actionProject,SIGNAL(triggered()),mpProjectTabs,SLOT(addNewProjectTab()));
    this->connect(this->actionLoadLibs,SIGNAL(triggered()),mpLibrary,SLOT(addLibrary()));
    this->connect(this->actionOpen,SIGNAL(triggered()),mpProjectTabs,SLOT(loadModel()));

    this->connect(this->actionPlot,SIGNAL(triggered()),SLOT(plot()));

    this->connect(this->actionSimulate,SIGNAL(triggered()),mpProjectTabs,SLOT(simulateCurrent()));
    connect(mpSimulationSetupWidget->mpSimulateButton, SIGNAL(released()), mpProjectTabs, SLOT(simulateCurrent()));
}

MainWindow::~MainWindow()
{
    delete mpProjectTabs;
    delete menubar;
    delete statusBar;
}

void MainWindow::plot()
{
    QDockWidget *varPlotDock = new QDockWidget(tr("Plot Variables"), this);
    varPlotDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
    VariableListDialog *variableList = new VariableListDialog(varPlotDock);
    varPlotDock->setWidget(variableList);
    //variableList->show();
    addDockWidget(Qt::RightDockWidgetArea, varPlotDock);

}

//! Event triggered re-implemented method that closes the main window.
//! First all tabs (models) are closed, if the user do not push Cancel
//! (closeAllProjectTabs then returns 'false') the event is accepted and
//! the main window is closed.
//! @param event contains information of the closing operation.
void MainWindow::closeEvent(QCloseEvent *event)
{
    if (mpProjectTabs->closeAllProjectTabs())
    {
        event->accept();
    }
    else
    {
        event->ignore();
    }
}

void MainWindow::createActions()
{

    newAction = new QAction(QIcon("../../HopsanGUI/icons/onebit_39.png"), tr("&New"), this);
    newAction->setShortcut(tr("New"));
    newAction->setStatusTip(tr("Create New Project"));
    connect(newAction, SIGNAL(triggered()), mpProjectTabs,SLOT(addNewProjectTab()));

    openAction = new QAction(QIcon("../../HopsanGUI/icons/onebit_13.png"), tr("&Open"), this);
    openAction->setShortcut(tr("Open"));
    openAction->setStatusTip(tr("Load Model File"));
    connect(openAction, SIGNAL(triggered()), mpProjectTabs,SLOT(loadModel()));

    saveAction = new QAction(QIcon("../../HopsanGUI/icons/onebit_11.png"), tr("&Save"), this);
    saveAction->setShortcut(tr("Save"));
    saveAction->setStatusTip(tr("Save Model File"));
    connect(saveAction, SIGNAL(triggered()), mpProjectTabs,SLOT(saveProjectTab()));

    saveAsAction = new QAction(QIcon("../../HopsanGUI/icons/onebit_12.png"), tr("&Save As"), this);
    saveAsAction->setShortcut(tr("Save As"));
    saveAsAction->setStatusTip(tr("Save Model File As"));
    connect(saveAsAction, SIGNAL(triggered()), mpProjectTabs,SLOT(saveProjectTabAs()));

    cutAction = new QAction(QIcon("../../HopsanGUI/icons/cut.png"), tr("&Cut"), this);
    cutAction->setShortcut(tr("Cut"));
    cutAction->setStatusTip(tr("Cut Selection"));
    connect(cutAction, SIGNAL(triggered()), this->mpProjectTabs->getCurrentTab()->mpGraphicsView,SLOT(cutSelected()));

    copyAction = new QAction(QIcon("../../HopsanGUI/icons/copy.png"), tr("&Copy"), this);
    copyAction->setShortcut(tr("Copy"));
    copyAction->setStatusTip(tr("Copy Selection"));
    connect(copyAction, SIGNAL(triggered()), this->mpProjectTabs->getCurrentTab()->mpGraphicsView,SLOT(copySelected()));

    pasteAction = new QAction(QIcon("../../HopsanGUI/icons/paste.png"), tr("&Paste"), this);
    pasteAction->setShortcut(tr("Paste"));
    pasteAction->setStatusTip(tr("Paste Selection"));
    connect(pasteAction, SIGNAL(triggered()), this->mpProjectTabs->getCurrentTab()->mpGraphicsView,SLOT(paste()));

    simulateAction = new QAction(QIcon("../../HopsanGUI/icons/onebit_27.png"), tr("&Simulate"), this);
    simulateAction->setShortcut(tr("Simulate"));
    simulateAction->setStatusTip(tr("Simulate Current Project"));
    connect(simulateAction, SIGNAL(triggered()), mpProjectTabs,SLOT(simulateCurrent()));

    plotAction = new QAction(QIcon("../../HopsanGUI/icons/onebit_20.png"), tr("&Plot"), this);
    plotAction->setShortcut(tr("Plot"));
    plotAction->setStatusTip(tr("Plot Something"));
    connect(plotAction, SIGNAL(triggered()), this,SLOT(plot()));
}

void MainWindow::createToolbars()
{
    fileToolBar = addToolBar(tr("File Toolbar"));
    fileToolBar->setAllowedAreas(Qt::TopToolBarArea);
    fileToolBar->addAction(newAction);
    fileToolBar->addAction(openAction);
    fileToolBar->addAction(saveAction);
    fileToolBar->addAction(saveAsAction);

    clipboardToolBar = addToolBar(tr("Clipboard Toolbar"));
    clipboardToolBar->setAllowedAreas(Qt::TopToolBarArea);
    clipboardToolBar->addAction(cutAction);
    clipboardToolBar->addAction(copyAction);
    clipboardToolBar->addAction(pasteAction);

    simToolBar = addToolBar(tr("Simulation Toolbar"));
    simToolBar->addAction(simulateAction);
    simToolBar->addAction(plotAction);

}
<commit_msg>Made the toolbars dockable only in top docking area<commit_after>//$Id$

//#include <QtGui/QFileDialog>
//#include <QtCore/QTextStream>
//#include <QDebug>
//
//#include <QtGui/QMainWindow>
//#include <QtGui/QWidget>
//#include <QtGui/QGridLayout>
//#include <QtGui/QTabWidget>
//#include <QtGui/QTreeWidget>
//#include <QtGui/QTreeWidgetItem>
//#include <QtGui/QMenuBar>
//#include <QtGui/QMenu>
//#include <QtGui/QStatusBar>
//#include <QtGui/QAction>
//#include <QtCore/QMetaObject>
//#include <QtCore/QString>
//#include <QtCore/QDir>
//#include <QtCore/QStringList>
//#include <QtCore/QIODevice>
//#include <QListWidgetItem>
//#include <QStringList>
//#include <QDockWidget>

#include <iostream>
#include <QtGui>

#include "mainwindow.h"
#include "treewidget.h"
#include "treewidgetitem.h"
#include "listwidget.h"
#include "listwidgetitem.h"
#include "ProjectTabWidget.h"
#include "LibraryWidget.h"
#include "SimulationSetupWidget.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    //Set the name and size of the main window
    this->setObjectName("MainWindow");
    this->resize(1024,768);
    this->setWindowTitle("HOPSAN NG");

    //Create a centralwidget for the main window
    mpCentralwidget = new QWidget(this);
    mpCentralwidget->setObjectName("centralwidget");

    //Create a grid on the centralwidget
    mpCentralgrid = new QGridLayout(mpCentralwidget);
    mpCentralgrid->setSpacing(10);

    //Create a dock for the MessageWidget
    QDockWidget *messagedock = new QDockWidget(tr("Messages"), this);
    messagedock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
    mpMessageWidget = new MessageWidget(this);
    mpMessageWidget->setReadOnly(true);
    messagedock->setWidget(mpMessageWidget);
    addDockWidget(Qt::BottomDockWidgetArea, messagedock);

    //Create a SimulationSetupWidget
    mpSimulationSetupWidget = new SimulationSetupWidget(tr("Simulation setup"), this);

    //Create the main tab container, need at least one tab
    mpProjectTabs = new ProjectTabWidget(this);
    mpProjectTabs->setObjectName("projectTabs");

    //Create a dock for the componentslibrary
    QDockWidget *libdock = new QDockWidget(tr("Components"), this);
    libdock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
    mpLibrary = new LibraryWidget(this);
    libdock->setWidget(mpLibrary);
    addDockWidget(Qt::LeftDockWidgetArea, libdock);

    mpCentralgrid->addWidget(mpSimulationSetupWidget,0,0);
    mpCentralgrid->addWidget(mpProjectTabs,1,0);

    mpCentralwidget->setLayout(mpCentralgrid);

    //Set the centralwidget
    this->setCentralWidget(mpCentralwidget);

    mpProjectTabs->addNewProjectTab();

    //Create the menubar
    menubar = new QMenuBar();
    menubar->setGeometry(QRect(0,0,800,25));
    menubar->setObjectName("menubar");

    //Create the menues
    menuFile = new QMenu(menubar);
    menuFile->setObjectName("menuFile");
    menuFile->setTitle("&File");

    menuNew = new QMenu(menubar);
    menuNew->setObjectName("menuNew");
    menuNew->setTitle("New");

    menuLibs = new QMenu(menubar);
    menuLibs->setObjectName("menuLibs");
    menuLibs->setTitle("&Libraries");

    menuSimulation = new QMenu(menubar);
    menuSimulation->setObjectName("menuSimulation");
    menuSimulation->setTitle("&Simulation");

    menuView = new QMenu(menubar);
    menuView->setTitle("&View");

    menuPlot = new QMenu(menubar);
    menuPlot->setTitle("&Plot");

    this->setMenuBar(menubar);

    //Create the Statusbar
    statusBar = new QStatusBar();
    statusBar->setObjectName("statusBar");
    this->setStatusBar(statusBar);

    //Create the actionsbuttons
    actionOpen = new QAction(this);
    actionOpen->setText("Open");
    actionOpen->setShortcut(QKeySequence("Ctrl+o"));

    actionClose = new QAction(this);
    actionClose->setText("Close");
    actionClose->setShortcut(QKeySequence("Ctrl+c"));

    actionSave = new QAction(this);
    actionSave->setText("Save");
    actionSave->setShortcut(QKeySequence("Ctrl+s"));

    actionSaveAs = new QAction(this);
    actionSaveAs->setText("Save As");

    actionProject = new QAction(this);
    actionProject->setText("Project");

    actionLoadLibs = new QAction(this);
    actionLoadLibs->setText("Load Libraries");

    actionSimulate = new QAction(this);
    actionSimulate->setText("Simulate");
    actionSimulate->setShortcut(Qt::Key_F9);

    actionPlot = new QAction(this);
    actionPlot->setText("Plot");

    this->createActions();
    this->createToolbars();

    //Add the actionbuttons to the menues
    menuNew->addAction(actionProject);

    menuFile->addAction(menuNew->menuAction());
    menuFile->addAction(actionOpen);
    menuFile->addAction(actionSave);
    menuFile->addAction(actionSaveAs);
    menuFile->addSeparator();
    menuFile->addAction(actionClose);

    menuLibs->addAction(actionLoadLibs);
    //menuLibs->addAction(actionOpen);

    menuSimulation->addAction(actionSimulate);

    menuView->addAction(libdock->toggleViewAction());
    menuView->addAction(messagedock->toggleViewAction());
    menuView->addAction(fileToolBar->toggleViewAction());
    menuView->addAction(clipboardToolBar->toggleViewAction());
    menuView->addAction(simToolBar->toggleViewAction());

    menuPlot->addAction(actionPlot);

    menubar->addAction(menuFile->menuAction());
    menubar->addAction(menuLibs->menuAction());
    menubar->addAction(menuSimulation->menuAction());
    menubar->addAction(menuView->menuAction());
    menubar->addAction(menuPlot->menuAction());

    //Load default libraries
    mpLibrary->addEmptyLibrary("User defined libraries");

    mpLibrary->addEmptyLibrary("Hydraulic");
    mpLibrary->addLibrary("../../HopsanGUI/componentData/hydraulic/sources","Hydraulic");
    mpLibrary->addLibrary("../../HopsanGUI/componentData/hydraulic/restrictors","Hydraulic");
    mpLibrary->addLibrary("../../HopsanGUI/componentData/hydraulic/volumes","Hydraulic");
    mpLibrary->addLibrary("../../HopsanGUI/componentData/hydraulic/actuators","Hydraulic");
    mpLibrary->addLibrary("../../HopsanGUI/componentData/hydraulic/valves","Hydraulic");
    mpLibrary->addLibrary("../../HopsanGUI/componentData/hydraulic/pumps","Hydraulic");

    mpLibrary->addLibrary("../../HopsanGUI/componentData/signal");

    mpLibrary->addLibrary("../../HopsanGUI/componentData/mechanic");

    QMetaObject::connectSlotsByName(this);

    //Establish connections
    this->connect(this->actionSave,SIGNAL(triggered()),mpProjectTabs,SLOT(saveProjectTab()));
    this->connect(this->actionSaveAs,SIGNAL(triggered()),mpProjectTabs,SLOT(saveProjectTabAs()));
    this->connect(this->actionClose,SIGNAL(triggered()),SLOT(close()));
    this->connect(this->actionProject,SIGNAL(triggered()),mpProjectTabs,SLOT(addNewProjectTab()));
    this->connect(this->actionLoadLibs,SIGNAL(triggered()),mpLibrary,SLOT(addLibrary()));
    this->connect(this->actionOpen,SIGNAL(triggered()),mpProjectTabs,SLOT(loadModel()));

    this->connect(this->actionPlot,SIGNAL(triggered()),SLOT(plot()));

    this->connect(this->actionSimulate,SIGNAL(triggered()),mpProjectTabs,SLOT(simulateCurrent()));
    connect(mpSimulationSetupWidget->mpSimulateButton, SIGNAL(released()), mpProjectTabs, SLOT(simulateCurrent()));
}

MainWindow::~MainWindow()
{
    delete mpProjectTabs;
    delete menubar;
    delete statusBar;
}

void MainWindow::plot()
{
    QDockWidget *varPlotDock = new QDockWidget(tr("Plot Variables"), this);
    varPlotDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
    VariableListDialog *variableList = new VariableListDialog(varPlotDock);
    varPlotDock->setWidget(variableList);
    //variableList->show();
    addDockWidget(Qt::RightDockWidgetArea, varPlotDock);

}

//! Event triggered re-implemented method that closes the main window.
//! First all tabs (models) are closed, if the user do not push Cancel
//! (closeAllProjectTabs then returns 'false') the event is accepted and
//! the main window is closed.
//! @param event contains information of the closing operation.
void MainWindow::closeEvent(QCloseEvent *event)
{
    if (mpProjectTabs->closeAllProjectTabs())
    {
        event->accept();
    }
    else
    {
        event->ignore();
    }
}

void MainWindow::createActions()
{

    newAction = new QAction(QIcon("../../HopsanGUI/icons/onebit_39.png"), tr("&New"), this);
    newAction->setShortcut(tr("New"));
    newAction->setStatusTip(tr("Create New Project"));
    connect(newAction, SIGNAL(triggered()), mpProjectTabs,SLOT(addNewProjectTab()));

    openAction = new QAction(QIcon("../../HopsanGUI/icons/onebit_13.png"), tr("&Open"), this);
    openAction->setShortcut(tr("Open"));
    openAction->setStatusTip(tr("Load Model File"));
    connect(openAction, SIGNAL(triggered()), mpProjectTabs,SLOT(loadModel()));

    saveAction = new QAction(QIcon("../../HopsanGUI/icons/onebit_11.png"), tr("&Save"), this);
    saveAction->setShortcut(tr("Save"));
    saveAction->setStatusTip(tr("Save Model File"));
    connect(saveAction, SIGNAL(triggered()), mpProjectTabs,SLOT(saveProjectTab()));

    saveAsAction = new QAction(QIcon("../../HopsanGUI/icons/onebit_12.png"), tr("&Save As"), this);
    saveAsAction->setShortcut(tr("Save As"));
    saveAsAction->setStatusTip(tr("Save Model File As"));
    connect(saveAsAction, SIGNAL(triggered()), mpProjectTabs,SLOT(saveProjectTabAs()));

    cutAction = new QAction(QIcon("../../HopsanGUI/icons/cut.png"), tr("&Cut"), this);
    cutAction->setShortcut(tr("Cut"));
    cutAction->setStatusTip(tr("Cut Selection"));
    connect(cutAction, SIGNAL(triggered()), this->mpProjectTabs->getCurrentTab()->mpGraphicsView,SLOT(cutSelected()));

    copyAction = new QAction(QIcon("../../HopsanGUI/icons/copy.png"), tr("&Copy"), this);
    copyAction->setShortcut(tr("Copy"));
    copyAction->setStatusTip(tr("Copy Selection"));
    connect(copyAction, SIGNAL(triggered()), this->mpProjectTabs->getCurrentTab()->mpGraphicsView,SLOT(copySelected()));

    pasteAction = new QAction(QIcon("../../HopsanGUI/icons/paste.png"), tr("&Paste"), this);
    pasteAction->setShortcut(tr("Paste"));
    pasteAction->setStatusTip(tr("Paste Selection"));
    connect(pasteAction, SIGNAL(triggered()), this->mpProjectTabs->getCurrentTab()->mpGraphicsView,SLOT(paste()));

    simulateAction = new QAction(QIcon("../../HopsanGUI/icons/onebit_27.png"), tr("&Simulate"), this);
    simulateAction->setShortcut(tr("Simulate"));
    simulateAction->setStatusTip(tr("Simulate Current Project"));
    connect(simulateAction, SIGNAL(triggered()), mpProjectTabs,SLOT(simulateCurrent()));

    plotAction = new QAction(QIcon("../../HopsanGUI/icons/onebit_20.png"), tr("&Plot"), this);
    plotAction->setShortcut(tr("Plot"));
    plotAction->setStatusTip(tr("Plot Something"));
    connect(plotAction, SIGNAL(triggered()), this,SLOT(plot()));
}

void MainWindow::createToolbars()
{
    fileToolBar = addToolBar(tr("File Toolbar"));
    fileToolBar->setAllowedAreas(Qt::TopToolBarArea);
    fileToolBar->addAction(newAction);
    fileToolBar->addAction(openAction);
    fileToolBar->addAction(saveAction);
    fileToolBar->addAction(saveAsAction);

    clipboardToolBar = addToolBar(tr("Clipboard Toolbar"));
    clipboardToolBar->setAllowedAreas(Qt::TopToolBarArea);
    clipboardToolBar->addAction(cutAction);
    clipboardToolBar->addAction(copyAction);
    clipboardToolBar->addAction(pasteAction);

    simToolBar = addToolBar(tr("Simulation Toolbar"));
    simToolBar->setAllowedAreas(Qt::TopToolBarArea);
    simToolBar->addAction(simulateAction);
    simToolBar->addAction(plotAction);

}
<|endoftext|>