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

#include "TH1F.h"
#include "TObjArray.h"
#include "TList.h"
#include "TROOT.h"
#include "TSystem.h"
#include "TCanvas.h"

#include "AliVEvent.h"
#include "AliVVertex.h"
#include "AliAODEvent.h"
#include "AliESDEvent.h"
#include "AliAnalysisVertexingHF.h"
#include "AliMixedEvent.h"
#include "AliAnalysisTaskMEVertexingHF.h"
#include "AliAnalysisManager.h"
#include "AliMultiEventInputHandler.h"

ClassImp(AliAnalysisTaskMEVertexingHF)

//________________________________________________________________________
AliAnalysisTaskMEVertexingHF::AliAnalysisTaskMEVertexingHF(const char *name) :
AliAnalysisTaskME(name),
fvHF(0),
fMixedEvent(),
fVerticesHFTClArr(0),
fD0toKpiTClArr(0),
fJPSItoEleTClArr(0),
fCharm3ProngTClArr(0),
fCharm4ProngTClArr(0),
fDstarTClArr(0),
fLikeSign2ProngTClArr(0),
fLikeSign3ProngTClArr(0)
{
  // Constructor
}
//________________________________________________________________________
void AliAnalysisTaskMEVertexingHF::Init()
{
 // Initialization
 // Instanciates vHF and loads its parameters
 // Some parameters are changed

  if(gROOT->LoadMacro("ConfigVertexingHF.C")) {
    printf("AnalysisTaskMEVertexingHF::Init() \n Using $ALICE_ROOT/PWG3/vertexingHF/ConfigVertexingHF.C\n");
    gROOT->LoadMacro("$ALICE_ROOT/PWG3/vertexingHF/ConfigVertexingHF.C");
  }
  fvHF = (AliAnalysisVertexingHF*)gROOT->ProcessLine("ConfigVertexingHF()");
  fvHF->SetMixEventOn();
  fvHF->SetInputAOD();
  fvHF->PrintStatus();
  if(fvHF->GetLikeSign()) {
    printf("WARNING: fLikeSign will be switched off!");
    fvHF->SetLikeSignOff();
  }
  if(fvHF->GetRecoPrimVtxSkippingTrks() || fvHF->GetRmTrksFromPrimVtx()){
    fvHF->UnsetRecoPrimVtxSkippingTrks();
    printf("WARNING: if on, fRecoPrimVtxSkippingTrks and fRmTrksFromPrimVtx  will be switched off!\n");
  }

  AliAnalysisManager::GetAnalysisManager()->RegisterExtraFile("AliAOD.VertexingHF.root");

  return;
}
//________________________________________________________________________
void AliAnalysisTaskMEVertexingHF::UserCreateOutputObjects()
{
// Create the output container

  if (!AODEvent()) {
    Fatal("UserCreateOutputObjects", "This task needs an AOD handler");
    return;
  }

  if(!fvHF) {
    printf("AnalysisTaskMEVertexingHF::UserCreateOutPutData() \n ERROR! no fvHF!\n");
    return;
  }
  fVerticesHFTClArr = new TClonesArray("AliAODVertex", 0);
  fVerticesHFTClArr->SetName("VerticesHF");
  AddAODBranch("TClonesArray", &fVerticesHFTClArr);
  if(fvHF->GetD0toKpi()) {
    fD0toKpiTClArr = new TClonesArray("AliAODRecoDecayHF2Prong", 0);
    fD0toKpiTClArr->SetName("D0toKpi");
    AddAODBranch("TClonesArray", &fD0toKpiTClArr);
  }
  if(fvHF->GetJPSItoEle()) {
    fJPSItoEleTClArr = new TClonesArray("AliAODRecoDecayHF2Prong", 0);
    fJPSItoEleTClArr->SetName("JPSItoEle");
    AddAODBranch("TClonesArray", &fJPSItoEleTClArr);
  }
  if(fvHF->Get3Prong()) {
    fCharm3ProngTClArr = new TClonesArray("AliAODRecoDecayHF3Prong", 0);
    fCharm3ProngTClArr->SetName("Charm3Prong");
    AddAODBranch("TClonesArray", &fCharm3ProngTClArr);
  }
  if(fvHF->Get4Prong()) {
    fCharm4ProngTClArr = new TClonesArray("AliAODRecoDecayHF4Prong", 0);
    fCharm4ProngTClArr->SetName("Charm4Prong");
    AddAODBranch("TClonesArray", &fCharm4ProngTClArr);
  }

  if(fvHF->GetDstar()) {
    fDstarTClArr = new TClonesArray("AliAODRecoCascadeHF", 0);
    fDstarTClArr->SetName("Dstar");
    AddAODBranch("TClonesArray", &fDstarTClArr);
  }

  if(fvHF->GetLikeSign()) {
    fLikeSign2ProngTClArr = new TClonesArray("AliAODRecoDecayHF2Prong", 0);
    fLikeSign2ProngTClArr->SetName("LikeSign2Prong");
    AddAODBranch("TClonesArray", &fLikeSign2ProngTClArr);
  }

  if(fvHF->GetLikeSign() && fvHF->Get3Prong()) {
    fLikeSign3ProngTClArr = new TClonesArray("AliAODRecoDecayHF3Prong", 0);
    fLikeSign3ProngTClArr->SetName("LikeSign3Prong");
    AddAODBranch("TClonesArray", &fLikeSign3ProngTClArr);
  }

  return;
}

//________________________________________________________________________
void AliAnalysisTaskMEVertexingHF::UserExec(Option_t *)
{
  // Execute analysis for current event:
  // first build the mixed event, compute the new primary vtx
  // then heavy flavor vertexing

  Int_t nev = fInputHandler->GetBufferSize();
  fMixedEvent = new AliMixedEvent();
  fMixedEvent->Reset();
  TString primTitle;
  TString primTitleFirst;

  TObjArray *vertices=new TObjArray(nev);
  for (Int_t iev = 0; iev < nev; iev++) {
    AliAODEvent *evt = (AliAODEvent*)GetEvent(iev);
    if(!evt) {delete vertices;return;}
    AliAODVertex *evtVtx=(AliAODVertex*)evt->GetPrimaryVertex();
    if(!evtVtx) {delete vertices;return;}
    primTitle = evtVtx->GetTitle();
    Int_t nContrib=evtVtx->GetNContributors();
    if(!primTitle.Contains("VertexerTracks") || nContrib<=0) {
      delete vertices;
      return;
    }

    AliAODVertex *vtxCopy=new AliAODVertex(*evtVtx);
    primTitleFirst=evtVtx->GetTitle();

    fMixedEvent->AddEvent(evt);

    vertices->AddLast(vtxCopy);
  }

  fMixedEvent->Init();
  Double_t vtxPos[3]={0.,0.,0.},vtxSigma[3]={0.,0.,0.};
  Int_t nContributors[1]={0};
  Double_t chi2=0;
  Bool_t primaryOk=fMixedEvent->ComputeVtx(vertices,vtxPos,vtxSigma,nContributors);
  if(!primaryOk) {delete vertices;return;}
  Int_t contribCopy=nContributors[0];
  AliVVertex* newVertex=new AliESDVertex(vtxPos,vtxSigma,chi2,contribCopy);
  newVertex->SetTitle(primTitleFirst.Data());
  fMixedEvent->SetPrimaryVertex(newVertex);

  delete vertices;

  fvHF->FindCandidates(fMixedEvent,
		       fVerticesHFTClArr,
		       fD0toKpiTClArr,
		       fJPSItoEleTClArr,
		       fCharm3ProngTClArr,
		       fCharm4ProngTClArr,
		       fDstarTClArr,
		       fLikeSign2ProngTClArr,
		       fLikeSign3ProngTClArr);

  return;
}

//________________________________________________________________________
void AliAnalysisTaskMEVertexingHF::Terminate(Option_t *)
{
  // Terminate analysis
}
<commit_msg>Fixing memory leak (Rossella)<commit_after>/**************************************************************************
 * Copyright(c) 1998-2009, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/
//*************************************************************************
// Class AliAnalysisTaskMEVertexingHF
// AliAnalysisTaskME for event mixing, building the background for
// heavy-flavour decay candidates
// Author: R.Romita, r.romita@gsi.de
//*************************************************************************

#include "TH1F.h"
#include "TObjArray.h"
#include "TList.h"
#include "TROOT.h"
#include "TSystem.h"
#include "TCanvas.h"

#include "AliVEvent.h"
#include "AliVVertex.h"
#include "AliAODEvent.h"
#include "AliESDEvent.h"
#include "AliAnalysisVertexingHF.h"
#include "AliMixedEvent.h"
#include "AliAnalysisTaskMEVertexingHF.h"
#include "AliAnalysisManager.h"
#include "AliMultiEventInputHandler.h"

ClassImp(AliAnalysisTaskMEVertexingHF)

//________________________________________________________________________
AliAnalysisTaskMEVertexingHF::AliAnalysisTaskMEVertexingHF(const char *name) :
AliAnalysisTaskME(name),
fvHF(0),
fMixedEvent(),
fVerticesHFTClArr(0),
fD0toKpiTClArr(0),
fJPSItoEleTClArr(0),
fCharm3ProngTClArr(0),
fCharm4ProngTClArr(0),
fDstarTClArr(0),
fLikeSign2ProngTClArr(0),
fLikeSign3ProngTClArr(0)
{
  // Constructor
}
//________________________________________________________________________
void AliAnalysisTaskMEVertexingHF::Init()
{
 // Initialization
 // Instanciates vHF and loads its parameters
 // Some parameters are changed

  if(gROOT->LoadMacro("ConfigVertexingHF.C")) {
    printf("AnalysisTaskMEVertexingHF::Init() \n Using $ALICE_ROOT/PWG3/vertexingHF/ConfigVertexingHF.C\n");
    gROOT->LoadMacro("$ALICE_ROOT/PWG3/vertexingHF/ConfigVertexingHF.C");
  }
  fvHF = (AliAnalysisVertexingHF*)gROOT->ProcessLine("ConfigVertexingHF()");
  fvHF->SetMixEventOn();
  fvHF->SetInputAOD();
  fvHF->PrintStatus();
  if(fvHF->GetLikeSign()) {
    printf("WARNING: fLikeSign will be switched off!");
    fvHF->SetLikeSignOff();
  }
  if(fvHF->GetRecoPrimVtxSkippingTrks() || fvHF->GetRmTrksFromPrimVtx()){
    fvHF->UnsetRecoPrimVtxSkippingTrks();
    printf("WARNING: if on, fRecoPrimVtxSkippingTrks and fRmTrksFromPrimVtx  will be switched off!\n");
  }

  AliAnalysisManager::GetAnalysisManager()->RegisterExtraFile("AliAOD.VertexingHF.root");

  return;
}
//________________________________________________________________________
void AliAnalysisTaskMEVertexingHF::UserCreateOutputObjects()
{
// Create the output container

  if (!AODEvent()) {
    Fatal("UserCreateOutputObjects", "This task needs an AOD handler");
    return;
  }

  if(!fvHF) {
    printf("AnalysisTaskMEVertexingHF::UserCreateOutPutData() \n ERROR! no fvHF!\n");
    return;
  }
  fVerticesHFTClArr = new TClonesArray("AliAODVertex", 0);
  fVerticesHFTClArr->SetName("VerticesHF");
  AddAODBranch("TClonesArray", &fVerticesHFTClArr);
  if(fvHF->GetD0toKpi()) {
    fD0toKpiTClArr = new TClonesArray("AliAODRecoDecayHF2Prong", 0);
    fD0toKpiTClArr->SetName("D0toKpi");
    AddAODBranch("TClonesArray", &fD0toKpiTClArr);
  }
  if(fvHF->GetJPSItoEle()) {
    fJPSItoEleTClArr = new TClonesArray("AliAODRecoDecayHF2Prong", 0);
    fJPSItoEleTClArr->SetName("JPSItoEle");
    AddAODBranch("TClonesArray", &fJPSItoEleTClArr);
  }
  if(fvHF->Get3Prong()) {
    fCharm3ProngTClArr = new TClonesArray("AliAODRecoDecayHF3Prong", 0);
    fCharm3ProngTClArr->SetName("Charm3Prong");
    AddAODBranch("TClonesArray", &fCharm3ProngTClArr);
  }
  if(fvHF->Get4Prong()) {
    fCharm4ProngTClArr = new TClonesArray("AliAODRecoDecayHF4Prong", 0);
    fCharm4ProngTClArr->SetName("Charm4Prong");
    AddAODBranch("TClonesArray", &fCharm4ProngTClArr);
  }

  if(fvHF->GetDstar()) {
    fDstarTClArr = new TClonesArray("AliAODRecoCascadeHF", 0);
    fDstarTClArr->SetName("Dstar");
    AddAODBranch("TClonesArray", &fDstarTClArr);
  }

  if(fvHF->GetLikeSign()) {
    fLikeSign2ProngTClArr = new TClonesArray("AliAODRecoDecayHF2Prong", 0);
    fLikeSign2ProngTClArr->SetName("LikeSign2Prong");
    AddAODBranch("TClonesArray", &fLikeSign2ProngTClArr);
  }

  if(fvHF->GetLikeSign() && fvHF->Get3Prong()) {
    fLikeSign3ProngTClArr = new TClonesArray("AliAODRecoDecayHF3Prong", 0);
    fLikeSign3ProngTClArr->SetName("LikeSign3Prong");
    AddAODBranch("TClonesArray", &fLikeSign3ProngTClArr);
  }

  return;
}

//________________________________________________________________________
void AliAnalysisTaskMEVertexingHF::UserExec(Option_t *)
{
  // Execute analysis for current event:
  // first build the mixed event, compute the new primary vtx
  // then heavy flavor vertexing

  Int_t nev = fInputHandler->GetBufferSize();
  fMixedEvent = new AliMixedEvent();
  fMixedEvent->Reset();
  TString primTitle;
  TString primTitleFirst;
  AliAODVertex *vtxCopy=0;

  TObjArray *vertices=new TObjArray(nev);
  for (Int_t iev = 0; iev < nev; iev++) {
    AliAODEvent *evt = (AliAODEvent*)GetEvent(iev);
    if(!evt) {delete vertices;return;}
    AliAODVertex *evtVtx=(AliAODVertex*)evt->GetPrimaryVertex();
    if(!evtVtx) {delete vertices;return;}
    primTitle = evtVtx->GetTitle();
    Int_t nContrib=evtVtx->GetNContributors();
    if(!primTitle.Contains("VertexerTracks") || nContrib<=0) {
      delete vertices;
      return;
    }

    vtxCopy=new AliAODVertex(*evtVtx);
    primTitleFirst=evtVtx->GetTitle();

    fMixedEvent->AddEvent(evt);

    vertices->AddLast(vtxCopy);
  }

  fMixedEvent->Init();
  Double_t vtxPos[3]={0.,0.,0.},vtxSigma[3]={0.,0.,0.};
  Int_t nContributors[1]={0};
  Double_t chi2=0;
  Bool_t primaryOk=fMixedEvent->ComputeVtx(vertices,vtxPos,vtxSigma,nContributors);
  if(!primaryOk) {
    delete vertices;
    delete vtxCopy;
    vtxCopy=NULL;
    return;
  }
  Int_t contribCopy=nContributors[0];
  AliVVertex* newVertex=new AliESDVertex(vtxPos,vtxSigma,chi2,contribCopy);
  newVertex->SetTitle(primTitleFirst.Data());
  fMixedEvent->SetPrimaryVertex(newVertex);

  delete vertices;
  delete vtxCopy;
  vtxCopy=NULL;

  fvHF->FindCandidates(fMixedEvent,
		       fVerticesHFTClArr,
		       fD0toKpiTClArr,
		       fJPSItoEleTClArr,
		       fCharm3ProngTClArr,
		       fCharm4ProngTClArr,
		       fDstarTClArr,
		       fLikeSign2ProngTClArr,
		       fLikeSign3ProngTClArr);

  delete newVertex;
  return;
}

//________________________________________________________________________
void AliAnalysisTaskMEVertexingHF::Terminate(Option_t *)
{
  // Terminate analysis
}
<|endoftext|>


<commit_before>/*
Copyright (c) 2021 Advanced Micro Devices, Inc. All rights reserved.
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 WARRANNTY OF ANY KIND, EXPRESS OR
IMPLIED, INNCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANNY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER INN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR INN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

/**
Testcase Scenarios :

1)Validates functionality of hipStreamAddCallback with created stream.

2)Validates functionality of stream with cu mask.

3)Create a stream with all CU masks disabled (0x00000000).
Verify that default CU mask is set for the stream.

4)Size is greater than physical CU number. In this case the extra elements
are ignored and hipExtStreamCreateWithCUMask must return hipSuccess.

5)Negative Testing of hipExtStreamCreateWithCUMask.
*/

