<commit_before>#include <algorithm>
#include <map>
#include <memory>

#include "common.h"

// Size of the buffer to store result of ReadDirectoryChangesW.
static const unsigned int kDirectoryWatcherBufferSize = 4096;

// Object template to create representation of WatcherHandle.
static Persistent<ObjectTemplate> g_object_template;

// Mutex for the HandleWrapper map.
static uv_mutex_t g_handle_wrap_map_mutex;

// The events to be waited on.
static std::vector<HANDLE> g_events;

// The dummy event to wakeup the thread.
static HANDLE g_wake_up_event;

struct ScopedLocker {
  ScopedLocker(uv_mutex_t& mutex) : mutex_(&mutex) { uv_mutex_lock(mutex_); }
  ~ScopedLocker() { Unlock(); }

  void Unlock() { uv_mutex_unlock(mutex_); }

  uv_mutex_t* mutex_;
};

struct HandleWrapper {
  HandleWrapper(WatcherHandle handle, const char* path_str)
      : dir_handle(handle),
        path(strlen(path_str)),
        canceled(false) {
    memset(&overlapped, 0, sizeof(overlapped));
    overlapped.hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
    g_events.push_back(overlapped.hEvent);

    std::copy(path_str, path_str + path.size(), path.data());
    map_[overlapped.hEvent] = this;
  }

  ~HandleWrapper() {
    CloseHandle(dir_handle);

    map_.erase(overlapped.hEvent);
    CloseHandle(overlapped.hEvent);
    g_events.erase(
        std::remove(g_events.begin(), g_events.end(), overlapped.hEvent),
        g_events.end());
  }

  WatcherHandle dir_handle;
  std::vector<char> path;
  bool canceled;
  OVERLAPPED overlapped;
  char buffer[kDirectoryWatcherBufferSize];

  static HandleWrapper* Get(HANDLE key) { return map_[key]; }

  static std::map<WatcherHandle, HandleWrapper*> map_;
};

std::map<WatcherHandle, HandleWrapper*> HandleWrapper::map_;

struct WatcherEvent {
  EVENT_TYPE type;
  WatcherHandle handle;
  std::vector<char> new_path;
  std::vector<char> old_path;
};

static bool QueueReaddirchanges(HandleWrapper* handle) {
  return ReadDirectoryChangesW(handle->dir_handle,
                               handle->buffer,
                               kDirectoryWatcherBufferSize,
                               FALSE,
                               FILE_NOTIFY_CHANGE_FILE_NAME      |
                                 FILE_NOTIFY_CHANGE_DIR_NAME     |
                                 FILE_NOTIFY_CHANGE_ATTRIBUTES   |
                                 FILE_NOTIFY_CHANGE_SIZE         |
                                 FILE_NOTIFY_CHANGE_LAST_WRITE   |
                                 FILE_NOTIFY_CHANGE_LAST_ACCESS  |
                                 FILE_NOTIFY_CHANGE_CREATION     |
                                 FILE_NOTIFY_CHANGE_SECURITY,
                               NULL,
                               &handle->overlapped,
                               NULL) == TRUE;
}

Handle<Value> WatcherHandleToV8Value(WatcherHandle handle) {
  Handle<Value> value = g_object_template->NewInstance();
  value->ToObject()->SetPointerInInternalField(0, handle);
  return value;
}

WatcherHandle V8ValueToWatcherHandle(Handle<Value> value) {
  return reinterpret_cast<WatcherHandle>(value->ToObject()->
      GetPointerFromInternalField(0));
}

bool IsV8ValueWatcherHandle(Handle<Value> value) {
  return value->IsObject() && value->ToObject()->InternalFieldCount() == 1;
}

void PlatformInit() {
  uv_mutex_init(&g_handle_wrap_map_mutex);

  g_wake_up_event = CreateEvent(NULL, FALSE, FALSE, NULL);
  g_events.push_back(g_wake_up_event);

  g_object_template = Persistent<ObjectTemplate>::New(ObjectTemplate::New());
  g_object_template->SetInternalFieldCount(1);

  WakeupNewThread();
}

void PlatformThread() {
  while (true) {
    // Do not use g_events directly, since reallocation could happen when there
    // are new watchers adding to g_events when WaitForMultipleObjects is still
    // polling.
    ScopedLocker locker(g_handle_wrap_map_mutex);
    std::vector<HANDLE> copied_events(g_events);
    locker.Unlock();

    DWORD r = WaitForMultipleObjects(copied_events.size(),
                                     copied_events.data(),
                                     FALSE,
                                     INFINITE);
    int i = r - WAIT_OBJECT_0;
    if (i >= 0 && i < copied_events.size()) {
      // It's a wake up event, there is no fs events.
      if (copied_events[i] == g_wake_up_event)
        continue;

      ScopedLocker locker(g_handle_wrap_map_mutex);

      HandleWrapper* handle = HandleWrapper::Get(copied_events[i]);
      if (!handle)
        continue;

      if (handle->canceled) {
        delete handle;
        continue;
      }

      DWORD bytes;
      if (GetOverlappedResult(handle->dir_handle,
                              &handle->overlapped,
                              &bytes,
                              FALSE) == FALSE)
        continue;

      std::vector<char> old_path;
      std::vector<WatcherEvent> events;

      DWORD offset = 0;
      while (true) {
        FILE_NOTIFY_INFORMATION* file_info =
            reinterpret_cast<FILE_NOTIFY_INFORMATION*>(handle->buffer + offset);

        // Emit events for children.
        EVENT_TYPE event = EVENT_NONE;
        switch (file_info->Action) {
          case FILE_ACTION_ADDED:
            event = EVENT_CHILD_CREATE;
            break;
          case FILE_ACTION_REMOVED:
            event = EVENT_CHILD_DELETE;
            break;
          case FILE_ACTION_RENAMED_OLD_NAME:
            event = EVENT_CHILD_RENAME;
            break;
          case FILE_ACTION_RENAMED_NEW_NAME:
            event = EVENT_CHILD_RENAME;
            break;
          case FILE_ACTION_MODIFIED:
            event = EVENT_CHILD_CHANGE;
            break;
        }

        if (event != EVENT_NONE) {
          // The FileNameLength is in "bytes", but the WideCharToMultiByte
          // requires the length to be in "characters"!
          int file_name_length_in_characters =
              file_info->FileNameLength / sizeof(wchar_t);

          char filename[MAX_PATH] = { 0 };
          int size = WideCharToMultiByte(CP_UTF8,
                                         0,
                                         file_info->FileName,
                                         file_name_length_in_characters,
                                         filename,
                                         MAX_PATH,
                                         NULL,
                                         NULL);

          // Convert file name to file path, same with:
          // path = handle->path + '\\' + filename
          std::vector<char> path(handle->path.size() + 1 + size);
          std::vector<char>::iterator iter = path.begin();
          iter = std::copy(handle->path.begin(), handle->path.end(), iter);
          *(iter++) = '\\';
          std::copy(filename, filename + size, iter);

          if (file_info->Action == FILE_ACTION_RENAMED_OLD_NAME) {
            // Do not send rename event until the NEW_NAME event, but still keep
            // a record of old name.
            old_path.swap(path);
          } else if (file_info->Action == FILE_ACTION_RENAMED_NEW_NAME) {
            WatcherEvent e = { event, handle->overlapped.hEvent };
            e.new_path.swap(path);
            e.old_path.swap(old_path);
            events.push_back(e);
          } else {
            WatcherEvent e = { event, handle->overlapped.hEvent };
            e.new_path.swap(path);
            events.push_back(e);
          }
        }

        if (file_info->NextEntryOffset == 0) break;
        offset += file_info->NextEntryOffset;
      }

      // Restart the monitor, it was reset after each call.
      QueueReaddirchanges(handle);

      locker.Unlock();

      for (size_t i = 0; i < events.size(); ++i)
        PostEventAndWait(events[i].type,
                         events[i].handle,
                         events[i].new_path,
                         events[i].old_path);
    }
  }
}

WatcherHandle PlatformWatch(const char* path) {
  wchar_t wpath[MAX_PATH] = { 0 };
  MultiByteToWideChar(CP_UTF8, 0, path, -1, wpath, MAX_PATH);

  // Requires a directory, file watching is emulated in js.
  DWORD attr = GetFileAttributesW(wpath);
  if (attr == INVALID_FILE_ATTRIBUTES || !(attr & FILE_ATTRIBUTE_DIRECTORY)) {
    fprintf(stderr, "%s is not a directory\n", path);
    return INVALID_HANDLE_VALUE;
  }

  WatcherHandle dir_handle = CreateFileW(wpath,
                                         FILE_LIST_DIRECTORY,
                                         FILE_SHARE_READ | FILE_SHARE_DELETE |
                                           FILE_SHARE_WRITE,
                                         NULL,
                                         OPEN_EXISTING,
                                         FILE_FLAG_BACKUP_SEMANTICS |
                                           FILE_FLAG_OVERLAPPED,
                                         NULL);
  if (!PlatformIsHandleValid(dir_handle)) {
    fprintf(stderr, "Unable to call CreateFileW for %s\n", path);
    return INVALID_HANDLE_VALUE;
  }

  std::unique_ptr<HandleWrapper> handle;
  {
    ScopedLocker locker(g_handle_wrap_map_mutex);
    handle.reset(new HandleWrapper(dir_handle, path));
  }

  if (!QueueReaddirchanges(handle.get())) {
    fprintf(stderr, "ReadDirectoryChangesW failed\n");
    return INVALID_HANDLE_VALUE;
  }

  // Wake up the thread to add the new event.
  SetEvent(g_wake_up_event);

  // The pointer is leaked if no error happened.
  return handle.release()->overlapped.hEvent;
}

void PlatformUnwatch(WatcherHandle key) {
  if (PlatformIsHandleValid(key)) {
    ScopedLocker locker(g_handle_wrap_map_mutex);

    HandleWrapper* handle = HandleWrapper::Get(key);
    handle->canceled = true;
    CancelIoEx(handle->dir_handle, &handle->overlapped);
  }
}

bool PlatformIsHandleValid(WatcherHandle handle) {
  return handle != INVALID_HANDLE_VALUE;
}
<commit_msg>:lipstick: Remove lint warnings<commit_after>#include <algorithm>
#include <map>
#include <memory>

#include "common.h"

// Size of the buffer to store result of ReadDirectoryChangesW.
static const unsigned int kDirectoryWatcherBufferSize = 4096;

// Object template to create representation of WatcherHandle.
static Persistent<ObjectTemplate> g_object_template;

// Mutex for the HandleWrapper map.
static uv_mutex_t g_handle_wrap_map_mutex;

// The events to be waited on.
static std::vector<HANDLE> g_events;

// The dummy event to wakeup the thread.
static HANDLE g_wake_up_event;

struct ScopedLocker {
  explicit ScopedLocker(const uv_mutex_t& mutex) : mutex_(&mutex) { uv_mutex_lock(mutex_); }
  ~ScopedLocker() { Unlock(); }

  void Unlock() { uv_mutex_unlock(mutex_); }

  uv_mutex_t* mutex_;
};

struct HandleWrapper {
  HandleWrapper(WatcherHandle handle, const char* path_str)
      : dir_handle(handle),
        path(strlen(path_str)),
        canceled(false) {
    memset(&overlapped, 0, sizeof(overlapped));
    overlapped.hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
    g_events.push_back(overlapped.hEvent);

    std::copy(path_str, path_str + path.size(), path.data());
    map_[overlapped.hEvent] = this;
  }

  ~HandleWrapper() {
    CloseHandle(dir_handle);

    map_.erase(overlapped.hEvent);
    CloseHandle(overlapped.hEvent);
    g_events.erase(
        std::remove(g_events.begin(), g_events.end(), overlapped.hEvent),
        g_events.end());
  }

  WatcherHandle dir_handle;
  std::vector<char> path;
  bool canceled;
  OVERLAPPED overlapped;
  char buffer[kDirectoryWatcherBufferSize];

  static HandleWrapper* Get(HANDLE key) { return map_[key]; }

  static std::map<WatcherHandle, HandleWrapper*> map_;
};

std::map<WatcherHandle, HandleWrapper*> HandleWrapper::map_;

struct WatcherEvent {
  EVENT_TYPE type;
  WatcherHandle handle;
  std::vector<char> new_path;
  std::vector<char> old_path;
};

