
#include "workqueue.h"

#include "assert.h"

#include "prim.h"
#include "globals.h"
#include "kdtree.h"
#include "render_worker.h"
#include "raycastablelist.h"
#include "reconmap.h"
#include "render_thread.h"

#define ALLOC_SLOP 10

WorkQueue::WorkQueue(int own_rw) : _own_rw (own_rw) {
  _current_rec = 0;
  _size = 0;
  _alloc_size = 1;
  _recs = new PWorkRec [1];
}


WorkQueue::~WorkQueue() {
  Clear();
  delete[] _recs;
}

void WorkQueue::Clear (void)
{
  if (_own_rw)
    {
      for (int i = 0; i < _size; i++)
	delete _recs[i];
    }
  _size = 0;
  _current_rec = 0;
}

WorkQueue& WorkQueue::CopyFrom(const WorkQueue &) {

  cerr << "Error: WorkQueue::CopyFrom() called" << endl;
  exit(-1);

  return *this;
}

/*
ostream& operator<<(ostream &co, const WorkQueue &W) {

	return co;
}

istream& operator>>(istream &ci, WorkQueue &W) {

	return ci;
}
*/


void WorkQueue::AddWorkRec(WorkRec *WR) {

  if (_size > _alloc_size) //increase size of array if necessary
    {
      //if we're frustum casting, we should have already 
      //set the size to be big enough
      if (!(truly_GS->_disabled_flags & DISABLE_FC))
	assert (0);
      SetSize (_alloc_size + ALLOC_SLOP);
    }

  _recs[_size] = WR;
  _size++;
}

void WorkQueue::SetSize (int size)
{
  //When FCing, we should never change the size of a buffer that has
  //something in it. Expensive copy!!
  if ((_size > 0) && (!(truly_GS->_disabled_flags & DISABLE_FC)))
    assert (0);

  if (size < _size) _size = size; //only copy as much as will fit 

  _alloc_size = size;
  //make a new buffer and copy everything into it
  PWorkRec *_new_recs = new PWorkRec [_alloc_size];
  for (int i = 0; i < _size; i++)
    _new_recs[i] = _recs[i];
  delete[] _recs;
  _recs = _new_recs;
}


