<commit_before>//===-- MCJIT.cpp - MC-based Just-in-Time Compiler --------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "MCJIT.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Function.h"
#include "llvm/ExecutionEngine/GenericValue.h"
#include "llvm/ExecutionEngine/MCJIT.h"
#include "llvm/ExecutionEngine/JITMemoryManager.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/DynamicLibrary.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Target/TargetData.h"

using namespace llvm;

namespace {

static struct RegisterJIT {
  RegisterJIT() { MCJIT::Register(); }
} JITRegistrator;

}

extern "C" void LLVMLinkInMCJIT() {
}

ExecutionEngine *MCJIT::createJIT(Module *M,
                                  std::string *ErrorStr,
                                  JITMemoryManager *JMM,
                                  CodeGenOpt::Level OptLevel,
                                  bool GVsWithCode,
                                  CodeModel::Model CMM,
                                  StringRef MArch,
                                  StringRef MCPU,
                                  const SmallVectorImpl<std::string>& MAttrs) {
  // Try to register the program as a source of symbols to resolve against.
  //
  // FIXME: Don't do this here.
  sys::DynamicLibrary::LoadLibraryPermanently(0, NULL);

  // Pick a target either via -march or by guessing the native arch.
  //
  // FIXME: This should be lifted out of here, it isn't something which should
  // be part of the JIT policy, rather the burden for this selection should be
  // pushed to clients.
  TargetMachine *TM = MCJIT::selectTarget(M, MArch, MCPU, MAttrs, ErrorStr);
  if (!TM || (ErrorStr && ErrorStr->length() > 0)) return 0;
  TM->setCodeModel(CMM);

  // If the target supports JIT code generation, create the JIT.
  if (TargetJITInfo *TJ = TM->getJITInfo())
    return new MCJIT(M, TM, *TJ, JMM, OptLevel, GVsWithCode);

  if (ErrorStr)
    *ErrorStr = "target does not support JIT code generation";
  return 0;
}

MCJIT::MCJIT(Module *m, TargetMachine *tm, TargetJITInfo &tji,
             JITMemoryManager *JMM, CodeGenOpt::Level OptLevel,
             bool AllocateGVsWithCode)
  : ExecutionEngine(m), TM(tm), M(m), OS(Buffer) {

  PM.add(new TargetData(*TM->getTargetData()));

  // Turn the machine code intermediate representation into bytes in memory
  // that may be executed.
  if (TM->addPassesToEmitMC(PM, Ctx, OS, CodeGenOpt::Default, false)) {
    report_fatal_error("Target does not support MC emission!");
  }

  // Initialize passes.
  ExecutionEngine::addModule(M);
  // FIXME: When we support multiple modules, we'll want to move the code
  // gen and finalization out of the constructor here and do it more
  // on-demand as part of getPointerToFunction().
  PM.run(*M);
  // Flush the output buffer so the SmallVector gets its data.
  OS.flush();

  // Load the object into the dynamic linker.
  // FIXME: It would be nice to avoid making yet another copy.
  MemoryBuffer *MB = MemoryBuffer::getMemBufferCopy(StringRef(Buffer.data(),
                                                              Buffer.size()));
  Dyld.loadObject(MB);
}

MCJIT::~MCJIT() {
}

void *MCJIT::getPointerToBasicBlock(BasicBlock *BB) {
  report_fatal_error("not yet implemented");
  return 0;
}

void *MCJIT::getPointerToFunction(Function *F) {
  if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
    bool AbortOnFailure = !F->hasExternalWeakLinkage();
    void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
    addGlobalMapping(F, Addr);
    return Addr;
  }

  Twine Name = TM->getMCAsmInfo()->getGlobalPrefix() + F->getName();
  return Dyld.getSymbolAddress(Name.str());
}

void *MCJIT::recompileAndRelinkFunction(Function *F) {
  report_fatal_error("not yet implemented");
}

void MCJIT::freeMachineCodeForFunction(Function *F) {
  report_fatal_error("not yet implemented");
}

GenericValue MCJIT::runFunction(Function *F,
                                const std::vector<GenericValue> &ArgValues) {
  assert(F && "Function *F was null at entry to run()");

  void *FPtr = getPointerToFunction(F);
  assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
  const FunctionType *FTy = F->getFunctionType();
  const Type *RetTy = FTy->getReturnType();

  assert((FTy->getNumParams() == ArgValues.size() ||
          (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
         "Wrong number of arguments passed into function!");
  assert(FTy->getNumParams() == ArgValues.size() &&
         "This doesn't support passing arguments through varargs (yet)!");

  // Handle some common cases first.  These cases correspond to common `main'
  // prototypes.
  if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
    switch (ArgValues.size()) {
    case 3:
      if (FTy->getParamType(0)->isIntegerTy(32) &&
          FTy->getParamType(1)->isPointerTy() &&
          FTy->getParamType(2)->isPointerTy()) {
        int (*PF)(int, char **, const char **) =
          (int(*)(int, char **, const char **))(intptr_t)FPtr;

        // Call the function.
        GenericValue rv;
        rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
                                 (char **)GVTOP(ArgValues[1]),
                                 (const char **)GVTOP(ArgValues[2])));
        return rv;
      }
      break;
    case 2:
      if (FTy->getParamType(0)->isIntegerTy(32) &&
          FTy->getParamType(1)->isPointerTy()) {
        int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;

        // Call the function.
        GenericValue rv;
        rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
                                 (char **)GVTOP(ArgValues[1])));
        return rv;
      }
      break;
    case 1:
      if (FTy->getNumParams() == 1 &&
          FTy->getParamType(0)->isIntegerTy(32)) {
        GenericValue rv;
        int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
        rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
        return rv;
      }
      break;
    }
  }

  // Handle cases where no arguments are passed first.
  if (ArgValues.empty()) {
    GenericValue rv;
    switch (RetTy->getTypeID()) {
    default: llvm_unreachable("Unknown return type for function call!");
    case Type::IntegerTyID: {
      unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
      if (BitWidth == 1)
        rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
      else if (BitWidth <= 8)
        rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
      else if (BitWidth <= 16)
        rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
      else if (BitWidth <= 32)
        rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
      else if (BitWidth <= 64)
        rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
      else
        llvm_unreachable("Integer types > 64 bits not supported");
      return rv;
    }
    case Type::VoidTyID:
      rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
      return rv;
    case Type::FloatTyID:
      rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
      return rv;
    case Type::DoubleTyID:
      rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
      return rv;
    case Type::X86_FP80TyID:
    case Type::FP128TyID:
    case Type::PPC_FP128TyID:
      llvm_unreachable("long double not supported yet");
      return rv;
    case Type::PointerTyID:
      return PTOGV(((void*(*)())(intptr_t)FPtr)());
    }
  }

  assert("Full-featured argument passing not supported yet!");
  return GenericValue();
}
<commit_msg>Make sure to report any errors from the runtime dyld.<commit_after>//===-- MCJIT.cpp - MC-based Just-in-Time Compiler --------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "MCJIT.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Function.h"
#include "llvm/ExecutionEngine/GenericValue.h"
#include "llvm/ExecutionEngine/MCJIT.h"
#include "llvm/ExecutionEngine/JITMemoryManager.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/DynamicLibrary.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Target/TargetData.h"

using namespace llvm;

namespace {

static struct RegisterJIT {
  RegisterJIT() { MCJIT::Register(); }
} JITRegistrator;

}

extern "C" void LLVMLinkInMCJIT() {
}

ExecutionEngine *MCJIT::createJIT(Module *M,
                                  std::string *ErrorStr,
                                  JITMemoryManager *JMM,
                                  CodeGenOpt::Level OptLevel,
                                  bool GVsWithCode,
                                  CodeModel::Model CMM,
                                  StringRef MArch,
                                  StringRef MCPU,
                                  const SmallVectorImpl<std::string>& MAttrs) {
  // Try to register the program as a source of symbols to resolve against.
  //
  // FIXME: Don't do this here.
  sys::DynamicLibrary::LoadLibraryPermanently(0, NULL);

  // Pick a target either via -march or by guessing the native arch.
  //
  // FIXME: This should be lifted out of here, it isn't something which should
  // be part of the JIT policy, rather the burden for this selection should be
  // pushed to clients.
  TargetMachine *TM = MCJIT::selectTarget(M, MArch, MCPU, MAttrs, ErrorStr);
  if (!TM || (ErrorStr && ErrorStr->length() > 0)) return 0;
  TM->setCodeModel(CMM);

  // If the target supports JIT code generation, create the JIT.
  if (TargetJITInfo *TJ = TM->getJITInfo())
    return new MCJIT(M, TM, *TJ, JMM, OptLevel, GVsWithCode);

  if (ErrorStr)
    *ErrorStr = "target does not support JIT code generation";
  return 0;
}

MCJIT::MCJIT(Module *m, TargetMachine *tm, TargetJITInfo &tji,
             JITMemoryManager *JMM, CodeGenOpt::Level OptLevel,
             bool AllocateGVsWithCode)
  : ExecutionEngine(m), TM(tm), M(m), OS(Buffer) {

  PM.add(new TargetData(*TM->getTargetData()));

  // Turn the machine code intermediate representation into bytes in memory
  // that may be executed.
  if (TM->addPassesToEmitMC(PM, Ctx, OS, CodeGenOpt::Default, false)) {
    report_fatal_error("Target does not support MC emission!");
  }

  // Initialize passes.
  ExecutionEngine::addModule(M);
  // FIXME: When we support multiple modules, we'll want to move the code
  // gen and finalization out of the constructor here and do it more
  // on-demand as part of getPointerToFunction().
  PM.run(*M);
  // Flush the output buffer so the SmallVector gets its data.
  OS.flush();

  // Load the object into the dynamic linker.
  // FIXME: It would be nice to avoid making yet another copy.
  MemoryBuffer *MB = MemoryBuffer::getMemBufferCopy(StringRef(Buffer.data(),
                                                              Buffer.size()));
  if (Dyld.loadObject(MB))
    report_fatal_error(Dyld.getErrorString());
}

MCJIT::~MCJIT() {
}

void *MCJIT::getPointerToBasicBlock(BasicBlock *BB) {
  report_fatal_error("not yet implemented");
  return 0;
}

void *MCJIT::getPointerToFunction(Function *F) {
  if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
    bool AbortOnFailure = !F->hasExternalWeakLinkage();
    void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
    addGlobalMapping(F, Addr);
    return Addr;
  }

  Twine Name = TM->getMCAsmInfo()->getGlobalPrefix() + F->getName();
  return Dyld.getSymbolAddress(Name.str());
}

void *MCJIT::recompileAndRelinkFunction(Function *F) {
  report_fatal_error("not yet implemented");
}

void MCJIT::freeMachineCodeForFunction(Function *F) {
  report_fatal_error("not yet implemented");
}