static bool QueueReaddirchanges(HandleWrapper* handle) {
  return ReadDirectoryChangesW(handle->dir_handle,
                               handle->buffer,
                               kDirectoryWatcherBufferSize,
                               FALSE,
                               FILE_NOTIFY_CHANGE_FILE_NAME      |
                                 FILE_NOTIFY_CHANGE_DIR_NAME     |
                                 FILE_NOTIFY_CHANGE_ATTRIBUTES   |
                                 FILE_NOTIFY_CHANGE_SIZE         |
                                 FILE_NOTIFY_CHANGE_LAST_WRITE   |
                                 FILE_NOTIFY_CHANGE_LAST_ACCESS  |
                                 FILE_NOTIFY_CHANGE_CREATION     |
                                 FILE_NOTIFY_CHANGE_SECURITY,
                               NULL,
                               &handle->overlapped,
                               NULL) == TRUE;
}

Handle<Value> WatcherHandleToV8Value(WatcherHandle handle) {
  Handle<Value> value = g_object_template->NewInstance();
  value->ToObject()->SetPointerInInternalField(0, handle);
  return value;
}

WatcherHandle V8ValueToWatcherHandle(Handle<Value> value) {
  return reinterpret_cast<WatcherHandle>(value->ToObject()->
      GetPointerFromInternalField(0));
}

bool IsV8ValueWatcherHandle(Handle<Value> value) {
  return value->IsObject() && value->ToObject()->InternalFieldCount() == 1;
}

void PlatformInit() {
  uv_mutex_init(&g_handle_wrap_map_mutex);

  g_wake_up_event = CreateEvent(NULL, FALSE, FALSE, NULL);
  g_events.push_back(g_wake_up_event);

  g_object_template = Persistent<ObjectTemplate>::New(ObjectTemplate::New());
  g_object_template->SetInternalFieldCount(1);

  WakeupNewThread();
}

void PlatformThread() {
  while (true) {
    // Do not use g_events directly, since reallocation could happen when there
    // are new watchers adding to g_events when WaitForMultipleObjects is still
    // polling.
    ScopedLocker locker(g_handle_wrap_map_mutex);
    std::vector<HANDLE> copied_events(g_events);
    locker.Unlock();

    DWORD r = WaitForMultipleObjects(copied_events.size(),
                                     copied_events.data(),
                                     FALSE,
                                     INFINITE);
    int i = r - WAIT_OBJECT_0;
    if (i >= 0 && i < copied_events.size()) {
      // It's a wake up event, there is no fs events.
      if (copied_events[i] == g_wake_up_event)
        continue;

      ScopedLocker locker(g_handle_wrap_map_mutex);

      HandleWrapper* handle = HandleWrapper::Get(copied_events[i]);
      if (!handle)
        continue;

      if (handle->canceled) {
        delete handle;
        continue;
      }

      DWORD bytes;
      if (GetOverlappedResult(handle->dir_handle,
                              &handle->overlapped,
                              &bytes,
                              FALSE) == FALSE)
        continue;

      std::vector<char> old_path;
      std::vector<WatcherEvent> events;

      DWORD offset = 0;
      while (true) {
        FILE_NOTIFY_INFORMATION* file_info =
            reinterpret_cast<FILE_NOTIFY_INFORMATION*>(handle->buffer + offset);

        // Emit events for children.
        EVENT_TYPE event = EVENT_NONE;
        switch (file_info->Action) {
          case FILE_ACTION_ADDED:
            event = EVENT_CHILD_CREATE;
            break;
          case FILE_ACTION_REMOVED:
            event = EVENT_CHILD_DELETE;
            break;
          case FILE_ACTION_RENAMED_OLD_NAME:
            event = EVENT_CHILD_RENAME;
            break;
          case FILE_ACTION_RENAMED_NEW_NAME:
            event = EVENT_CHILD_RENAME;
            break;
          case FILE_ACTION_MODIFIED:
            event = EVENT_CHILD_CHANGE;
            break;
        }

        if (event != EVENT_NONE) {
          // The FileNameLength is in "bytes", but the WideCharToMultiByte
          // requires the length to be in "characters"!
          int file_name_length_in_characters =
              file_info->FileNameLength / sizeof(wchar_t);

          char filename[MAX_PATH] = { 0 };
          int size = WideCharToMultiByte(CP_UTF8,
                                         0,
                                         file_info->FileName,
                                         file_name_length_in_characters,
                                         filename,
                                         MAX_PATH,
                                         NULL,
                                         NULL);

          // Convert file name to file path, same with:
          // path = handle->path + '\\' + filename
          std::vector<char> path(handle->path.size() + 1 + size);
          std::vector<char>::iterator iter = path.begin();
          iter = std::copy(handle->path.begin(), handle->path.end(), iter);
          *(iter++) = '\\';
          std::copy(filename, filename + size, iter);

          if (file_info->Action == FILE_ACTION_RENAMED_OLD_NAME) {
            // Do not send rename event until the NEW_NAME event, but still keep
            // a record of old name.
            old_path.swap(path);
          } else if (file_info->Action == FILE_ACTION_RENAMED_NEW_NAME) {
            WatcherEvent e = { event, handle->overlapped.hEvent };
            e.new_path.swap(path);
            e.old_path.swap(old_path);
            events.push_back(e);
          } else {
            WatcherEvent e = { event, handle->overlapped.hEvent };
            e.new_path.swap(path);
            events.push_back(e);
          }
        }

        if (file_info->NextEntryOffset == 0) break;
        offset += file_info->NextEntryOffset;
      }

      // Restart the monitor, it was reset after each call.
      QueueReaddirchanges(handle);

      locker.Unlock();

      for (size_t i = 0; i < events.size(); ++i)
        PostEventAndWait(events[i].type,
                         events[i].handle,
                         events[i].new_path,
                         events[i].old_path);
    }
  }
}

WatcherHandle PlatformWatch(const char* path) {
  wchar_t wpath[MAX_PATH] = { 0 };
  MultiByteToWideChar(CP_UTF8, 0, path, -1, wpath, MAX_PATH);

  // Requires a directory, file watching is emulated in js.
  DWORD attr = GetFileAttributesW(wpath);
  if (attr == INVALID_FILE_ATTRIBUTES || !(attr & FILE_ATTRIBUTE_DIRECTORY)) {
    fprintf(stderr, "%s is not a directory\n", path);
    return INVALID_HANDLE_VALUE;
  }

  WatcherHandle dir_handle = CreateFileW(wpath,
                                         FILE_LIST_DIRECTORY,
                                         FILE_SHARE_READ | FILE_SHARE_DELETE |
                                           FILE_SHARE_WRITE,
                                         NULL,
                                         OPEN_EXISTING,
                                         FILE_FLAG_BACKUP_SEMANTICS |
                                           FILE_FLAG_OVERLAPPED,
                                         NULL);
  if (!PlatformIsHandleValid(dir_handle)) {
    fprintf(stderr, "Unable to call CreateFileW for %s\n", path);
    return INVALID_HANDLE_VALUE;
  }

  std::unique_ptr<HandleWrapper> handle;
  {
    ScopedLocker locker(g_handle_wrap_map_mutex);
    handle.reset(new HandleWrapper(dir_handle, path));
  }

  if (!QueueReaddirchanges(handle.get())) {
    fprintf(stderr, "ReadDirectoryChangesW failed\n");
    return INVALID_HANDLE_VALUE;
  }

  // Wake up the thread to add the new event.
  SetEvent(g_wake_up_event);

  // The pointer is leaked if no error happened.
  return handle.release()->overlapped.hEvent;
}

void PlatformUnwatch(WatcherHandle key) {
  if (PlatformIsHandleValid(key)) {
    ScopedLocker locker(g_handle_wrap_map_mutex);

    HandleWrapper* handle = HandleWrapper::Get(key);
    handle->canceled = true;
    CancelIoEx(handle->dir_handle, &handle->overlapped);
  }
}

bool PlatformIsHandleValid(WatcherHandle handle) {
  return handle != INVALID_HANDLE_VALUE;
}
<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id$ */

//*-- Author: Rachid Guernane (LPCCFd)

#include "AliMUONRegionalTriggerBoard.h"

#include "TBits.h"

#include <Riostream.h>

ClassImp(AliMUONRegionalTriggerBoard)

//___________________________________________
AliMUONRegionalTriggerBoard::AliMUONRegionalTriggerBoard()
{
   for (Int_t i=0; i<16; i++) fLocalResponse[i] = 0;
}

//___________________________________________
AliMUONRegionalTriggerBoard::AliMUONRegionalTriggerBoard(const char *name, Int_t a) : AliMUONTriggerBoard(name, a)
{
   for (Int_t i=0; i<16; i++) fLocalResponse[i] = 0;
}

//___________________________________________
void AliMUONRegionalTriggerBoard::Response()
{
   Int_t t[16];

   for (Int_t i=0;i<16;i++) t[i] = fLocalResponse[i];

   Int_t rank = 8;

   for (Int_t i=0;i<4;i++)
   {
      Int_t ip = 0;

      for (Int_t j=0;j<rank;j++)
      {
         UShort_t athres = Algo(t[2*j],t[2*j+1],"APT",i);

         UShort_t lthres = Algo(t[2*j],t[2*j+1],"LPT",i); lthres <<= 4;

         UShort_t hthres = Algo(t[2*j],t[2*j+1],"HPT",i); hthres <<= 8;

         t[ip] = athres | lthres | hthres;

         ip++;
      }

      rank /= 2;
   }

   fResponse = t[0]; // 12-bit [H4:L4:A4]
}

//___________________________________________
UShort_t AliMUONRegionalTriggerBoard::Algo(UShort_t i, UShort_t j, char *thres, Int_t level)
{
   TBits a(12), b(12); a.Set(12,&i); b.Set(12,&j);

   TBits trg1(2), trg2(2), trg(2);

   if (!strcmp(thres,"APT"))
   {
      if (!level)
      {
         trg1[0] = a[0]; trg1[1] = a[1];
         trg2[0] = b[0]; trg2[1] = b[1];
      }
      else
      {
         trg1[0] = a[2]; trg1[1] = a[3];
         trg2[0] = b[2]; trg2[1] = b[3];
      }
   }
   else if (!strcmp(thres,"LPT"))
   {
      if (!level)
      {
         trg1[0] = a[2]; trg1[1] = a[3];
         trg2[0] = b[2]; trg2[1] = b[3];
      }
      else
      {
         trg1[0] = a[6]; trg1[1] = a[7];
         trg2[0] = b[6]; trg2[1] = b[7];
      }
   }
   else
   {
      if (!level)
      {
         trg1[0] = a[4]; trg1[1] = a[5];
         trg2[0] = b[4]; trg2[1] = b[5];
      }
      else
      {
         trg1[0] = a[10]; trg1[1] = a[11];
         trg2[0] = b[10]; trg2[1] = b[11];
      }
   }

   TBits trgLS1(1), trgUS1(1), trgLS2(1), trgUS2(1), trgLS(1), trgUS(1);

   if (!level)
   {
      trgLS1[0] = trgUS1[0] = trgLS2[0] = trgUS2[0] = 0;
   }
   else
   {
      if (!strcmp(thres,"APT"))
      {
         trgLS1[0] = a[1]; trgUS1[0] = a[0];
         trgLS2[0] = b[1]; trgUS2[0] = b[0];
      }
      else if (!strcmp(thres,"LPT"))
      {
         trgLS1[0] = a[5]; trgUS1[0] = a[4];
         trgLS2[0] = b[5]; trgUS2[0] = b[4];
      }
      else
      {
         trgLS1[0] = a[9]; trgUS1[0] = a[8];
         trgLS2[0] = b[9]; trgUS2[0] = b[8];
      }
   }

   trgLS[0] = ( trg1[0] & trg2[0] ) | ( trg1[1] & trg2[1] ) | trgLS1[0] | trgLS2[0];
   trgUS[0] = ( trg1[0] & trg2[1] ) | ( trg1[1] & trg2[0] ) | trgUS1[0] | trgUS2[0];

   trg[0] = trg1[0] | trg2[0];
   trg[1] = trg1[1] | trg2[1];

   TBits v(4);

   v[0] = trgUS[0];
   v[1] = trgLS[0];
   v[2] = trg[0];
   v[3] = trg[1];

   UShort_t rv = 0;
   v.Get(&rv);

   return rv;
}
//___________________________________________
void AliMUONRegionalTriggerBoard::Scan(Option_t*)
{

}

ClassImp(AliMUONRegionalTriggerBoard)
<commit_msg>Implemented Scan() method (Rachid)<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id$ */

//*-- Author: Rachid Guernane (LPCCFd)

