/* c_base.cc 1.11 95/12/23 03:11:27 */


// xspacewarp by Greg Walker (gow@math.orst.edu)

// This is free software. Non-profit redistribution and/or modification
// is allowed and welcome.


// define members of class Base

#include "c_base.hh"
#include <iostream.h>
#include <stdio.h>		// sprintf()
#include <stdlib.h>		// rand()
#include "c_body.hh"
#include "globals.hh"		// access endever for its location
#include "c_sector.hh"		// access rm_base() member
#include "messages.hh"

extern void echo(const char *, int);
extern void clear_echo(void);
extern void draw_losemesg(void);


Base::Base(): Ship()
{
  energy.thrusters = 0;
  energy.warpdrive = 0;
  energy.fasers = 0;
  energy.shields = maxerg;
}


// How a base dies.

void Base::die(Identity cause)
{
  char mesg[45];

  universe[urow-1][ucol-1].rm_base();
  draw(pixmap, defrv_GC);

  if ((urow == endever.geturow()) && (ucol == endever.getucol()) &&
      (gamestate.visual == SECTOR))  // if base is visible...
  {
    explode(EXPLODERAD);
  }

  if (--pop == 0)  // game lost, all bases destroyed.
  {
    clear_echo();
    echo(last_base_str, XtNumber(last_base_str) - 1);
    if (gamestate.visual != SECTOR)
       draw_losemesg();
    gamestate.input = REPLAY;
    gamestate.visual = LOSE;
  }
}


void Base::draw(Drawable drawable, GC gc) const
{
  Body *bdy = (Body *)this;

  bdy->draw(drawable, gc, icon, icon_len);
}


// re-energize base at a rate that varies linearly from BASEMINERGRATE
// (when base is least energized) to BASEMAXERGRATE (when base fully
// energized). This rate is then perturbed by an amount varying from
// -BASEERGVAR to +BASEERGVAR. This is called by energize_to().

void Base::energize()
{
  int newerg, perturb;

  newerg = ((BASEMAXERGRATE-BASEMINERGRATE) * energy.shields)/maxerg
             + BASEMINERGRATE;
  // rand perturbation of newerg
  perturb = (rand() % (2*BASEERGVAR)) - BASEERGVAR;
  newerg = max(newerg+perturb, 0);
  energy.shields = min(maxerg, energy.shields+newerg);
}


/********************* static members ********************/

const int Base::icon_len = 3;
char Base::icon[icon_len+1];
const int Base::maxerg = BASEMAXERG;
int Base::pop = 0;


// define static functions

void Base::seticon(const char *str)
{
  if (strlen(str) != icon_len)
  {
    cerr << "xspacewarp: bad base icon in X resources." << endl;
    exit(1);
  }
  (void) strcpy(icon, str);
}

void Base::setpop(int p)
{
  if (p >= 0)			// does nothing if neg arg
    pop = p;
}

int Base::getpop()
{
  return (pop);
}


int Base::geticon_len()
{
  return (icon_len);
}


// end