GenericValue MCJIT::runFunction(Function *F,
                                const std::vector<GenericValue> &ArgValues) {
  assert(F && "Function *F was null at entry to run()");

  void *FPtr = getPointerToFunction(F);
  assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
  const FunctionType *FTy = F->getFunctionType();
  const Type *RetTy = FTy->getReturnType();

  assert((FTy->getNumParams() == ArgValues.size() ||
          (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
         "Wrong number of arguments passed into function!");
  assert(FTy->getNumParams() == ArgValues.size() &&
         "This doesn't support passing arguments through varargs (yet)!");

  // Handle some common cases first.  These cases correspond to common `main'
  // prototypes.
  if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
    switch (ArgValues.size()) {
    case 3:
      if (FTy->getParamType(0)->isIntegerTy(32) &&
          FTy->getParamType(1)->isPointerTy() &&
          FTy->getParamType(2)->isPointerTy()) {
        int (*PF)(int, char **, const char **) =
          (int(*)(int, char **, const char **))(intptr_t)FPtr;

        // Call the function.
        GenericValue rv;
        rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
                                 (char **)GVTOP(ArgValues[1]),
                                 (const char **)GVTOP(ArgValues[2])));
        return rv;
      }
      break;
    case 2:
      if (FTy->getParamType(0)->isIntegerTy(32) &&
          FTy->getParamType(1)->isPointerTy()) {
        int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;

        // Call the function.
        GenericValue rv;
        rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
                                 (char **)GVTOP(ArgValues[1])));
        return rv;
      }
      break;
    case 1:
      if (FTy->getNumParams() == 1 &&
          FTy->getParamType(0)->isIntegerTy(32)) {
        GenericValue rv;
        int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
        rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
        return rv;
      }
      break;
    }
  }

  // Handle cases where no arguments are passed first.
  if (ArgValues.empty()) {
    GenericValue rv;
    switch (RetTy->getTypeID()) {
    default: llvm_unreachable("Unknown return type for function call!");
    case Type::IntegerTyID: {
      unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
      if (BitWidth == 1)
        rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
      else if (BitWidth <= 8)
        rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
      else if (BitWidth <= 16)
        rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
      else if (BitWidth <= 32)
        rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
      else if (BitWidth <= 64)
        rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
      else
        llvm_unreachable("Integer types > 64 bits not supported");
      return rv;
    }
    case Type::VoidTyID:
      rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
      return rv;
    case Type::FloatTyID:
      rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
      return rv;
    case Type::DoubleTyID:
      rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
      return rv;
    case Type::X86_FP80TyID:
    case Type::FP128TyID:
    case Type::PPC_FP128TyID:
      llvm_unreachable("long double not supported yet");
      return rv;
    case Type::PointerTyID:
      return PTOGV(((void*(*)())(intptr_t)FPtr)());
    }
  }

  assert("Full-featured argument passing not supported yet!");
  return GenericValue();
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2015 WinT 3794 <http://wint3794.org>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#include "LibDS/Core/ProtocolBase.h"

DS_ProtocolBase::DS_ProtocolBase() {
    m_team = 0;
    m_resetCount = 0;
    m_sentPackets = 0;
    m_robotCode = false;
    m_useFallbackAddress = false;
    m_communicationStatus = kFailing;
    m_alliance = kAllianceRed1;
    m_robotAddress = QString ("");
    m_controlMode = kControlDisabled;

    m_joysticks = new QList<DS_Joystick*>;

    connect (&m_watchdog, SIGNAL (timeout()), this, SLOT (reset()));
    connect (this, SIGNAL (packetReceived()), &m_watchdog, SLOT (restart()));
    connect (&m_pingSocket, SIGNAL (stateChanged   (QAbstractSocket::SocketState)),
             this,          SLOT   (onStateChanged (QAbstractSocket::SocketState)));
}

DS_ProtocolBase::~DS_ProtocolBase() {
    m_pingSocket.abort();
    delete m_joysticks;
}

quint16 DS_ProtocolBase::team() const {
    return m_team;
}

quint16 DS_ProtocolBase::status() const {
    return m_status;
}

bool DS_ProtocolBase::robotCode() const {
    return m_robotCode;
}

quint16 DS_ProtocolBase::sentPackets() const {
    return m_sentPackets;
}

bool DS_ProtocolBase::isConnected() const {
    return communicationStatus() == kFull;
}

bool DS_ProtocolBase::sendDateTime() const {
    return m_sendDateTime;
}

DS_Alliance DS_ProtocolBase::alliance() const {
    return m_alliance;
}

DS_ControlMode DS_ProtocolBase::controlMode() const {
    return m_controlMode;
}

DS_CommunicationStatus DS_ProtocolBase::communicationStatus() const {
    return m_communicationStatus;
}

QList<DS_Joystick*>* DS_ProtocolBase::joysticks() const {
    return m_joysticks;
}

QString DS_ProtocolBase::radioAddress() {
    return m_radioAddress.isEmpty() ? defaultRadioAddress() : m_radioAddress;
}

QString DS_ProtocolBase::robotAddress() {
    if (m_robotAddress.isEmpty()) {
        if (m_useFallbackAddress)
            return DS_GetStaticIp (team(), 2);
        else
            return defaultRobotAddress();
    }

    return m_robotAddress;
}

QByteArray DS_ProtocolBase::getClientPacket() {
    m_sentPackets += 1;
    return generateClientPacket();
}

void DS_ProtocolBase::reset() {
    resetProtocol();

    updateVoltage (0, 0);
    updateRobotCode (false);
    updateSendDateTime (false);
    updateCommunications (kFailing);

    /* Toggle the usage of the fallback robot address every 10 resets */
    m_resetCount += 1;
    if (m_resetCount >= 10) {
        m_resetCount = 0;
        m_useFallbackAddress = !m_useFallbackAddress;
    }

    /* Figure out the robot address and ping the robot */
    emit robotAddressChanged (robotAddress());
    m_discovery.getIp (robotAddress(), this, SLOT (onIpFound (QString, QString)));
}

void DS_ProtocolBase::setTeamNumber (quint16 team) {
    m_team = team;
    emit robotAddressChanged (robotAddress());
}

void DS_ProtocolBase::setRobotAddress (QString address) {
    m_robotAddress = address;
    emit robotAddressChanged (robotAddress());
}

void DS_ProtocolBase::setAlliance (DS_Alliance alliance) {
    m_alliance = alliance;
}

void DS_ProtocolBase::setControlMode (DS_ControlMode mode) {
    if (m_controlMode != kControlEmergencyStop) {
        m_controlMode = isConnected() ? mode : kControlDisabled;
        emit controlModeChanged (controlMode());
    }
}

void DS_ProtocolBase::setJoysticks (QList<DS_Joystick*>* joysticks) {
    m_joysticks = joysticks;
}

void DS_ProtocolBase::readRobotPacket (QByteArray data) {
    if (!data.isEmpty())
        readRobotData (data);
}

QByteArray DS_ProtocolBase::bitsToBytes (QBitArray bits) {
    QByteArray bytes (bits.count() / 8, 0);

    for (int i = 0; i < bits.count(); ++i)
        bytes [i / 8] = (bytes.at (i / 8) | ((bits [i] ? 1 : 0) << (i % 8)));

    return bytes;
}

void DS_ProtocolBase::updateStatus (quint8 status) {
    m_status = status;
}

void DS_ProtocolBase::updateRobotCode (bool available) {
    m_robotCode = available;
    emit codeChanged (m_robotCode);
}

void DS_ProtocolBase::updateSendDateTime (bool sendDT) {
    m_sendDateTime = sendDT;
}

void DS_ProtocolBase::updateCommunications (DS_CommunicationStatus status) {
    m_communicationStatus = status;
    emit communicationsChanged (m_communicationStatus);
}

void DS_ProtocolBase::updateVoltage (quint8 major, quint8 minor) {
    QString maj = QString::number (major);
    QString min = QString::number (minor);

    maj = maj.replace ("-", "");
    min = min.replace ("-", "");

    if (min.length() == 1)
        min = QString ("0%1").arg (min);

    else if (min.length() > 2)
        min = QString (min.at (0)) + QString (min.at (1));

    emit voltageChanged (QString ("%1.%2").arg (maj, min));
}

void DS_ProtocolBase::pingRobot() {
    m_pingSocket.abort();
    m_pingSocket.connectToHost (robotAddress(), 80, QTcpSocket::ReadOnly);
}

void DS_ProtocolBase::onIpFound (QString address, QString ip) {
    if (address.toLower() == robotAddress().toLower() && address != ip)
        emit robotAddressChanged (ip);

    pingRobot();
}

void DS_ProtocolBase::onStateChanged (QAbstractSocket::SocketState state) {
    if (communicationStatus() == kFailing
            && state == QAbstractSocket::ConnectedState)
        updateCommunications (kPartial);
}
<commit_msg>Update UI when robot code crashes<commit_after>/*
 * Copyright (c) 2015 WinT 3794 <http://wint3794.org>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#include "LibDS/Core/ProtocolBase.h"

DS_ProtocolBase::DS_ProtocolBase() {
    m_team = 0;
    m_resetCount = 0;
    m_sentPackets = 0;
    m_robotCode = false;
    m_useFallbackAddress = false;
    m_communicationStatus = kFailing;
    m_alliance = kAllianceRed1;
    m_robotAddress = QString ("");
    m_controlMode = kControlDisabled;

    m_joysticks = new QList<DS_Joystick*>;

    connect (&m_watchdog, SIGNAL (timeout()), this, SLOT (reset()));
    connect (this, SIGNAL (packetReceived()), &m_watchdog, SLOT (restart()));
    connect (&m_pingSocket, SIGNAL (stateChanged   (QAbstractSocket::SocketState)),
             this,          SLOT   (onStateChanged (QAbstractSocket::SocketState)));
}

DS_ProtocolBase::~DS_ProtocolBase() {
    m_pingSocket.abort();
    delete m_joysticks;
}

quint16 DS_ProtocolBase::team() const {
    return m_team;
}

quint16 DS_ProtocolBase::status() const {
    return m_status;
}

bool DS_ProtocolBase::robotCode() const {
    return m_robotCode;
}

quint16 DS_ProtocolBase::sentPackets() const {
    return m_sentPackets;
}

bool DS_ProtocolBase::isConnected() const {
    return communicationStatus() == kFull;
}

bool DS_ProtocolBase::sendDateTime() const {
    return m_sendDateTime;
}

DS_Alliance DS_ProtocolBase::alliance() const {
    return m_alliance;
}

DS_ControlMode DS_ProtocolBase::controlMode() const {
    return m_controlMode;
}

DS_CommunicationStatus DS_ProtocolBase::communicationStatus() const {
    return m_communicationStatus;
}

QList<DS_Joystick*>* DS_ProtocolBase::joysticks() const {
    return m_joysticks;
}

QString DS_ProtocolBase::radioAddress() {
    return m_radioAddress.isEmpty() ? defaultRadioAddress() : m_radioAddress;
}

QString DS_ProtocolBase::robotAddress() {
    if (m_robotAddress.isEmpty()) {
        if (m_useFallbackAddress)
            return DS_GetStaticIp (team(), 2);
        else
            return defaultRobotAddress();
    }

    return m_robotAddress;
}

QByteArray DS_ProtocolBase::getClientPacket() {
    m_sentPackets += 1;
    return generateClientPacket();
}

void DS_ProtocolBase::reset() {
    resetProtocol();

    updateVoltage (0, 0);
    updateRobotCode (false);
    updateSendDateTime (false);
    updateCommunications (kFailing);

    /* Toggle the usage of the fallback robot address every 10 resets */
    m_resetCount += 1;
    if (m_resetCount >= 10) {
        m_resetCount = 0;
        m_useFallbackAddress = !m_useFallbackAddress;
    }

    /* Figure out the robot address and ping the robot */
    emit robotAddressChanged (robotAddress());
    m_discovery.getIp (robotAddress(), this, SLOT (onIpFound (QString, QString)));
}

void DS_ProtocolBase::setTeamNumber (quint16 team) {
    m_team = team;
    emit robotAddressChanged (robotAddress());
}

void DS_ProtocolBase::setRobotAddress (QString address) {
    m_robotAddress = address;
    emit robotAddressChanged (robotAddress());
}

void DS_ProtocolBase::setAlliance (DS_Alliance alliance) {
    m_alliance = alliance;
}

void DS_ProtocolBase::setControlMode (DS_ControlMode mode) {
    if (m_controlMode != kControlEmergencyStop) {
        m_controlMode = isConnected() ? mode : kControlDisabled;
        emit controlModeChanged (controlMode());
    }
}

void DS_ProtocolBase::setJoysticks (QList<DS_Joystick*>* joysticks) {
    m_joysticks = joysticks;
}

void DS_ProtocolBase::readRobotPacket (QByteArray data) {
    if (!data.isEmpty())
        readRobotData (data);
}

QByteArray DS_ProtocolBase::bitsToBytes (QBitArray bits) {
    QByteArray bytes (bits.count() / 8, 0);

    for (int i = 0; i < bits.count(); ++i)
        bytes [i / 8] = (bytes.at (i / 8) | ((bits [i] ? 1 : 0) << (i % 8)));

    return bytes;
}