#include "AliMUONRegionalTriggerBoard.h"

#include "TBits.h"

#include <Riostream.h>

ClassImp(AliMUONRegionalTriggerBoard)

//___________________________________________
AliMUONRegionalTriggerBoard::AliMUONRegionalTriggerBoard()
{
   for (Int_t i=0; i<16; i++) fLocalResponse[i] = 0;
}

//___________________________________________
AliMUONRegionalTriggerBoard::AliMUONRegionalTriggerBoard(const char *name, Int_t a) : AliMUONTriggerBoard(name, a)
{
   for (Int_t i=0; i<16; i++) fLocalResponse[i] = 0;
}

//___________________________________________
void AliMUONRegionalTriggerBoard::Response()
{
   Int_t t[16];

   for (Int_t i=0;i<16;i++) t[i] = fLocalResponse[i];

   Int_t rank = 8;

   for (Int_t i=0;i<4;i++)
   {
      Int_t ip = 0;

      for (Int_t j=0;j<rank;j++)
      {
         UShort_t athres = Algo(t[2*j],t[2*j+1],"APT",i);

         UShort_t lthres = Algo(t[2*j],t[2*j+1],"LPT",i); lthres <<= 4;

         UShort_t hthres = Algo(t[2*j],t[2*j+1],"HPT",i); hthres <<= 8;

         t[ip] = athres | lthres | hthres;

         ip++;
      }

      rank /= 2;
   }

   fResponse = t[0]; // 12-bit [H4:L4:A4]
}

//___________________________________________
UShort_t AliMUONRegionalTriggerBoard::Algo(UShort_t i, UShort_t j, char *thres, Int_t level)
{
   TBits a(12), b(12); a.Set(12,&i); b.Set(12,&j);

   TBits trg1(2), trg2(2), trg(2);

   if (!strcmp(thres,"APT"))
   {
      if (!level)
      {
         trg1[0] = a[0]; trg1[1] = a[1];
         trg2[0] = b[0]; trg2[1] = b[1];
      }
      else
      {
         trg1[0] = a[2]; trg1[1] = a[3];
         trg2[0] = b[2]; trg2[1] = b[3];
      }
   }
   else if (!strcmp(thres,"LPT"))
   {
      if (!level)
      {
         trg1[0] = a[2]; trg1[1] = a[3];
         trg2[0] = b[2]; trg2[1] = b[3];
      }
      else
      {
         trg1[0] = a[6]; trg1[1] = a[7];
         trg2[0] = b[6]; trg2[1] = b[7];
      }
   }
   else
   {
      if (!level)
      {
         trg1[0] = a[4]; trg1[1] = a[5];
         trg2[0] = b[4]; trg2[1] = b[5];
      }
      else
      {
         trg1[0] = a[10]; trg1[1] = a[11];
         trg2[0] = b[10]; trg2[1] = b[11];
      }
   }

   TBits trgLS1(1), trgUS1(1), trgLS2(1), trgUS2(1), trgLS(1), trgUS(1);

   if (!level)
   {
      trgLS1[0] = trgUS1[0] = trgLS2[0] = trgUS2[0] = 0;
   }
   else
   {
      if (!strcmp(thres,"APT"))
      {
         trgLS1[0] = a[1]; trgUS1[0] = a[0];
         trgLS2[0] = b[1]; trgUS2[0] = b[0];
      }
      else if (!strcmp(thres,"LPT"))
      {
         trgLS1[0] = a[5]; trgUS1[0] = a[4];
         trgLS2[0] = b[5]; trgUS2[0] = b[4];
      }
      else
      {
         trgLS1[0] = a[9]; trgUS1[0] = a[8];
         trgLS2[0] = b[9]; trgUS2[0] = b[8];
      }
   }

   trgLS[0] = ( trg1[0] & trg2[0] ) | ( trg1[1] & trg2[1] ) | trgLS1[0] | trgLS2[0];
   trgUS[0] = ( trg1[0] & trg2[1] ) | ( trg1[1] & trg2[0] ) | trgUS1[0] | trgUS2[0];

   trg[0] = trg1[0] | trg2[0];
   trg[1] = trg1[1] | trg2[1];

   TBits v(4);

   v[0] = trgUS[0];
   v[1] = trgLS[0];
   v[2] = trg[0];
   v[3] = trg[1];

   UShort_t rv = 0;
   v.Get(&rv);

   return rv;
}
//___________________________________________
void AliMUONRegionalTriggerBoard::Scan(Option_t*)
{
   for (Int_t i=0; i<16; i++)
   {
      TBits b;
      b.Set(6,&fLocalResponse[i]);

      cout << "Entry " << i << " is " << b << endl;

   }

}

ClassImp(AliMUONRegionalTriggerBoard)
<|endoftext|>


<commit_before>
/*
-----------------------------------------------------------------------------
This source file is part of OGRE
    (Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2006 Torus Knot Software Ltd
Also see acknowledgements in Readme.html

This program is free software you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free Software
Foundation either version 2 of the License, or (at your option) any later
version.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along with
this program if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA, or go to
http://www.gnu.org/copyleft/lesser.txt.

You may alternatively use this source under the terms of a specific version of
the OGRE Unrestricted License provided you have obtained such a license from
Torus Knot Software Ltd.
-----------------------------------------------------------------------------
*/
#include "OgreStableHeaders.h"
#include "OgreGpuProgramUsage.h"
#include "OgreGpuProgramManager.h"
#include "OgreException.h"

namespace Ogre
{
    //-----------------------------------------------------------------------------
    GpuProgramUsage::GpuProgramUsage(GpuProgramType gptype) :
        mType(gptype), mProgram()
    {
    }
	//-----------------------------------------------------------------------------
	GpuProgramUsage::GpuProgramUsage(const GpuProgramUsage& oth)
        : mType(oth.mType)
        , mProgram(oth.mProgram)
        // nfz: parameters should be copied not just use a shared ptr to the original
		, mParameters(OGRE_NEW GpuProgramParameters(*oth.mParameters))
	{
	}
	//-----------------------------------------------------------------------------
	void GpuProgramUsage::setProgramName(const String& name, bool resetParams)
	{
		mProgram = GpuProgramManager::getSingleton().getByName(name);

        if (mProgram.isNull())
        {
			String progType = (mType == GPT_VERTEX_PROGRAM ? "vertex" :
				(mType == GPT_GEOMETRY_PROGRAM ? "geometry" : "fragment"));
            OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND,
                "Unable to locate " + progType + " program called " + name + ".",
                "GpuProgramUsage::setProgramName");
        }
        // Reset parameters
        if (resetParams || mParameters.isNull())
            mParameters = mProgram->createParameters();

	}
    //-----------------------------------------------------------------------------
    void GpuProgramUsage::setParameters(GpuProgramParametersSharedPtr params)
    {
        mParameters = params;
    }
    //-----------------------------------------------------------------------------
    GpuProgramParametersSharedPtr GpuProgramUsage::getParameters(void)
    {
        if (mParameters.isNull())
        {
            OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "You must specify a program before "
                "you can retrieve parameters.", "GpuProgramUsage::getParameters");
        }

        return mParameters;
    }
    //-----------------------------------------------------------------------------
	void GpuProgramUsage::setProgram(GpuProgramPtr& prog)
	{
        mProgram = prog;
        // Reset parameters
        mParameters = mProgram->createParameters();
    }
    //-----------------------------------------------------------------------------
    void GpuProgramUsage::_load(void)
    {
        if (!mProgram->isLoaded())
            mProgram->load();
    }
    //-----------------------------------------------------------------------------
    void GpuProgramUsage::_unload(void)
    {
        // TODO?
    }

}
<commit_msg>GpuProgramUsage::setProgramName - check the type of the program assigned matches the type of usage it's assigned to (make copy/paste errors in scripts easier to diagnose)<commit_after>
/*
-----------------------------------------------------------------------------
This source file is part of OGRE
    (Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2006 Torus Knot Software Ltd
Also see acknowledgements in Readme.html

This program is free software you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free Software
Foundation either version 2 of the License, or (at your option) any later
version.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along with
this program if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA, or go to
http://www.gnu.org/copyleft/lesser.txt.

You may alternatively use this source under the terms of a specific version of
the OGRE Unrestricted License provided you have obtained such a license from
Torus Knot Software Ltd.
-----------------------------------------------------------------------------
*/
#include "OgreStableHeaders.h"
#include "OgreGpuProgramUsage.h"
#include "OgreGpuProgramManager.h"
#include "OgreException.h"

namespace Ogre
{
    //-----------------------------------------------------------------------------
    GpuProgramUsage::GpuProgramUsage(GpuProgramType gptype) :
        mType(gptype), mProgram()
    {
    }
	//-----------------------------------------------------------------------------
	GpuProgramUsage::GpuProgramUsage(const GpuProgramUsage& oth)
        : mType(oth.mType)
        , mProgram(oth.mProgram)
        // nfz: parameters should be copied not just use a shared ptr to the original
		, mParameters(OGRE_NEW GpuProgramParameters(*oth.mParameters))
	{
	}
	//-----------------------------------------------------------------------------
	void GpuProgramUsage::setProgramName(const String& name, bool resetParams)
	{
		mProgram = GpuProgramManager::getSingleton().getByName(name);

        if (mProgram.isNull())
        {
			String progType = (mType == GPT_VERTEX_PROGRAM ? "vertex" :
				(mType == GPT_GEOMETRY_PROGRAM ? "geometry" : "fragment"));
            OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND,
                "Unable to locate " + progType + " program called " + name + ".",
                "GpuProgramUsage::setProgramName");
        }
		// check type
		if (mProgram->getType() != mType)
		{
			String myType = (mType == GPT_VERTEX_PROGRAM ? "vertex" :
				(mType == GPT_GEOMETRY_PROGRAM ? "geometry" : "fragment"));
			String yourType = (mProgram->getType() == GPT_VERTEX_PROGRAM ? "vertex" :
				(mProgram->getType() == GPT_GEOMETRY_PROGRAM ? "geometry" : "fragment"));
			OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
				name + "is a " + yourType + " program, but you are assigning it to a "
				+ myType + " program slot. This is invalid.",
				"GpuProgramUsage::setProgramName");

		}

        // Reset parameters
        if (resetParams || mParameters.isNull())
            mParameters = mProgram->createParameters();

	}
    //-----------------------------------------------------------------------------
    void GpuProgramUsage::setParameters(GpuProgramParametersSharedPtr params)
    {
        mParameters = params;
    }
    //-----------------------------------------------------------------------------
    GpuProgramParametersSharedPtr GpuProgramUsage::getParameters(void)
    {
        if (mParameters.isNull())
        {
            OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "You must specify a program before "
                "you can retrieve parameters.", "GpuProgramUsage::getParameters");
        }

        return mParameters;
    }
    //-----------------------------------------------------------------------------
	void GpuProgramUsage::setProgram(GpuProgramPtr& prog)
	{
        mProgram = prog;
        // Reset parameters
        mParameters = mProgram->createParameters();
    }
    //-----------------------------------------------------------------------------
    void GpuProgramUsage::_load(void)
    {
        if (!mProgram->isLoaded())
            mProgram->load();
    }
    //-----------------------------------------------------------------------------
    void GpuProgramUsage::_unload(void)
    {
        // TODO?
    }

}
<|endoftext|>


<commit_before>#include <windows.h>
#include <d3d9.h>

#include "d3d9overlay.h"
#include "d3d9font.h"
#include "d3d9hook.h"
#include <OvRender.h>

Dx9Font* Dx9OvFont;
extern Dx9Overlay* D3D9Overlay;
IDirect3DDevice9* Dx9OvDevice;
OV_WINDOW_MODE D3D9Hook_WindowMode;
UINT32 BackBufferWidth;
UINT32 BackBufferHeight;
UINT32 BackBufferCount;

VOID Log(const wchar_t* Format, ...);

VOID DebugRec()
{
    D3DRECT rec = { 0, 0, 10, 10 };
    Dx9OvDevice->Clear(1, &rec, D3DCLEAR_TARGET, D3DCOLOR_ARGB(225, 225, 0, 0), 0, 0);
}

VOID ChangeVsync(BOOLEAN Setting)
{
    if (Setting)
        D3D9Overlay->VsyncOverrideMode = VSYNC_FORCE_ON;
    else
        D3D9Overlay->VsyncOverrideMode = VSYNC_FORCE_OFF;

    D3D9Hook_ForceReset = TRUE;
}