#include <hip_test_common.hh>
#include <hip_test_kernels.hh>
#include <unistd.h>
#include <iostream>
#include <vector>

#define NUM_CU_PARTITIONS 4
#define CONSTANT 1.618f
#define SIZE_INBYTES_OF_MB (1024*1024)
#define GRIDSIZE 512
#define BLOCKSIZE 256
#define ZERO_MASK 0x00000000

namespace hipExtStreamCreateWithCUMaskTest {

float *A_h, *C_h;
bool cbDone = false;
bool isPassed = true;
size_t N = 4 * SIZE_INBYTES_OF_MB;

// Make a default CU mask bit-array where all CUs are active
// this default mask is expected to be returned when there is no
// custom or global CU mask defined.
void createDefaultCUMask(std::vector<uint32_t> *pdefaultCUMask,
                         int numOfCUs) {
  uint32_t temp = 0;
  uint32_t bit_index = 0;
  for (int i = 0; i < numOfCUs; i++) {
    temp |= 1UL << bit_index;
    if (bit_index >= 32) {
      (*pdefaultCUMask).push_back(temp);
      temp = 0;
      bit_index = 0;
      temp |= 1UL << bit_index;
    }
    bit_index += 1;
  }
  if (bit_index != 0) {
    (*pdefaultCUMask).push_back(temp);
  }
}
// Create masks of disabled CU masks.
void createDisabledCUMask(std::vector<uint32_t> *pdisabledCUMask,
                         int numOfCUs) {
  uint32_t temp = ZERO_MASK;
  uint32_t bit_index = 0;
  for (int i = 0; i < numOfCUs; i++) {
    if (bit_index >= 32) {
      (*pdisabledCUMask).push_back(temp);
      temp = ZERO_MASK;
      bit_index = 0;
    }
    bit_index += 1;
  }
  if (bit_index != 0) {
    (*pdisabledCUMask).push_back(temp);
  }
}

void Callback(hipStream_t stream, hipError_t status,
              void* userData) {
  isPassed = true;
  stream = 0;
  HIP_CHECK(status);
  REQUIRE(userData == nullptr);
  for (size_t i = 0; i < N; i++) {
    if (C_h[i] != A_h[i] * A_h[i]) {
      UNSCOPED_INFO("Data mismatch at index: " << i);
      isPassed = false;
      break;
    }
  }
  cbDone = true;
}
}  // namespace hipExtStreamCreateWithCUMaskTest

using hipExtStreamCreateWithCUMaskTest::A_h;
using hipExtStreamCreateWithCUMaskTest::C_h;
using hipExtStreamCreateWithCUMaskTest::cbDone;
using hipExtStreamCreateWithCUMaskTest::isPassed;
using hipExtStreamCreateWithCUMaskTest::N;
using hipExtStreamCreateWithCUMaskTest::createDefaultCUMask;
using hipExtStreamCreateWithCUMaskTest::createDisabledCUMask;
using hipExtStreamCreateWithCUMaskTest::Callback;

/**
 * Scenario: Validates functionality of hipStreamAddCallback with created stream.
 */
TEST_CASE("Unit_hipExtStreamCreateWithCUMask_ValidateCallbackFunc") {
  float *A_d, *C_d;
  size_t Nbytes = N * sizeof(float);
  cbDone = false;
  A_h = reinterpret_cast<float*>(malloc(Nbytes));
  REQUIRE(A_h != nullptr);
  C_h = reinterpret_cast<float*>(malloc(Nbytes));
  REQUIRE(C_h != nullptr);

  // Fill with Phi + i
  for (size_t i = 0; i < N; i++) {
    A_h[i] = CONSTANT + i;
  }

  HIP_CHECK(hipMalloc(&A_d, Nbytes));
  HIP_CHECK(hipMalloc(&C_d, Nbytes));

  hipStream_t mystream;
  std::vector<uint32_t> defaultCUMask;
  HIP_CHECK(hipSetDevice(0));
  hipDeviceProp_t props;
  HIP_CHECK(hipGetDeviceProperties(&props, 0));
  createDefaultCUMask(&defaultCUMask, props.multiProcessorCount);

  hipExtStreamCreateWithCUMask(&mystream, defaultCUMask.size(),
                               defaultCUMask.data());
  HIP_CHECK(hipMemcpyAsync(A_d, A_h, Nbytes, hipMemcpyHostToDevice,
          mystream));
  const unsigned blocks = GRIDSIZE;
  const unsigned threadsPerBlock = BLOCKSIZE;
  hipLaunchKernelGGL((HipTest::vector_square), dim3(blocks),
                     dim3(threadsPerBlock), 0, mystream, A_d, C_d, N);
  HIP_CHECK(hipMemcpyAsync(C_h, C_d, Nbytes, hipMemcpyDeviceToHost,
          mystream));
  HIP_CHECK(hipStreamAddCallback(mystream, Callback, nullptr, 0));
  while (!cbDone) usleep(100000);  // Sleep for 100 ms
  HIP_CHECK(hipStreamDestroy(mystream));
  HIP_CHECK(hipFree(reinterpret_cast<void*>(C_d)));
  HIP_CHECK(hipFree(reinterpret_cast<void*>(A_d)));
  free(C_h);
  free(A_h);
  REQUIRE(isPassed == true);
}

/**
 * Scenario: Validates functionality of stream with cu mask.
 */
TEST_CASE("Unit_hipExtStreamCreateWithCUMask_Functionality") {
  const int KNumPartition = NUM_CU_PARTITIONS;
  float *dA[KNumPartition], *dC[KNumPartition];
  float *hA, *hC;
  size_t N = 25*SIZE_INBYTES_OF_MB;
  size_t Nbytes = N * sizeof(float);
  std::vector<hipStream_t> streams(KNumPartition);
  std::vector<std::vector<uint32_t>> cuMasks(KNumPartition);
  std::stringstream ss[KNumPartition];

  int nGpu = 0;
  HIP_CHECK(hipGetDeviceCount(&nGpu));
  if (nGpu < 1) {
    WARN("Didn't find any GPU! skipping the test!");
    return;
  }

  static int device = 0;
  HIP_CHECK(hipSetDevice(device));
  hipDeviceProp_t props;
  HIP_CHECK(hipGetDeviceProperties(&props, device));
  INFO("info: running on bus " << "0x" << props.pciBusID << " "
  << props.name << " with " << props.multiProcessorCount << " CUs");

  hA =  new float[Nbytes];
  REQUIRE(hA != nullptr);
  hC =  new float[Nbytes];
  REQUIRE(hC != nullptr);
  for (size_t i = 0; i < N; i++) {
    hA[i] = CONSTANT + i;
  }

  for (int np = 0; np < KNumPartition; np++) {
    HIP_CHECK(hipMalloc(&dA[np], Nbytes));
    HIP_CHECK(hipMalloc(&dC[np], Nbytes));
    // make unique CU masks in the multiple of dwords for each stream
    uint32_t temp = 0;
    uint32_t bit_index = np;
    for (int i = np; i < props.multiProcessorCount; i = i + 4) {
      temp |= 1UL << bit_index;
      if (bit_index >= 32) {
        cuMasks[np].push_back(temp);
        temp = 0;
        bit_index = np;
        temp |= 1UL << bit_index;
      }
      bit_index += 4;
    }
    if (bit_index != 0) {
      cuMasks[np].push_back(temp);
    }

    HIP_CHECK(hipExtStreamCreateWithCUMask(&streams[np], cuMasks[np].size(),
            cuMasks[np].data()));

    HIP_CHECK(hipMemcpy(dA[np], hA, Nbytes, hipMemcpyHostToDevice));

    ss[np] << std::hex;
    for (int i = cuMasks[np].size() - 1; i >= 0; i--) {
      ss[np] << cuMasks[np][i];
    }
  }

  const unsigned blocks = GRIDSIZE;
  const unsigned threadsPerBlock = BLOCKSIZE;

  auto single_start = std::chrono::steady_clock::now();
  INFO("info: launch 'vector_square' kernel on one stream " <<
  streams[0] << " with CU mask: 0x" << ss[0].str().c_str());

  hipLaunchKernelGGL(HipTest::vector_square, dim3(blocks),
                     dim3(threadsPerBlock), 0, streams[0], dA[0], dC[0], N);
  hipDeviceSynchronize();

  auto single_end = std::chrono::steady_clock::now();
  std::chrono::duration<double> single_kernel_time = single_end - single_start;

  HIP_CHECK(hipMemcpy(hC, dC[0], Nbytes, hipMemcpyDeviceToHost));

  for (size_t i = 0; i < N; i++) {
    REQUIRE(hC[i] == (hA[i] * hA[i]));
  }

  INFO("info: launch 'vector_square' kernel on "
  << KNumPartition << " streams:");
  auto all_start = std::chrono::steady_clock::now();
  for (int np = 0; np < KNumPartition; np++) {
    INFO("info: launch 'vector_square' kernel on the stream "
    << streams[np] << " with CU mask: 0x" << ss[np].str().c_str());
    hipLaunchKernelGGL(HipTest::vector_square, dim3(blocks),
    dim3(threadsPerBlock), 0, streams[np], dA[np], dC[np], N);
  }
  hipDeviceSynchronize();

  auto all_end = std::chrono::steady_clock::now();
  std::chrono::duration<double> all_kernel_time = all_end - all_start;

  for (int np = 0; np < KNumPartition; np++) {
    HIP_CHECK(hipMemcpy(hC, dC[np], Nbytes, hipMemcpyDeviceToHost));
    for (size_t i = 0; i < N; i++) {
      REQUIRE(hC[i] == (hA[i] * hA[i]));
    }
  }

  INFO("info: kernel launched on one stream took: " <<
  single_kernel_time.count() << " seconds");
  INFO("info: kernels launched on " << KNumPartition <<
  " streams took: " << all_kernel_time.count() << " seconds");
  INFO("info: launching kernels on " << KNumPartition <<
  " streams asynchronously is " <<
  single_kernel_time.count() / (all_kernel_time.count() / KNumPartition)
  << " times faster per stream than launching on one stream alone");

  delete [] hA;
  delete [] hC;
  for (int np = 0; np < KNumPartition; np++) {
    hipFree(dC[np]);
    hipFree(dA[np]);
    HIP_CHECK(hipStreamDestroy(streams[np]));
  }
}

/**
 * Scenario: Create a stream with all CU masks disabled (0x00000000).
 * Verify that default CU mask is set for the stream.
 */
TEST_CASE("Unit_hipExtStreamCreateWithCUMask_AllCUsMasked") {
  HIP_CHECK(hipSetDevice(0));
  hipDeviceProp_t props;
  HIP_CHECK(hipGetDeviceProperties(&props, 0));
  // make a CU mask with all CUs disabled.
  std::vector<uint32_t> allCUDisabled;
  createDisabledCUMask(&allCUDisabled, props.multiProcessorCount);
  hipStream_t stream;
  HIP_CHECK(hipExtStreamCreateWithCUMask(&stream, allCUDisabled.size(),
          allCUDisabled.data()));
  // Verify whether default CU mask is set for the stream.
  uint32_t size = (props.multiProcessorCount / 32) + 1;
  std::vector<uint32_t> cuMask(size);
  std::vector<uint32_t> defaultCUMask;
  createDefaultCUMask(&defaultCUMask, props.multiProcessorCount);
  HIP_CHECK(hipExtStreamGetCUMask(stream, cuMask.size(), &cuMask[0]));
  for (int i = 0; i < static_cast<int>(defaultCUMask.size()); i++) {
    REQUIRE(defaultCUMask[i] == cuMask[i]);
  }
  HIP_CHECK(hipStreamDestroy(stream));
}