void DS_ProtocolBase::updateStatus (quint8 status) {
    m_status = status;
}

void DS_ProtocolBase::updateRobotCode (bool available) {
    /* Robot code just crashed/failed */
    if (m_robotCode && !available)
        setControlMode (kControlDisabled);

    /* Update DS information */
    m_robotCode = available;
    emit codeChanged (m_robotCode);
}

void DS_ProtocolBase::updateSendDateTime (bool sendDT) {
    m_sendDateTime = sendDT;
}

void DS_ProtocolBase::updateCommunications (DS_CommunicationStatus status) {
    m_communicationStatus = status;
    emit communicationsChanged (m_communicationStatus);
}

void DS_ProtocolBase::updateVoltage (quint8 major, quint8 minor) {
    QString maj = QString::number (major);
    QString min = QString::number (minor);

    maj = maj.replace ("-", "");
    min = min.replace ("-", "");

    if (min.length() == 1)
        min = QString ("0%1").arg (min);

    else if (min.length() > 2)
        min = QString (min.at (0)) + QString (min.at (1));

    emit voltageChanged (QString ("%1.%2").arg (maj, min));
}

void DS_ProtocolBase::pingRobot() {
    m_pingSocket.abort();
    m_pingSocket.connectToHost (robotAddress(), 80, QTcpSocket::ReadOnly);
}

void DS_ProtocolBase::onIpFound (QString address, QString ip) {
    if (address.toLower() == robotAddress().toLower() && address != ip)
        emit robotAddressChanged (ip);

    pingRobot();
}

void DS_ProtocolBase::onStateChanged (QAbstractSocket::SocketState state) {
    if (communicationStatus() == kFailing
            && state == QAbstractSocket::ConnectedState)
        updateCommunications (kPartial);
}
<|endoftext|>


<commit_before>// GreedyMarket.cpp
// Implements the GreedyMarket class
#include <iostream>
#include <cmath>

#include "GreedyMarket.h"

#include "Logger.h"
#include "IsoVector.h"
#include "CycException.h"
#include "InputXML.h"