WCHAR* GetVsyncChar( OV_VSYNC_OVERRIDE_MODE Mode )
{
    switch (Mode)
    {
    case VSYNC_UNCHANGED:
        return L"VSYNC_UNCHANGED";
        break;
    case VSYNC_FORCE_ON:
        return L"VSYNC_FORCE_ON";
        break;
    case VSYNC_FORCE_OFF:
        return L"VSYNC_FORCE_OFF";
        break;
    default:
        return L"VYSNC_UNKNOWN";
        break;
    }
}

VOID UpdatePresentationParameters( D3DPRESENT_PARAMETERS* PresentationParameters )
{
    // Force vsync?
    Log(L"UpdatePresentationParameters(%s)", GetVsyncChar(D3D9Overlay->VsyncOverrideMode));

    if (D3D9Overlay->VsyncOverrideMode == VSYNC_FORCE_ON)
    {
        PresentationParameters->PresentationInterval = D3DPRESENT_INTERVAL_ONE;
    }
    else if (D3D9Overlay->VsyncOverrideMode == VSYNC_FORCE_OFF)
    {
        PresentationParameters->PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
    }

    if (D3D9Hook_WindowMode == WINDOW_WINDOWED)
    {
        RECT r;

        PresentationParameters->Windowed = TRUE;
        PresentationParameters->Flags = 0;
        PresentationParameters->FullScreen_RefreshRateInHz = 0;

        SetWindowLong(
            PresentationParameters->hDeviceWindow,
            GWL_STYLE,
            WS_POPUP | WS_CAPTION | WS_MINIMIZEBOX | WS_SYSMENU | WS_VISIBLE
            );

        GetClientRect(PresentationParameters->hDeviceWindow, &r);

        SetWindowPos(
            PresentationParameters->hDeviceWindow,
            HWND_NOTOPMOST,
            0,
            0,
            PresentationParameters->BackBufferWidth + (PresentationParameters->BackBufferWidth - r.right),
            PresentationParameters->BackBufferHeight + (PresentationParameters->BackBufferHeight - r.bottom),
            SWP_FRAMECHANGED | SWP_SHOWWINDOW | SWP_NOMOVE
            );
    }
    else if (D3D9Hook_WindowMode == WINDOW_FULLSCREEN)
    {
        PresentationParameters->Windowed = FALSE;
    }

    BackBufferHeight = PresentationParameters->BackBufferHeight;
    BackBufferWidth = PresentationParameters->BackBufferWidth;
    BackBufferCount = PresentationParameters->BackBufferCount;
}

VOID Dx9Overlay_CreateDevice( D3DPRESENT_PARAMETERS* PresentationParameters )
{
    Log(L"Dx9Overlay_CreateDevice()");
    UpdatePresentationParameters(PresentationParameters);
}

VOID Dx9Overlay_Reset( D3DPRESENT_PARAMETERS* PresentationParameters )
{
    Log(L"Dx9Overlay_Reset()");

    if (Dx9OvFont)
    {
        Dx9OvFont->InvalidateDeviceObjects();
        Dx9OvFont->DeleteDeviceObjects();
    }

    Dx9OvFont = NULL;

    UpdatePresentationParameters(PresentationParameters);
}

VOID Dx9OvRender( IDirect3DDevice9* Device )
{
    IDirect3DSurface9 *renderTarget = NULL;
    IDirect3DSurface9 *backBuffer = NULL;
    D3DSURFACE_DESC backBufferDesc;
    D3DVIEWPORT9 viewport;

    if (Dx9OvFont == NULL)
    {
        Dx9OvFont = new Dx9Font(Device);

        Dx9OvFont->InitDeviceObjects();
        Dx9OvFont->RestoreDeviceObjects();

        Dx9OvDevice = Device;
    }

    // Backup render target.

    Device->GetRenderTarget( 0, &renderTarget );
    Device->GetViewport(&viewport);

    // Set backbuffer as new render target.

    Device->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &backBuffer);
    backBuffer->GetDesc(&backBufferDesc);

    if (backBufferDesc.Width != 1 && backBufferDesc.Height != 1)
    {
        Device->SetRenderTarget(0, backBuffer);
    }

    // Render our stuff.
    D3D9Overlay->Render();

    // Restore render target.

    Device->SetRenderTarget( 0, renderTarget );
    Device->SetViewport(&viewport);

    // Cleanup.

    backBuffer->Release();
    renderTarget->Release();
}

VOID Dx9Overlay_Present( IDirect3DDevice9* Device )
{
    static BOOLEAN initialized = FALSE;

    Dx9OvRender(Device);

    if (!initialized)
    {
        if (D3D9Overlay->VsyncOverrideMode == VSYNC_FORCE_ON
         || D3D9Overlay->VsyncOverrideMode == VSYNC_FORCE_OFF)
        {
            D3D9Hook_ForceReset = TRUE;
        }

        initialized = TRUE;
    }
}

Dx9Overlay::Dx9Overlay( OV_RENDER RenderFunction )
{
    D3D9HOOK_PARAMS hookParams;

    hookParams.PresentCallback = Dx9Overlay_Present;
    hookParams.ResetCallback = Dx9Overlay_Reset;
    hookParams.CreateDeviceCallback = Dx9Overlay_CreateDevice;

    Log(L"Dx9Overlay::Dx9Overlay( => )");

    Dx9Hook_Initialize(&hookParams);

    UserRenderFunction = RenderFunction;
}

VOID
Dx9Overlay::DrawText( WCHAR* Text )
{
    DrawText(Text, 0xFFFFFF00);
}

VOID
Dx9Overlay::DrawText( WCHAR* Text, DWORD Color )
{
    DrawText(Text, 20, Line, Color);

    Line += 15;
}

VOID Dx9Overlay::DrawText( WCHAR* Text, int X, int Y, DWORD Color )
{
    Dx9OvFont->DrawText((FLOAT)X, (FLOAT)Y, Color, Text, NULL);
}

VOID
Dx9Overlay::Begin()
{

}

VOID
Dx9Overlay::End()
{

}

VOID*
Dx9Overlay::GetDevice()
{
    return Dx9OvDevice;
}<commit_msg>fix crash when d3d9 renderer not initialized<commit_after>#include <windows.h>
#include <d3d9.h>

#include "d3d9overlay.h"
#include "d3d9font.h"
#include "d3d9hook.h"
#include <OvRender.h>

Dx9Font* Dx9OvFont;
extern Dx9Overlay* D3D9Overlay;
IDirect3DDevice9* Dx9OvDevice;
OV_WINDOW_MODE D3D9Hook_WindowMode;
UINT32 BackBufferWidth;
UINT32 BackBufferHeight;
UINT32 BackBufferCount;

VOID Log(const wchar_t* Format, ...);

VOID DebugRec()
{
    D3DRECT rec = { 0, 0, 10, 10 };

    if (Dx9OvDevice)
        Dx9OvDevice->Clear(1, &rec, D3DCLEAR_TARGET, D3DCOLOR_ARGB(225, 225, 0, 0), 0, 0);
}

VOID ChangeVsync(BOOLEAN Setting)
{
    if (Setting)
        D3D9Overlay->VsyncOverrideMode = VSYNC_FORCE_ON;
    else
        D3D9Overlay->VsyncOverrideMode = VSYNC_FORCE_OFF;

    D3D9Hook_ForceReset = TRUE;
}

WCHAR* GetVsyncChar( OV_VSYNC_OVERRIDE_MODE Mode )
{
    switch (Mode)
    {
    case VSYNC_UNCHANGED:
        return L"VSYNC_UNCHANGED";
        break;
    case VSYNC_FORCE_ON:
        return L"VSYNC_FORCE_ON";
        break;
    case VSYNC_FORCE_OFF:
        return L"VSYNC_FORCE_OFF";
        break;
    default:
        return L"VYSNC_UNKNOWN";
        break;
    }
}

VOID UpdatePresentationParameters( D3DPRESENT_PARAMETERS* PresentationParameters )
{
    // Force vsync?
    Log(L"UpdatePresentationParameters(%s)", GetVsyncChar(D3D9Overlay->VsyncOverrideMode));

    if (D3D9Overlay->VsyncOverrideMode == VSYNC_FORCE_ON)
    {
        PresentationParameters->PresentationInterval = D3DPRESENT_INTERVAL_ONE;
    }
    else if (D3D9Overlay->VsyncOverrideMode == VSYNC_FORCE_OFF)
    {
        PresentationParameters->PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
    }

    if (D3D9Hook_WindowMode == WINDOW_WINDOWED)
    {
        RECT r;

        PresentationParameters->Windowed = TRUE;
        PresentationParameters->Flags = 0;
        PresentationParameters->FullScreen_RefreshRateInHz = 0;

        SetWindowLong(
            PresentationParameters->hDeviceWindow,
            GWL_STYLE,
            WS_POPUP | WS_CAPTION | WS_MINIMIZEBOX | WS_SYSMENU | WS_VISIBLE
            );

        GetClientRect(PresentationParameters->hDeviceWindow, &r);

        SetWindowPos(
            PresentationParameters->hDeviceWindow,
            HWND_NOTOPMOST,
            0,
            0,
            PresentationParameters->BackBufferWidth + (PresentationParameters->BackBufferWidth - r.right),
            PresentationParameters->BackBufferHeight + (PresentationParameters->BackBufferHeight - r.bottom),
            SWP_FRAMECHANGED | SWP_SHOWWINDOW | SWP_NOMOVE
            );
    }
    else if (D3D9Hook_WindowMode == WINDOW_FULLSCREEN)
    {
        PresentationParameters->Windowed = FALSE;
    }

    BackBufferHeight = PresentationParameters->BackBufferHeight;
    BackBufferWidth = PresentationParameters->BackBufferWidth;
    BackBufferCount = PresentationParameters->BackBufferCount;
}

VOID Dx9Overlay_CreateDevice( D3DPRESENT_PARAMETERS* PresentationParameters )
{
    Log(L"Dx9Overlay_CreateDevice()");
    UpdatePresentationParameters(PresentationParameters);
}

VOID Dx9Overlay_Reset( D3DPRESENT_PARAMETERS* PresentationParameters )
{
    Log(L"Dx9Overlay_Reset()");

    if (Dx9OvFont)
    {
        Dx9OvFont->InvalidateDeviceObjects();
        Dx9OvFont->DeleteDeviceObjects();
    }

    Dx9OvFont = NULL;

    UpdatePresentationParameters(PresentationParameters);
}

VOID Dx9OvRender( IDirect3DDevice9* Device )
{
    IDirect3DSurface9 *renderTarget = NULL;
    IDirect3DSurface9 *backBuffer = NULL;
    D3DSURFACE_DESC backBufferDesc;
    D3DVIEWPORT9 viewport;

    if (Dx9OvFont == NULL)
    {
        Dx9OvFont = new Dx9Font(Device);

        Dx9OvFont->InitDeviceObjects();
        Dx9OvFont->RestoreDeviceObjects();

        Dx9OvDevice = Device;
    }

    // Backup render target.

    Device->GetRenderTarget( 0, &renderTarget );
    Device->GetViewport(&viewport);

    // Set backbuffer as new render target.

    Device->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &backBuffer);
    backBuffer->GetDesc(&backBufferDesc);

    if (backBufferDesc.Width != 1 && backBufferDesc.Height != 1)
    {
        Device->SetRenderTarget(0, backBuffer);
    }

    // Render our stuff.
    D3D9Overlay->Render();

    // Restore render target.

    Device->SetRenderTarget( 0, renderTarget );
    Device->SetViewport(&viewport);

    // Cleanup.

    backBuffer->Release();
    renderTarget->Release();
}

VOID Dx9Overlay_Present( IDirect3DDevice9* Device )
{
    static BOOLEAN initialized = FALSE;

    Dx9OvRender(Device);

    if (!initialized)
    {
        if (D3D9Overlay->VsyncOverrideMode == VSYNC_FORCE_ON
         || D3D9Overlay->VsyncOverrideMode == VSYNC_FORCE_OFF)
        {
            D3D9Hook_ForceReset = TRUE;
        }

        initialized = TRUE;
    }
}

Dx9Overlay::Dx9Overlay( OV_RENDER RenderFunction )
{
    D3D9HOOK_PARAMS hookParams;

    hookParams.PresentCallback = Dx9Overlay_Present;
    hookParams.ResetCallback = Dx9Overlay_Reset;
    hookParams.CreateDeviceCallback = Dx9Overlay_CreateDevice;

    Log(L"Dx9Overlay::Dx9Overlay( => )");

    Dx9Hook_Initialize(&hookParams);

    UserRenderFunction = RenderFunction;
}