/**
 * Scenario: Negative Testing of hipExtStreamCreateWithCUMask.
 */
TEST_CASE("Unit_hipExtStreamCreateWithCUMask_NegTst") {
  std::vector<uint32_t> defaultCUMask;
  REQUIRE(hipSuccess == hipSetDevice(0));
  hipDeviceProp_t props;
  REQUIRE(hipSuccess == hipGetDeviceProperties(&props, 0));
  createDefaultCUMask(&defaultCUMask, props.multiProcessorCount);
  hipStream_t stream;
  // Negative Scenario 1: stream = nullptr
  SECTION("stream is nullptr") {
    REQUIRE_FALSE(hipExtStreamCreateWithCUMask(nullptr,
                  defaultCUMask.size(),
                  defaultCUMask.data()) == hipSuccess);
  }
  // Negative Scenario 2: cuMaskSize = 0
  SECTION("cuMaskSize is 0") {
    REQUIRE_FALSE(hipExtStreamCreateWithCUMask(&stream, 0,
                  defaultCUMask.data()) == hipSuccess);
  }
  // Negative Scenario 3: cuMask = nullptr
  SECTION("cuMask is nullptr") {
    REQUIRE_FALSE(hipExtStreamCreateWithCUMask(&stream,
                  defaultCUMask.size(),
                  nullptr) == hipSuccess);
  }
}
<commit_msg>SWDEV-303262 - Catch2 test fix for -Wunused-but-set-parameter compilation error. (#2357)<commit_after>/*
Copyright (c) 2021 Advanced Micro Devices, Inc. All rights reserved.
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 WARRANNTY OF ANY KIND, EXPRESS OR
IMPLIED, INNCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANNY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER INN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR INN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

/**
Testcase Scenarios :

1)Validates functionality of hipStreamAddCallback with created stream.

2)Validates functionality of stream with cu mask.

3)Create a stream with all CU masks disabled (0x00000000).
Verify that default CU mask is set for the stream.

4)Size is greater than physical CU number. In this case the extra elements
are ignored and hipExtStreamCreateWithCUMask must return hipSuccess.

5)Negative Testing of hipExtStreamCreateWithCUMask.
*/

#include <hip_test_common.hh>
#include <hip_test_kernels.hh>
#include <unistd.h>
#include <iostream>
#include <vector>

#define NUM_CU_PARTITIONS 4
#define CONSTANT 1.618f
#define SIZE_INBYTES_OF_MB (1024*1024)
#define GRIDSIZE 512
#define BLOCKSIZE 256
#define ZERO_MASK 0x00000000

namespace hipExtStreamCreateWithCUMaskTest {

float *A_h, *C_h;
bool cbDone = false;
bool isPassed = true;
size_t N = 4 * SIZE_INBYTES_OF_MB;

// Make a default CU mask bit-array where all CUs are active
// this default mask is expected to be returned when there is no
// custom or global CU mask defined.
void createDefaultCUMask(std::vector<uint32_t> *pdefaultCUMask,
                         int numOfCUs) {
  uint32_t temp = 0;
  uint32_t bit_index = 0;
  for (int i = 0; i < numOfCUs; i++) {
    temp |= 1UL << bit_index;
    if (bit_index >= 32) {
      (*pdefaultCUMask).push_back(temp);
      temp = 0;
      bit_index = 0;
      temp |= 1UL << bit_index;
    }
    bit_index += 1;
  }
  if (bit_index != 0) {
    (*pdefaultCUMask).push_back(temp);
  }
}
// Create masks of disabled CU masks.
void createDisabledCUMask(std::vector<uint32_t> *pdisabledCUMask,
                         int numOfCUs) {
  uint32_t temp = ZERO_MASK;
  uint32_t bit_index = 0;
  for (int i = 0; i < numOfCUs; i++) {
    if (bit_index >= 32) {
      (*pdisabledCUMask).push_back(temp);
      temp = ZERO_MASK;
      bit_index = 0;
    }
    bit_index += 1;
  }
  if (bit_index != 0) {
    (*pdisabledCUMask).push_back(temp);
  }
}

void Callback(hipStream_t, hipError_t status,
              void* userData) {
  isPassed = true;
  HIP_CHECK(status);
  REQUIRE(userData == nullptr);
  for (size_t i = 0; i < N; i++) {
    if (C_h[i] != A_h[i] * A_h[i]) {
      UNSCOPED_INFO("Data mismatch at index: " << i);
      isPassed = false;
      break;
    }
  }
  cbDone = true;
}
}  // namespace hipExtStreamCreateWithCUMaskTest

using hipExtStreamCreateWithCUMaskTest::A_h;
using hipExtStreamCreateWithCUMaskTest::C_h;
using hipExtStreamCreateWithCUMaskTest::cbDone;
using hipExtStreamCreateWithCUMaskTest::isPassed;
using hipExtStreamCreateWithCUMaskTest::N;
using hipExtStreamCreateWithCUMaskTest::createDefaultCUMask;
using hipExtStreamCreateWithCUMaskTest::createDisabledCUMask;
using hipExtStreamCreateWithCUMaskTest::Callback;

/**
 * Scenario: Validates functionality of hipStreamAddCallback with created stream.
 */
TEST_CASE("Unit_hipExtStreamCreateWithCUMask_ValidateCallbackFunc") {
  float *A_d, *C_d;
  size_t Nbytes = N * sizeof(float);
  cbDone = false;
  A_h = reinterpret_cast<float*>(malloc(Nbytes));
  REQUIRE(A_h != nullptr);
  C_h = reinterpret_cast<float*>(malloc(Nbytes));
  REQUIRE(C_h != nullptr);

  // Fill with Phi + i
  for (size_t i = 0; i < N; i++) {
    A_h[i] = CONSTANT + i;
  }

  HIP_CHECK(hipMalloc(&A_d, Nbytes));
  HIP_CHECK(hipMalloc(&C_d, Nbytes));

  hipStream_t mystream;
  std::vector<uint32_t> defaultCUMask;
  HIP_CHECK(hipSetDevice(0));
  hipDeviceProp_t props;
  HIP_CHECK(hipGetDeviceProperties(&props, 0));
  createDefaultCUMask(&defaultCUMask, props.multiProcessorCount);

  hipExtStreamCreateWithCUMask(&mystream, defaultCUMask.size(),
                               defaultCUMask.data());
  HIP_CHECK(hipMemcpyAsync(A_d, A_h, Nbytes, hipMemcpyHostToDevice,
          mystream));
  const unsigned blocks = GRIDSIZE;
  const unsigned threadsPerBlock = BLOCKSIZE;
  hipLaunchKernelGGL((HipTest::vector_square), dim3(blocks),
                     dim3(threadsPerBlock), 0, mystream, A_d, C_d, N);
  HIP_CHECK(hipMemcpyAsync(C_h, C_d, Nbytes, hipMemcpyDeviceToHost,
          mystream));
  HIP_CHECK(hipStreamAddCallback(mystream, Callback, nullptr, 0));
  while (!cbDone) usleep(100000);  // Sleep for 100 ms
  HIP_CHECK(hipStreamDestroy(mystream));
  HIP_CHECK(hipFree(reinterpret_cast<void*>(C_d)));
  HIP_CHECK(hipFree(reinterpret_cast<void*>(A_d)));
  free(C_h);
  free(A_h);
  REQUIRE(isPassed == true);
}

/**
 * Scenario: Validates functionality of stream with cu mask.
 */
TEST_CASE("Unit_hipExtStreamCreateWithCUMask_Functionality") {
  const int KNumPartition = NUM_CU_PARTITIONS;
  float *dA[KNumPartition], *dC[KNumPartition];
  float *hA, *hC;
  size_t N = 25*SIZE_INBYTES_OF_MB;
  size_t Nbytes = N * sizeof(float);
  std::vector<hipStream_t> streams(KNumPartition);
  std::vector<std::vector<uint32_t>> cuMasks(KNumPartition);
  std::stringstream ss[KNumPartition];

  int nGpu = 0;
  HIP_CHECK(hipGetDeviceCount(&nGpu));
  if (nGpu < 1) {
    WARN("Didn't find any GPU! skipping the test!");
    return;
  }

  static int device = 0;
  HIP_CHECK(hipSetDevice(device));
  hipDeviceProp_t props;
  HIP_CHECK(hipGetDeviceProperties(&props, device));
  INFO("info: running on bus " << "0x" << props.pciBusID << " "
  << props.name << " with " << props.multiProcessorCount << " CUs");

  hA =  new float[Nbytes];
  REQUIRE(hA != nullptr);
  hC =  new float[Nbytes];
  REQUIRE(hC != nullptr);
  for (size_t i = 0; i < N; i++) {
    hA[i] = CONSTANT + i;
  }

  for (int np = 0; np < KNumPartition; np++) {
    HIP_CHECK(hipMalloc(&dA[np], Nbytes));
    HIP_CHECK(hipMalloc(&dC[np], Nbytes));
    // make unique CU masks in the multiple of dwords for each stream
    uint32_t temp = 0;
    uint32_t bit_index = np;
    for (int i = np; i < props.multiProcessorCount; i = i + 4) {
      temp |= 1UL << bit_index;
      if (bit_index >= 32) {
        cuMasks[np].push_back(temp);
        temp = 0;
        bit_index = np;
        temp |= 1UL << bit_index;
      }
      bit_index += 4;
    }
    if (bit_index != 0) {
      cuMasks[np].push_back(temp);
    }

    HIP_CHECK(hipExtStreamCreateWithCUMask(&streams[np], cuMasks[np].size(),
            cuMasks[np].data()));

    HIP_CHECK(hipMemcpy(dA[np], hA, Nbytes, hipMemcpyHostToDevice));

    ss[np] << std::hex;
    for (int i = cuMasks[np].size() - 1; i >= 0; i--) {
      ss[np] << cuMasks[np][i];
    }
  }

  const unsigned blocks = GRIDSIZE;
  const unsigned threadsPerBlock = BLOCKSIZE;

  auto single_start = std::chrono::steady_clock::now();
  INFO("info: launch 'vector_square' kernel on one stream " <<
  streams[0] << " with CU mask: 0x" << ss[0].str().c_str());

  hipLaunchKernelGGL(HipTest::vector_square, dim3(blocks),
                     dim3(threadsPerBlock), 0, streams[0], dA[0], dC[0], N);
  hipDeviceSynchronize();

  auto single_end = std::chrono::steady_clock::now();
  std::chrono::duration<double> single_kernel_time = single_end - single_start;

  HIP_CHECK(hipMemcpy(hC, dC[0], Nbytes, hipMemcpyDeviceToHost));

  for (size_t i = 0; i < N; i++) {
    REQUIRE(hC[i] == (hA[i] * hA[i]));
  }

  INFO("info: launch 'vector_square' kernel on "
  << KNumPartition << " streams:");
  auto all_start = std::chrono::steady_clock::now();
  for (int np = 0; np < KNumPartition; np++) {
    INFO("info: launch 'vector_square' kernel on the stream "
    << streams[np] << " with CU mask: 0x" << ss[np].str().c_str());
    hipLaunchKernelGGL(HipTest::vector_square, dim3(blocks),
    dim3(threadsPerBlock), 0, streams[np], dA[np], dC[np], N);
  }
  hipDeviceSynchronize();

  auto all_end = std::chrono::steady_clock::now();
  std::chrono::duration<double> all_kernel_time = all_end - all_start;

  for (int np = 0; np < KNumPartition; np++) {
    HIP_CHECK(hipMemcpy(hC, dC[np], Nbytes, hipMemcpyDeviceToHost));
    for (size_t i = 0; i < N; i++) {
      REQUIRE(hC[i] == (hA[i] * hA[i]));
    }
  }

  INFO("info: kernel launched on one stream took: " <<
  single_kernel_time.count() << " seconds");
  INFO("info: kernels launched on " << KNumPartition <<
  " streams took: " << all_kernel_time.count() << " seconds");
  INFO("info: launching kernels on " << KNumPartition <<
  " streams asynchronously is " <<
  single_kernel_time.count() / (all_kernel_time.count() / KNumPartition)
  << " times faster per stream than launching on one stream alone");

  delete [] hA;
  delete [] hC;
  for (int np = 0; np < KNumPartition; np++) {
    hipFree(dC[np]);
    hipFree(dA[np]);
    HIP_CHECK(hipStreamDestroy(streams[np]));
  }
}

/**
 * Scenario: Create a stream with all CU masks disabled (0x00000000).
 * Verify that default CU mask is set for the stream.
 */
TEST_CASE("Unit_hipExtStreamCreateWithCUMask_AllCUsMasked") {
  HIP_CHECK(hipSetDevice(0));
  hipDeviceProp_t props;
  HIP_CHECK(hipGetDeviceProperties(&props, 0));
  // make a CU mask with all CUs disabled.
  std::vector<uint32_t> allCUDisabled;
  createDisabledCUMask(&allCUDisabled, props.multiProcessorCount);
  hipStream_t stream;
  HIP_CHECK(hipExtStreamCreateWithCUMask(&stream, allCUDisabled.size(),
          allCUDisabled.data()));
  // Verify whether default CU mask is set for the stream.
  uint32_t size = (props.multiProcessorCount / 32) + 1;
  std::vector<uint32_t> cuMask(size);
  std::vector<uint32_t> defaultCUMask;
  createDefaultCUMask(&defaultCUMask, props.multiProcessorCount);
  HIP_CHECK(hipExtStreamGetCUMask(stream, cuMask.size(), &cuMask[0]));
  for (int i = 0; i < static_cast<int>(defaultCUMask.size()); i++) {
    REQUIRE(defaultCUMask[i] == cuMask[i]);
  }
  HIP_CHECK(hipStreamDestroy(stream));
}

/**
 * Scenario: Negative Testing of hipExtStreamCreateWithCUMask.
 */
TEST_CASE("Unit_hipExtStreamCreateWithCUMask_NegTst") {
  std::vector<uint32_t> defaultCUMask;
  REQUIRE(hipSuccess == hipSetDevice(0));
  hipDeviceProp_t props;
  REQUIRE(hipSuccess == hipGetDeviceProperties(&props, 0));
  createDefaultCUMask(&defaultCUMask, props.multiProcessorCount);
  hipStream_t stream;
  // Negative Scenario 1: stream = nullptr
  SECTION("stream is nullptr") {
    REQUIRE_FALSE(hipExtStreamCreateWithCUMask(nullptr,
                  defaultCUMask.size(),
                  defaultCUMask.data()) == hipSuccess);
  }
  // Negative Scenario 2: cuMaskSize = 0
  SECTION("cuMaskSize is 0") {
    REQUIRE_FALSE(hipExtStreamCreateWithCUMask(&stream, 0,
                  defaultCUMask.data()) == hipSuccess);
  }
  // Negative Scenario 3: cuMask = nullptr
  SECTION("cuMask is nullptr") {
    REQUIRE_FALSE(hipExtStreamCreateWithCUMask(&stream,
                  defaultCUMask.size(),
                  nullptr) == hipSuccess);
  }
}
<|endoftext|>


<commit_before>//#include "wrapper_jni.h"
#ifndef WRAPPER_JNI
#define WRAPPER_JNI

#ifdef __cplusplus
extern "C" {
#endif

#include <jni.h>
#include <android/log.h>
#include "wrapper.h"

#define jniTAG "WRAPPER_JNI"

#define jniLOGV(X)  __android_log_print(ANDROID_LOG_VERBOSE, jniTAG, X)
#define jniLOGI(X)  __android_log_print(ANDROID_LOG_INFO, jniTAG, X)
#define jniLOGE(X)  __android_log_print(ANDROID_LOG_ERROR, jniTAG, X)

#define CAST_HANDLE(wr) jclass c = env->GetObjectClass(obj);\
                        if (!c) return;\
                        jfieldID fid = env->GetFieldID(c, "handle", "J");\
                        if (!fid){\
                          __android_log_print(ANDROID_LOG_ERROR, jniTAG, "No Field ID, ERROR");\
                          return;\
                        }\
                        jlong h = env->GetLongField(obj, fid);\
                        CNativeWrapper* wr = static_cast<CNativeWrapper*> (h);
//                        __android_log_print(ANDROID_LOG_VERBOSE, jniTAG, "Handle = %p", wr);

/*
 * Class:     com_gpac_Osmo4_GPACInstance
 * Method:    createInstance
 * Signature: (Lcom/gpac/Osmo4/GpacCallback;IILjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)I
 */
JNIEXPORT jlong JNICALL Java_com_gpac_Osmo4_GPACInstance_createInstance(JNIEnv * env, jclass obj, jobject callback, jint width, jint height, jstring cfg_dir, jstring modules_dir, jstring cache_dir, jstring font_dir, jstring gui_dir, jstring url_to_open);
//-----------------------------------
JNIEXPORT void JNICALL Java_com_gpac_Osmo4_GPACInstance_gpacconnect(JNIEnv * env, jobject obj, jstring fileName);
//-----------------------------------
JNIEXPORT void JNICALL Java_com_gpac_Osmo4_GPACInstance_gpacdisconnect(JNIEnv * env, jobject obj);
//-----------------------------------
JNIEXPORT void JNICALL Java_com_gpac_Osmo4_GPACInstance_gpacfree(JNIEnv * env, jobject obj);
//-----------------------------------
JNIEXPORT void JNICALL Java_com_gpac_Osmo4_GPACInstance_gpacrender (JNIEnv * env, jobject obj);
//-----------------------------------
JNIEXPORT void JNICALL Java_com_gpac_Osmo4_GPACInstance_gpacresize (JNIEnv * env, jobject obj, jint width, jint height);
//-----------------------------------
JNIEXPORT void JNICALL Java_com_gpac_Osmo4_GPACInstance_gpaceventmousedown(JNIEnv * env, jobject obj, jfloat x, jfloat y);
//-----------------------------------
JNIEXPORT void JNICALL Java_com_gpac_Osmo4_GPACInstance_gpaceventmouseup(JNIEnv * env, jobject obj, jfloat x, jfloat y);
//-----------------------------------
JNIEXPORT void JNICALL Java_com_gpac_Osmo4_GPACInstance_gpaceventmousemove(JNIEnv * env, jobject obj, jfloat x, jfloat y);
//-----------------------------------
JNIEXPORT void JNICALL Java_com_gpac_Osmo4_GPACInstance_gpaceventkeypress(JNIEnv * env, jobject obj, jint keycode, jint rawkeycode, jint up, jint flag, jint unicode);
/*
JNIEXPORT void JNICALL Java_com_gpac_Osmo4_GPACInstance_getdpi(JNIEnv * env, jobject obj, jint keycode,jfloat x, jfloat y){
        CAST_HANDLE(wr);
        jniLOGV("get DPI::start");
	jclass cls = (*env)->GetObjectClass(env, obj);
	jmethodID mid = (*env)->GetStaticMethodID(env, cls, "getdpi", "(FF)V");
	if (mid == 0)
	  return;
	(*env)->CallStaticIntMethod(env, cls, mid, x,y);
        jniLOGV("get DPI::end");
}
*/

/*
 * Class:     com_gpac_Osmo4_GPACInstance
 * Method:    setGpacPreference
 * Signature: (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V
 */
JNIEXPORT void JNICALL Java_com_gpac_Osmo4_GPACInstance_setGpacPreference
(JNIEnv * env, jobject obj, jstring category, jstring name, jstring value);

JNIEXPORT void JNICALL Java_com_gpac_Osmo4_GPACInstance_setGpacLogs(JNIEnv * env, jobject obj, jstring tools_at_levels);
JNIEXPORT void JNICALL Java_com_gpac_Osmo4_GPACInstance_gpaceventorientationchange(JNIEnv * env, jobject obj, jfloat x, jfloat y, jfloat z);

#ifdef __cplusplus
}
#endif
#endif
<commit_msg>fixed android compil<commit_after>//#include "wrapper_jni.h"
#ifndef WRAPPER_JNI
#define WRAPPER_JNI

#ifdef __cplusplus
extern "C" {
#endif

#include <jni.h>
#include <android/log.h>
#include "wrapper.h"

#define jniTAG "WRAPPER_JNI"

#define jniLOGV(X)  __android_log_print(ANDROID_LOG_VERBOSE, jniTAG, X)
#define jniLOGI(X)  __android_log_print(ANDROID_LOG_INFO, jniTAG, X)
#define jniLOGE(X)  __android_log_print(ANDROID_LOG_ERROR, jniTAG, X)

#define CAST_HANDLE(wr) jclass c = env->GetObjectClass(obj);\
                        if (!c) return;\
                        jfieldID fid = env->GetFieldID(c, "handle", "J");\
                        if (!fid){\
                          __android_log_print(ANDROID_LOG_ERROR, jniTAG, "No Field ID, ERROR");\
                          return;\
                        }\
                        jlong h = env->GetLongField(obj, fid);\
                        CNativeWrapper* wr = reinterpret_cast<CNativeWrapper*> (h);
//                        __android_log_print(ANDROID_LOG_VERBOSE, jniTAG, "Handle = %p", wr);

/*
 * Class:     com_gpac_Osmo4_GPACInstance
 * Method:    createInstance
 * Signature: (Lcom/gpac/Osmo4/GpacCallback;IILjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)I
 */
JNIEXPORT jlong JNICALL Java_com_gpac_Osmo4_GPACInstance_createInstance(JNIEnv * env, jclass obj, jobject callback, jint width, jint height, jstring cfg_dir, jstring modules_dir, jstring cache_dir, jstring font_dir, jstring gui_dir, jstring url_to_open);
//-----------------------------------
JNIEXPORT void JNICALL Java_com_gpac_Osmo4_GPACInstance_gpacconnect(JNIEnv * env, jobject obj, jstring fileName);
//-----------------------------------
JNIEXPORT void JNICALL Java_com_gpac_Osmo4_GPACInstance_gpacdisconnect(JNIEnv * env, jobject obj);
//-----------------------------------
JNIEXPORT void JNICALL Java_com_gpac_Osmo4_GPACInstance_gpacfree(JNIEnv * env, jobject obj);
//-----------------------------------
JNIEXPORT void JNICALL Java_com_gpac_Osmo4_GPACInstance_gpacrender (JNIEnv * env, jobject obj);
//-----------------------------------
JNIEXPORT void JNICALL Java_com_gpac_Osmo4_GPACInstance_gpacresize (JNIEnv * env, jobject obj, jint width, jint height);
//-----------------------------------
JNIEXPORT void JNICALL Java_com_gpac_Osmo4_GPACInstance_gpaceventmousedown(JNIEnv * env, jobject obj, jfloat x, jfloat y);
//-----------------------------------
JNIEXPORT void JNICALL Java_com_gpac_Osmo4_GPACInstance_gpaceventmouseup(JNIEnv * env, jobject obj, jfloat x, jfloat y);
//-----------------------------------
JNIEXPORT void JNICALL Java_com_gpac_Osmo4_GPACInstance_gpaceventmousemove(JNIEnv * env, jobject obj, jfloat x, jfloat y);
//-----------------------------------
JNIEXPORT void JNICALL Java_com_gpac_Osmo4_GPACInstance_gpaceventkeypress(JNIEnv * env, jobject obj, jint keycode, jint rawkeycode, jint up, jint flag, jint unicode);
/*
JNIEXPORT void JNICALL Java_com_gpac_Osmo4_GPACInstance_getdpi(JNIEnv * env, jobject obj, jint keycode,jfloat x, jfloat y){
        CAST_HANDLE(wr);
        jniLOGV("get DPI::start");
	jclass cls = (*env)->GetObjectClass(env, obj);
	jmethodID mid = (*env)->GetStaticMethodID(env, cls, "getdpi", "(FF)V");
	if (mid == 0)
	  return;
	(*env)->CallStaticIntMethod(env, cls, mid, x,y);
        jniLOGV("get DPI::end");
}
*/

/*
 * Class:     com_gpac_Osmo4_GPACInstance
 * Method:    setGpacPreference
 * Signature: (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V
 */
JNIEXPORT void JNICALL Java_com_gpac_Osmo4_GPACInstance_setGpacPreference
(JNIEnv * env, jobject obj, jstring category, jstring name, jstring value);

JNIEXPORT void JNICALL Java_com_gpac_Osmo4_GPACInstance_setGpacLogs(JNIEnv * env, jobject obj, jstring tools_at_levels);
JNIEXPORT void JNICALL Java_com_gpac_Osmo4_GPACInstance_gpaceventorientationchange(JNIEnv * env, jobject obj, jfloat x, jfloat y, jfloat z);

#ifdef __cplusplus
}
#endif
#endif
<|endoftext|>


<commit_before>#include "PololuQik.h"

byte cmd[5]; // serial command buffer

PololuQik::PololuQik(unsigned char receivePin, unsigned char transmitPin, unsigned char resetPin) : SoftwareSerial(receivePin, transmitPin)
{
  _resetPin = resetPin;
}

void PololuQik::init(long speed /* = 9600 */)
{
  // reset the qik
  digitalWrite(_resetPin, LOW);
  pinMode(_resetPin, OUTPUT); // drive low
  delay(1);
  pinMode(_resetPin, INPUT); // return to high-impedance input (reset is internally pulled up on qik)
  delay(10);

  begin(speed);
  write(0xAA); // allow qik to autodetect baud rate
}

char PololuQik::getFirmwareVersion()
{
  write(QIK_GET_FIRMWARE_VERSION);
  while (available() < 1);
  return read();
}

byte PololuQik::getErrors()
{
  write(QIK_GET_ERROR_BYTE);
  while (available() < 1);
  return read();
}

byte PololuQik::getConfigurationParameter(byte parameter)
{
  cmd[0] = QIK_GET_CONFIGURATION_PARAMETER;
  cmd[1] = parameter;
  write(cmd, 2);
  while (available() < 1);
  return read();
}

byte PololuQik::setConfigurationParameter(byte parameter, byte value)
{
  cmd[0] = QIK_SET_CONFIGURATION_PARAMETER;
  cmd[1] = parameter;
  cmd[2] = value;
  cmd[3] = 0x55;
  cmd[4] = 0x2A;
  write(cmd, 5);
  while (available() < 1);
  return read();
}

void PololuQik::setM0Speed(int speed)
{
  boolean reverse = 0;

  if (speed < 0)
  {
    speed = -speed; // make speed a positive quantity
    reverse = 1; // preserve the direction
  }

  if (speed > 255)
    speed = 255;

  if (speed > 127)
  {
    // 8-bit mode: actual speed is (speed + 128)
    cmd[0] = reverse ? QIK_MOTOR_M0_REVERSE_8_BIT : QIK_MOTOR_M0_FORWARD_8_BIT;
    cmd[1] = speed - 128;
  }
  else
  {
    cmd[0] = reverse ? QIK_MOTOR_M0_REVERSE : QIK_MOTOR_M0_FORWARD;
    cmd[1] = speed;
  }

  write(cmd, 2);
}

void PololuQik::setM1Speed(int speed)
{
  boolean reverse = 0;

  if (speed < 0)
  {
    speed = -speed; // make speed a positive quantity
    reverse = 1; // preserve the direction
  }

  if (speed > 255)
    speed = 255;

  if (speed > 127)
  {
    // 8-bit mode: actual speed is (speed + 128)
    cmd[0] = reverse ? QIK_MOTOR_M1_REVERSE_8_BIT : QIK_MOTOR_M1_FORWARD_8_BIT;
    cmd[1] = speed - 128;
  }
  else
  {
    cmd[0] = reverse ? QIK_MOTOR_M1_REVERSE : QIK_MOTOR_M1_FORWARD;
    cmd[1] = speed;
  }

  write(cmd, 2);
}

void PololuQik::setSpeeds(int m0Speed, int m1Speed)
{
  setM0Speed(m0Speed);
  setM1Speed(m1Speed);
}

// 2s9v1

void PololuQik2s9v1::setM0Coast()
{
  write(QIK_2S9V1_MOTOR_M0_COAST);
}

void PololuQik2s9v1::setM1Coast()
{
  write(QIK_2S9V1_MOTOR_M1_COAST);
}

void PololuQik2s9v1::setCoasts()
{
  setM0Coast();
  setM1Coast();
}

// 2s12v10

void PololuQik2s12v10::setM0Brake(unsigned char brake)
{
  if (brake > 127)
    brake = 127;

  cmd[0] = QIK_2S12V10_MOTOR_M0_BRAKE;
  cmd[1] = brake;
  write(cmd, 2);
}

void PololuQik2s12v10::setM1Brake(unsigned char brake)
{
  if (brake > 127)
    brake = 127;

  cmd[0] = QIK_2S12V10_MOTOR_M1_BRAKE;
  cmd[1] = brake;
  write(cmd, 2);
}

void PololuQik2s12v10::setBrakes(unsigned char m0Brake, unsigned char m1Brake)
{
  setM0Brake(m0Brake);
  setM1Brake(m1Brake);
}

unsigned char PololuQik2s12v10::getM0Current()
{
  write(QIK_2S12V10_GET_MOTOR_M0_CURRENT);
  while (available() < 1);
  return read();
}

unsigned char PololuQik2s12v10::getM1Current()
{
  write(QIK_2S12V10_GET_MOTOR_M1_CURRENT);
  while (available() < 1);
  return read();
}

unsigned int PololuQik2s12v10::getM0CurrentMilliamps()
{
  return getM0Current() * 150;
}

unsigned int PololuQik2s12v10::getM1CurrentMilliamps()
{
  return getM1Current() * 150;
}

unsigned char PololuQik2s12v10::getM0Speed()
{
  write(QIK_2S12V10_GET_MOTOR_M0_SPEED);
  while (available() < 1);
  return read();
}

unsigned char PololuQik2s12v10::getM1Speed()
{
  write(QIK_2S12V10_GET_MOTOR_M1_SPEED);
  while (available() < 1);
  return read();
}<commit_msg>added calls to listen() for better behavior with multiple instances<commit_after>#include "PololuQik.h"

byte cmd[5]; // serial command buffer

PololuQik::PololuQik(unsigned char receivePin, unsigned char transmitPin, unsigned char resetPin) : SoftwareSerial(receivePin, transmitPin)
{
  _resetPin = resetPin;
}

void PololuQik::init(long speed /* = 9600 */)
{
  // reset the qik
  digitalWrite(_resetPin, LOW);
  pinMode(_resetPin, OUTPUT); // drive low
  delay(1);
  pinMode(_resetPin, INPUT); // return to high-impedance input (reset is internally pulled up on qik)
  delay(10);

  begin(speed);
  write(0xAA); // allow qik to autodetect baud rate
}

char PololuQik::getFirmwareVersion()
{
  listen();
  write(QIK_GET_FIRMWARE_VERSION);
  while (available() < 1);
  return read();
}

byte PololuQik::getErrors()
{
  listen();
  write(QIK_GET_ERROR_BYTE);
  while (available() < 1);
  return read();
}

byte PololuQik::getConfigurationParameter(byte parameter)
{
  listen();
  cmd[0] = QIK_GET_CONFIGURATION_PARAMETER;
  cmd[1] = parameter;
  write(cmd, 2);
  while (available() < 1);
  return read();
}

byte PololuQik::setConfigurationParameter(byte parameter, byte value)
{
  listen();
  cmd[0] = QIK_SET_CONFIGURATION_PARAMETER;
  cmd[1] = parameter;
  cmd[2] = value;
  cmd[3] = 0x55;
  cmd[4] = 0x2A;
  write(cmd, 5);
  while (available() < 1);
  return read();
}

void PololuQik::setM0Speed(int speed)
{
  boolean reverse = 0;

  if (speed < 0)
  {
    speed = -speed; // make speed a positive quantity
    reverse = 1; // preserve the direction
  }

  if (speed > 255)
    speed = 255;

  if (speed > 127)
  {
    // 8-bit mode: actual speed is (speed + 128)
    cmd[0] = reverse ? QIK_MOTOR_M0_REVERSE_8_BIT : QIK_MOTOR_M0_FORWARD_8_BIT;
    cmd[1] = speed - 128;
  }
  else
  {
    cmd[0] = reverse ? QIK_MOTOR_M0_REVERSE : QIK_MOTOR_M0_FORWARD;
    cmd[1] = speed;
  }

  write(cmd, 2);
}

void PololuQik::setM1Speed(int speed)
{
  boolean reverse = 0;

  if (speed < 0)
  {
    speed = -speed; // make speed a positive quantity
    reverse = 1; // preserve the direction
  }

  if (speed > 255)
    speed = 255;

  if (speed > 127)
  {
    // 8-bit mode: actual speed is (speed + 128)
    cmd[0] = reverse ? QIK_MOTOR_M1_REVERSE_8_BIT : QIK_MOTOR_M1_FORWARD_8_BIT;
    cmd[1] = speed - 128;
  }
  else
  {
    cmd[0] = reverse ? QIK_MOTOR_M1_REVERSE : QIK_MOTOR_M1_FORWARD;
    cmd[1] = speed;
  }

  write(cmd, 2);
}

void PololuQik::setSpeeds(int m0Speed, int m1Speed)
{
  setM0Speed(m0Speed);
  setM1Speed(m1Speed);
}

// 2s9v1

void PololuQik2s9v1::setM0Coast()
{
  write(QIK_2S9V1_MOTOR_M0_COAST);
}

void PololuQik2s9v1::setM1Coast()
{
  write(QIK_2S9V1_MOTOR_M1_COAST);
}

void PololuQik2s9v1::setCoasts()
{
  setM0Coast();
  setM1Coast();
}

// 2s12v10

void PololuQik2s12v10::setM0Brake(unsigned char brake)
{
  if (brake > 127)
    brake = 127;

  cmd[0] = QIK_2S12V10_MOTOR_M0_BRAKE;
  cmd[1] = brake;
  write(cmd, 2);
}

void PololuQik2s12v10::setM1Brake(unsigned char brake)
{
  if (brake > 127)
    brake = 127;

  cmd[0] = QIK_2S12V10_MOTOR_M1_BRAKE;
  cmd[1] = brake;
  write(cmd, 2);
}

void PololuQik2s12v10::setBrakes(unsigned char m0Brake, unsigned char m1Brake)
{
  setM0Brake(m0Brake);
  setM1Brake(m1Brake);
}

unsigned char PololuQik2s12v10::getM0Current()
{
  listen();
  write(QIK_2S12V10_GET_MOTOR_M0_CURRENT);
  while (available() < 1);
  return read();
}

unsigned char PololuQik2s12v10::getM1Current()
{
  listen();
  write(QIK_2S12V10_GET_MOTOR_M1_CURRENT);
  while (available() < 1);
  return read();
}

unsigned int PololuQik2s12v10::getM0CurrentMilliamps()
{
  return getM0Current() * 150;
}

unsigned int PololuQik2s12v10::getM1CurrentMilliamps()
{
  return getM1Current() * 150;
}

unsigned char PololuQik2s12v10::getM0Speed()
{
  listen();
  write(QIK_2S12V10_GET_MOTOR_M0_SPEED);
  while (available() < 1);
  return read();
}

unsigned char PololuQik2s12v10::getM1Speed()
{
  listen();
  write(QIK_2S12V10_GET_MOTOR_M1_SPEED);
  while (available() < 1);
  return read();
}<|endoftext|>


<commit_before>/* This file is part of Ingen.
 * Copyright 2007-2011 David Robillard <http://drobilla.net>
 *
 * Ingen is free software; you can redistribute it and/or modify it under the
 * terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 2 of the License, or (at your option) any later
 * version.
 *
 * Ingen 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 General Public License for details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include <cassert>
#include "raul/log.hpp"
#include "raul/Atom.hpp"
#include "ingen/ServerInterface.hpp"
#include "ingen/shared/LV2URIMap.hpp"
#include "ingen/client/PatchModel.hpp"
#include "ingen/client/NodeModel.hpp"
#include "ingen/client/PluginModel.hpp"
#include "ingen/client/PluginUI.hpp"
#include "App.hpp"
#include "WidgetFactory.hpp"
#include "NodeControlWindow.hpp"
#include "NodeModule.hpp"
#include "PatchCanvas.hpp"
#include "PatchWindow.hpp"
#include "Port.hpp"
#include "RenameWindow.hpp"
#include "SubpatchModule.hpp"
#include "WindowFactory.hpp"
#include "Configuration.hpp"
#include "NodeMenu.hpp"

using namespace std;
using namespace Raul;

namespace Ingen {
namespace GUI {

NodeModule::NodeModule(PatchCanvas&               canvas,
                       SharedPtr<const NodeModel> node)
	: FlowCanvas::Module(canvas, node->path().symbol(), 0, 0, true, canvas.show_port_names())
	, _node(node)
	, _gui_widget(NULL)
	, _gui_window(NULL)
{
	assert(_node);

	node->signal_new_port().connect(
		sigc::mem_fun(this, &NodeModule::new_port_view));
	node->signal_removed_port().connect(
		sigc::hide_return(sigc::mem_fun(this, &NodeModule::delete_port_view)));
	node->signal_property().connect(
		sigc::mem_fun(this, &NodeModule::property_changed));
	node->signal_moved().connect(
		sigc::mem_fun(this, &NodeModule::rename));

	const PluginModel* plugin = dynamic_cast<const PluginModel*>(node->plugin());
	if (plugin) {
		plugin->signal_changed().connect(
			sigc::mem_fun(this, &NodeModule::plugin_changed));
	}
}

NodeModule::~NodeModule()
{
	embed_gui(false);

	NodeControlWindow* win = app().window_factory()->control_window(_node);
	delete win; // Will be removed from window factory via signal
}

bool
NodeModule::show_menu(GdkEventButton* ev)
{
	WidgetFactory::get_widget_derived("object_menu", _menu);
	_menu->init(app(), _node);
	_menu->signal_embed_gui.connect(
		sigc::mem_fun(this, &NodeModule::embed_gui));
	_menu->signal_popup_gui.connect(
		sigc::hide_return(sigc::mem_fun(this, &NodeModule::popup_gui)));
	_menu->popup(ev->button, ev->time);
	return true;
}

NodeModule*
NodeModule::create(PatchCanvas&               canvas,
                   SharedPtr<const NodeModel> node,
                   bool                       human)
{
	NodeModule* ret;

	SharedPtr<const PatchModel> patch = PtrCast<const PatchModel>(node);
	if (patch)
		ret = new SubpatchModule(canvas, patch);
	else
		ret = new NodeModule(canvas, node);

	for (GraphObject::Properties::const_iterator m = node->properties().begin();
	     m != node->properties().end(); ++m)
		ret->property_changed(m->first, m->second);

	for (NodeModel::Ports::const_iterator p = node->ports().begin();
	     p != node->ports().end(); ++p)
		ret->new_port_view(*p);

	ret->set_stacked_border(node->polyphonic());

	if (human)
		ret->show_human_names(human); // FIXME: double port iteration

	return ret;
}

App&
NodeModule::app() const
{
	return ((PatchCanvas*)canvas())->app();
}

void
NodeModule::show_human_names(bool b)
{
	const URIs& uris = app().uris();

	if (b && node()->plugin()) {
		const Raul::Atom& name_property = node()->get_property(uris.lv2_name);
		if (name_property.type() == Atom::STRING)
			set_name(name_property.get_string());
		else
			set_name(node()->plugin_model()->human_name());
	} else {
		b = false;
		set_name(node()->symbol().c_str());
	}

	for (Ports::const_iterator i = ports().begin(); i != ports().end(); ++i) {
		Ingen::GUI::Port* const port = dynamic_cast<Ingen::GUI::Port*>(*i);
		Glib::ustring label(port->model()->symbol().c_str());
		if (b) {
			const Raul::Atom& name_property = port->model()->get_property(uris.lv2_name);
			if (name_property.type() == Atom::STRING) {
				label = name_property.get_string();
			} else {
				Glib::ustring hn = node()->plugin_model()->port_human_name(
						port->model()->index());
				if (!hn.empty())
					label = hn;
			}
		}
		(*i)->set_name(label);
	}
}

void
NodeModule::value_changed(uint32_t index, const Atom& value)
{
	if (!_plugin_ui)
		return;

	float float_val = 0.0f;

	switch (value.type()) {
	case Atom::FLOAT:
		float_val = value.get_float();
		_plugin_ui->port_event(index, 4, 0, &float_val);
		break;
	case Atom::STRING:
		_plugin_ui->port_event(index, strlen(value.get_string()), 0, value.get_string());
		break;
	default:
		break;
	}
}

void
NodeModule::plugin_changed()
{
	for (Ports::const_iterator p = ports().begin(); p != ports().end(); ++p)
		dynamic_cast<Ingen::GUI::Port*>(*p)->update_metadata();
}

void
NodeModule::embed_gui(bool embed)
{
	const URIs& uris = app().uris();
	if (embed) {

		if (_gui_window) {
			warn << "LV2 GUI already popped up, cannot embed" << endl;
			return;
		}

		if (!_plugin_ui) {
			const PluginModel* const pm = dynamic_cast<const PluginModel*>(_node->plugin());
			_plugin_ui = pm->ui(app().world(), _node);
		}

		if (_plugin_ui) {
			GtkWidget* c_widget = (GtkWidget*)_plugin_ui->get_widget();
			_gui_widget = Glib::wrap(c_widget);

			Gtk::Container* container = new Gtk::EventBox();
			container->set_name("ingen_embedded_node_gui_container");
			container->add(*_gui_widget);
			FlowCanvas::Module::embed(container);
		} else {
			error << "Failed to create LV2 UI" << endl;
		}

		if (_gui_widget) {
			_gui_widget->show_all();

			for (NodeModel::Ports::const_iterator p = _node->ports().begin();
					p != _node->ports().end(); ++p)
				if ((*p)->is_output() && app().can_control(p->get()))
					app().engine()->set_property((*p)->path(), uris.ingen_broadcast, true);
		}

	} else { // un-embed

		FlowCanvas::Module::embed(NULL);
		_plugin_ui.reset();

		for (NodeModel::Ports::const_iterator p = _node->ports().begin();
		     p != _node->ports().end(); ++p)
			if ((*p)->is_output() && app().can_control(p->get()))
				app().engine()->set_property((*p)->path(),
				                                       uris.ingen_broadcast,
				                                       false);
	}

	if (embed && _embed_item) {
		set_control_values();
		set_base_color(0x212222FF);
	} else {
		set_default_base_color();
	}
}

void
NodeModule::rename()
{
	if (app().configuration()->name_style() == Configuration::PATH) {
		set_name(_node->path().symbol());
	}
}

void
NodeModule::new_port_view(SharedPtr<const PortModel> port)
{
	Port::create(app(), *this, port,
	             app().configuration()->name_style() == Configuration::HUMAN);

	port->signal_value_changed().connect(
		sigc::bind<0>(sigc::mem_fun(this, &NodeModule::value_changed),
		              port->index()));
}

Port*
NodeModule::port(boost::shared_ptr<const PortModel> model)
{
	for (Ports::const_iterator p = ports().begin(); p != ports().end(); ++p) {
		Port* const port = dynamic_cast<Port*>(*p);
		if (port->model() == model)
			return port;
	}
	return NULL;
}

void
NodeModule::delete_port_view(SharedPtr<const PortModel> model)
{
	Port* p = port(model);
	if (p) {
		delete p;
	} else {
		warn << "Failed to find port on module " << model->path() << endl;
	}
}

bool
NodeModule::popup_gui()
{
	if (_node->plugin() && _node->plugin()->type() == PluginModel::LV2) {
		if (_plugin_ui) {
			warn << "LV2 GUI already embedded, cannot pop up" << endl;
			return false;
		}

		const PluginModel* const plugin = dynamic_cast<const PluginModel*>(_node->plugin());
		assert(plugin);

		_plugin_ui = plugin->ui(app().world(), _node);

		if (_plugin_ui) {
			GtkWidget* c_widget = (GtkWidget*)_plugin_ui->get_widget();
			_gui_widget = Glib::wrap(c_widget);

			_gui_window = new Gtk::Window();
			_gui_window->set_title(_node->path().chop_scheme() + " UI - Ingen");
			_gui_window->set_role("plugin_ui");
			_gui_window->add(*_gui_widget);
			_gui_widget->show_all();
			set_control_values();

			_gui_window->signal_unmap().connect(
					sigc::mem_fun(this, &NodeModule::on_gui_window_close));
			_gui_window->present();

			return true;
		} else {
			warn << "No LV2 GUI for " << _node->path().chop_scheme() << endl;
		}
	}

	return false;
}

void
NodeModule::on_gui_window_close()
{
	delete _gui_window;
	_gui_window = NULL;
	_plugin_ui.reset();
	_gui_widget = NULL;
}

void
NodeModule::set_control_values()
{
	uint32_t index = 0;
	for (NodeModel::Ports::const_iterator p = _node->ports().begin();
	     p != _node->ports().end(); ++p) {
		if (app().can_control(p->get()))
			value_changed(index, (*p)->value());
		++index;
	}
}

void
NodeModule::show_control_window()
{
	app().window_factory()->present_controls(_node);
}

void
NodeModule::on_double_click(GdkEventButton* ev)
{
	if ( ! popup_gui() )
		show_control_window();
}

void
NodeModule::store_location()
{
	const Atom x(static_cast<float>(property_x()));
	const Atom y(static_cast<float>(property_y()));

	const URIs& uris = app().uris();

	const Atom& existing_x = _node->get_property(uris.ingen_canvas_x);
	const Atom& existing_y = _node->get_property(uris.ingen_canvas_y);

	if (x != existing_x && y != existing_y) {
		Resource::Properties remove;
		remove.insert(make_pair(uris.ingen_canvas_x, uris.wildcard));
		remove.insert(make_pair(uris.ingen_canvas_y, uris.wildcard));
		Resource::Properties add;
		add.insert(make_pair(uris.ingen_canvas_x, x));
		add.insert(make_pair(uris.ingen_canvas_y, y));
		app().engine()->delta(_node->path(), remove, add);
	}
}

void
NodeModule::property_changed(const URI& key, const Atom& value)
{
	const Shared::URIs& uris = app().uris();
	switch (value.type()) {
	case Atom::FLOAT:
		if (key == uris.ingen_canvas_x) {
			move_to(value.get_float(), property_y());
		} else if (key == uris.ingen_canvas_y) {
			move_to(property_x(), value.get_float());
		}
		break;
	case Atom::BOOL:
		if (key == uris.ingen_polyphonic) {
			set_stacked_border(value.get_bool());
		} else if (key == uris.ingen_selected) {
			if (value.get_bool() != selected()) {
				if (value.get_bool())
					_canvas->select_item(this);
				else
					_canvas->unselect_item(this);
			}
		}
		break;
	case Atom::STRING:
		if (key == uris.lv2_name
				&& app().configuration()->name_style() == Configuration::HUMAN) {
			set_name(value.get_string());
		}
	default: break;
	}
}

void
NodeModule::set_selected(bool b)
{
	const URIs& uris = app().uris();
	if (b != selected()) {
		Module::set_selected(b);
		if (b) {
			PatchWindow* win = app().window_factory()->parent_patch_window(node());
			if (win) {
				std::string doc;
				bool        html = false;
				if (node()->plugin_model()) {
					doc = node()->plugin_model()->documentation(&html);
				}
				if (!doc.empty()) {
					win->show_documentation(doc, html);
				} else {
					win->hide_documentation();
				}
			}
		}
		if (app().signal())
			app().engine()->set_property(_node->path(), uris.ingen_selected, b);
	}
}

} // namespace GUI
} // namespace Ingen
<commit_msg>Make FlowCanvas::Port no longer a Gnome::Canvas::Group.<commit_after>/* This file is part of Ingen.
 * Copyright 2007-2011 David Robillard <http://drobilla.net>
 *
 * Ingen is free software; you can redistribute it and/or modify it under the
 * terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 2 of the License, or (at your option) any later
 * version.
 *
 * Ingen 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 General Public License for details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include <cassert>
#include "raul/log.hpp"
#include "raul/Atom.hpp"
#include "ingen/ServerInterface.hpp"
#include "ingen/shared/LV2URIMap.hpp"
#include "ingen/client/PatchModel.hpp"
#include "ingen/client/NodeModel.hpp"
#include "ingen/client/PluginModel.hpp"
#include "ingen/client/PluginUI.hpp"
#include "App.hpp"
#include "WidgetFactory.hpp"
#include "NodeControlWindow.hpp"
#include "NodeModule.hpp"
#include "PatchCanvas.hpp"
#include "PatchWindow.hpp"
#include "Port.hpp"
#include "RenameWindow.hpp"
#include "SubpatchModule.hpp"
#include "WindowFactory.hpp"
#include "Configuration.hpp"
#include "NodeMenu.hpp"

using namespace std;
using namespace Raul;

namespace Ingen {
namespace GUI {

NodeModule::NodeModule(PatchCanvas&               canvas,
                       SharedPtr<const NodeModel> node)
	: FlowCanvas::Module(canvas, node->path().symbol(), 0, 0, true, canvas.show_port_names())
	, _node(node)
	, _gui_widget(NULL)
	, _gui_window(NULL)
{
	assert(_node);

	node->signal_new_port().connect(
		sigc::mem_fun(this, &NodeModule::new_port_view));
	node->signal_removed_port().connect(
		sigc::hide_return(sigc::mem_fun(this, &NodeModule::delete_port_view)));
	node->signal_property().connect(
		sigc::mem_fun(this, &NodeModule::property_changed));
	node->signal_moved().connect(
		sigc::mem_fun(this, &NodeModule::rename));

	const PluginModel* plugin = dynamic_cast<const PluginModel*>(node->plugin());
	if (plugin) {
		plugin->signal_changed().connect(
			sigc::mem_fun(this, &NodeModule::plugin_changed));
	}
}

NodeModule::~NodeModule()
{
	delete _gui_widget;
	delete _gui_window;

	NodeControlWindow* win = app().window_factory()->control_window(_node);
	delete win; // Will be removed from window factory via signal
}

bool
NodeModule::show_menu(GdkEventButton* ev)
{
	WidgetFactory::get_widget_derived("object_menu", _menu);
	_menu->init(app(), _node);
	_menu->signal_embed_gui.connect(
		sigc::mem_fun(this, &NodeModule::embed_gui));
	_menu->signal_popup_gui.connect(
		sigc::hide_return(sigc::mem_fun(this, &NodeModule::popup_gui)));
	_menu->popup(ev->button, ev->time);
	return true;
}

NodeModule*
NodeModule::create(PatchCanvas&               canvas,
                   SharedPtr<const NodeModel> node,
                   bool                       human)
{
	NodeModule* ret;

	SharedPtr<const PatchModel> patch = PtrCast<const PatchModel>(node);
	if (patch)
		ret = new SubpatchModule(canvas, patch);
	else
		ret = new NodeModule(canvas, node);

	for (GraphObject::Properties::const_iterator m = node->properties().begin();
	     m != node->properties().end(); ++m)
		ret->property_changed(m->first, m->second);

	for (NodeModel::Ports::const_iterator p = node->ports().begin();
	     p != node->ports().end(); ++p)
		ret->new_port_view(*p);

	ret->set_stacked_border(node->polyphonic());

	if (human)
		ret->show_human_names(human); // FIXME: double port iteration

	return ret;
}

App&
NodeModule::app() const
{
	return ((PatchCanvas*)canvas())->app();
}

void
NodeModule::show_human_names(bool b)
{
	const URIs& uris = app().uris();

	if (b && node()->plugin()) {
		const Raul::Atom& name_property = node()->get_property(uris.lv2_name);
		if (name_property.type() == Atom::STRING)
			set_name(name_property.get_string());
		else
			set_name(node()->plugin_model()->human_name());
	} else {
		b = false;
		set_name(node()->symbol().c_str());
	}

	for (Ports::const_iterator i = ports().begin(); i != ports().end(); ++i) {
		Ingen::GUI::Port* const port = dynamic_cast<Ingen::GUI::Port*>(*i);
		Glib::ustring label(port->model()->symbol().c_str());
		if (b) {
			const Raul::Atom& name_property = port->model()->get_property(uris.lv2_name);
			if (name_property.type() == Atom::STRING) {
				label = name_property.get_string();
			} else {
				Glib::ustring hn = node()->plugin_model()->port_human_name(
						port->model()->index());
				if (!hn.empty())
					label = hn;
			}
		}
		(*i)->set_name(label);
	}
}

void
NodeModule::value_changed(uint32_t index, const Atom& value)
{
	if (!_plugin_ui)
		return;

	float float_val = 0.0f;

	switch (value.type()) {
	case Atom::FLOAT:
		float_val = value.get_float();
		_plugin_ui->port_event(index, 4, 0, &float_val);
		break;
	case Atom::STRING:
		_plugin_ui->port_event(index, strlen(value.get_string()), 0, value.get_string());
		break;
	default:
		break;
	}
}

void
NodeModule::plugin_changed()
{
	for (Ports::const_iterator p = ports().begin(); p != ports().end(); ++p)
		dynamic_cast<Ingen::GUI::Port*>(*p)->update_metadata();
}

void
NodeModule::embed_gui(bool embed)
{
	const URIs& uris = app().uris();
	if (embed) {

		if (_gui_window) {
			warn << "LV2 GUI already popped up, cannot embed" << endl;
			return;
		}

		if (!_plugin_ui) {
			const PluginModel* const pm = dynamic_cast<const PluginModel*>(_node->plugin());
			_plugin_ui = pm->ui(app().world(), _node);
		}

		if (_plugin_ui) {
			GtkWidget* c_widget = (GtkWidget*)_plugin_ui->get_widget();
			_gui_widget = Glib::wrap(c_widget);

			Gtk::Container* container = new Gtk::EventBox();
			container->set_name("ingen_embedded_node_gui_container");
			container->add(*_gui_widget);
			FlowCanvas::Module::embed(container);
		} else {
			error << "Failed to create LV2 UI" << endl;
		}

		if (_gui_widget) {
			_gui_widget->show_all();

			for (NodeModel::Ports::const_iterator p = _node->ports().begin();
					p != _node->ports().end(); ++p)
				if ((*p)->is_output() && app().can_control(p->get()))
					app().engine()->set_property((*p)->path(), uris.ingen_broadcast, true);
		}

	} else { // un-embed

		FlowCanvas::Module::embed(NULL);
		_plugin_ui.reset();

		for (NodeModel::Ports::const_iterator p = _node->ports().begin();
		     p != _node->ports().end(); ++p)
			if ((*p)->is_output() && app().can_control(p->get()))
				app().engine()->set_property((*p)->path(),
				                                       uris.ingen_broadcast,
				                                       false);
	}

	if (embed && _embed_item) {
		set_control_values();
		set_base_color(0x212222FF);
	} else {
		set_default_base_color();
	}
}

void
NodeModule::rename()
{
	if (app().configuration()->name_style() == Configuration::PATH) {
		set_name(_node->path().symbol());
	}
}

void
NodeModule::new_port_view(SharedPtr<const PortModel> port)
{
	Port::create(app(), *this, port,
	             app().configuration()->name_style() == Configuration::HUMAN);

	port->signal_value_changed().connect(
		sigc::bind<0>(sigc::mem_fun(this, &NodeModule::value_changed),
		              port->index()));
}

Port*
NodeModule::port(boost::shared_ptr<const PortModel> model)
{
	for (Ports::const_iterator p = ports().begin(); p != ports().end(); ++p) {
		Port* const port = dynamic_cast<Port*>(*p);
		if (port->model() == model)
			return port;
	}
	return NULL;
}

void
NodeModule::delete_port_view(SharedPtr<const PortModel> model)
{
	Port* p = port(model);
	if (p) {
		delete p;
	} else {
		warn << "Failed to find port on module " << model->path() << endl;
	}
}

bool
NodeModule::popup_gui()
{
	if (_node->plugin() && _node->plugin()->type() == PluginModel::LV2) {
		if (_plugin_ui) {
			warn << "LV2 GUI already embedded, cannot pop up" << endl;
			return false;
		}

		const PluginModel* const plugin = dynamic_cast<const PluginModel*>(_node->plugin());
		assert(plugin);

		_plugin_ui = plugin->ui(app().world(), _node);

		if (_plugin_ui) {
			GtkWidget* c_widget = (GtkWidget*)_plugin_ui->get_widget();
			_gui_widget = Glib::wrap(c_widget);

			_gui_window = new Gtk::Window();
			_gui_window->set_title(_node->path().chop_scheme() + " UI - Ingen");
			_gui_window->set_role("plugin_ui");
			_gui_window->add(*_gui_widget);
			_gui_widget->show_all();
			set_control_values();

			_gui_window->signal_unmap().connect(
					sigc::mem_fun(this, &NodeModule::on_gui_window_close));
			_gui_window->present();

			return true;
		} else {
			warn << "No LV2 GUI for " << _node->path().chop_scheme() << endl;
		}
	}

	return false;
}

void
NodeModule::on_gui_window_close()
{
	delete _gui_window;
	_gui_window = NULL;
	_plugin_ui.reset();
	_gui_widget = NULL;
}

void
NodeModule::set_control_values()
{
	uint32_t index = 0;
	for (NodeModel::Ports::const_iterator p = _node->ports().begin();
	     p != _node->ports().end(); ++p) {
		if (app().can_control(p->get()))
			value_changed(index, (*p)->value());
		++index;
	}
}

void
NodeModule::show_control_window()
{
	app().window_factory()->present_controls(_node);
}

void
NodeModule::on_double_click(GdkEventButton* ev)
{
	if ( ! popup_gui() )
		show_control_window();
}

void
NodeModule::store_location()
{
	const Atom x(static_cast<float>(property_x()));
	const Atom y(static_cast<float>(property_y()));

	const URIs& uris = app().uris();

	const Atom& existing_x = _node->get_property(uris.ingen_canvas_x);
	const Atom& existing_y = _node->get_property(uris.ingen_canvas_y);

	if (x != existing_x && y != existing_y) {
		Resource::Properties remove;
		remove.insert(make_pair(uris.ingen_canvas_x, uris.wildcard));
		remove.insert(make_pair(uris.ingen_canvas_y, uris.wildcard));
		Resource::Properties add;
		add.insert(make_pair(uris.ingen_canvas_x, x));
		add.insert(make_pair(uris.ingen_canvas_y, y));
		app().engine()->delta(_node->path(), remove, add);
	}
}

void
NodeModule::property_changed(const URI& key, const Atom& value)
{
	const Shared::URIs& uris = app().uris();
	switch (value.type()) {
	case Atom::FLOAT:
		if (key == uris.ingen_canvas_x) {
			move_to(value.get_float(), property_y());
		} else if (key == uris.ingen_canvas_y) {
			move_to(property_x(), value.get_float());
		}
		break;
	case Atom::BOOL:
		if (key == uris.ingen_polyphonic) {
			set_stacked_border(value.get_bool());
		} else if (key == uris.ingen_selected) {
			if (value.get_bool() != selected()) {
				if (value.get_bool())
					_canvas->select_item(this);
				else
					_canvas->unselect_item(this);
			}
		}
		break;
	case Atom::STRING:
		if (key == uris.lv2_name
				&& app().configuration()->name_style() == Configuration::HUMAN) {
			set_name(value.get_string());
		}
	default: break;
	}
}

void
NodeModule::set_selected(bool b)
{
	const URIs& uris = app().uris();
	if (b != selected()) {
		Module::set_selected(b);
		if (b) {
			PatchWindow* win = app().window_factory()->parent_patch_window(node());
			if (win) {
				std::string doc;
				bool        html = false;
				if (node()->plugin_model()) {
					doc = node()->plugin_model()->documentation(&html);
				}
				if (!doc.empty()) {
					win->show_documentation(doc, html);
				} else {
					win->hide_documentation();
				}
			}
		}
		if (app().signal())
			app().engine()->set_property(_node->path(), uris.ingen_selected, b);
	}
}

} // namespace GUI
} // namespace Ingen
<|endoftext|>


<commit_before>#include "GameProcess.h"
#include "Object.h"
#include "Engine.h"
#include "World.h"
#include "App.h"
#include "ToolsCamera.h"
#include "ControlsApp.h"
#include "MathLib.h"
#include "Game.h"

using namespace MathLib;

CGameProcess::CGameProcess(void)
{

}

CGameProcess::~CGameProcess(void)
{

}
int CGameProcess::Init()
{
	g_Engine.pFileSystem->CacheFilesFormExt("char");
	g_Engine.pFileSystem->CacheFilesFormExt("node");
	g_Engine.pFileSystem->CacheFilesFormExt("smesh");
	g_Engine.pFileSystem->CacheFilesFormExt("sanim");

	g_Engine.pWorld->LoadWorld("data/scene/terrain/test/test.world");
	//g_Engine.pWorld->LoadWorld("data/scene/terrain/cj/cj.world");
	g_Engine.pControls->SetKeyPressFunc(KeyPress);
	g_Engine.pControls->SetKeyReleaseFunc(KeyRelease);

	m_pRole = new CFPSRoleLocal();
	m_pRole->Init(10001, "data/role/hero/FpsRole/fps.char");		//ؽɫԴ

	m_pRole->SetActorPosition(vec3(0, 0, 0));	//ýɫʼλáŴΪԭ㣬άϵvec3
	m_pSkillSystem = new CSkillSystem(this);
	m_pCameraBase = new CCameraBase();
	m_pCameraBase->SetEnabled(1);
	g_pSysControl->SetMouseGrab(1);

	m_pStarControl = new CStarControl();
	m_pRayControl = new CRayControl();

	return 1;
}

int CGameProcess::ShutDown()			//رϷ
{
	delete m_pRole;
	delete m_pSkillSystem;
	delete m_pCameraBase;
	delete m_pStarControl;
}<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "GameProcess.h"
#include "Object.h"
#include "Engine.h"
#include "World.h"
#include "App.h"
#include "ToolsCamera.h"
#include "ControlsApp.h"
#include "MathLib.h"
#include "Game.h"
#include "Editor.h"

using namespace MathLib;

CGameProcess::CGameProcess(void)
{

}

CGameProcess::~CGameProcess(void)
{

}
int CGameProcess::Init()
{
	g_Engine.pFileSystem->CacheFilesFormExt("char");
	g_Engine.pFileSystem->CacheFilesFormExt("node");
	g_Engine.pFileSystem->CacheFilesFormExt("smesh");
	g_Engine.pFileSystem->CacheFilesFormExt("sanim");

	g_Engine.pWorld->LoadWorld("data/scene/terrain/test/test.world");
	//g_Engine.pWorld->LoadWorld("data/scene/terrain/cj/cj.world");
	g_Engine.pControls->SetKeyPressFunc(KeyPress);
	g_Engine.pControls->SetKeyReleaseFunc(KeyRelease);

	m_pRole = new CFPSRoleLocal();
	m_pRole->Init(10001, "data/role/hero/FpsRole/fps.char");		//ؽɫԴ

	m_pRole->SetActorPosition(vec3(0, 0, 0));	//ýɫʼλáŴΪԭ㣬άϵvec3
	m_pSkillSystem = new CSkillSystem(this);
	m_pCameraBase = new CCameraBase();
	m_pCameraBase->SetEnabled(1);
	g_pSysControl->SetMouseGrab(1);

	m_pStarControl = new CStarControl();
	m_pRayControl = new CRayControl();

	return 1;
}

int CGameProcess::ShutDown()			//رϷ
{
	delete m_pRole;
	delete m_pSkillSystem;
	delete m_pCameraBase;
	delete m_pStarControl;
	delete m_pRayControl;

}<|endoftext|>


<commit_before>/*
 * DynamicMat.cpp
 *
 *  Created on: Nov 10, 2013
 *      Author: andresf
 */

#include <stdexcept>

#include <DynamicMat.hpp>
#include <FileUtils.hpp>

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

DynamicMat::DynamicMat() :
		m_descriptorsIndex(DEFAULT_INDICES), m_descriptorsFilenames(
				DEFAULT_FILENAMES), m_cachedMat(cv::Mat()), m_cachedMatStartIdx(
				-1), m_memoryCount(0), m_descriptorType(-1), rows(0), cols(0) {
#if DYNMATVERBOSE
	printf("[DynamicMat] Initializing empty\n");
#endif
}

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

DynamicMat::DynamicMat(const DynamicMat& other) {

#if DYNMATVERBOSE
	printf("[DynamicMat] Initializing by copy\n");
#endif

	m_descriptorsIndex = other.getDescriptorsIndex();
	m_descriptorsFilenames = other.getDescriptorsFilenames();
	std::vector<cv::Mat>(m_descriptorsIndex.size(), cv::Mat()).swap(
			m_descriptorsCache);
	m_cachedMat = cv::Mat();
	m_cachedMatStartIdx = -1;
	m_cachingOrder = std::queue<int>();
	m_memoryCount = other.m_memoryCount;
	m_descriptorType = other.type();
	rows = other.rows;
	cols = other.cols;
}

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

DynamicMat& DynamicMat::operator=(const DynamicMat& other) {

#if DYNMATVERBOSE
	printf("[DynamicMat] Initializing by assignment\n");
#endif

	m_descriptorsIndex = other.getDescriptorsIndex();
	m_descriptorsFilenames = other.getDescriptorsFilenames();
	std::vector<cv::Mat>(m_descriptorsIndex.size(), cv::Mat()).swap(
			m_descriptorsCache);
	m_cachedMat = cv::Mat();
	m_cachedMatStartIdx = -1;
	m_cachingOrder = std::queue<int>();
	m_memoryCount = other.m_memoryCount;
	m_descriptorType = other.type();
	rows = other.rows;
	cols = other.cols;

	return *this;
}

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

DynamicMat::DynamicMat(std::vector<std::string>& descriptorsFilenames) :
		m_descriptorsFilenames(descriptorsFilenames), m_cachedMatStartIdx(-1) {

#if DYNMATVERBOSE
	printf("[DynamicMat] Initializing using filenames\n");
#endif

	cv::Mat imgDescriptors;

	m_descriptorsIndex.clear();

	int descCount = 0, descLen = 0, descType = -1, imgIdx = 0;

	double mytime = cv::getTickCount();

	// Initialize descriptors index
	for (std::string descriptorsFilename : descriptorsFilenames) {

#if DYNMATVERBOSE
		printf("[DynamicMat] Loading descriptors file [%d/%lu]\n", imgIdx + 1, descriptorsFilenames.size());
#endif

		// Clear descriptors matrix
		imgDescriptors = cv::Mat();

		// Load descriptors
		FileUtils::loadDescriptors(descriptorsFilename, imgDescriptors);

		if (imgDescriptors.empty() == false) {
			for (size_t i = 0; (int) i < imgDescriptors.rows; i++) {
				image img;
				img.imgIdx = imgIdx;
				img.startIdx = descCount;
				m_descriptorsIndex.push_back(img);
			}
			// Increase descriptors counter
			descCount += imgDescriptors.rows;

			// If initialized check descriptors length
			if (descLen != 0) {
				// Recall that all descriptors must be of the same length
				CV_Assert(descLen == imgDescriptors.cols);
			} else {
				descLen = imgDescriptors.cols;
			}
			// If initialized check descriptors type
			if (descType != -1) {
				// Recall that all descriptors must be of the same type
				CV_Assert(descType == imgDescriptors.type());
			} else {
				descType = imgDescriptors.type();
			}
		}
		// Increase images counter
		imgIdx++;
	}

	mytime = (double(cv::getTickCount()) - mytime) / cv::getTickFrequency()
			* 1000;
#if DYNMATVERBOSE
	printf("[DynamicMat] Initialized descriptors index in [%lf] ms\n", mytime);
#endif

	rows = descCount;
	cols = descLen;
	m_memoryCount = 0;
	m_descriptorType = descType;
	m_descriptorsCache.resize(m_descriptorsIndex.size(), cv::Mat());
}

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

DynamicMat::~DynamicMat() {
#if DYNMATVERBOSE
	printf("[DynamicMat] Destroying\n");
#endif
}

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

cv::Mat DynamicMat::row(int descriptorIdx) {

#if DYNMATVERBOSE
	printf("[DynamicMat] Obtaining descriptor [%d]\n", descriptorIdx);
#endif

	if (descriptorIdx < 0 || descriptorIdx > int(m_descriptorsIndex.size())) {
		std::stringstream ss;
		ss << "[DynamicMat] Error while obtaining descriptor,"
				" the index should be in the range"
				" [0, " << m_descriptorsIndex.size() << ")";
		throw std::out_of_range(ss.str());
	}

	// Initialize descriptor
	cv::Mat descriptor = cv::Mat();

	std::vector<cv::Mat>::iterator it = m_descriptorsCache.begin()
			+ descriptorIdx;

	if ((*it).empty() == false) {
		// The descriptor is loaded in cache
		descriptor = *it;
	} else {
		// The descriptor is not loaded in cache

		// Load corresponding descriptors matrix if it isn't loaded
		if (m_cachedMatStartIdx == -1 || descriptorIdx < m_cachedMatStartIdx
				|| descriptorIdx >= m_cachedMatStartIdx + m_cachedMat.rows) {
			FileUtils::loadDescriptors(
					m_descriptorsFilenames[m_descriptorsIndex[descriptorIdx].imgIdx],
					m_cachedMat);
			m_cachedMatStartIdx = m_descriptorsIndex[descriptorIdx].startIdx;
		}

		// Compute descriptor index relative to the descriptors matrix it belongs to
		int relIdx = descriptorIdx - m_descriptorsIndex[descriptorIdx].startIdx;

		// Check relative descriptor index to be in range
		if (relIdx < 0 || relIdx > m_cachedMat.rows) {
			std::stringstream ss;
			ss << "Relative descriptor index [" << relIdx << "]"
					" should be in the range [0, " << m_cachedMat.rows << ")";
			throw std::out_of_range(ss.str());
		}

		// Obtain a reference to the descriptor
		descriptor = m_cachedMat.row(relIdx);

		// Check whether cache is full, if it does then pop the first added descriptor
		if (m_memoryCount != 0
				&& m_memoryCount + computeUsedMemory(descriptor) > MAX_MEM) {

#if DYNMATVERBOSE
			printf("[DynamicMat] Cache full, deleting first descriptor\n");
#endif

			// Remove descriptor from the cache
			it = m_descriptorsCache.begin() + m_cachingOrder.front();
			*it = cv::Mat();
			// Decrease memory counter
			m_memoryCount -= computeUsedMemory(*it);
			// Pop its index from the queue
			m_cachingOrder.pop();
		}

		// Add descriptor to the cache
		std::vector<cv::Mat>::iterator it = m_descriptorsCache.begin()
				+ descriptorIdx;
		descriptor.copyTo(*it);
		// Increase memory counter
		m_memoryCount += computeUsedMemory(*it);
		// Push its index to the queue
		m_cachingOrder.push(descriptorIdx);
	}

	return *it;
}

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

int DynamicMat::type() const {
	return m_descriptorType;
}

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

bool DynamicMat::empty() const {
	return rows == 0;
}

void DynamicMat::clearCache() {
	std::vector<cv::Mat>(m_descriptorsIndex.size(), cv::Mat()).swap(
			m_descriptorsCache);
	m_cachingOrder = std::queue<int>();
	m_memoryCount = 0;
}
<commit_msg>Common/src/DynamicMat.cpp * Removed preprocessor directive controlling compilation of output status message.<commit_after>/*
 * DynamicMat.cpp
 *
 *  Created on: Nov 10, 2013
 *      Author: andresf
 */

#include <stdexcept>

#include <DynamicMat.hpp>
#include <FileUtils.hpp>

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

DynamicMat::DynamicMat() :
		m_descriptorsIndex(DEFAULT_INDICES), m_descriptorsFilenames(
				DEFAULT_FILENAMES), m_cachedMat(cv::Mat()), m_cachedMatStartIdx(
				-1), m_memoryCount(0), m_descriptorType(-1), rows(0), cols(0) {
#if DYNMATVERBOSE
	printf("[DynamicMat] Initializing empty\n");
#endif
}

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

DynamicMat::DynamicMat(const DynamicMat& other) {

#if DYNMATVERBOSE
	printf("[DynamicMat] Initializing by copy\n");
#endif

	m_descriptorsIndex = other.getDescriptorsIndex();
	m_descriptorsFilenames = other.getDescriptorsFilenames();
	std::vector<cv::Mat>(m_descriptorsIndex.size(), cv::Mat()).swap(
			m_descriptorsCache);
	m_cachedMat = cv::Mat();
	m_cachedMatStartIdx = -1;
	m_cachingOrder = std::queue<int>();
	m_memoryCount = other.m_memoryCount;
	m_descriptorType = other.type();
	rows = other.rows;
	cols = other.cols;
}

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

DynamicMat& DynamicMat::operator=(const DynamicMat& other) {

#if DYNMATVERBOSE
	printf("[DynamicMat] Initializing by assignment\n");
#endif

	m_descriptorsIndex = other.getDescriptorsIndex();
	m_descriptorsFilenames = other.getDescriptorsFilenames();
	std::vector<cv::Mat>(m_descriptorsIndex.size(), cv::Mat()).swap(
			m_descriptorsCache);
	m_cachedMat = cv::Mat();
	m_cachedMatStartIdx = -1;
	m_cachingOrder = std::queue<int>();
	m_memoryCount = other.m_memoryCount;
	m_descriptorType = other.type();
	rows = other.rows;
	cols = other.cols;

	return *this;
}

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

DynamicMat::DynamicMat(std::vector<std::string>& descriptorsFilenames) :
		m_descriptorsFilenames(descriptorsFilenames), m_cachedMatStartIdx(-1) {

#if DYNMATVERBOSE
	printf("[DynamicMat] Initializing using filenames\n");
#endif

	cv::Mat imgDescriptors;

	m_descriptorsIndex.clear();

	int descCount = 0, descLen = 0, descType = -1, imgIdx = 0;

	double mytime = cv::getTickCount();

	// Initialize descriptors index
	for (std::string descriptorsFilename : descriptorsFilenames) {

		printf("[DynamicMat] Loading descriptors file [%d/%lu]\n", imgIdx + 1,
				descriptorsFilenames.size());

		// Clear descriptors matrix
		imgDescriptors = cv::Mat();

		// Load descriptors
		FileUtils::loadDescriptors(descriptorsFilename, imgDescriptors);

		if (imgDescriptors.empty() == false) {
			for (size_t i = 0; (int) i < imgDescriptors.rows; i++) {
				image img;
				img.imgIdx = imgIdx;
				img.startIdx = descCount;
				m_descriptorsIndex.push_back(img);
			}
			// Increase descriptors counter
			descCount += imgDescriptors.rows;

			// If initialized check descriptors length
			if (descLen != 0) {
				// Recall that all descriptors must be of the same length
				CV_Assert(descLen == imgDescriptors.cols);
			} else {
				descLen = imgDescriptors.cols;
			}
			// If initialized check descriptors type
			if (descType != -1) {
				// Recall that all descriptors must be of the same type
				CV_Assert(descType == imgDescriptors.type());
			} else {
				descType = imgDescriptors.type();
			}
		}
		// Increase images counter
		imgIdx++;
	}

	mytime = (double(cv::getTickCount()) - mytime) / cv::getTickFrequency()
			* 1000;
#if DYNMATVERBOSE
	printf("[DynamicMat] Initialized descriptors index in [%lf] ms\n", mytime);
#endif

	rows = descCount;
	cols = descLen;
	m_memoryCount = 0;
	m_descriptorType = descType;
	m_descriptorsCache.resize(m_descriptorsIndex.size(), cv::Mat());
}

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

DynamicMat::~DynamicMat() {
#if DYNMATVERBOSE
	printf("[DynamicMat] Destroying\n");
#endif
}

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

cv::Mat DynamicMat::row(int descriptorIdx) {

#if DYNMATVERBOSE
	printf("[DynamicMat] Obtaining descriptor [%d]\n", descriptorIdx);
#endif

	if (descriptorIdx < 0 || descriptorIdx > int(m_descriptorsIndex.size())) {
		std::stringstream ss;
		ss << "[DynamicMat] Error while obtaining descriptor,"
				" the index should be in the range"
				" [0, " << m_descriptorsIndex.size() << ")";
		throw std::out_of_range(ss.str());
	}

	// Initialize descriptor
	cv::Mat descriptor = cv::Mat();

	std::vector<cv::Mat>::iterator it = m_descriptorsCache.begin()
			+ descriptorIdx;

	if ((*it).empty() == false) {
		// The descriptor is loaded in cache
		descriptor = *it;
	} else {
		// The descriptor is not loaded in cache

		// Load corresponding descriptors matrix if it isn't loaded
		if (m_cachedMatStartIdx == -1 || descriptorIdx < m_cachedMatStartIdx
				|| descriptorIdx >= m_cachedMatStartIdx + m_cachedMat.rows) {
			FileUtils::loadDescriptors(
					m_descriptorsFilenames[m_descriptorsIndex[descriptorIdx].imgIdx],
					m_cachedMat);
			m_cachedMatStartIdx = m_descriptorsIndex[descriptorIdx].startIdx;
		}

		// Compute descriptor index relative to the descriptors matrix it belongs to
		int relIdx = descriptorIdx - m_descriptorsIndex[descriptorIdx].startIdx;

		// Check relative descriptor index to be in range
		if (relIdx < 0 || relIdx > m_cachedMat.rows) {
			std::stringstream ss;
			ss << "Relative descriptor index [" << relIdx << "]"
					" should be in the range [0, " << m_cachedMat.rows << ")";
			throw std::out_of_range(ss.str());
		}

		// Obtain a reference to the descriptor
		descriptor = m_cachedMat.row(relIdx);

		// Check whether cache is full, if it does then pop the first added descriptor
		if (m_memoryCount != 0
				&& m_memoryCount + computeUsedMemory(descriptor) > MAX_MEM) {

#if DYNMATVERBOSE
			printf("[DynamicMat] Cache full, deleting first descriptor\n");
#endif

			// Remove descriptor from the cache
			it = m_descriptorsCache.begin() + m_cachingOrder.front();
			*it = cv::Mat();
			// Decrease memory counter
			m_memoryCount -= computeUsedMemory(*it);
			// Pop its index from the queue
			m_cachingOrder.pop();
		}

		// Add descriptor to the cache
		std::vector<cv::Mat>::iterator it = m_descriptorsCache.begin()
				+ descriptorIdx;
		descriptor.copyTo(*it);
		// Increase memory counter
		m_memoryCount += computeUsedMemory(*it);
		// Push its index to the queue
		m_cachingOrder.push(descriptorIdx);
	}

	return *it;
}

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

int DynamicMat::type() const {
	return m_descriptorType;
}

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

bool DynamicMat::empty() const {
	return rows == 0;
}

void DynamicMat::clearCache() {
	std::vector<cv::Mat>(m_descriptorsIndex.size(), cv::Mat()).swap(
			m_descriptorsCache);
	m_cachingOrder = std::queue<int>();
	m_memoryCount = 0;
}
<|endoftext|>


<commit_before>#include "GameProcess.h"
#include "Object.h"
#include "Engine.h"
#include "World.h"
#include "App.h"
#include "ToolsCamera.h"
#include "ControlsApp.h"
#include "MathLib.h"
#include "Game.h"
#include "Editor.h"

using namespace MathLib;

CGameProcess::CGameProcess(void)
{

}

CGameProcess::~CGameProcess(void)
{

}
int CGameProcess::Init()
{
	g_Engine.pFileSystem->CacheFilesFormExt("char");
	g_Engine.pFileSystem->CacheFilesFormExt("node");
	g_Engine.pFileSystem->CacheFilesFormExt("smesh");
	g_Engine.pFileSystem->CacheFilesFormExt("sanim");

	g_Engine.pWorld->LoadWorld("data/scene/terrain/test/test.world");
	//g_Engine.pWorld->LoadWorld("data/scene/terrain/cj/cj.world");
	g_Engine.pControls->SetKeyPressFunc(KeyPress);
	g_Engine.pControls->SetKeyReleaseFunc(KeyRelease);

	m_pRole = new CFPSRoleLocal();
	m_pRole->Init(10001, "data/role/hero/FpsRole/fps.char");		//ؽɫԴ

	m_pRole->SetActorPosition(vec3(0, 0, 0));	//ýɫʼλáŴΪԭ㣬άϵvec3
	m_pSkillSystem = new CSkillSystem(this);
	m_pCameraBase = new CCameraBase();
	m_pCameraBase->SetEnabled(1);
	g_pSysControl->SetMouseGrab(1);

	m_pStarControl = new CStarControl();
	m_pRayControl = new CRayControl();

	return 1;
}

int CGameProcess::ShutDown()			//رϷ
{
	delete m_pRole;
	delete m_pSkillSystem;
	delete m_pCameraBase;
	delete m_pStarControl;
	delete m_pRayControl;

	DelAllListen();
	return 0;
}<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "GameProcess.h"
#include "Object.h"
#include "Engine.h"
#include "World.h"
#include "App.h"
#include "ToolsCamera.h"
#include "ControlsApp.h"
#include "MathLib.h"
#include "Game.h"
#include "Editor.h"

using namespace MathLib;

CGameProcess::CGameProcess(void)
{

}

CGameProcess::~CGameProcess(void)
{

}
int CGameProcess::Init()
{
	g_Engine.pFileSystem->CacheFilesFormExt("char");
	g_Engine.pFileSystem->CacheFilesFormExt("node");
	g_Engine.pFileSystem->CacheFilesFormExt("smesh");
	g_Engine.pFileSystem->CacheFilesFormExt("sanim");

	g_Engine.pWorld->LoadWorld("data/scene/terrain/test/test.world");
	//g_Engine.pWorld->LoadWorld("data/scene/terrain/cj/cj.world");
	g_Engine.pControls->SetKeyPressFunc(KeyPress);
	g_Engine.pControls->SetKeyReleaseFunc(KeyRelease);

	m_pRole = new CFPSRoleLocal();
	m_pRole->Init(10001, "data/role/hero/FpsRole/fps.char");		//ؽɫԴ

	m_pRole->SetActorPosition(vec3(0, 0, 0));	//ýɫʼλáŴΪԭ㣬άϵvec3
	m_pSkillSystem = new CSkillSystem(this);
	m_pCameraBase = new CCameraBase();
	m_pCameraBase->SetEnabled(1);
	g_pSysControl->SetMouseGrab(1);

	m_pStarControl = new CStarControl();
	m_pRayControl = new CRayControl();

	return 1;
}

int CGameProcess::ShutDown()			//رϷ
{
	delete m_pRole;
	delete m_pSkillSystem;
	delete m_pCameraBase;
	delete m_pStarControl;
	delete m_pRayControl;

	DelAllListen();
	return 0;
}

int CGameProcess::Update()
{

	return 0;
}
<|endoftext|>