using namespace std;

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GreedyMarket::receiveMessage(msg_ptr msg) {
  messages_.insert(msg);

  if (msg->isOffer()) {
    offers_.insert(indexedMsg(msg->resource()->quantity(), msg));
  } else {
    requests_.insert(indexedMsg(msg->resource()->quantity(), msg));
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GreedyMarket::resolve() {

  sortedMsgList::iterator request;

  firmOrders_ = 0;

  /// while requests_ remain and there is at least one offer left
  while (requests_.size() > 0) {

    request = requests_.end();
    request--;

    if(match_request(request)) {
      process_request();
    }

    // remove this request
    messages_.erase((*request).second);
    requests_.erase(request);
  }

  for (int i = 0; i < orders_.size(); i++) {
    msg_ptr msg = orders_.at(i);
    msg->setDir(DOWN_MSG);
    msg->sendOn();
  }
  orders_.clear();
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GreedyMarket::reject_request(sortedMsgList::iterator request) {
  // delete the tentative orders
  while ( orders_.size() > firmOrders_) {
    orders_.pop_back();
  }

  // put all matched offers_ back in the sorted list
  while (matchedOffers_.size() > 0) {
    msg_ptr msg = *(matchedOffers_.begin());
    offers_.insert(indexedMsg(msg->resource()->quantity(),msg));
    matchedOffers_.erase(msg);
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GreedyMarket::process_request() {
  // update pointer to firm orders
  firmOrders_ = orders_.size();

  while (matchedOffers_.size() > 0) {
    msg_ptr msg = *(matchedOffers_.begin());
    messages_.erase(msg);
    matchedOffers_.erase(msg);
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
bool GreedyMarket::match_request(sortedMsgList::iterator request) {
  sortedMsgList::iterator offer;
  double requestAmt,offerAmt;
  msg_ptr offerMsg;
  msg_ptr requestMsg;

  requestAmt = request->first;
  requestMsg = request->second;

  // if this request is not yet satisfied &&
  // there are more offers_ left
  while ( fabs(requestAmt) > EPS_KG && offers_.size() > 0) {
    // get a new offer
    offer = offers_.end();
    offer--;
    offerAmt = offer->first;
    offerMsg = offer->second;

    LOG(LEV_DEBUG2, "GreedM") << "offeramt=" << offerAmt
                    << ", requestamt=" << requestAmt;

    // pop off this offer
    offers_.erase(offer);
    if (requestMsg->resource()->checkQuality(offerMsg->resource())) {
      if (requestAmt - offerAmt > EPS_KG) {
        // put a new message in the order stack
        // it goes down to supplier
        offerMsg->setRequester(requestMsg->requester());

        // tenatively queue a new order (don't execute yet)
        matchedOffers_.insert(offerMsg);

        orders_.push_back(offerMsg);

        LOG(LEV_DEBUG1, "GreedM")
          << "GreedyMarket has resolved a transaction "
          << " which is a match from "
          << offerMsg->supplier()->ID()
          << " to "
          << offerMsg->requester()->ID()
          << " for the amount:  "
          << offerMsg->resource()->quantity();

        requestAmt -= offerAmt;
      } else {
        // split offer

        // queue a new order
        msg_ptr maybe_offer = offerMsg->clone();
        maybe_offer->resource()->setQuantity(requestAmt);
        maybe_offer->setRequester(requestMsg->requester());

        matchedOffers_.insert(offerMsg);

        orders_.push_back(maybe_offer);

        LOG(LEV_DEBUG1, "GreedM")
          << "GreedyMarket has resolved a transaction "
          << " which is a match from "
          << maybe_offer->supplier()->ID()
          << " (offer split) to "
          << maybe_offer->requester()->ID()
          << " for the amount:  "
          << maybe_offer->resource()->quantity();

        // reduce the offer amount
        offerAmt -= requestAmt;

        // if the residual is above threshold,
        // make a new offer with reduced amount

        if(offerAmt > EPS_KG) {
          msg_ptr new_offer = offerMsg->clone();
          new_offer->resource()->setQuantity(offerAmt);
          receiveMessage(new_offer);
        }

        // request fulfilled via an offer larger than it.
        requestAmt = 0;
      }
    }
  }

  if (fabs(requestAmt) > EPS_KG) {
    LOG(LEV_DEBUG2, "GreedM") << "The request from Requester "
      << requestMsg->requester()->ID()
      << " for the amount " << requestAmt << " rejected. ";
      reject_request(request);
  }

  return (fabs(requestAmt) < EPS_KG);
}

/* --------------------
 * all MODEL classes have these members
 * --------------------
 */
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
extern "C" Model* constructGreedyMarket() {
  return new GreedyMarket();
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

/* -------------------- */

<commit_msg>removed problematic checkQuality statement from GreedyMarket offer/request matching.<commit_after>// GreedyMarket.cpp
// Implements the GreedyMarket class
#include <iostream>
#include <cmath>

#include "GreedyMarket.h"

#include "Logger.h"
#include "IsoVector.h"
#include "CycException.h"
#include "InputXML.h"

using namespace std;

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GreedyMarket::receiveMessage(msg_ptr msg) {
  messages_.insert(msg);

  if (msg->isOffer()) {
    offers_.insert(indexedMsg(msg->resource()->quantity(), msg));
  } else {
    requests_.insert(indexedMsg(msg->resource()->quantity(), msg));
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GreedyMarket::resolve() {

  sortedMsgList::iterator request;

  firmOrders_ = 0;

  /// while requests_ remain and there is at least one offer left
  while (requests_.size() > 0) {

    request = requests_.end();
    request--;

    if(match_request(request)) {
      process_request();
    }

    // remove this request
    messages_.erase((*request).second);
    requests_.erase(request);
  }

  for (int i = 0; i < orders_.size(); i++) {
    msg_ptr msg = orders_.at(i);
    msg->setDir(DOWN_MSG);
    msg->sendOn();
  }
  orders_.clear();
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GreedyMarket::reject_request(sortedMsgList::iterator request) {
  // delete the tentative orders
  while ( orders_.size() > firmOrders_) {
    orders_.pop_back();
  }

  // put all matched offers_ back in the sorted list
  while (matchedOffers_.size() > 0) {
    msg_ptr msg = *(matchedOffers_.begin());
    offers_.insert(indexedMsg(msg->resource()->quantity(),msg));
    matchedOffers_.erase(msg);
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GreedyMarket::process_request() {
  // update pointer to firm orders
  firmOrders_ = orders_.size();

  while (matchedOffers_.size() > 0) {
    msg_ptr msg = *(matchedOffers_.begin());
    messages_.erase(msg);
    matchedOffers_.erase(msg);
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
bool GreedyMarket::match_request(sortedMsgList::iterator request) {
  sortedMsgList::iterator offer;
  double requestAmt,offerAmt;
  msg_ptr offerMsg;
  msg_ptr requestMsg;

  requestAmt = request->first;
  requestMsg = request->second;

  // if this request is not yet satisfied &&
  // there are more offers_ left
  while ( fabs(requestAmt) > EPS_KG && offers_.size() > 0) {
    // get a new offer
    offer = offers_.end();
    offer--;
    offerAmt = offer->first;
    offerMsg = offer->second;

    LOG(LEV_DEBUG2, "GreedM") << "offeramt=" << offerAmt
                    << ", requestamt=" << requestAmt;

    // pop off this offer
    offers_.erase(offer);
    if (requestAmt - offerAmt > EPS_KG) {
      // put a new message in the order stack
      // it goes down to supplier
      offerMsg->setRequester(requestMsg->requester());

      // tenatively queue a new order (don't execute yet)
      matchedOffers_.insert(offerMsg);

      orders_.push_back(offerMsg);

      LOG(LEV_DEBUG1, "GreedM")
        << "GreedyMarket has resolved a transaction "
        << " which is a match from "
        << offerMsg->supplier()->ID()
        << " to "
        << offerMsg->requester()->ID()
        << " for the amount:  "
        << offerMsg->resource()->quantity();

      requestAmt -= offerAmt;
    } else {
      // split offer

      // queue a new order
      msg_ptr maybe_offer = offerMsg->clone();
      maybe_offer->resource()->setQuantity(requestAmt);
      maybe_offer->setRequester(requestMsg->requester());

      matchedOffers_.insert(offerMsg);

      orders_.push_back(maybe_offer);

      LOG(LEV_DEBUG1, "GreedM")
        << "GreedyMarket has resolved a transaction "
        << " which is a match from "
        << maybe_offer->supplier()->ID()
        << " (offer split) to "
        << maybe_offer->requester()->ID()
        << " for the amount:  "
        << maybe_offer->resource()->quantity();

      // reduce the offer amount
      offerAmt -= requestAmt;

      // if the residual is above threshold,
      // make a new offer with reduced amount

      if(offerAmt > EPS_KG) {
        msg_ptr new_offer = offerMsg->clone();
        new_offer->resource()->setQuantity(offerAmt);
        receiveMessage(new_offer);
      }

      // request fulfilled via an offer larger than it.
      requestAmt = 0;
    }
  }

  if (fabs(requestAmt) > EPS_KG) {
    LOG(LEV_DEBUG2, "GreedM") << "The request from Requester "
      << requestMsg->requester()->ID()
      << " for the amount " << requestAmt << " rejected. ";
      reject_request(request);
  }

  return (fabs(requestAmt) < EPS_KG);
}

/* --------------------
 * all MODEL classes have these members
 * --------------------
 */
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
extern "C" Model* constructGreedyMarket() {
  return new GreedyMarket();
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

/* -------------------- */

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: cppdep.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: hjs $ $Date: 2004-06-28 16:28:02 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library 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 library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <stdio.h>
#include <string.h>

#include <unistd.h>

#include <sys/stat.h>
#include <stream.hxx>
#include "cppdep.hxx"

//#define TEST

CppDep::CppDep( ByteString aFileName )
{
    aSourceFile = aFileName;

    pSearchPath = new ByteStringList;
    pFileList = new ByteStringList;
}

CppDep::CppDep()
{
    pSources = new ByteStringList;
    pSearchPath = new ByteStringList;
    pFileList = new ByteStringList;
}

CppDep::~CppDep()
{
    delete pSearchPath;
    delete pFileList;
}

void CppDep::Execute()
{
    ULONG nCount = pSources->Count();
    for ( ULONG n=0; n<nCount;n++)
    {
        ByteString *pStr = pSources->GetObject(n);
        Search( *pStr );
    }
}

BOOL CppDep::AddSearchPath( const char* aPath )
{
    ByteString *pStr = new ByteString( aPath );
    pSearchPath->Insert( pStr, LIST_APPEND );
    return FALSE;
}

BOOL CppDep::AddSource( const char* aSource )
{
    ByteString *pStr = new ByteString( aSource );
    pSources->Insert( pStr, LIST_APPEND );
    return FALSE;
}

BOOL CppDep::Search( ByteString aFileName )
{
#ifdef DEBUG_VERBOSE
    fprintf( stderr, "SEARCH : %s\n", aFileName.GetBuffer());
#endif
    BOOL bRet = FALSE;

    SvFileStream aFile;
    ByteString aReadLine;

    UniString suFileName( aFileName, gsl_getSystemTextEncoding());

    aFile.Open( suFileName, STREAM_READ );
    while ( aFile.ReadLine( aReadLine ))
    {
        USHORT nPos;
        if ( nPos = aReadLine.Search( "include" ) != STRING_NOTFOUND  )
        {
#ifdef DEBUG_VERBOSE
            fprintf( stderr, "found : %d %s\n", nPos, aReadLine.GetBuffer() );
#endif
            ByteString aResult = IsIncludeStatement( aReadLine );
#ifdef DEBUG_VERBOSE
            fprintf( stderr, "Result : %s\n", aResult.GetBuffer() );
#endif

            ByteString aNewFile;
            if ( aResult !="")
            if ( (aNewFile = Exists( aResult )) != "" )
            {
                BOOL bFound = FALSE;
                ULONG nCount = pFileList->Count();
                for ( ULONG i=0; i<nCount; i++ )
                {
                    ByteString *pStr = pFileList->GetObject(i);
                    if ( *pStr == aNewFile )
                        bFound = TRUE;
                }
#ifdef DEBUG_VERBOSE
                fprintf( stderr, "not in list : %d %s\n", nPos, aReadLine.GetBuffer() );
#endif
                if ( !bFound )
                {
                    pFileList->Insert( new ByteString( aNewFile ), LIST_APPEND );
#ifdef DEBUG_VERBOSE
                    fprintf( stderr, " CppDep %s\\\n", aNewFile.GetBuffer() );
#endif
                    Search(aNewFile);
                }
            }
        }
    }
    aFile.Close();

    return bRet;
}

ByteString CppDep::Exists( ByteString aFileName )
{
    char pFullName[1023];
    ByteString aString;

#ifdef DEBUG_VERBOSE
    fprintf( stderr, "Searching %s \n", aFileName.GetBuffer() );
#endif

    ULONG nCount = pSearchPath->Count();
    for ( ULONG n=0; n<nCount; n++)
    {
        struct stat aBuf;
        ByteString *pPathName = pSearchPath->GetObject(n);

        strcpy( pFullName, pPathName->GetBuffer());
        strcat( pFullName, DIR_SEP );
        strcat( pFullName, aFileName.GetBuffer());

#ifdef DEBUG_VERBOSE
        fprintf( stderr, "looking for %s\t ", pFullName );
#endif
        if ( stat( pFullName, &aBuf ) == 0 )
        {
#ifdef DEBUG_VERBOSE
            fprintf( stderr, "Got Dependency ", pFullName );
#endif
#ifdef DEBUG_VERBOSE
            fprintf( stderr, "%s \\\n", pFullName );
#endif

            return ByteString(pFullName);
        }
    }
    return aString;
}

ByteString CppDep::IsIncludeStatement( ByteString aLine )
{
    ByteString aRetStr;
    // WhiteSpacesfressen
    aLine.EraseAllChars(' ');
    aLine.EraseAllChars('\t');
#ifdef DEBUG_VERBOSE
    fprintf( stderr, "now : %s\n", aLine.GetBuffer() );
#endif
    // ist der erste Teil ein #include ?
    ByteString aTmpStr;
    aTmpStr = aLine.Copy( 0, 8 );
#ifdef DEBUG_VERBOSE
    fprintf( stderr, "is include : %s\n", aTmpStr.GetBuffer() );
#endif
    if ( aTmpStr.Equals("#include") )
    {
        aTmpStr = aLine.Erase( 0, 8 );
        USHORT nLen = aLine.Len();
        aLine.Erase( nLen-1, 1 );
        aLine.Erase( 0, 1 );
#ifdef DEBUG_VERBOSE
        fprintf( stderr, "Gotcha : %s\n", aLine.GetBuffer() );
#endif
        aRetStr = aLine;
    }
    return aRetStr;
}

#ifdef TEST

int main( int argc, char **argv )
{
    CppDep *pDep = new CppDep( "cppdep.cxx" );
    pDep->AddSearchPath(".");
    pDep->AddSearchPath("/usr/include");
    pDep->AddSearchPath("/usr/local/include");
    pDep->AddSearchPath("/usr/include/sys");
    pDep->AddSearchPath("/usr/include/X11");
    pDep->Execute();
    delete pDep;
    return 0;
}

#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.10.144); FILE MERGED 2005/09/05 13:58:13 rt 1.10.144.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: cppdep.cxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 13:28:36 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library 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 library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include <stdio.h>
#include <string.h>

#include <unistd.h>

#include <sys/stat.h>
#include <stream.hxx>
#include "cppdep.hxx"

//#define TEST

CppDep::CppDep( ByteString aFileName )
{
    aSourceFile = aFileName;

    pSearchPath = new ByteStringList;
    pFileList = new ByteStringList;
}

CppDep::CppDep()
{
    pSources = new ByteStringList;
    pSearchPath = new ByteStringList;
    pFileList = new ByteStringList;
}

CppDep::~CppDep()
{
    delete pSearchPath;
    delete pFileList;
}

void CppDep::Execute()
{
    ULONG nCount = pSources->Count();
    for ( ULONG n=0; n<nCount;n++)
    {
        ByteString *pStr = pSources->GetObject(n);
        Search( *pStr );
    }
}

BOOL CppDep::AddSearchPath( const char* aPath )
{
    ByteString *pStr = new ByteString( aPath );
    pSearchPath->Insert( pStr, LIST_APPEND );
    return FALSE;
}

BOOL CppDep::AddSource( const char* aSource )
{
    ByteString *pStr = new ByteString( aSource );
    pSources->Insert( pStr, LIST_APPEND );
    return FALSE;
}

BOOL CppDep::Search( ByteString aFileName )
{
#ifdef DEBUG_VERBOSE
    fprintf( stderr, "SEARCH : %s\n", aFileName.GetBuffer());
#endif
    BOOL bRet = FALSE;

    SvFileStream aFile;
    ByteString aReadLine;

    UniString suFileName( aFileName, gsl_getSystemTextEncoding());

    aFile.Open( suFileName, STREAM_READ );
    while ( aFile.ReadLine( aReadLine ))
    {
        USHORT nPos;
        if ( nPos = aReadLine.Search( "include" ) != STRING_NOTFOUND  )
        {
#ifdef DEBUG_VERBOSE
            fprintf( stderr, "found : %d %s\n", nPos, aReadLine.GetBuffer() );
#endif
            ByteString aResult = IsIncludeStatement( aReadLine );
#ifdef DEBUG_VERBOSE
            fprintf( stderr, "Result : %s\n", aResult.GetBuffer() );
#endif

            ByteString aNewFile;
            if ( aResult !="")
            if ( (aNewFile = Exists( aResult )) != "" )
            {
                BOOL bFound = FALSE;
                ULONG nCount = pFileList->Count();
                for ( ULONG i=0; i<nCount; i++ )
                {
                    ByteString *pStr = pFileList->GetObject(i);
                    if ( *pStr == aNewFile )
                        bFound = TRUE;
                }
#ifdef DEBUG_VERBOSE
                fprintf( stderr, "not in list : %d %s\n", nPos, aReadLine.GetBuffer() );
#endif
                if ( !bFound )
                {
                    pFileList->Insert( new ByteString( aNewFile ), LIST_APPEND );
#ifdef DEBUG_VERBOSE
                    fprintf( stderr, " CppDep %s\\\n", aNewFile.GetBuffer() );
#endif
                    Search(aNewFile);
                }
            }
        }
    }
    aFile.Close();

    return bRet;
}

ByteString CppDep::Exists( ByteString aFileName )
{
    char pFullName[1023];
    ByteString aString;

#ifdef DEBUG_VERBOSE
    fprintf( stderr, "Searching %s \n", aFileName.GetBuffer() );
#endif

    ULONG nCount = pSearchPath->Count();
    for ( ULONG n=0; n<nCount; n++)
    {
        struct stat aBuf;
        ByteString *pPathName = pSearchPath->GetObject(n);

        strcpy( pFullName, pPathName->GetBuffer());
        strcat( pFullName, DIR_SEP );
        strcat( pFullName, aFileName.GetBuffer());

#ifdef DEBUG_VERBOSE
        fprintf( stderr, "looking for %s\t ", pFullName );
#endif
        if ( stat( pFullName, &aBuf ) == 0 )
        {
#ifdef DEBUG_VERBOSE
            fprintf( stderr, "Got Dependency ", pFullName );
#endif
#ifdef DEBUG_VERBOSE
            fprintf( stderr, "%s \\\n", pFullName );
#endif

            return ByteString(pFullName);
        }
    }
    return aString;
}

ByteString CppDep::IsIncludeStatement( ByteString aLine )
{
    ByteString aRetStr;
    // WhiteSpacesfressen
    aLine.EraseAllChars(' ');
    aLine.EraseAllChars('\t');
#ifdef DEBUG_VERBOSE
    fprintf( stderr, "now : %s\n", aLine.GetBuffer() );
#endif
    // ist der erste Teil ein #include ?
    ByteString aTmpStr;
    aTmpStr = aLine.Copy( 0, 8 );
#ifdef DEBUG_VERBOSE
    fprintf( stderr, "is include : %s\n", aTmpStr.GetBuffer() );
#endif
    if ( aTmpStr.Equals("#include") )
    {
        aTmpStr = aLine.Erase( 0, 8 );
        USHORT nLen = aLine.Len();
        aLine.Erase( nLen-1, 1 );
        aLine.Erase( 0, 1 );
#ifdef DEBUG_VERBOSE
        fprintf( stderr, "Gotcha : %s\n", aLine.GetBuffer() );
#endif
        aRetStr = aLine;
    }
    return aRetStr;
}

#ifdef TEST

int main( int argc, char **argv )
{
    CppDep *pDep = new CppDep( "cppdep.cxx" );
    pDep->AddSearchPath(".");
    pDep->AddSearchPath("/usr/include");
    pDep->AddSearchPath("/usr/local/include");
    pDep->AddSearchPath("/usr/include/sys");
    pDep->AddSearchPath("/usr/include/X11");
    pDep->Execute();
    delete pDep;
    return 0;
}

#endif
<|endoftext|>


<commit_before>/*
 * Copyright 2013 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkBicubicImageFilter.h"
#include "SkBitmap.h"
#include "SkBitmapDevice.h"
#include "SkBitmapSource.h"
#include "SkBlurImageFilter.h"
#include "SkCanvas.h"
#include "SkColorFilterImageFilter.h"
#include "SkColorMatrixFilter.h"
#include "SkDeviceImageFilterProxy.h"
#include "SkDisplacementMapEffect.h"
#include "SkDropShadowImageFilter.h"
#include "SkLightingImageFilter.h"
#include "SkMatrixConvolutionImageFilter.h"
#include "SkMergeImageFilter.h"
#include "SkMorphologyImageFilter.h"
#include "SkOffsetImageFilter.h"
#include "SkRect.h"
#include "SkTileImageFilter.h"
#include "SkXfermodeImageFilter.h"
#include "Test.h"

#if SK_SUPPORT_GPU
#include "GrContextFactory.h"
#include "SkGpuDevice.h"
#endif

static const int kBitmapSize = 4;

static void make_small_bitmap(SkBitmap& bitmap) {
    bitmap.setConfig(SkBitmap::kARGB_8888_Config, kBitmapSize, kBitmapSize);
    bitmap.allocPixels();
    SkBitmapDevice device(bitmap);
    SkCanvas canvas(&device);
    canvas.clear(0x00000000);
    SkPaint darkPaint;
    darkPaint.setColor(0xFF804020);
    SkPaint lightPaint;
    lightPaint.setColor(0xFF244484);
    const int i = kBitmapSize / 4;
    for (int y = 0; y < kBitmapSize; y += i) {
        for (int x = 0; x < kBitmapSize; x += i) {
            canvas.save();
            canvas.translate(SkIntToScalar(x), SkIntToScalar(y));
            canvas.drawRect(SkRect::MakeXYWH(0, 0,
                                             SkIntToScalar(i),
                                             SkIntToScalar(i)), darkPaint);
            canvas.drawRect(SkRect::MakeXYWH(SkIntToScalar(i),
                                             0,
                                             SkIntToScalar(i),
                                             SkIntToScalar(i)), lightPaint);
            canvas.drawRect(SkRect::MakeXYWH(0,
                                             SkIntToScalar(i),
                                             SkIntToScalar(i),
                                             SkIntToScalar(i)), lightPaint);
            canvas.drawRect(SkRect::MakeXYWH(SkIntToScalar(i),
                                             SkIntToScalar(i),
                                             SkIntToScalar(i),
                                             SkIntToScalar(i)), darkPaint);
            canvas.restore();
        }
    }
}

static SkImageFilter* make_scale(float amount, SkImageFilter* input = NULL) {
    SkScalar s = amount;
    SkScalar matrix[20] = { s, 0, 0, 0, 0,
                            0, s, 0, 0, 0,
                            0, 0, s, 0, 0,
                            0, 0, 0, s, 0 };
    SkAutoTUnref<SkColorFilter> filter(new SkColorMatrixFilter(matrix));
    return SkColorFilterImageFilter::Create(filter, input);
}

static SkImageFilter* make_grayscale(SkImageFilter* input = NULL, const SkImageFilter::CropRect* cropRect = NULL) {
    SkScalar matrix[20];
    memset(matrix, 0, 20 * sizeof(SkScalar));
    matrix[0] = matrix[5] = matrix[10] = 0.2126f;
    matrix[1] = matrix[6] = matrix[11] = 0.7152f;
    matrix[2] = matrix[7] = matrix[12] = 0.0722f;
    matrix[18] = 1.0f;
    SkAutoTUnref<SkColorFilter> filter(new SkColorMatrixFilter(matrix));
    return SkColorFilterImageFilter::Create(filter, input, cropRect);
}

DEF_TEST(ImageFilter, reporter) {
    {
        // Check that two non-clipping color matrices concatenate into a single filter.
        SkAutoTUnref<SkImageFilter> halfBrightness(make_scale(0.5f));
        SkAutoTUnref<SkImageFilter> quarterBrightness(make_scale(0.5f, halfBrightness));
        REPORTER_ASSERT(reporter, NULL == quarterBrightness->getInput(0));
    }

    {
        // Check that a clipping color matrix followed by a grayscale does not concatenate into a single filter.
        SkAutoTUnref<SkImageFilter> doubleBrightness(make_scale(2.0f));
        SkAutoTUnref<SkImageFilter> halfBrightness(make_scale(0.5f, doubleBrightness));
        REPORTER_ASSERT(reporter, NULL != halfBrightness->getInput(0));
    }

    {
        // Check that a color filter image filter without a crop rect can be
        // expressed as a color filter.
        SkAutoTUnref<SkImageFilter> gray(make_grayscale());
        REPORTER_ASSERT(reporter, true == gray->asColorFilter(NULL));
    }

    {
        // Check that a color filter image filter with a crop rect cannot
        // be expressed as a color filter.
        SkImageFilter::CropRect cropRect(SkRect::MakeXYWH(0, 0, 100, 100));
        SkAutoTUnref<SkImageFilter> grayWithCrop(make_grayscale(NULL, &cropRect));
        REPORTER_ASSERT(reporter, false == grayWithCrop->asColorFilter(NULL));
    }

    {
        // Tests pass by not asserting
        SkBitmap bitmap, result;
        make_small_bitmap(bitmap);
        result.setConfig(SkBitmap::kARGB_8888_Config, kBitmapSize, kBitmapSize);
        result.allocPixels();

        {
            // This tests for :
            // 1 ) location at (0,0,1)
            SkPoint3 location(0, 0, SK_Scalar1);
            // 2 ) location and target at same value
            SkPoint3 target(location.fX, location.fY, location.fZ);
            // 3 ) large negative specular exponent value
            SkScalar specularExponent = -1000;

            SkAutoTUnref<SkImageFilter> bmSrc(new SkBitmapSource(bitmap));
            SkPaint paint;
            paint.setImageFilter(SkLightingImageFilter::CreateSpotLitSpecular(
                    location, target, specularExponent, 180,
                    0xFFFFFFFF, SK_Scalar1, SK_Scalar1, SK_Scalar1,
                    bmSrc))->unref();
            SkCanvas canvas(result);
            SkRect r = SkRect::MakeWH(SkIntToScalar(kBitmapSize),
                                      SkIntToScalar(kBitmapSize));
            canvas.drawRect(r, paint);
        }

        {
            // This tests for scale bringing width to 0
            SkSize scale = SkSize::Make(-0.001f, SK_Scalar1);
            SkAutoTUnref<SkImageFilter> bmSrc(new SkBitmapSource(bitmap));
            SkAutoTUnref<SkBicubicImageFilter> bicubic(
                SkBicubicImageFilter::CreateMitchell(scale, bmSrc));
            SkBitmapDevice device(bitmap);
            SkDeviceImageFilterProxy proxy(&device);
            SkIPoint loc = SkIPoint::Make(0, 0);
            // An empty input should early return and return false
            REPORTER_ASSERT(reporter,
                            !bicubic->filterImage(&proxy, bitmap, SkMatrix::I(), &result, &loc));
        }
    }
}

static void test_crop_rects(SkBaseDevice* device, skiatest::Reporter* reporter) {
    // Check that all filters offset to their absolute crop rect,
    // unaffected by the input crop rect.
    // Tests pass by not asserting.
    SkBitmap bitmap;
    bitmap.setConfig(SkBitmap::kARGB_8888_Config, 100, 100);
    bitmap.allocPixels();
    bitmap.eraseARGB(0, 0, 0, 0);
    SkDeviceImageFilterProxy proxy(device);

    SkImageFilter::CropRect inputCropRect(SkRect::MakeXYWH(8, 13, 80, 80));
    SkImageFilter::CropRect cropRect(SkRect::MakeXYWH(20, 30, 60, 60));
    SkAutoTUnref<SkImageFilter> input(make_grayscale(NULL, &inputCropRect));

    SkAutoTUnref<SkColorFilter> cf(SkColorFilter::CreateModeFilter(SK_ColorRED, SkXfermode::kSrcIn_Mode));
    SkPoint3 location(0, 0, SK_Scalar1);
    SkPoint3 target(SK_Scalar1, SK_Scalar1, SK_Scalar1);
    SkScalar kernel[9] = {
        SkIntToScalar( 1), SkIntToScalar( 1), SkIntToScalar( 1),
        SkIntToScalar( 1), SkIntToScalar(-7), SkIntToScalar( 1),
        SkIntToScalar( 1), SkIntToScalar( 1), SkIntToScalar( 1),
    };
    SkISize kernelSize = SkISize::Make(3, 3);
    SkScalar gain = SK_Scalar1, bias = 0;

    SkImageFilter* filters[] = {
        SkColorFilterImageFilter::Create(cf.get(), input.get(), &cropRect),
        new SkDisplacementMapEffect(SkDisplacementMapEffect::kR_ChannelSelectorType,
                                    SkDisplacementMapEffect::kB_ChannelSelectorType,
                                    40.0f, input.get(), input.get(), &cropRect),
        new SkBlurImageFilter(SK_Scalar1, SK_Scalar1, input.get(), &cropRect),
        new SkDropShadowImageFilter(SK_Scalar1, SK_Scalar1, SK_Scalar1, SK_Scalar1, SK_ColorGREEN, input.get(), &cropRect),
        SkLightingImageFilter::CreatePointLitDiffuse(location, SK_ColorGREEN, 0, 0, input.get(), &cropRect),
        SkLightingImageFilter::CreatePointLitSpecular(location, SK_ColorGREEN, 0, 0, 0, input.get(), &cropRect),
        new SkMatrixConvolutionImageFilter(kernelSize, kernel, gain, bias, SkIPoint::Make(1, 1), SkMatrixConvolutionImageFilter::kRepeat_TileMode, false, input.get(), &cropRect),
        new SkMergeImageFilter(input.get(), input.get(), SkXfermode::kSrcOver_Mode, &cropRect),
        new SkOffsetImageFilter(SK_Scalar1, SK_Scalar1, input.get(), &cropRect),
        new SkOffsetImageFilter(SK_Scalar1, SK_Scalar1, input.get(), &cropRect),
        new SkDilateImageFilter(3, 2, input.get(), &cropRect),
        new SkErodeImageFilter(2, 3, input.get(), &cropRect),
        new SkTileImageFilter(inputCropRect.rect(), cropRect.rect(), input.get()),
        new SkXfermodeImageFilter(SkXfermode::Create(SkXfermode::kSrcOver_Mode), input.get(), input.get(), &cropRect),
    };

    for (size_t i = 0; i < SK_ARRAY_COUNT(filters); ++i) {
        SkImageFilter* filter = filters[i];
        SkBitmap result;
        SkIPoint offset;
        SkString str;
        str.printf("filter %ld", i);
        REPORTER_ASSERT_MESSAGE(reporter, filter->filterImage(&proxy, bitmap, SkMatrix::I(), &result, &offset), str.c_str());
        REPORTER_ASSERT_MESSAGE(reporter, offset.fX == 20 && offset.fY == 30, str.c_str());
    }

    for (size_t i = 0; i < SK_ARRAY_COUNT(filters); ++i) {
        SkSafeUnref(filters[i]);
    }
}

DEF_TEST(ImageFilterCropRect, reporter) {
    SkBitmap temp;
    temp.setConfig(SkBitmap::kARGB_8888_Config, 100, 100);
    temp.allocPixels();
    SkBitmapDevice device(temp);
    test_crop_rects(&device, reporter);
}

DEF_GPUTEST(ImageFilterCropRectGPU, reporter, factory) {
    GrContext* context = factory->get(static_cast<GrContextFactory::GLContextType>(0));
    SkGpuDevice device(context, SkBitmap::kARGB_8888_Config, 100, 100);
    test_crop_rects(&device, reporter);
}
<commit_msg>Fix skia_gpu=0 build.<commit_after>/*
 * Copyright 2013 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkBicubicImageFilter.h"
#include "SkBitmap.h"
#include "SkBitmapDevice.h"
#include "SkBitmapSource.h"
#include "SkBlurImageFilter.h"
#include "SkCanvas.h"
#include "SkColorFilterImageFilter.h"
#include "SkColorMatrixFilter.h"
#include "SkDeviceImageFilterProxy.h"
#include "SkDisplacementMapEffect.h"
#include "SkDropShadowImageFilter.h"
#include "SkLightingImageFilter.h"
#include "SkMatrixConvolutionImageFilter.h"
#include "SkMergeImageFilter.h"
#include "SkMorphologyImageFilter.h"
#include "SkOffsetImageFilter.h"
#include "SkRect.h"
#include "SkTileImageFilter.h"
#include "SkXfermodeImageFilter.h"
#include "Test.h"

#if SK_SUPPORT_GPU
#include "GrContextFactory.h"
#include "SkGpuDevice.h"
#endif

static const int kBitmapSize = 4;

static void make_small_bitmap(SkBitmap& bitmap) {
    bitmap.setConfig(SkBitmap::kARGB_8888_Config, kBitmapSize, kBitmapSize);
    bitmap.allocPixels();
    SkBitmapDevice device(bitmap);
    SkCanvas canvas(&device);
    canvas.clear(0x00000000);
    SkPaint darkPaint;
    darkPaint.setColor(0xFF804020);
    SkPaint lightPaint;
    lightPaint.setColor(0xFF244484);
    const int i = kBitmapSize / 4;
    for (int y = 0; y < kBitmapSize; y += i) {
        for (int x = 0; x < kBitmapSize; x += i) {
            canvas.save();
            canvas.translate(SkIntToScalar(x), SkIntToScalar(y));
            canvas.drawRect(SkRect::MakeXYWH(0, 0,
                                             SkIntToScalar(i),
                                             SkIntToScalar(i)), darkPaint);
            canvas.drawRect(SkRect::MakeXYWH(SkIntToScalar(i),
                                             0,
                                             SkIntToScalar(i),
                                             SkIntToScalar(i)), lightPaint);
            canvas.drawRect(SkRect::MakeXYWH(0,
                                             SkIntToScalar(i),
                                             SkIntToScalar(i),
                                             SkIntToScalar(i)), lightPaint);
            canvas.drawRect(SkRect::MakeXYWH(SkIntToScalar(i),
                                             SkIntToScalar(i),
                                             SkIntToScalar(i),
                                             SkIntToScalar(i)), darkPaint);
            canvas.restore();
        }
    }
}

static SkImageFilter* make_scale(float amount, SkImageFilter* input = NULL) {
    SkScalar s = amount;
    SkScalar matrix[20] = { s, 0, 0, 0, 0,
                            0, s, 0, 0, 0,
                            0, 0, s, 0, 0,
                            0, 0, 0, s, 0 };
    SkAutoTUnref<SkColorFilter> filter(new SkColorMatrixFilter(matrix));
    return SkColorFilterImageFilter::Create(filter, input);
}

static SkImageFilter* make_grayscale(SkImageFilter* input = NULL, const SkImageFilter::CropRect* cropRect = NULL) {
    SkScalar matrix[20];
    memset(matrix, 0, 20 * sizeof(SkScalar));
    matrix[0] = matrix[5] = matrix[10] = 0.2126f;
    matrix[1] = matrix[6] = matrix[11] = 0.7152f;
    matrix[2] = matrix[7] = matrix[12] = 0.0722f;
    matrix[18] = 1.0f;
    SkAutoTUnref<SkColorFilter> filter(new SkColorMatrixFilter(matrix));
    return SkColorFilterImageFilter::Create(filter, input, cropRect);
}

DEF_TEST(ImageFilter, reporter) {
    {
        // Check that two non-clipping color matrices concatenate into a single filter.
        SkAutoTUnref<SkImageFilter> halfBrightness(make_scale(0.5f));
        SkAutoTUnref<SkImageFilter> quarterBrightness(make_scale(0.5f, halfBrightness));
        REPORTER_ASSERT(reporter, NULL == quarterBrightness->getInput(0));
    }

    {
        // Check that a clipping color matrix followed by a grayscale does not concatenate into a single filter.
        SkAutoTUnref<SkImageFilter> doubleBrightness(make_scale(2.0f));
        SkAutoTUnref<SkImageFilter> halfBrightness(make_scale(0.5f, doubleBrightness));
        REPORTER_ASSERT(reporter, NULL != halfBrightness->getInput(0));
    }

    {
        // Check that a color filter image filter without a crop rect can be
        // expressed as a color filter.
        SkAutoTUnref<SkImageFilter> gray(make_grayscale());
        REPORTER_ASSERT(reporter, true == gray->asColorFilter(NULL));
    }

    {
        // Check that a color filter image filter with a crop rect cannot
        // be expressed as a color filter.
        SkImageFilter::CropRect cropRect(SkRect::MakeXYWH(0, 0, 100, 100));
        SkAutoTUnref<SkImageFilter> grayWithCrop(make_grayscale(NULL, &cropRect));
        REPORTER_ASSERT(reporter, false == grayWithCrop->asColorFilter(NULL));
    }

    {
        // Tests pass by not asserting
        SkBitmap bitmap, result;
        make_small_bitmap(bitmap);
        result.setConfig(SkBitmap::kARGB_8888_Config, kBitmapSize, kBitmapSize);
        result.allocPixels();

        {
            // This tests for :
            // 1 ) location at (0,0,1)
            SkPoint3 location(0, 0, SK_Scalar1);
            // 2 ) location and target at same value
            SkPoint3 target(location.fX, location.fY, location.fZ);
            // 3 ) large negative specular exponent value
            SkScalar specularExponent = -1000;

            SkAutoTUnref<SkImageFilter> bmSrc(new SkBitmapSource(bitmap));
            SkPaint paint;
            paint.setImageFilter(SkLightingImageFilter::CreateSpotLitSpecular(
                    location, target, specularExponent, 180,
                    0xFFFFFFFF, SK_Scalar1, SK_Scalar1, SK_Scalar1,
                    bmSrc))->unref();
            SkCanvas canvas(result);
            SkRect r = SkRect::MakeWH(SkIntToScalar(kBitmapSize),
                                      SkIntToScalar(kBitmapSize));
            canvas.drawRect(r, paint);
        }

        {
            // This tests for scale bringing width to 0
            SkSize scale = SkSize::Make(-0.001f, SK_Scalar1);
            SkAutoTUnref<SkImageFilter> bmSrc(new SkBitmapSource(bitmap));
            SkAutoTUnref<SkBicubicImageFilter> bicubic(
                SkBicubicImageFilter::CreateMitchell(scale, bmSrc));
            SkBitmapDevice device(bitmap);
            SkDeviceImageFilterProxy proxy(&device);
            SkIPoint loc = SkIPoint::Make(0, 0);
            // An empty input should early return and return false
            REPORTER_ASSERT(reporter,
                            !bicubic->filterImage(&proxy, bitmap, SkMatrix::I(), &result, &loc));
        }
    }
}

static void test_crop_rects(SkBaseDevice* device, skiatest::Reporter* reporter) {
    // Check that all filters offset to their absolute crop rect,
    // unaffected by the input crop rect.
    // Tests pass by not asserting.
    SkBitmap bitmap;
    bitmap.setConfig(SkBitmap::kARGB_8888_Config, 100, 100);
    bitmap.allocPixels();
    bitmap.eraseARGB(0, 0, 0, 0);
    SkDeviceImageFilterProxy proxy(device);

    SkImageFilter::CropRect inputCropRect(SkRect::MakeXYWH(8, 13, 80, 80));
    SkImageFilter::CropRect cropRect(SkRect::MakeXYWH(20, 30, 60, 60));
    SkAutoTUnref<SkImageFilter> input(make_grayscale(NULL, &inputCropRect));

    SkAutoTUnref<SkColorFilter> cf(SkColorFilter::CreateModeFilter(SK_ColorRED, SkXfermode::kSrcIn_Mode));
    SkPoint3 location(0, 0, SK_Scalar1);
    SkPoint3 target(SK_Scalar1, SK_Scalar1, SK_Scalar1);
    SkScalar kernel[9] = {
        SkIntToScalar( 1), SkIntToScalar( 1), SkIntToScalar( 1),
        SkIntToScalar( 1), SkIntToScalar(-7), SkIntToScalar( 1),
        SkIntToScalar( 1), SkIntToScalar( 1), SkIntToScalar( 1),
    };
    SkISize kernelSize = SkISize::Make(3, 3);
    SkScalar gain = SK_Scalar1, bias = 0;

    SkImageFilter* filters[] = {
        SkColorFilterImageFilter::Create(cf.get(), input.get(), &cropRect),
        new SkDisplacementMapEffect(SkDisplacementMapEffect::kR_ChannelSelectorType,
                                    SkDisplacementMapEffect::kB_ChannelSelectorType,
                                    40.0f, input.get(), input.get(), &cropRect),
        new SkBlurImageFilter(SK_Scalar1, SK_Scalar1, input.get(), &cropRect),
        new SkDropShadowImageFilter(SK_Scalar1, SK_Scalar1, SK_Scalar1, SK_Scalar1, SK_ColorGREEN, input.get(), &cropRect),
        SkLightingImageFilter::CreatePointLitDiffuse(location, SK_ColorGREEN, 0, 0, input.get(), &cropRect),
        SkLightingImageFilter::CreatePointLitSpecular(location, SK_ColorGREEN, 0, 0, 0, input.get(), &cropRect),
        new SkMatrixConvolutionImageFilter(kernelSize, kernel, gain, bias, SkIPoint::Make(1, 1), SkMatrixConvolutionImageFilter::kRepeat_TileMode, false, input.get(), &cropRect),
        new SkMergeImageFilter(input.get(), input.get(), SkXfermode::kSrcOver_Mode, &cropRect),
        new SkOffsetImageFilter(SK_Scalar1, SK_Scalar1, input.get(), &cropRect),
        new SkOffsetImageFilter(SK_Scalar1, SK_Scalar1, input.get(), &cropRect),
        new SkDilateImageFilter(3, 2, input.get(), &cropRect),
        new SkErodeImageFilter(2, 3, input.get(), &cropRect),
        new SkTileImageFilter(inputCropRect.rect(), cropRect.rect(), input.get()),
        new SkXfermodeImageFilter(SkXfermode::Create(SkXfermode::kSrcOver_Mode), input.get(), input.get(), &cropRect),
    };

    for (size_t i = 0; i < SK_ARRAY_COUNT(filters); ++i) {
        SkImageFilter* filter = filters[i];
        SkBitmap result;
        SkIPoint offset;
        SkString str;
        str.printf("filter %ld", i);
        REPORTER_ASSERT_MESSAGE(reporter, filter->filterImage(&proxy, bitmap, SkMatrix::I(), &result, &offset), str.c_str());
        REPORTER_ASSERT_MESSAGE(reporter, offset.fX == 20 && offset.fY == 30, str.c_str());
    }

    for (size_t i = 0; i < SK_ARRAY_COUNT(filters); ++i) {
        SkSafeUnref(filters[i]);
    }
}

DEF_TEST(ImageFilterCropRect, reporter) {
    SkBitmap temp;
    temp.setConfig(SkBitmap::kARGB_8888_Config, 100, 100);
    temp.allocPixels();
    SkBitmapDevice device(temp);
    test_crop_rects(&device, reporter);
}

#if SK_SUPPORT_GPU
DEF_GPUTEST(ImageFilterCropRectGPU, reporter, factory) {
    GrContext* context = factory->get(static_cast<GrContextFactory::GLContextType>(0));
    SkGpuDevice device(context, SkBitmap::kARGB_8888_Config, 100, 100);
    test_crop_rects(&device, reporter);
}
#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: cppdep.cxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 13:19:39 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library 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 library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include <stdio.h>
#include <string.h>

#include <unistd.h>

#include <sys/stat.h>
#include <stream.hxx>
#include "cppdep.hxx"

//#define TEST

CppDep::CppDep( ByteString aFileName )
{
    aSourceFile = aFileName;

    pSearchPath = new ByteStringList;
    pFileList = new ByteStringList;
}

CppDep::CppDep()
{
    pSources = new ByteStringList;
    pSearchPath = new ByteStringList;
    pFileList = new ByteStringList;
}

CppDep::~CppDep()
{
    delete pSearchPath;
    delete pFileList;
}

void CppDep::Execute()
{
    ULONG nCount = pSources->Count();
    for ( ULONG n=0; n<nCount;n++)
    {
        ByteString *pStr = pSources->GetObject(n);
        Search( *pStr );
    }
}

BOOL CppDep::AddSearchPath( const char* aPath )
{
    ByteString *pStr = new ByteString( aPath );
    pSearchPath->Insert( pStr, LIST_APPEND );
    return FALSE;
}

BOOL CppDep::AddSource( const char* aSource )
{
    ByteString *pStr = new ByteString( aSource );
    pSources->Insert( pStr, LIST_APPEND );
    return FALSE;
}

BOOL CppDep::Search( ByteString aFileName )
{
#ifdef DEBUG_VERBOSE
    fprintf( stderr, "SEARCH : %s\n", aFileName.GetBuffer());
#endif
    BOOL bRet = FALSE;

    SvFileStream aFile;
    ByteString aReadLine;

    UniString suFileName( aFileName, gsl_getSystemTextEncoding());

    aFile.Open( suFileName, STREAM_READ );
    while ( aFile.ReadLine( aReadLine ))
    {
        USHORT nPos = aReadLine.Search( "include" );
        if ( nPos != STRING_NOTFOUND  )
        {
#ifdef DEBUG_VERBOSE
            fprintf( stderr, "found : %d %s\n", nPos, aReadLine.GetBuffer() );
#endif
            ByteString aResult = IsIncludeStatement( aReadLine );
#ifdef DEBUG_VERBOSE
            fprintf( stderr, "Result : %s\n", aResult.GetBuffer() );
#endif

            ByteString aNewFile;
            if ( aResult !="")
            if ( (aNewFile = Exists( aResult )) != "" )
            {
                BOOL bFound = FALSE;
                ULONG nCount = pFileList->Count();
                for ( ULONG i=0; i<nCount; i++ )
                {
                    ByteString *pStr = pFileList->GetObject(i);
                    if ( *pStr == aNewFile )
                        bFound = TRUE;
                }
#ifdef DEBUG_VERBOSE
                fprintf( stderr, "not in list : %d %s\n", nPos, aReadLine.GetBuffer() );
#endif
                if ( !bFound )
                {
                    pFileList->Insert( new ByteString( aNewFile ), LIST_APPEND );
#ifdef DEBUG_VERBOSE
                    fprintf( stderr, " CppDep %s\\\n", aNewFile.GetBuffer() );
#endif
                    Search(aNewFile);
                }
            }
        }
    }
    aFile.Close();

    return bRet;
}

ByteString CppDep::Exists( ByteString aFileName )
{
    char pFullName[1023];
    ByteString aString;

#ifdef DEBUG_VERBOSE
    fprintf( stderr, "Searching %s \n", aFileName.GetBuffer() );
#endif

    ULONG nCount = pSearchPath->Count();
    for ( ULONG n=0; n<nCount; n++)
    {
        struct stat aBuf;
        ByteString *pPathName = pSearchPath->GetObject(n);

        strcpy( pFullName, pPathName->GetBuffer());
        strcat( pFullName, DIR_SEP );
        strcat( pFullName, aFileName.GetBuffer());

#ifdef DEBUG_VERBOSE
        fprintf( stderr, "looking for %s\t ", pFullName );
#endif
        if ( stat( pFullName, &aBuf ) == 0 )
        {
#ifdef DEBUG_VERBOSE
            fprintf( stderr, "Got Dependency ", pFullName );
#endif
#ifdef DEBUG_VERBOSE
            fprintf( stderr, "%s \\\n", pFullName );
#endif

            return ByteString(pFullName);
        }
    }
    return aString;
}

ByteString CppDep::IsIncludeStatement( ByteString aLine )
{
    ByteString aRetStr;
    // WhiteSpacesfressen
    aLine.EraseAllChars(' ');
    aLine.EraseAllChars('\t');
#ifdef DEBUG_VERBOSE
    fprintf( stderr, "now : %s\n", aLine.GetBuffer() );
#endif
    // ist der erste Teil ein #include ?
    ByteString aTmpStr;
    aTmpStr = aLine.Copy( 0, 8 );
#ifdef DEBUG_VERBOSE
    fprintf( stderr, "is include : %s\n", aTmpStr.GetBuffer() );
#endif
    if ( aTmpStr.Equals("#include") )
    {
        aTmpStr = aLine.Erase( 0, 8 );
        USHORT nLen = aLine.Len();
        aLine.Erase( nLen-1, 1 );
        aLine.Erase( 0, 1 );
#ifdef DEBUG_VERBOSE
        fprintf( stderr, "Gotcha : %s\n", aLine.GetBuffer() );
#endif
        aRetStr = aLine;
    }
    return aRetStr;
}

#ifdef TEST

int main( int argc, char **argv )
{
    CppDep *pDep = new CppDep( "cppdep.cxx" );
    pDep->AddSearchPath(".");
    pDep->AddSearchPath("/usr/include");
    pDep->AddSearchPath("/usr/local/include");
    pDep->AddSearchPath("/usr/include/sys");
    pDep->AddSearchPath("/usr/include/X11");
    pDep->Execute();
    delete pDep;
    return 0;
}

#endif
<commit_msg>INTEGRATION: CWS pchfix02 (1.12.44); FILE MERGED 2006/09/01 17:54:46 kaib 1.12.44.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: cppdep.cxx,v $
 *
 *  $Revision: 1.13 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 00:48:05 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library 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 library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_tools.hxx"

#include <stdio.h>
#include <string.h>

#include <unistd.h>

#include <sys/stat.h>
#include <stream.hxx>
#include "cppdep.hxx"

//#define TEST

CppDep::CppDep( ByteString aFileName )
{
    aSourceFile = aFileName;

    pSearchPath = new ByteStringList;
    pFileList = new ByteStringList;
}

CppDep::CppDep()
{
    pSources = new ByteStringList;
    pSearchPath = new ByteStringList;
    pFileList = new ByteStringList;
}

CppDep::~CppDep()
{
    delete pSearchPath;
    delete pFileList;
}

void CppDep::Execute()
{
    ULONG nCount = pSources->Count();
    for ( ULONG n=0; n<nCount;n++)
    {
        ByteString *pStr = pSources->GetObject(n);
        Search( *pStr );
    }
}

BOOL CppDep::AddSearchPath( const char* aPath )
{
    ByteString *pStr = new ByteString( aPath );
    pSearchPath->Insert( pStr, LIST_APPEND );
    return FALSE;
}

BOOL CppDep::AddSource( const char* aSource )
{
    ByteString *pStr = new ByteString( aSource );
    pSources->Insert( pStr, LIST_APPEND );
    return FALSE;
}

BOOL CppDep::Search( ByteString aFileName )
{
#ifdef DEBUG_VERBOSE
    fprintf( stderr, "SEARCH : %s\n", aFileName.GetBuffer());
#endif
    BOOL bRet = FALSE;

    SvFileStream aFile;
    ByteString aReadLine;

    UniString suFileName( aFileName, gsl_getSystemTextEncoding());

    aFile.Open( suFileName, STREAM_READ );
    while ( aFile.ReadLine( aReadLine ))
    {
        USHORT nPos = aReadLine.Search( "include" );
        if ( nPos != STRING_NOTFOUND  )
        {
#ifdef DEBUG_VERBOSE
            fprintf( stderr, "found : %d %s\n", nPos, aReadLine.GetBuffer() );
#endif
            ByteString aResult = IsIncludeStatement( aReadLine );
#ifdef DEBUG_VERBOSE
            fprintf( stderr, "Result : %s\n", aResult.GetBuffer() );
#endif

            ByteString aNewFile;
            if ( aResult !="")
            if ( (aNewFile = Exists( aResult )) != "" )
            {
                BOOL bFound = FALSE;
                ULONG nCount = pFileList->Count();
                for ( ULONG i=0; i<nCount; i++ )
                {
                    ByteString *pStr = pFileList->GetObject(i);
                    if ( *pStr == aNewFile )
                        bFound = TRUE;
                }
#ifdef DEBUG_VERBOSE
                fprintf( stderr, "not in list : %d %s\n", nPos, aReadLine.GetBuffer() );
#endif
                if ( !bFound )
                {
                    pFileList->Insert( new ByteString( aNewFile ), LIST_APPEND );
#ifdef DEBUG_VERBOSE
                    fprintf( stderr, " CppDep %s\\\n", aNewFile.GetBuffer() );
#endif
                    Search(aNewFile);
                }
            }
        }
    }
    aFile.Close();

    return bRet;
}

ByteString CppDep::Exists( ByteString aFileName )
{
    char pFullName[1023];
    ByteString aString;

#ifdef DEBUG_VERBOSE
    fprintf( stderr, "Searching %s \n", aFileName.GetBuffer() );
#endif

    ULONG nCount = pSearchPath->Count();
    for ( ULONG n=0; n<nCount; n++)
    {
        struct stat aBuf;
        ByteString *pPathName = pSearchPath->GetObject(n);

        strcpy( pFullName, pPathName->GetBuffer());
        strcat( pFullName, DIR_SEP );
        strcat( pFullName, aFileName.GetBuffer());

#ifdef DEBUG_VERBOSE
        fprintf( stderr, "looking for %s\t ", pFullName );
#endif
        if ( stat( pFullName, &aBuf ) == 0 )
        {
#ifdef DEBUG_VERBOSE
            fprintf( stderr, "Got Dependency ", pFullName );
#endif
#ifdef DEBUG_VERBOSE
            fprintf( stderr, "%s \\\n", pFullName );
#endif

            return ByteString(pFullName);
        }
    }
    return aString;
}

ByteString CppDep::IsIncludeStatement( ByteString aLine )
{
    ByteString aRetStr;
    // WhiteSpacesfressen
    aLine.EraseAllChars(' ');
    aLine.EraseAllChars('\t');
#ifdef DEBUG_VERBOSE
    fprintf( stderr, "now : %s\n", aLine.GetBuffer() );
#endif
    // ist der erste Teil ein #include ?
    ByteString aTmpStr;
    aTmpStr = aLine.Copy( 0, 8 );
#ifdef DEBUG_VERBOSE
    fprintf( stderr, "is include : %s\n", aTmpStr.GetBuffer() );
#endif
    if ( aTmpStr.Equals("#include") )
    {
        aTmpStr = aLine.Erase( 0, 8 );
        USHORT nLen = aLine.Len();
        aLine.Erase( nLen-1, 1 );
        aLine.Erase( 0, 1 );
#ifdef DEBUG_VERBOSE
        fprintf( stderr, "Gotcha : %s\n", aLine.GetBuffer() );
#endif
        aRetStr = aLine;
    }
    return aRetStr;
}

#ifdef TEST

int main( int argc, char **argv )
{
    CppDep *pDep = new CppDep( "cppdep.cxx" );
    pDep->AddSearchPath(".");
    pDep->AddSearchPath("/usr/include");
    pDep->AddSearchPath("/usr/local/include");
    pDep->AddSearchPath("/usr/include/sys");
    pDep->AddSearchPath("/usr/include/X11");
    pDep->Execute();
    delete pDep;
    return 0;
}

#endif
<|endoftext|>


<commit_before>//Copyright (c) 2015 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.

#include "LinearAlg2DTest.h"

#include <../src/utils/linearAlg2D.h>

namespace cura
{
    CPPUNIT_TEST_SUITE_REGISTRATION(LinearAlg2DTest);

void LinearAlg2DTest::setUp()
{
    //Do nothing.
}

void LinearAlg2DTest::tearDown()
{
    //Do nothing.
}

void LinearAlg2DTest::getDist2FromLineSegmentHorizontalNearTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(100,0),Point(25,3),9,0);
}

void LinearAlg2DTest::getDist2FromLineSegmentHorizontalOnTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(100,0),Point(25,0),0,0);
}

void LinearAlg2DTest::getDist2FromLineSegmentHorizontalBeyondTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(100,0),Point(200,0),10000,1);
}

void LinearAlg2DTest::getDist2FromLineSegmentHorizontalBeforeTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(100,0),Point(-100,0),10000,-1);
}

void LinearAlg2DTest::getDist2FromLineSegmentHorizontalCornerTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(100,0),Point(-1,-1),2,-1);
}

void LinearAlg2DTest::getDist2FromLineSegmentHorizontalPerpendicularTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(100,0),Point(0,3),9,0);
}

void LinearAlg2DTest::getDist2FromLineSegmentVerticalNearTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(0,100),Point(5,25),25,0);
}

void LinearAlg2DTest::getDist2FromLineSegmentVerticalOnTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(0,100),Point(0,25),0,0);
}

void LinearAlg2DTest::getDist2FromLineSegmentVerticalBeyondTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(0,100),Point(0,200),10000,1);
}

void LinearAlg2DTest::getDist2FromLineSegmentVerticalBeforeTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(0,100),Point(0,-100),10000,-1);
}

void LinearAlg2DTest::getDist2FromLineSegmentVerticalCornerTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(0,100),Point(-1,-1),2,-1);
}

void LinearAlg2DTest::getDist2FromLineSegmentVerticalPerpendicularTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(0,100),Point(3,0),9,0);
}

void LinearAlg2DTest::getDist2FromLineSegmentDiagonalNearTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(100,100),Point(30,20),50,0);
}

void LinearAlg2DTest::getDist2FromLineSegmentDiagonalOnTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(100,100),Point(25,25),0,0);
}

void LinearAlg2DTest::getDist2FromLineSegmentDiagonalBeyondTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(100,100),Point(200,200),20000,1);
}

void LinearAlg2DTest::getDist2FromLineSegmentDiagonalBeforeTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(100,100),Point(-100,-100),20000,-1);
}

void LinearAlg2DTest::getDist2FromLineSegmentDiagonalCornerTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(100,100),Point(-3,0),9,-1);
}

void LinearAlg2DTest::getDist2FromLineSegmentDiagonalPerpendicularTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(100,100),Point(3,-3),9,0);
}

void LinearAlg2DTest::getDist2FromLineSegmentDiagonal2NearTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(100,50),Point(20,30),320,0);
}

void LinearAlg2DTest::getDist2FromLineSegmentDiagonal2OnTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(100,50),Point(40,20),0,0);
}

void LinearAlg2DTest::getDist2FromLineSegmentDiagonal2PointTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(100,50),Point(0,0),0,0);
}

void LinearAlg2DTest::getDist2FromLineSegmentDiagonal2BeyondTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(100,50),Point(200,100),12500,1);
}

void LinearAlg2DTest::getDist2FromLineSegmentDiagonal2BeforeTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(100,50),Point(-100,-50),12500,-1);
}

void LinearAlg2DTest::getDist2FromLineSegmentDiagonal2CornerTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(100,50),Point(-3,0),9,-1);
}

void LinearAlg2DTest::getDist2FromLineSegmentDiagonal2PerpendicularTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(100,50),Point(-2,4),20,0);
}

void LinearAlg2DTest::getDist2FromLineSegmentZeroNearTest()
{
    //Since the actual is_beyond may be either -1 or 1, we must make this test more specific.
    char supposed_is_beyond = 0;
    int64_t supposed_distance = LinearAlg2D::getDist2FromLineSegment(Point(0,0),Point(20,0),Point(0,0),&supposed_is_beyond);
    int64_t actual_distance = 40;
    std::stringstream ss;
    ss << "Line [0,0] -- [0,0], point [20,0], squared distance was ";
    ss << supposed_distance;
    ss << " rather than ";
    ss << actual_distance;
    ss << ".";
    CPPUNIT_ASSERT_MESSAGE(ss.str(),std::abs(supposed_distance - actual_distance) <= maximum_error);
    CPPUNIT_ASSERT_MESSAGE("Line [0,0] -- [0,0], point [20,0] was not said to be beyond the line, but it should be.",static_cast<int>(supposed_is_beyond) != 0);
}

void LinearAlg2DTest::getDist2FromLineSegmentZeroOnTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(0,0),Point(0,0),0,0);
}

void LinearAlg2DTest::getDist2FromLineSegmentAssert(Point line_start,Point line_end,Point point,int64_t actual_distance2,char actual_is_beyond)
{
    char supposed_is_beyond;
    int64_t supposed_distance = LinearAlg2D::getDist2FromLineSegment(line_start,point,line_end,&supposed_is_beyond);
    {
        std::stringstream ss;
        ss << "Line [";
        ss << line_start.X;
        ss << ",";
        ss << line_start.Y;
        ss << "] -- [";
        ss << line_end.X;
        ss << ",";
        ss << line_end.Y;
        ss << "], point [";
        ss << point.X;
        ss << ",";
        ss << point.Y;
        ss << "], squared distance was ";
        ss << supposed_distance;
        ss << " rather than ";
        ss << actual_distance2;
        ss << ".";
        CPPUNIT_ASSERT_MESSAGE(ss.str(),std::abs(supposed_distance - actual_distance2) <= maximum_error);
    }
    {
        std::stringstream ss;
        ss << "Line [";
        ss << line_start.X;
        ss << ",";
        ss << line_start.Y;
        ss << "] -- [";
        ss << line_end.X;
        ss << ",";
        ss << line_end.Y;
        ss << "], point [";
        ss << point.X;
        ss << ",";
        ss << point.Y;
        ss << "], check whether it is beyond was ";
        ss << static_cast<int>(supposed_is_beyond);
        ss << " rather than ";
        ss << static_cast<int>(actual_is_beyond);
        ss << ".";
        CPPUNIT_ASSERT_MESSAGE(ss.str(),supposed_is_beyond == actual_is_beyond);
    }
}

}<commit_msg>relaxed tests of LinAlg2D (CURA-359)<commit_after>//Copyright (c) 2015 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.

#include "LinearAlg2DTest.h"

#include <../src/utils/linearAlg2D.h>

namespace cura
{
    CPPUNIT_TEST_SUITE_REGISTRATION(LinearAlg2DTest);

void LinearAlg2DTest::setUp()
{
    //Do nothing.
}

void LinearAlg2DTest::tearDown()
{
    //Do nothing.
}

void LinearAlg2DTest::getDist2FromLineSegmentHorizontalNearTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(100,0),Point(25,3),9,0);
}

void LinearAlg2DTest::getDist2FromLineSegmentHorizontalOnTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(100,0),Point(25,0),0,0);
}

void LinearAlg2DTest::getDist2FromLineSegmentHorizontalBeyondTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(100,0),Point(200,0),10000,1);
}

void LinearAlg2DTest::getDist2FromLineSegmentHorizontalBeforeTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(100,0),Point(-100,0),10000,-1);
}

void LinearAlg2DTest::getDist2FromLineSegmentHorizontalCornerTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(100,0),Point(-1,-1),2,-1);
}

void LinearAlg2DTest::getDist2FromLineSegmentHorizontalPerpendicularTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(100,0),Point(0,3),9,0);
}

void LinearAlg2DTest::getDist2FromLineSegmentVerticalNearTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(0,100),Point(5,25),25,0);
}

void LinearAlg2DTest::getDist2FromLineSegmentVerticalOnTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(0,100),Point(0,25),0,0);
}

void LinearAlg2DTest::getDist2FromLineSegmentVerticalBeyondTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(0,100),Point(0,200),10000,1);
}

void LinearAlg2DTest::getDist2FromLineSegmentVerticalBeforeTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(0,100),Point(0,-100),10000,-1);
}

void LinearAlg2DTest::getDist2FromLineSegmentVerticalCornerTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(0,100),Point(-1,-1),2,-1);
}

void LinearAlg2DTest::getDist2FromLineSegmentVerticalPerpendicularTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(0,100),Point(3,0),9,0);
}

void LinearAlg2DTest::getDist2FromLineSegmentDiagonalNearTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(100,100),Point(30,20),50,0);
}

void LinearAlg2DTest::getDist2FromLineSegmentDiagonalOnTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(100,100),Point(25,25),0,0);
}

void LinearAlg2DTest::getDist2FromLineSegmentDiagonalBeyondTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(100,100),Point(200,200),20000,1);
}

void LinearAlg2DTest::getDist2FromLineSegmentDiagonalBeforeTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(100,100),Point(-100,-100),20000,-1);
}

void LinearAlg2DTest::getDist2FromLineSegmentDiagonalCornerTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(100,100),Point(-3,0),9,-1);
}

void LinearAlg2DTest::getDist2FromLineSegmentDiagonalPerpendicularTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(100,100),Point(3,-3),9,0);
}

void LinearAlg2DTest::getDist2FromLineSegmentDiagonal2NearTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(100,50),Point(20,30),320,0);
}

void LinearAlg2DTest::getDist2FromLineSegmentDiagonal2OnTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(100,50),Point(40,20),0,0);
}

void LinearAlg2DTest::getDist2FromLineSegmentDiagonal2PointTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(100,50),Point(0,0),0,0);
}

void LinearAlg2DTest::getDist2FromLineSegmentDiagonal2BeyondTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(100,50),Point(200,100),12500,1);
}

void LinearAlg2DTest::getDist2FromLineSegmentDiagonal2BeforeTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(100,50),Point(-100,-50),12500,-1);
}

void LinearAlg2DTest::getDist2FromLineSegmentDiagonal2CornerTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(100,50),Point(-3,0),9,-1);
}

void LinearAlg2DTest::getDist2FromLineSegmentDiagonal2PerpendicularTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(100,50),Point(-2,4),20,0);
}

void LinearAlg2DTest::getDist2FromLineSegmentZeroNearTest()
{
    //Since the actual is_beyond may be either -1 or 1, we must make this test more specific.
    char supposed_is_beyond = 0;
    int64_t supposed_distance = LinearAlg2D::getDist2FromLineSegment(Point(0,0),Point(20,0),Point(0,0),&supposed_is_beyond);
    int64_t actual_distance = 40;
    std::stringstream ss;
    ss << "Line [0,0] -- [0,0], point [20,0], squared distance was ";
    ss << supposed_distance;
    ss << " rather than ";
    ss << actual_distance;
    ss << ".";
    CPPUNIT_ASSERT_MESSAGE(ss.str(),std::abs(supposed_distance - actual_distance) <= maximum_error);
    CPPUNIT_ASSERT_MESSAGE("Line [0,0] -- [0,0], point [20,0] was not said to be beyond the line, but it should be.",static_cast<int>(supposed_is_beyond) != 0);
}

void LinearAlg2DTest::getDist2FromLineSegmentZeroOnTest()
{
    getDist2FromLineSegmentAssert(Point(0,0),Point(0,0),Point(0,0),0,0);
}

void LinearAlg2DTest::getDist2FromLineSegmentAssert(Point line_start,Point line_end,Point point,int64_t actual_distance2,char actual_is_beyond)
{
    char supposed_is_beyond;
    int64_t supposed_distance = LinearAlg2D::getDist2FromLineSegment(line_start,point,line_end,&supposed_is_beyond);
    {
        std::stringstream ss;
        ss << "Line [";
        ss << line_start.X;
        ss << ",";
        ss << line_start.Y;
        ss << "] -- [";
        ss << line_end.X;
        ss << ",";
        ss << line_end.Y;
        ss << "], point [";
        ss << point.X;
        ss << ",";
        ss << point.Y;
        ss << "], squared distance was ";
        ss << supposed_distance;
        ss << " rather than ";
        ss << actual_distance2;
        ss << ".";
        CPPUNIT_ASSERT_MESSAGE(ss.str(),std::fabs(sqrt(double(supposed_distance)) - sqrt(double(actual_distance2))) <= maximum_error);
    }
    {
        std::stringstream ss;
        ss << "Line [";
        ss << line_start.X;
        ss << ",";
        ss << line_start.Y;
        ss << "] -- [";
        ss << line_end.X;
        ss << ",";
        ss << line_end.Y;
        ss << "], point [";
        ss << point.X;
        ss << ",";
        ss << point.Y;
        ss << "], check whether it is beyond was ";
        ss << static_cast<int>(supposed_is_beyond);
        ss << " rather than ";
        ss << static_cast<int>(actual_is_beyond);
        ss << ".";
        CPPUNIT_ASSERT_MESSAGE(ss.str(),supposed_is_beyond == actual_is_beyond);
    }
}

}<|endoftext|>