VOID
Dx9Overlay::DrawText( WCHAR* Text )
{
    DrawText(Text, 0xFFFFFF00);
}

VOID
Dx9Overlay::DrawText( WCHAR* Text, DWORD Color )
{
    DrawText(Text, 20, Line, Color);

    Line += 15;
}

VOID Dx9Overlay::DrawText( WCHAR* Text, int X, int Y, DWORD Color )
{
    Dx9OvFont->DrawText((FLOAT)X, (FLOAT)Y, Color, Text, NULL);
}

VOID
Dx9Overlay::Begin()
{

}

VOID
Dx9Overlay::End()
{

}

VOID*
Dx9Overlay::GetDevice()
{
    return Dx9OvDevice;
}<|endoftext|>


<commit_before>//
// Created by Xiaoqian Mu on 4/1/17.
//

#include <List>
#include "point_location.h"
#include <iostream>
using namespace geo;
using namespace std;

PointLocation::PointLocation(DoubleEdgeList* dcel){

    Create_edgeslist(dcel);
    Create_verticeslist(dcel);
    Create_PLTree();
    //double l=pl_tree.Find_location(360,100);

//    if(l!=-1) {
//        Vector2 p = Vector2(360, 100);
//        PointLocationVertex *ver = new PointLocationVertex(p);
//        DoubleEdgeListFace *f = pl_tree.Search_point(l, ver);
//        if(f!= nullptr) {
//            auto k = f->edge;
//        }
//        else{
//            std::cout<<"Out of the polygon"<<endl;
//        }
//    }
//    else{
//        std::cout<<"Out of the polygon"<<endl;
//    }
}

bool PointLocation::Find_point_location(Vector2 &p, geo::Triangle &triangle) {
    double l=pl_tree.Find_location(p.x,p.y);

    if(l!=-1) {
        PointLocationVertex *ver = new PointLocationVertex(p);
        PointLocationEdge *e = pl_tree.Search_point(l, ver);
        if(e!= nullptr) {
			triangle.point1 = e->v_l->point;
			triangle.point2 = e->v_r->point;
			triangle.point3 = (e->v_r->getEdgeTo(e->v_l))->next->twin->origin->point;
            return true;
        }
        else{
            //std::cout<<"Out of the polygon"<<endl;
            return false;
        }
    }
    else{
        //std::cout<<"Out of the polygon"<<endl;
        return false;
    }
}

void PointLocation::Create_edgeslist(DoubleEdgeList *dcel) {
    DoubleEdgeListHalfEdge* start;
    for(int i=0;i<dcel->edges.size();i++){
        start=dcel->edges.front();
        if(!start->visited) {
            PointLocationEdge new_edge =PointLocationEdge(start);
            edges.push_back(new_edge);
        }

        dcel->edges.pop_front();
        dcel->edges.push_back(start);

    }

//    for(auto it=dcel->edges.begin(); it!=dcel->edges.end();++it){
//        if(!it->visited)
//    }
}

void PointLocation::Create_verticeslist(DoubleEdgeList *dcel) {
    //DoubleEdgeListVertex* new_vertex=dcel->vertices.front();

    for(int i=0;i<dcel->vertices.size();i++){
        PointLocationVertex new_vertex=PointLocationVertex(dcel->vertices.front());
//        new_vertex.vertex=dcel->vertices.front();
//
        for(int j=0;j<edges.size();j++){
            if(edges[j].v_l==new_vertex.vertex){
                new_vertex.edge_insert.push_back(&edges[j]);
            }
            if(edges[j].v_r==new_vertex.vertex){
                new_vertex.edge_delete.push_back(&edges[j]);
            }
        }

        dcel->vertices.pop_front();
        dcel->vertices.push_back(new_vertex.vertex);
        vertices.push_back(new_vertex);

        int s=vertices.size();
        s=s+0;
    }
}

void PointLocation::Create_PLTree() {
    pl_tree=PLRbTree(edges,vertices);
}

//void PointLocation::Find_location(double x, double y) {
//    int low=0;
//    int high=pl_tree.roots.size()-1;
//    int mid=0;
//    int location=-1;
//
//    if(x>=pl_tree.roots[low]&&x<pl_tree.roots[low+1]) {
//        location = low;
//    }
//    if(x>=pl_tree.roots[high]&&x<pl_tree.roots[high+1]) {
//        location = high;
//    }
//
//    while(location<0) {
//        mid=(low+high)/2;
//        if(x>=pl_tree.roots[mid]&&x<pl_tree.roots[mid+1])
//            location=mid;
//        if(x<pl_tree.roots[mid]){
//            high=mid;
//        }
//        if(x>pl_tree.roots[mid+1])
//            low=mid;
//    }
//}

<commit_msg>Fix bug<commit_after>//
// Created by Xiaoqian Mu on 4/1/17.
//

//#include <list>
#include "point_location.h"
#include <iostream>
using namespace geo;
using namespace std;

PointLocation::PointLocation(DoubleEdgeList* dcel){

    Create_edgeslist(dcel);
    Create_verticeslist(dcel);
    Create_PLTree();
    //double l=pl_tree.Find_location(360,100);

//    if(l!=-1) {
//        Vector2 p = Vector2(360, 100);
//        PointLocationVertex *ver = new PointLocationVertex(p);
//        DoubleEdgeListFace *f = pl_tree.Search_point(l, ver);
//        if(f!= nullptr) {
//            auto k = f->edge;
//        }
//        else{
//            std::cout<<"Out of the polygon"<<endl;
//        }
//    }
//    else{
//        std::cout<<"Out of the polygon"<<endl;
//    }
}

bool PointLocation::Find_point_location(Vector2 &p, geo::Triangle &triangle) {
    double l=pl_tree.Find_location(p.x,p.y);

    if(l!=-1) {
        PointLocationVertex *ver = new PointLocationVertex(p);
        PointLocationEdge *e = pl_tree.Search_point(l, ver);
        if(e!= nullptr) {
			triangle.point1 = e->v_l->point;
			triangle.point2 = e->v_r->point;
			triangle.point3 = (e->v_r->getEdgeTo(e->v_l))->next->twin->origin->point;
            return true;
        }
        else{
            //std::cout<<"Out of the polygon"<<endl;
            return false;
        }
    }
    else{
        //std::cout<<"Out of the polygon"<<endl;
        return false;
    }
}

void PointLocation::Create_edgeslist(DoubleEdgeList *dcel) {
    DoubleEdgeListHalfEdge* start;
    for(int i=0;i<dcel->edges.size();i++){
        start=dcel->edges.front();
        if(!start->visited) {
            PointLocationEdge new_edge =PointLocationEdge(start);
            edges.push_back(new_edge);
        }

        dcel->edges.pop_front();
        dcel->edges.push_back(start);

    }

//    for(auto it=dcel->edges.begin(); it!=dcel->edges.end();++it){
//        if(!it->visited)
//    }
}

void PointLocation::Create_verticeslist(DoubleEdgeList *dcel) {
    //DoubleEdgeListVertex* new_vertex=dcel->vertices.front();

    for(int i=0;i<dcel->vertices.size();i++){
        PointLocationVertex new_vertex=PointLocationVertex(dcel->vertices.front());
//        new_vertex.vertex=dcel->vertices.front();
//
        for(int j=0;j<edges.size();j++){
            if(edges[j].v_l==new_vertex.vertex){
                new_vertex.edge_insert.push_back(&edges[j]);
            }
            if(edges[j].v_r==new_vertex.vertex){
                new_vertex.edge_delete.push_back(&edges[j]);
            }
        }

        dcel->vertices.pop_front();
        dcel->vertices.push_back(new_vertex.vertex);
        vertices.push_back(new_vertex);

        int s=vertices.size();
        s=s+0;
    }
}

void PointLocation::Create_PLTree() {
    pl_tree=PLRbTree(edges,vertices);
}

//void PointLocation::Find_location(double x, double y) {
//    int low=0;
//    int high=pl_tree.roots.size()-1;
//    int mid=0;
//    int location=-1;
//
//    if(x>=pl_tree.roots[low]&&x<pl_tree.roots[low+1]) {
//        location = low;
//    }
//    if(x>=pl_tree.roots[high]&&x<pl_tree.roots[high+1]) {
//        location = high;
//    }
//
//    while(location<0) {
//        mid=(low+high)/2;
//        if(x>=pl_tree.roots[mid]&&x<pl_tree.roots[mid+1])
//            location=mid;
//        if(x<pl_tree.roots[mid]){
//            high=mid;
//        }
//        if(x>pl_tree.roots[mid+1])
//            low=mid;
//    }
//}

<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright NumFOCUS
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/
#ifndef itkImageRegionConstIteratorWithIndex_hxx
#define itkImageRegionConstIteratorWithIndex_hxx

#include "itkImageRegionConstIteratorWithIndex.h"

namespace itk
{
//----------------------------------------------------------------------
//  Advance along the line
//----------------------------------------------------------------------
template <typename TImage>
ImageRegionConstIteratorWithIndex<TImage> &
ImageRegionConstIteratorWithIndex<TImage>::operator++()
{
  this->m_Remaining = false;
  for (unsigned int in = 0; in < TImage::ImageDimension; in++)
  {
    this->m_PositionIndex[in]++;
    if (this->m_PositionIndex[in] < this->m_EndIndex[in])
    {
      this->m_Position += this->m_OffsetTable[in];
      this->m_Remaining = true;
      break;
    }
    else
    {
      this->m_Position -= this->m_OffsetTable[in] * (static_cast<OffsetValueType>(this->m_Region.GetSize()[in]) - 1);
      this->m_PositionIndex[in] = this->m_BeginIndex[in];
    }
  }

  if (!this->m_Remaining) // It will not advance here otherwise
  {
    this->m_Position = this->m_End;
  }

  return *this;
}

//----------------------------------------------------------------------
//  Advance along the line in reverse direction
//----------------------------------------------------------------------
template <typename TImage>
ImageRegionConstIteratorWithIndex<TImage> &
ImageRegionConstIteratorWithIndex<TImage>::operator--()
{
  this->m_Remaining = false;
  for (unsigned int in = 0; in < TImage::ImageDimension; in++)
  {
    if (this->m_PositionIndex[in] > this->m_BeginIndex[in])
    {
      this->m_PositionIndex[in]--;
      this->m_Position -= this->m_OffsetTable[in];
      this->m_Remaining = true;
      break;
    }
    else
    {
      this->m_Position += this->m_OffsetTable[in] * (static_cast<OffsetValueType>(this->m_Region.GetSize()[in]) - 1);
      this->m_PositionIndex[in] = this->m_EndIndex[in] - 1;
    }
  }

  if (!this->m_Remaining) // It will not advance here otherwise
  {
    this->m_Position = this->m_End;
  }

  return *this;
}
} // end namespace itk

#endif
<commit_msg>COMP: Fix -Wstrict-overflow warning in itkImageRegionConstIteratorWithIndex<commit_after>/*=========================================================================
 *
 *  Copyright NumFOCUS
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/
#ifndef itkImageRegionConstIteratorWithIndex_hxx
#define itkImageRegionConstIteratorWithIndex_hxx

#include "itkImageRegionConstIteratorWithIndex.h"

namespace itk
{
//----------------------------------------------------------------------
//  Advance along the line
//----------------------------------------------------------------------
template <typename TImage>
ImageRegionConstIteratorWithIndex<TImage> &
ImageRegionConstIteratorWithIndex<TImage>::operator++()
{
  this->m_Remaining = false;
  for (unsigned int in = 0; in < TImage::ImageDimension; in++)
  {
    const IndexValueType positionIndex = ++this->m_PositionIndex[in];
    if (positionIndex < this->m_EndIndex[in])
    {
      this->m_Position += this->m_OffsetTable[in];
      this->m_Remaining = true;
      break;
    }
    else
    {
      this->m_Position -= this->m_OffsetTable[in] * (static_cast<OffsetValueType>(this->m_Region.GetSize()[in]) - 1);
      this->m_PositionIndex[in] = this->m_BeginIndex[in];
    }
  }

  if (!this->m_Remaining) // It will not advance here otherwise
  {
    this->m_Position = this->m_End;
  }

  return *this;
}

//----------------------------------------------------------------------
//  Advance along the line in reverse direction
//----------------------------------------------------------------------
template <typename TImage>
ImageRegionConstIteratorWithIndex<TImage> &
ImageRegionConstIteratorWithIndex<TImage>::operator--()
{
  this->m_Remaining = false;
  for (unsigned int in = 0; in < TImage::ImageDimension; in++)
  {
    if (this->m_PositionIndex[in] > this->m_BeginIndex[in])
    {
      this->m_PositionIndex[in]--;
      this->m_Position -= this->m_OffsetTable[in];
      this->m_Remaining = true;
      break;
    }
    else
    {
      this->m_Position += this->m_OffsetTable[in] * (static_cast<OffsetValueType>(this->m_Region.GetSize()[in]) - 1);
      this->m_PositionIndex[in] = this->m_EndIndex[in] - 1;
    }
  }

  if (!this->m_Remaining) // It will not advance here otherwise
  {
    this->m_Position = this->m_End;
  }

  return *this;
}
} // end namespace itk

#endif
<|endoftext|>


<commit_before>
#include "catch.hpp"

#include <iostream>
#include <cstring>
#include <mapnik/color.hpp>
#include <mapnik/image.hpp>
#include <mapnik/image_reader.hpp>
#include <mapnik/image_util.hpp>
#include <mapnik/image_util_jpeg.hpp>
#include <mapnik/util/fs.hpp>
#if defined(HAVE_CAIRO)
#include <mapnik/cairo/cairo_context.hpp>
#include <mapnik/cairo/cairo_image_util.hpp>
#endif

#pragma GCC diagnostic push
#include <mapnik/warning_ignore.hpp>
#include <boost/format.hpp>
#include <boost/filesystem/convenience.hpp>
#pragma GCC diagnostic pop

inline void make_directory(std::string const& dir) {
    boost::filesystem::create_directories(dir);
}

TEST_CASE("image io") {

SECTION("readers") {

    std::string should_throw;
    boost::optional<std::string> type;
    try
    {
        mapnik::image_rgba8 im_og;
        auto im_size = mapnik::image_rgba8::pixel_size * im_og.width() * im_og.height();
        mapnik::detail::buffer buf(im_og.bytes(), im_size);
        mapnik::image_rgba8 im2(im_og.width(), im_og.height(), buf.data());
        CHECK( im2.bytes() == im_og.bytes() );
#if defined(HAVE_JPEG)
        should_throw = "./test/data/images/blank.jpg";
        REQUIRE( mapnik::util::exists( should_throw ) );
        type = mapnik::type_from_filename(should_throw);
        REQUIRE( type );
        REQUIRE_THROWS(std::unique_ptr<mapnik::image_reader> reader(mapnik::get_image_reader(should_throw,*type)));

        // actually a png so jpeg reader should throw
        should_throw = "./test/data/images/landusepattern.jpg";
        REQUIRE( mapnik::util::exists( should_throw ) );
        type = mapnik::type_from_filename(should_throw);
        REQUIRE( type );
        try
        {
            std::unique_ptr<mapnik::image_reader> reader(mapnik::get_image_reader(should_throw,*type));
            REQUIRE(false);
        }
        catch (std::exception const& ex)
        {
            REQUIRE( std::string(ex.what()) == std::string("JPEG Reader: libjpeg could not read image: Not a JPEG file: starts with 0x89 0x50") );
        }

#endif

        REQUIRE_THROWS(mapnik::image_rgba8 im(-10,-10)); // should throw rather than overflow

#if defined(HAVE_CAIRO)
        mapnik::cairo_surface_ptr image_surface(
            cairo_image_surface_create(CAIRO_FORMAT_ARGB32,256,257),
            mapnik::cairo_surface_closer());
        mapnik::image_rgba8 im_data(cairo_image_surface_get_width(&*image_surface), cairo_image_surface_get_height(&*image_surface));
        im_data.set(1);
        REQUIRE( (unsigned)im_data(0,0) == unsigned(1) );
        // Should set back to fully transparent
        mapnik::cairo_image_to_rgba8(im_data, image_surface);
        REQUIRE( (unsigned)im_data(0,0) == unsigned(0) );
#endif

#if defined(HAVE_PNG)
        should_throw = "./test/data/images/blank.png";
        REQUIRE( mapnik::util::exists( should_throw ) );
        type = mapnik::type_from_filename(should_throw);
        REQUIRE( type );
        REQUIRE_THROWS(std::unique_ptr<mapnik::image_reader> reader(mapnik::get_image_reader(should_throw,*type)));

        should_throw = "./test/data/images/xcode-CgBI.png";
        REQUIRE( mapnik::util::exists( should_throw ) );
        type = mapnik::type_from_filename(should_throw);
        REQUIRE( type );
        REQUIRE_THROWS(std::unique_ptr<mapnik::image_reader> reader(mapnik::get_image_reader(should_throw,*type)));
#endif

#if defined(HAVE_TIFF)
        should_throw = "./test/data/images/blank.tiff";
        REQUIRE( mapnik::util::exists( should_throw ) );
        type = mapnik::type_from_filename(should_throw);
        REQUIRE( type );
        REQUIRE_THROWS(std::unique_ptr<mapnik::image_reader> reader(mapnik::get_image_reader(should_throw,*type)));
#endif

#if defined(HAVE_WEBP)
        should_throw = "./test/data/images/blank.webp";
        REQUIRE( mapnik::util::exists( should_throw ) );
        type = mapnik::type_from_filename(should_throw);
        REQUIRE( type );
        REQUIRE_THROWS(std::unique_ptr<mapnik::image_reader> reader(mapnik::get_image_reader(should_throw,*type)));
#endif
    }
    catch (std::exception const & ex)
    {
        std::clog << ex.what() << "\n";
        REQUIRE(false);
    }

} // END SECTION

SECTION("writers options")
{
#if defined(HAVE_JPEG)
    // test we can parse both jpegXX and quality=XX options
    REQUIRE_THROWS(mapnik::detail::parse_jpeg_quality("jpegXX"));
    REQUIRE_THROWS(mapnik::detail::parse_jpeg_quality("jpeg:quality=XX"));
    int q0 = mapnik::detail::parse_jpeg_quality("jpeg50");
    int q1 = mapnik::detail::parse_jpeg_quality("jpeg:quality=50");
    REQUIRE(q0 == q1);
#endif
} // END SECTION

SECTION("image_util : save_to_file/save_to_stream/save_to_string")
{
    mapnik::image_rgba8 im(256,256);
    std::string named_color = "lightblue";
    mapnik::fill(im, mapnik::color(named_color).rgba());
    ////////////////////////////////////////////////////
    std::vector<std::tuple<std::string, std::string> > supported_types;
#if defined(HAVE_PNG)
    supported_types.push_back(std::make_tuple("png","png"));
    supported_types.push_back(std::make_tuple("png","png24"));
    supported_types.push_back(std::make_tuple("png","png32"));
    supported_types.push_back(std::make_tuple("png","png8"));
    supported_types.push_back(std::make_tuple("png","png256"));
#endif
#if defined(HAVE_JPEG)
    supported_types.push_back(std::make_tuple("jpeg","jpeg"));
    supported_types.push_back(std::make_tuple("jpeg","jpeg80"));
    supported_types.push_back(std::make_tuple("jpeg","jpeg90"));
#endif
#if defined(HAVE_TIFF)
    supported_types.push_back(std::make_tuple("tiff","tiff"));
#endif
#if defined(HAVE_WEBP)
    supported_types.push_back(std::make_tuple("webp","webp"));
#endif

    std::string directory_name("/tmp/mapnik-tests/");
    make_directory(directory_name);
    REQUIRE(mapnik::util::exists(directory_name));

    for (auto const& info : supported_types)
    {
        std::string extension;
        std::string format;
        std::tie(extension, format) = info;
        std::string filename = (boost::format(directory_name + "mapnik-%1%.%2%") % named_color % extension).str();
        mapnik::save_to_file(im, filename);
        std::string str = mapnik::save_to_string(im, format);
        std::ostringstream ss;
        mapnik::save_to_stream(im, ss, format);
        CHECK(str.length() == ss.str().length());
        // wrap reader in scope to ensure the file handle is
        // released before we try to remove the file
        {
            std::unique_ptr<mapnik::image_reader> reader(mapnik::get_image_reader(filename, extension));
            unsigned w = reader->width();
            unsigned h = reader->height();
            auto im2 = reader->read(0, 0, w, h);
            CHECK(im2.size() == im.size());
            if (extension == "png" || extension == "tiff")
            {
                CHECK(0 == std::memcmp(im2.bytes(), im.bytes(), im.width() * im.height()));
            }
        }
        if (mapnik::util::exists(filename))
        {
            mapnik::util::remove(filename);
        }
    }
}
} // END TEST_CASE
<commit_msg>image - add tiny image quantising tests (ref #3466)<commit_after>#include "catch.hpp"

#include <cstring>
#include <mapnik/color.hpp>
#include <mapnik/image.hpp>
#include <mapnik/image_reader.hpp>
#include <mapnik/image_util.hpp>
#include <mapnik/image_util_jpeg.hpp>
#include <mapnik/util/fs.hpp>
#if defined(HAVE_CAIRO)
#include <mapnik/cairo/cairo_context.hpp>
#include <mapnik/cairo/cairo_image_util.hpp>
#endif

#pragma GCC diagnostic push
#include <mapnik/warning_ignore.hpp>
#include <boost/format.hpp>
#include <boost/filesystem/convenience.hpp>
#pragma GCC diagnostic pop

inline void make_directory(std::string const& dir) {
    boost::filesystem::create_directories(dir);
}

namespace {
template <typename T>
void check_tiny_png_image_quantising(T const& im)
{
    std::ostringstream ss(std::ios::binary);
    mapnik::save_to_stream(im, ss, "png8");
    ss.flush();
    std::string str = ss.str();
    std::unique_ptr<mapnik::image_reader> reader(mapnik::get_image_reader(str.data(), str.size()));
    auto w = reader->width();
    auto h = reader->height();
    CHECK(w > 0);
    CHECK(h > 0);
    auto im2 = mapnik::util::get<mapnik::image_rgba8>(reader->read(0, 0, w, h));
    for (std::size_t i = 0; i < w; ++i)
    {
        for (std::size_t j = 0; j < h; ++j)
        {
            REQUIRE(im2(i,j) == im(i,j));
        }
    }
}

}

TEST_CASE("image io") {

SECTION("readers") {

    std::string should_throw;
    boost::optional<std::string> type;
    try
    {
        mapnik::image_rgba8 im_og;
        auto im_size = mapnik::image_rgba8::pixel_size * im_og.width() * im_og.height();
        mapnik::detail::buffer buf(im_og.bytes(), im_size);
        mapnik::image_rgba8 im2(im_og.width(), im_og.height(), buf.data());
        CHECK( im2.bytes() == im_og.bytes() );
#if defined(HAVE_JPEG)
        should_throw = "./test/data/images/blank.jpg";
        REQUIRE( mapnik::util::exists( should_throw ) );
        type = mapnik::type_from_filename(should_throw);
        REQUIRE( type );
        REQUIRE_THROWS(std::unique_ptr<mapnik::image_reader> reader(mapnik::get_image_reader(should_throw,*type)));

        // actually a png so jpeg reader should throw
        should_throw = "./test/data/images/landusepattern.jpg";
        REQUIRE( mapnik::util::exists( should_throw ) );
        type = mapnik::type_from_filename(should_throw);
        REQUIRE( type );
        try
        {
            std::unique_ptr<mapnik::image_reader> reader(mapnik::get_image_reader(should_throw,*type));
            REQUIRE(false);
        }
        catch (std::exception const& ex)
        {
            REQUIRE( std::string(ex.what()) == std::string("JPEG Reader: libjpeg could not read image: Not a JPEG file: starts with 0x89 0x50") );
        }

#endif

        REQUIRE_THROWS(mapnik::image_rgba8 im(-10,-10)); // should throw rather than overflow

#if defined(HAVE_CAIRO)
        mapnik::cairo_surface_ptr image_surface(
            cairo_image_surface_create(CAIRO_FORMAT_ARGB32,256,257),
            mapnik::cairo_surface_closer());
        mapnik::image_rgba8 im_data(cairo_image_surface_get_width(&*image_surface), cairo_image_surface_get_height(&*image_surface));
        im_data.set(1);
        REQUIRE( (unsigned)im_data(0,0) == unsigned(1) );
        // Should set back to fully transparent
        mapnik::cairo_image_to_rgba8(im_data, image_surface);
        REQUIRE( (unsigned)im_data(0,0) == unsigned(0) );
#endif

#if defined(HAVE_PNG)
        should_throw = "./test/data/images/blank.png";
        REQUIRE( mapnik::util::exists( should_throw ) );
        type = mapnik::type_from_filename(should_throw);
        REQUIRE( type );
        REQUIRE_THROWS(std::unique_ptr<mapnik::image_reader> reader(mapnik::get_image_reader(should_throw,*type)));

        should_throw = "./test/data/images/xcode-CgBI.png";
        REQUIRE( mapnik::util::exists( should_throw ) );
        type = mapnik::type_from_filename(should_throw);
        REQUIRE( type );
        REQUIRE_THROWS(std::unique_ptr<mapnik::image_reader> reader(mapnik::get_image_reader(should_throw,*type)));
#endif

#if defined(HAVE_TIFF)
        should_throw = "./test/data/images/blank.tiff";
        REQUIRE( mapnik::util::exists( should_throw ) );
        type = mapnik::type_from_filename(should_throw);
        REQUIRE( type );
        REQUIRE_THROWS(std::unique_ptr<mapnik::image_reader> reader(mapnik::get_image_reader(should_throw,*type)));
#endif

#if defined(HAVE_WEBP)
        should_throw = "./test/data/images/blank.webp";
        REQUIRE( mapnik::util::exists( should_throw ) );
        type = mapnik::type_from_filename(should_throw);
        REQUIRE( type );
        REQUIRE_THROWS(std::unique_ptr<mapnik::image_reader> reader(mapnik::get_image_reader(should_throw,*type)));
#endif
    }
    catch (std::exception const & ex)
    {
        std::clog << ex.what() << "\n";
        REQUIRE(false);
    }

} // END SECTION

SECTION("writers options")
{
#if defined(HAVE_JPEG)
    // test we can parse both jpegXX and quality=XX options
    REQUIRE_THROWS(mapnik::detail::parse_jpeg_quality("jpegXX"));
    REQUIRE_THROWS(mapnik::detail::parse_jpeg_quality("jpeg:quality=XX"));
    int q0 = mapnik::detail::parse_jpeg_quality("jpeg50");
    int q1 = mapnik::detail::parse_jpeg_quality("jpeg:quality=50");
    REQUIRE(q0 == q1);
#endif
} // END SECTION

SECTION("image_util : save_to_file/save_to_stream/save_to_string")
{
    mapnik::image_rgba8 im(256,256);
    std::string named_color = "lightblue";
    mapnik::fill(im, mapnik::color(named_color).rgba());
    ////////////////////////////////////////////////////
    std::vector<std::tuple<std::string, std::string> > supported_types;
#if defined(HAVE_PNG)
    supported_types.push_back(std::make_tuple("png","png"));
    supported_types.push_back(std::make_tuple("png","png24"));
    supported_types.push_back(std::make_tuple("png","png32"));
    supported_types.push_back(std::make_tuple("png","png8"));
    supported_types.push_back(std::make_tuple("png","png256"));
#endif
#if defined(HAVE_JPEG)
    supported_types.push_back(std::make_tuple("jpeg","jpeg"));
    supported_types.push_back(std::make_tuple("jpeg","jpeg80"));
    supported_types.push_back(std::make_tuple("jpeg","jpeg90"));
#endif
#if defined(HAVE_TIFF)
    supported_types.push_back(std::make_tuple("tiff","tiff"));
#endif
#if defined(HAVE_WEBP)
    supported_types.push_back(std::make_tuple("webp","webp"));
#endif

    std::string directory_name("/tmp/mapnik-tests/");
    make_directory(directory_name);
    REQUIRE(mapnik::util::exists(directory_name));

    for (auto const& info : supported_types)
    {
        std::string extension;
        std::string format;
        std::tie(extension, format) = info;
        std::string filename = (boost::format(directory_name + "mapnik-%1%.%2%") % named_color % extension).str();
        mapnik::save_to_file(im, filename);
        std::string str = mapnik::save_to_string(im, format);
        std::ostringstream ss;
        mapnik::save_to_stream(im, ss, format);
        CHECK(str.length() == ss.str().length());
        // wrap reader in scope to ensure the file handle is
        // released before we try to remove the file
        {
            std::unique_ptr<mapnik::image_reader> reader(mapnik::get_image_reader(filename, extension));
            unsigned w = reader->width();
            unsigned h = reader->height();
            auto im2 = reader->read(0, 0, w, h);
            CHECK(im2.size() == im.size());
            if (extension == "png" || extension == "tiff")
            {
                CHECK(0 == std::memcmp(im2.bytes(), im.bytes(), im.width() * im.height()));
            }
        }
        if (mapnik::util::exists(filename))
        {
            mapnik::util::remove(filename);
        }
    }
}

SECTION("Quantising small (less than 3 pixel images preserve original colours")
{
#if defined(HAVE_PNG)
    { // 1x1
        mapnik::image_rgba8 im(1,1); // 1 pixel
        im(0,0) = mapnik::color("green").rgba();
        check_tiny_png_image_quantising(im);
    }
    { // 1x2
        mapnik::image_rgba8 im(1,2); // 2 pixels
        mapnik::fill(im, mapnik::color("red").rgba());
        im(0,0) = mapnik::color("green").rgba();
        check_tiny_png_image_quantising(im);
    }
    { // 2x1
        mapnik::image_rgba8 im(2,1); // 2 pixels
        mapnik::fill(im, mapnik::color("red").rgba());
        im(0,0) = mapnik::color("green").rgba();
        check_tiny_png_image_quantising(im);
    }
#endif
} // END SECTION

} // END TEST_CASE
<|endoftext|>


<commit_before>#pragma once

#include "CppUnitTest.h"

#include "..\Quantities\Dimensionless.hpp"
#include "..\Quantities\Quantities.hpp"

namespace Principia {
namespace TestUtilities {

// The Microsoft equivalent supports errors only for double.
template<typename ValueType, typename ErrorType>
void AssertEqualWithin(ValueType const& left,
                       ValueType const& right,
                       ErrorType const& ε) {
  std::wstring message = L"Should be equal within " + ToString(ε, 3) +
                         L": " + ToString(left) + L" and " + ToString(right) +
                         L".";
  LogLine(message);
  AssertTrue(left == right || Abs(left / right - 1) < ε, message);
}

template<typename ValueType, typename ErrorType>
void AssertNotEqualWithin(ValueType const& left,
                          ValueType const& right,
                          ErrorType const& ε) {
  std::wstring message = L"Should differ by more than " + ToString(ε, 3) +
                         L": " + ToString(left) + L" and " + ToString(right) +
                         L".";
  LogLine(message);
  AssertTrue(Abs(left / right - 1) > ε, message);
}

inline void WriteLog(std::wstring const& message) {
  Microsoft::VisualStudio::CppUnitTestFramework::Logger::WriteMessage(
      message.c_str());
}

inline void NewLine() {
  Microsoft::VisualStudio::CppUnitTestFramework::Logger::WriteMessage(L"\n");
}

// Equivalent to Log(message); Newline();
inline void LogLine(std::wstring const& message) {
  WriteLog(message);
  NewLine();
}

// The Microsoft equivalent only takes a wchar_t*.
inline void AssertTrue(bool const test, std::wstring const& message) {
  Microsoft::VisualStudio::CppUnitTestFramework::Assert::IsTrue(
      test,
      message.c_str());
}

}  // namespace TestUtilities
}  // namespace Principia
<commit_msg>Extraneous comments are redundant.<commit_after>#pragma once

#include "CppUnitTest.h"

#include "..\Quantities\Dimensionless.hpp"
#include "..\Quantities\Quantities.hpp"

namespace Principia {
namespace TestUtilities {

template<typename ValueType, typename ErrorType>
void AssertEqualWithin(ValueType const& left,
                       ValueType const& right,
                       ErrorType const& ε) {
  std::wstring message = L"Should be equal within " + ToString(ε, 3) +
                         L": " + ToString(left) + L" and " + ToString(right) +
                         L".";
  LogLine(message);
  AssertTrue(left == right || Abs(left / right - 1) < ε, message);
}

template<typename ValueType, typename ErrorType>
void AssertNotEqualWithin(ValueType const& left,
                          ValueType const& right,
                          ErrorType const& ε) {
  std::wstring message = L"Should differ by more than " + ToString(ε, 3) +
                         L": " + ToString(left) + L" and " + ToString(right) +
                         L".";
  LogLine(message);
  AssertTrue(Abs(left / right - 1) > ε, message);
}

inline void WriteLog(std::wstring const& message) {
  Microsoft::VisualStudio::CppUnitTestFramework::Logger::WriteMessage(
      message.c_str());
}

inline void NewLine() {
  Microsoft::VisualStudio::CppUnitTestFramework::Logger::WriteMessage(L"\n");
}

inline void LogLine(std::wstring const& message) {
  WriteLog(message);
  NewLine();
}

inline void AssertTrue(bool const test, std::wstring const& message) {
  Microsoft::VisualStudio::CppUnitTestFramework::Assert::IsTrue(
      test,
      message.c_str());
}

}  // namespace TestUtilities
}  // namespace Principia
<|endoftext|>


<commit_before>/*=========================================================================

Program:   Insight Segmentation & Registration Toolkit
Module:    $RCSfile$
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include <list>
#include <itkImage.h>
#include <itkITTFilterContext.h>
#include <itkImageToTreeFilter.h>
#include <itkStartPointData.h>
#include <itkTubeSegmentModel.h>
#include <itkRegistrationModelXMLWriter.h>

#include <mitkVesselTreeData.h>

// image type
typedef unsigned char   PixelType;
const unsigned int      Dimension = 3;
typedef itk::Image<PixelType, Dimension>            ImageType;
typedef ImageType::Pointer                          ImagePointer;
typedef ImageType::PointType                        PointType;
typedef ImageType::DirectionType                    DirectionType;

// tree type
typedef mitk::VesselTreeData                        OutputTreeType;
typedef OutputTreeType::Pointer                     OutputTreePointer;

//   typedef itk::ImageFileReader<ImageType>         ImageReaderType;
//   typedef ImageReaderType::Pointer                ImageReaderPointer;

// test classes
typedef itk::ImageToTreeFilter<ImageType, OutputTreeType>
                                                    ImageToTreeFilterType;
typedef ImageToTreeFilterType::Pointer              ImageToTreeFilterPointer;
typedef itk::ITTFilterContext<ImageType, OutputTreeType>
                                                    FilterContextType;
typedef FilterContextType::Pointer                  FilterContextPointer;
typedef FilterContextType::StartPointQueueType      StartPointQueueType;
typedef itk::StartPointData<ImageType>              StartPointDataType;
typedef StartPointDataType::Pointer                 StartPointDataPointer;

typedef itk::TubeSegmentModel<PixelType, DirectionType>
                                                    TubeSegmentModelType;
typedef TubeSegmentModelType::Pointer               TubeSegmentModelPointer;

typedef itk::RegistrationModel<PixelType, DirectionType>
                                                    RegistrationModelType;

typedef itk::RegistrationModelXMLWriter<RegistrationModelType>
                                                    RegistrationModelWriterType;
typedef RegistrationModelWriterType::Pointer        RegistrationModelWriterPointer;

typedef std::list<int>                              ResultListType;

/******************************************************************
 * TEST 1: Saving and loading data objects to the filter context
 *****************************************************************/
int testFilterContext()
{
  // init some test data
  PointType testPoint1;
  testPoint1.Fill(0);
  DirectionType testDirection1;
  testDirection1.Fill(0);
  StartPointDataPointer data1 = StartPointDataType::New();
  data1->SetStartPoint(&testPoint1);
  data1->SetStartDirection(&testDirection1);

  PointType testPoint2;
  testPoint2.Fill(1);
  DirectionType testDirection2;
  testDirection2.Fill(0);
  StartPointDataPointer data2 = StartPointDataType::New();
  data2->SetStartPoint(&testPoint2);
  data2->SetStartDirection(&testDirection2);

  std::cout << " *** Testing ITTFilterContext for storage of objects ***\n";
  FilterContextPointer filterContext = FilterContextType::New();

  StartPointQueueType* pointQueue1 = filterContext->GetStartPointQueue();
  std::cout << "Pushing points to filter context...\n";
  pointQueue1->push(data1);
  pointQueue1->push(data2);

  std::cout << "Reading points from filter context...\n";
  StartPointQueueType* pointQueue2 = filterContext->GetStartPointQueue();
  if (pointQueue2->front() == data1)
  {
    pointQueue2->pop();
  }
  else
  {
    std::cout << "Points not in queue.\n";
    std::cout << "[TEST FAILED]\n";
    return EXIT_FAILURE;
  }

  if (pointQueue2->front() == data2)
  {
    pointQueue2->pop();
  }
  else
  {
    std::cout << "Points not in queue.\n";
    std::cout << " *** [TEST FAILED] ***\n";
    return EXIT_FAILURE;
  }

  std::cout << " *** [TEST PASSED] ***\n";
  return EXIT_SUCCESS;
}

/****************************************************************
 * TEST 2: Initialising the filter
 ****************************************************************/
 // TODO: test init of image
int testInitFilter()
{
    // init some test data
  PointType testPoint1;
  testPoint1.Fill(0);

  DirectionType testDirection1;
  testDirection1.Fill(0);

  std::cout << " *** Testing initialization of filter ***\n";
  std::cout << "Loading new StartPointData to filter...\n";
  ImageToTreeFilterPointer testFilter = ImageToTreeFilterType::New();
  testFilter->SetStartPoint(&testPoint1);
  testFilter->SetStartDirection(&testDirection1);

  // start point should be the first point in the filter
  std::cout << "Reading StartPointData from filter...\n";
  FilterContextPointer testFilterContext = testFilter->GetFilterContext();
  StartPointQueueType* testQueue = testFilterContext->GetStartPointQueue();
  StartPointDataPointer testData = testQueue->front();
  PointType* testPoint2 = testData->GetStartPoint();
  DirectionType* testDirection2 = testData->GetStartDirection();

  if(testPoint1 != *testPoint2)
  {
    std::cout << "Startpoint not in queue.\n";
    std::cout << " *** [TEST FAILED] ***\n";
    return EXIT_FAILURE;
  }

  if(testDirection1 != *testDirection2)
  {
    std::cout << "Startdirection not in queue.\n";
    std::cout << " *** [TEST FAILED] ***\n";
    return EXIT_FAILURE;
  }

  std::cout << " *** [TEST PASSED] ***\n";
  return EXIT_SUCCESS;
}

/****************************************************************
 * TEST 3: TubeSegmentModel
 ****************************************************************/
int testTubeSegmentModel()
{
  std::cout << " *** Testing the tube segments ***\n";
  TubeSegmentModelPointer tubeSegment = TubeSegmentModelType::New();

  std::cout << " *** [TEST PASSED] ***\n";
  return EXIT_SUCCESS;
}

/****************************************************************
 * TEST 4: XML Writer
 ****************************************************************/
int testRegistrationModelXMLWriter()
{
  std::cout << " *** Testing the RegistrationModelXMLWriter ***\n";
  RegistrationModelWriterPointer modelWriter = RegistrationModelWriterType::New();

  std::cout << " *** [TEST PASSED] ***\n";
  return EXIT_SUCCESS;
}

int itkImageToTreeFilterTest(int, char* argv[] )
{
  ResultListType resultList;
  int failedCount = 0;
  int testCount;
  float failRatio;

  // run all tests
  resultList.push_back(testFilterContext());
  resultList.push_back(testInitFilter());
  resultList.push_back(testTubeSegmentModel());
  resultList.push_back(testRegistrationModelXMLWriter());

  std::cout << " *** [ALL TESTS DONE] ***\n";

  testCount = resultList.size();

  while (resultList.size() > 0)
  {
    int value = resultList.front();
    if(value == EXIT_FAILURE) { failedCount++; }
    resultList.pop_front();
  }

  failRatio = 100 * (float) failedCount / (float) testCount;

  std::cout << "Result: ";
  std::cout << failedCount;
  std::cout << "/";
  std::cout << testCount;
  std::cout << " Tests failed (";
  std::cout << failRatio;
  std::cout << " %)\n";

  return EXIT_SUCCESS;
}
<commit_msg>- xml writer is working - new structure with cli-program for generation<commit_after>/*=========================================================================

Program:   Insight Segmentation & Registration Toolkit
Module:    $RCSfile$
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include <list>
#include <itkImage.h>
#include <itkTreeContainer.h>

#include <itkImageToTreeFilter.h>
#include <itkITTFilterContext.h>
#include <itkRegistrationModelXMLWriter.h>
#include <itkStartPointData.h>
#include <itkTubeSegmentModel.h>

// image type
typedef unsigned char   PixelType;
const unsigned int      Dimension = 3;
typedef itk::Image<PixelType, Dimension>              ImageType;
typedef ImageType::Pointer                            ImagePointer;
typedef ImageType::PointType                          PointType;
typedef ImageType::DirectionType                      DirectionType;

typedef itk::RegistrationModel<PixelType>             RegistrationModelType;
typedef RegistrationModelType::Pointer                RegistrationModelPointer;

// tree type
typedef itk::TreeContainer<RegistrationModelPointer>  OutputTreeType;
typedef OutputTreeType::Pointer                       OutputTreePointer;

// test classes
typedef itk::ImageToTreeFilter<ImageType, OutputTreeType>
                                                      ImageToTreeFilterType;
typedef ImageToTreeFilterType::Pointer                ImageToTreeFilterPointer;
typedef itk::ITTFilterContext<ImageType, OutputTreeType>
                                                      FilterContextType;
typedef FilterContextType::Pointer                    FilterContextPointer;
typedef FilterContextType::StartPointQueueType        StartPointQueueType;
typedef itk::StartPointData<ImageType>                StartPointDataType;
typedef StartPointDataType::Pointer                   StartPointDataPointer;

typedef itk::TubeSegmentModel<PixelType>              TubeSegmentModelType;
typedef TubeSegmentModelType::Pointer                 TubeSegmentModelPointer;

typedef itk::RegistrationModelXMLWriter<TubeSegmentModelType>
                                                      RegistrationModelWriterType;
typedef RegistrationModelWriterType::Pointer          RegistrationModelWriterPointer;

typedef std::list<int>                                ResultListType;

/******************************************************************
 * TEST 1: Saving and loading data objects to the filter context
 *****************************************************************/
int testFilterContext()
{
  // init some test data
  PointType testPoint1;
  testPoint1.Fill(0);
  DirectionType testDirection1;
  testDirection1.Fill(0);
  StartPointDataPointer data1 = StartPointDataType::New();
  data1->SetStartPoint(&testPoint1);
  data1->SetStartDirection(&testDirection1);

  PointType testPoint2;
  testPoint2.Fill(1);
  DirectionType testDirection2;
  testDirection2.Fill(0);
  StartPointDataPointer data2 = StartPointDataType::New();
  data2->SetStartPoint(&testPoint2);
  data2->SetStartDirection(&testDirection2);

  std::cout << " *** Testing ITTFilterContext for storage of objects ***\n";
  FilterContextPointer filterContext = FilterContextType::New();

  StartPointQueueType* pointQueue1 = filterContext->GetStartPointQueue();
  std::cout << "Pushing points to filter context...\n";
  pointQueue1->push(data1);
  pointQueue1->push(data2);

  std::cout << "Reading points from filter context...\n";
  StartPointQueueType* pointQueue2 = filterContext->GetStartPointQueue();
  if (pointQueue2->front() == data1)
  {
    pointQueue2->pop();
  }
  else
  {
    std::cout << "Points not in queue.\n";
    std::cout << "[TEST FAILED]\n";
    return EXIT_FAILURE;
  }

  if (pointQueue2->front() == data2)
  {
    pointQueue2->pop();
  }
  else
  {
    std::cout << "Points not in queue.\n";
    std::cout << " *** [TEST FAILED] ***\n";
    return EXIT_FAILURE;
  }

  std::cout << " *** [TEST PASSED] ***\n";
  return EXIT_SUCCESS;
}

/****************************************************************
 * TEST 2: Initialising the filter
 ****************************************************************/
 // TODO: test init of image
int testInitFilter()
{
    // init some test data
  PointType testPoint1;
  testPoint1.Fill(0);

  DirectionType testDirection1;
  testDirection1.Fill(0);

  std::cout << " *** Testing initialization of filter ***\n";
  std::cout << "Loading new StartPointData to filter...\n";
  ImageToTreeFilterPointer testFilter = ImageToTreeFilterType::New();
  testFilter->SetStartPoint(&testPoint1);
  testFilter->SetStartDirection(&testDirection1);

  // start point should be the first point in the filter
  std::cout << "Reading StartPointData from filter...\n";
  FilterContextPointer testFilterContext = testFilter->GetFilterContext();
  StartPointQueueType* testQueue = testFilterContext->GetStartPointQueue();
  StartPointDataPointer testData = testQueue->front();
  PointType* testPoint2 = testData->GetStartPoint();
  DirectionType* testDirection2 = testData->GetStartDirection();

  if(testPoint1 != *testPoint2)
  {
    std::cout << "Startpoint not in queue.\n";
    std::cout << " *** [TEST FAILED] ***\n";
    return EXIT_FAILURE;
  }

  if(testDirection1 != *testDirection2)
  {
    std::cout << "Startdirection not in queue.\n";
    std::cout << " *** [TEST FAILED] ***\n";
    return EXIT_FAILURE;
  }

  std::cout << " *** [TEST PASSED] ***\n";
  return EXIT_SUCCESS;
}

/****************************************************************
 * TEST 3: XML Writer
 ****************************************************************/
int testRegistrationModelXMLWriter()
{
  std::cout << " *** Testing the RegistrationModelXMLWriter ***\n";

  typedef TubeSegmentModelType::PointSetType          PointSetType;
  typedef PointSetType::Pointer                       PointSetPointer;
  typedef PointSetType::PointType                     PointType;
  typedef PointSetType::PointsContainer               PointsContainerType;
  typedef PointsContainerType::Pointer                PointsContainerPointer;
  typedef PointsContainerType::ElementIdentifier      ElementIdentifier;
  typedef PointSetType::PointDataContainer            PointDataContainerType;
  typedef PointDataContainerType::Pointer             PointDataContainerPointer;

  TubeSegmentModelPointer tubeSegment = TubeSegmentModelType::New();
  ElementIdentifier index = 0;
  PointSetPointer pointSet = PointSetType::New();
  PointsContainerPointer pointsContainer = PointsContainerType::New();
  PointDataContainerPointer pointDataContainer = PointDataContainerType::New();

  // init test data
  PointType startPoint;
  startPoint.Fill(0);
  tubeSegment->SetStartPoint(&startPoint);

  PointType point1; // 1, 1, 0
  point1[0] = 1;
  point1[1] = 1;
  point1[2] = 0;
//   pointsContainer->InsertElement(index, &point1);
//   pointDataContainer->InsertElement(index, 1);
  index++;

  PointType point2; // 1, 0, 1
  point2[0] = 1;
  point2[1] = 0;
  point2[2] = 1;
//   pointsContainer->InsertElement(index, &point2);
//   pointDataContainer->InsertElement(index, 1);
  index++;

  PointType point3; // 1, 0, 1
  point3[0] = 1;
  point3[1] = 0;
  point3[2] = 1;
//   pointsContainer->InsertElement(index, &point3);
//   pointDataContainer->InsertElement(index, 1);
  index++;

  pointSet->SetPoints(pointsContainer);
  pointSet->SetPointData(pointDataContainer);
  tubeSegment->SetPointSet(pointSet);

  RegistrationModelWriterPointer modelWriter = RegistrationModelWriterType::New();
  modelWriter->SetRegistrationModel(tubeSegment);
  modelWriter->SetFilename("test.xml");
  modelWriter->WriteFile();

  // TODO: compare to normal data

  std::cout << " *** [TEST PASSED] ***\n";
  return EXIT_SUCCESS;
}

int itkImageToTreeFilterTest(int i, char* argv[] )
{
  ResultListType resultList;
  int failedCount = 0;
  int testCount;
  float failRatio;

  // run all tests
  resultList.push_back(testFilterContext());
  resultList.push_back(testInitFilter());
  resultList.push_back(testRegistrationModelXMLWriter());

  std::cout << " *** [ALL TESTS DONE] ***\n";

  testCount = resultList.size();

  while (resultList.size() > 0)
  {
    int value = resultList.front();
    if(value == EXIT_FAILURE) { failedCount++; }
    resultList.pop_front();
  }

  failRatio = 100 * (float) failedCount / (float) testCount;

  std::cout << "Result: ";
  std::cout << failedCount;
  std::cout << "/";
  std::cout << testCount;
  std::cout << " Tests failed (";
  std::cout << failRatio;
  std::cout << " %)\n";

  return EXIT_SUCCESS;
}
<|endoftext|>