<commit_before>/* This file is part of Strigi Desktop Search
 *
 * Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */
#ifdef HAVE_CONFIG_H
 #include "config.h"
#endif

#include "strigiconfig.h"
#include "fileinputstream.h"
#include "bz2inputstream.h"
#include "diranalyzer.h"
#include "analyzerconfiguration.h"
#include "streamendanalyzer.h"
#include "streamthroughanalyzer.h"
#include "streamlineanalyzer.h"
#include "streamsaxanalyzer.h"
#include "streameventanalyzer.h"
#include "xmlindexwriter.h"

#include <cstdio>
#include <cstring>
#include <algorithm>
#ifdef HAVE_UNISTD_H
 #include <unistd.h>
#endif
#ifdef HAVE_DIRECT_H
 #include <direct.h>
#endif
#include <iostream>
#include <sstream>
#include <fstream>
#include <set>
using namespace Strigi;
using namespace std;

class SelectedAnalyzerConfiguration : public Strigi::AnalyzerConfiguration {
public:
    const set<string> requiredAnalyzers;
    mutable set<string> usedAnalyzers;
    mutable set<string> availableAnalyzers;

    explicit SelectedAnalyzerConfiguration(const set<string> an)
        : requiredAnalyzers(an) {}

    bool valid() const {
        return requiredAnalyzers.size() == usedAnalyzers.size()
            || requiredAnalyzers.size() == 0;
    }
    bool useFactory(const string& name) const {
        bool use = requiredAnalyzers.find(name) != requiredAnalyzers.end()
            || requiredAnalyzers.size() == 0;
        if (use) {
            usedAnalyzers.insert(name);
        }
        availableAnalyzers.insert(name);
        return use;
    }
    bool useFactory(StreamEndAnalyzerFactory* f) const {
        return useFactory(f->name());
    }
    bool useFactory(StreamThroughAnalyzerFactory* f) const {
        return useFactory(f->name());
    }
    bool useFactory(StreamSaxAnalyzerFactory* f) const {
        return useFactory(f->name());
    }
    bool useFactory(StreamEventAnalyzerFactory* f) const {
        return useFactory(f->name());
    }
    bool useFactory(StreamLineAnalyzerFactory* f) const {
        return useFactory(f->name());
    }
};

void
printUsage(char** argv) {
    fprintf(stderr, "Usage: %s [OPTIONS] SOURCE\n"
        "Analyze the given file and output the result as XML.\n"
        " -c   configuration file\n"
        " -a   comma-separated list of analyzers\n"
        " -r   reference output, when specified, the reference output is \n"
        "      compared to the given output and the first difference is \n"
        "      reported.\n",
        argv[0]);
}
bool
containsHelp(int argc, char **argv) {
    for (int i=1; i<argc; ++i) {
         if (strcmp(argv[i], "--help") == 0
             || strcmp(argv[i], "-h") == 0) return true;
    }
    return false;
}
set<string>
parseAnalyzerNames(const char* names) {
    set<string> n;
    string ns(names);
    string::size_type start = 0, p = ns.find(',');
    while (p != string::npos) {
        n.insert(ns.substr(start, p-start));
        start  = p + 1;
        p = ns.find(',', start);
    }
    n.insert(ns.substr(start));
    return n;
}
set<string>
parseConfig(const char* config) {
    set<string> n;
    ifstream f(config);
    string line;
    while (f.good()) {
        getline(f, line);
        if (strncmp("analyzer=", line.c_str(), 9) == 0) {
            n.insert(line.substr(9));
        }
    }

    return n;
}
/**
 * Usage: $0 [OPTIONS] SOURCE
 **/
int
main(int argc, char** argv) {
    // there are 2 optional options that both require an argument.
    // one can specify 1 source, so the number of arguments must be
    // 2, 4 or 6
    if (containsHelp(argc, argv) || (argc != 2 && argc != 4 && argc != 6)) {
        printUsage(argv);
        return -1;
    }

    set<string> analyzers;
    const char* targetFile;
    const char* referenceFile = 0;
    if (argc == 4) {
        if (strcmp(argv[1],"-a") == 0) {
            analyzers = parseAnalyzerNames(argv[2]);
        } else if (strcmp(argv[1], "-r") == 0) {
            referenceFile = argv[2];
        } else if (strcmp(argv[1], "-c") == 0) {
            analyzers = parseConfig(argv[2]);
        } else {
            printUsage(argv);
            return -1;
        }
        targetFile = argv[3];
    } else if (argc == 6) {
        if (strcmp(argv[1], "-a") == 0) {
            analyzers = parseAnalyzerNames(argv[2]);
            if (strcmp(argv[3], "-r") == 0) {
                referenceFile = argv[4];
            }
        } else if (strcmp(argv[1], "-c") == 0) {
            analyzers = parseConfig(argv[2]);
            if (strcmp(argv[3], "-r") == 0) {
                referenceFile = argv[4];
            }
        } else if (strcmp(argv[1], "-r") == 0) {
            referenceFile = argv[2];
            if (strcmp(argv[3], "-a") == 0) {
                analyzers = parseAnalyzerNames(argv[4]);
            } else if (strcmp(argv[3], "-c") == 0) {
                analyzers = parseConfig(argv[4]);
            }
        } else {
            printUsage(argv);
            return -1;
        }
        targetFile = argv[5];
    } else {
        targetFile = argv[1];
    }

    const char* mappingFile = 0;

    // check that the target file exists
    {
        ifstream filetest(targetFile);
        if (!filetest.good()) {
            cerr << "The file '" << targetFile << "' cannot be read." << endl;
            return 1;
        }
    }
    // check that the result file is ok
    FileInputStream f(referenceFile);
//    BZ2InputStream bz2(&f);
    if (referenceFile != 0 && f.status() != Ok) {
        cerr << "The file '" << referenceFile << "' cannot be read." << endl;
        return 1;
    }

    const TagMapping mapping(mappingFile);
    ostringstream out;
    out << "<?xml version='1.0' encoding='UTF-8'?>\n<"
        << mapping.map("metadata");
    map<string, string>::const_iterator i = mapping.namespaces().begin();
    while (i != mapping.namespaces().end()) {
        out << " xmlns:" << i->first << "='" << i->second << "'";
        i++;
    }
    out << ">\n";

    SelectedAnalyzerConfiguration ic(analyzers);

    XmlIndexWriter writer(out, mapping);
    DirAnalyzer analyzer(writer, &ic);
    if (!ic.valid()) {
        set<string>::const_iterator i;
        set<string> missing;
        set_difference(analyzers.begin(), analyzers.end(),
            ic.availableAnalyzers.begin(), ic.availableAnalyzers.end(),
            insert_iterator<set<string> >(missing, missing.begin()));
        if (missing.size() == 1) {
            fprintf(stderr, "No analyzer with name %s was found.\n",
               missing.begin()->c_str());
        } else {
            cerr << "The analyzers";
            for (i = missing.begin(); i != missing.end(); ++i) {
                cerr << ", " << *i;
            }
            cerr << " were not found." << endl;
        }
        fprintf(stderr, "Choose from:\n");
        for (i = ic.availableAnalyzers.begin(); i != ic.availableAnalyzers.end(); ++i) {
            cerr << " " << *i << endl;
        }
        return 1;
    }

    // change to the directory of the file to analyze
    // this ensures a consistent naming of the file uris, regardless of cwd
    string targetPath(targetFile);
    string::size_type slashpos = targetPath.rfind('/');
    if (slashpos == string::npos) {
         analyzer.analyzeDir(targetFile);
    } else {
         chdir(targetPath.substr(0,slashpos).c_str());
         analyzer.analyzeDir(targetPath.substr(slashpos+1).c_str());
    }
    string str = out.str();
    int32_t n = 2*str.length();

    // if no reference file was specified, we output the analysis
    if (referenceFile == 0) {
        cout << str;
        return 0;
    }

    // load the file to compare with
    const char* c;
    n = f.read(c, n, n);
    if (n < 0) {
        fprintf(stderr, "Error: %s\n", f.error());
        return -1;
    }
    if (n != (int32_t)out.str().length()) {
        printf("output length differs %i instead of %i\n", n, out.str().length());
    }

    const char* p1 = c;
    const char* p2 = str.c_str();
    int32_t n1 = n;
    int32_t n2 = str.length();
    while (n1-- && n2-- && *p1 == *p2) {
        p1++;
        p2++;
    }
    if (n1 ==0 && (*p1 || *p2)) {
         printf("difference at position %i\n", p1-c);

         int32_t m = (80 > str.length())?str.length():80;
         printf("%i %.*s\n", m, m, str.c_str());

         m = (80 > n)?n:80;
         printf("%i %.*s\n", m, m, c);

         return -1;
    }

    return 0;
}
<commit_msg>fix error output: numbers were in the wrong order<commit_after>/* This file is part of Strigi Desktop Search
 *
 * Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */
#ifdef HAVE_CONFIG_H
 #include "config.h"
#endif

#include "strigiconfig.h"
#include "fileinputstream.h"
#include "bz2inputstream.h"
#include "diranalyzer.h"
#include "analyzerconfiguration.h"
#include "streamendanalyzer.h"
#include "streamthroughanalyzer.h"
#include "streamlineanalyzer.h"
#include "streamsaxanalyzer.h"
#include "streameventanalyzer.h"
#include "xmlindexwriter.h"

#include <cstdio>
#include <cstring>
#include <algorithm>
#ifdef HAVE_UNISTD_H
 #include <unistd.h>
#endif
#ifdef HAVE_DIRECT_H
 #include <direct.h>
#endif
#include <iostream>
#include <sstream>
#include <fstream>
#include <set>
using namespace Strigi;
using namespace std;

class SelectedAnalyzerConfiguration : public Strigi::AnalyzerConfiguration {
public:
    const set<string> requiredAnalyzers;
    mutable set<string> usedAnalyzers;
    mutable set<string> availableAnalyzers;

    explicit SelectedAnalyzerConfiguration(const set<string> an)
        : requiredAnalyzers(an) {}

    bool valid() const {
        return requiredAnalyzers.size() == usedAnalyzers.size()
            || requiredAnalyzers.size() == 0;
    }
    bool useFactory(const string& name) const {
        bool use = requiredAnalyzers.find(name) != requiredAnalyzers.end()
            || requiredAnalyzers.size() == 0;
        if (use) {
            usedAnalyzers.insert(name);
        }
        availableAnalyzers.insert(name);
        return use;
    }
    bool useFactory(StreamEndAnalyzerFactory* f) const {
        return useFactory(f->name());
    }
    bool useFactory(StreamThroughAnalyzerFactory* f) const {
        return useFactory(f->name());
    }
    bool useFactory(StreamSaxAnalyzerFactory* f) const {
        return useFactory(f->name());
    }
    bool useFactory(StreamEventAnalyzerFactory* f) const {
        return useFactory(f->name());
    }
    bool useFactory(StreamLineAnalyzerFactory* f) const {
        return useFactory(f->name());
    }
};

void
printUsage(char** argv) {
    fprintf(stderr, "Usage: %s [OPTIONS] SOURCE\n"
        "Analyze the given file and output the result as XML.\n"
        " -c   configuration file\n"
        " -a   comma-separated list of analyzers\n"
        " -r   reference output, when specified, the reference output is \n"
        "      compared to the given output and the first difference is \n"
        "      reported.\n",
        argv[0]);
}
bool
containsHelp(int argc, char **argv) {
    for (int i=1; i<argc; ++i) {
         if (strcmp(argv[i], "--help") == 0
             || strcmp(argv[i], "-h") == 0) return true;
    }
    return false;
}
set<string>
parseAnalyzerNames(const char* names) {
    set<string> n;
    string ns(names);
    string::size_type start = 0, p = ns.find(',');
    while (p != string::npos) {
        n.insert(ns.substr(start, p-start));
        start  = p + 1;
        p = ns.find(',', start);
    }
    n.insert(ns.substr(start));
    return n;
}
set<string>
parseConfig(const char* config) {
    set<string> n;
    ifstream f(config);
    string line;
    while (f.good()) {
        getline(f, line);
        if (strncmp("analyzer=", line.c_str(), 9) == 0) {
            n.insert(line.substr(9));
        }
    }

    return n;
}
/**
 * Usage: $0 [OPTIONS] SOURCE
 **/
int
main(int argc, char** argv) {
    // there are 2 optional options that both require an argument.
    // one can specify 1 source, so the number of arguments must be
    // 2, 4 or 6
    if (containsHelp(argc, argv) || (argc != 2 && argc != 4 && argc != 6)) {
        printUsage(argv);
        return -1;
    }

    set<string> analyzers;
    const char* targetFile;
    const char* referenceFile = 0;
    if (argc == 4) {
        if (strcmp(argv[1],"-a") == 0) {
            analyzers = parseAnalyzerNames(argv[2]);
        } else if (strcmp(argv[1], "-r") == 0) {
            referenceFile = argv[2];
        } else if (strcmp(argv[1], "-c") == 0) {
            analyzers = parseConfig(argv[2]);
        } else {
            printUsage(argv);
            return -1;
        }
        targetFile = argv[3];
    } else if (argc == 6) {
        if (strcmp(argv[1], "-a") == 0) {
            analyzers = parseAnalyzerNames(argv[2]);
            if (strcmp(argv[3], "-r") == 0) {
                referenceFile = argv[4];
            }
        } else if (strcmp(argv[1], "-c") == 0) {
            analyzers = parseConfig(argv[2]);
            if (strcmp(argv[3], "-r") == 0) {
                referenceFile = argv[4];
            }
        } else if (strcmp(argv[1], "-r") == 0) {
            referenceFile = argv[2];
            if (strcmp(argv[3], "-a") == 0) {
                analyzers = parseAnalyzerNames(argv[4]);
            } else if (strcmp(argv[3], "-c") == 0) {
                analyzers = parseConfig(argv[4]);
            }
        } else {
            printUsage(argv);
            return -1;
        }
        targetFile = argv[5];
    } else {
        targetFile = argv[1];
    }

    const char* mappingFile = 0;

    // check that the target file exists
    {
        ifstream filetest(targetFile);
        if (!filetest.good()) {
            cerr << "The file '" << targetFile << "' cannot be read." << endl;
            return 1;
        }
    }
    // check that the result file is ok
    FileInputStream f(referenceFile);
//    BZ2InputStream bz2(&f);
    if (referenceFile != 0 && f.status() != Ok) {
        cerr << "The file '" << referenceFile << "' cannot be read." << endl;
        return 1;
    }

    const TagMapping mapping(mappingFile);
    ostringstream out;
    out << "<?xml version='1.0' encoding='UTF-8'?>\n<"
        << mapping.map("metadata");
    map<string, string>::const_iterator i = mapping.namespaces().begin();
    while (i != mapping.namespaces().end()) {
        out << " xmlns:" << i->first << "='" << i->second << "'";
        i++;
    }
    out << ">\n";

    SelectedAnalyzerConfiguration ic(analyzers);

    XmlIndexWriter writer(out, mapping);
    DirAnalyzer analyzer(writer, &ic);
    if (!ic.valid()) {
        set<string>::const_iterator i;
        set<string> missing;
        set_difference(analyzers.begin(), analyzers.end(),
            ic.availableAnalyzers.begin(), ic.availableAnalyzers.end(),
            insert_iterator<set<string> >(missing, missing.begin()));
        if (missing.size() == 1) {
            fprintf(stderr, "No analyzer with name %s was found.\n",
               missing.begin()->c_str());
        } else {
            cerr << "The analyzers";
            for (i = missing.begin(); i != missing.end(); ++i) {
                cerr << ", " << *i;
            }
            cerr << " were not found." << endl;
        }
        fprintf(stderr, "Choose from:\n");
        for (i = ic.availableAnalyzers.begin(); i != ic.availableAnalyzers.end(); ++i) {
            cerr << " " << *i << endl;
        }
        return 1;
    }

    // change to the directory of the file to analyze
    // this ensures a consistent naming of the file uris, regardless of cwd
    string targetPath(targetFile);
    string::size_type slashpos = targetPath.rfind('/');
    if (slashpos == string::npos) {
         analyzer.analyzeDir(targetFile);
    } else {
         chdir(targetPath.substr(0,slashpos).c_str());
         analyzer.analyzeDir(targetPath.substr(slashpos+1).c_str());
    }
    string str = out.str();
    int32_t n = 2*str.length();

    // if no reference file was specified, we output the analysis
    if (referenceFile == 0) {
        cout << str;
        return 0;
    }

    // load the file to compare with
    const char* c;
    n = f.read(c, n, n);
    if (n < 0) {
        fprintf(stderr, "Error: %s\n", f.error());
        return -1;
    }
    if (n != (int32_t)out.str().length()) {
        printf("output length differs %i instead of %i\n", out.str().length(),
            n);
    }

    const char* p1 = c;
    const char* p2 = str.c_str();
    int32_t n1 = n;
    int32_t n2 = str.length();
    while (n1-- && n2-- && *p1 == *p2) {
        p1++;
        p2++;
    }
    if (n1 ==0 && (*p1 || *p2)) {
         printf("difference at position %i\n", p1-c);

         int32_t m = (80 > str.length())?str.length():80;
         printf("%i %.*s\n", m, m, str.c_str());

         m = (80 > n)?n:80;
         printf("%i %.*s\n", m, m, c);

         return -1;
    }

    return 0;
}
<|endoftext|>


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

/* $Id$ */

//_________________________________________________________________________
//  EMCAL digit:
//      A Digit is the sum of the energy lost in an EMCAL Tower
//      It also stores information on Primary, and enterring particle
//      tracknumbers Digits are created using AliEMCALSDigitizer, followed
//      by AliEMCALDigitizer
//
//*-- Author: Sahal Yacoob (LBL)
// based on : AliPHOSDigit
//__________________________________________________________________________

// --- ROOT system ---
#include <Riostream.h>
#include <TMath.h>

// --- Standard library ---

// --- AliRoot header files ---

#include "AliEMCALDigit.h"
#include "AliEMCALGeometry.h"

ClassImp(AliEMCALDigit)

//____________________________________________________________________________
AliEMCALDigit::AliEMCALDigit() :
  AliDigitNew(),
  fNprimary(0),
  fNMaxPrimary(5),
  fPrimary(0x0),
  fDEPrimary(0x0),
  fNiparent(0),
  fNMaxiparent(5),
  fIparent(0x0),
  fDEParent(0x0),
  fMaxIter(0),
  fTime(0.),
  fTimeR(0.)

{
  // default ctor

  // Need to initialise for reading old files
  fPrimary = new Int_t[fNMaxPrimary] ;
  fDEPrimary = new Float_t[fNMaxPrimary] ;
  fIparent = new Int_t[fNMaxiparent] ;
  fDEParent = new Float_t[fNMaxiparent] ;
  for ( Int_t i = 0; i < fNMaxPrimary ; i++) {
    fPrimary[i]  = -1 ;
    fDEPrimary[i]  = 0 ;
  }

  for ( Int_t i = 0; i < fNMaxiparent ; i++) {
    fIparent[i] = -1 ;
    fDEParent[i] = 0 ;
  }
}

//____________________________________________________________________________
AliEMCALDigit::AliEMCALDigit(Int_t primary, Int_t iparent, Int_t id, Int_t DigEnergy, Float_t time, Int_t index, Float_t dE)
  : AliDigitNew(),
    fNprimary(0),
    fNMaxPrimary(25),
    fPrimary(0x0),
    fDEPrimary(0x0),
    fNiparent(0),
    fNMaxiparent(150),
    fIparent(0x0),
    fDEParent(0x0),
    fMaxIter(5),
    fTime(time),
    fTimeR(time)
{
  // ctor with all data

  // data memebrs of the base class (AliNewDigit)
  fAmp         = DigEnergy ;
  fId          = id ;
  fIndexInList = index ;

  // data members
  fPrimary = new Int_t[fNMaxPrimary] ;
  fDEPrimary = new Float_t[fNMaxPrimary] ;
  fIparent = new Int_t[fNMaxiparent] ;
  fDEParent = new Float_t[fNMaxiparent] ;
  if( primary != -1){
    fNprimary    = 1 ;
    fPrimary[0]  = primary ;
    fDEPrimary[0] = dE ;
    fNiparent   = 1 ;
    fIparent[0] = iparent ;
    fDEParent[0] = dE ;
  }
  else{  //If the contribution of this primary smaller than fDigitThreshold (AliEMCALv1)
    fNprimary    = 0 ;
    fPrimary[0]  = -1 ;
    fDEPrimary[0]  = 0 ;
    fNiparent   = 0 ;
    fIparent[0] = -1 ;
    fDEParent[0]  = 0 ;
  }
  Int_t i ;
  for ( i = 1; i < fNMaxPrimary ; i++) {
    fPrimary[i]  = -1 ;
    fDEPrimary[i]  = 0 ;
  }

  for ( i = 1; i< fNMaxiparent ; i++) {
    fIparent[i] = -1 ;
    fDEParent[i] = 0 ;
  }
}

//____________________________________________________________________________
AliEMCALDigit::AliEMCALDigit(const AliEMCALDigit & digit)
  : AliDigitNew(digit),
    fNprimary(digit.fNprimary),
    fNMaxPrimary(digit.fNMaxPrimary),
    fPrimary(0x0),
    fDEPrimary(0x0),
    fNiparent(digit.fNiparent),
    fNMaxiparent(digit.fNMaxiparent),
    fIparent(0x0),
    fDEParent(0x0),
    fMaxIter(digit.fMaxIter),
    fTime(digit.fTime),
    fTimeR(digit.fTimeR)
{
  // copy ctor

  // data memebrs of the base class (AliNewDigit)
  fAmp         = digit.fAmp ;
  fId          = digit.fId;
  fIndexInList = digit.fIndexInList ;

  // data members
  fPrimary = new Int_t[fNMaxPrimary] ;
  fDEPrimary = new Float_t[fNMaxPrimary] ;
  fIparent = new Int_t[fNMaxiparent] ;
  fDEParent = new Float_t[fNMaxiparent] ;
  Int_t i ;
  for ( i = 0; i < fNprimary ; i++) {
    fPrimary[i]  = digit.fPrimary[i] ;
    fDEPrimary[i]  = digit.fDEPrimary[i] ;
  }
  Int_t j ;
  for (j = 0; j< fNiparent ; j++) {
    fIparent[j]  = digit.fIparent[j] ;
    fDEParent[j]  = digit.fDEParent[j] ;
  }
}

//____________________________________________________________________________
AliEMCALDigit::~AliEMCALDigit()
{
  // Delete array of primiries if any
    delete [] fPrimary ;
    delete [] fDEPrimary ;
    delete [] fIparent ;
    delete [] fDEParent ;
}

//____________________________________________________________________________
Int_t AliEMCALDigit::Compare(const TObject * obj) const
{
  // Compares two digits with respect to its Id
  // to sort according increasing Id

  Int_t rv ;

  AliEMCALDigit * digit = (AliEMCALDigit *)obj ;

  Int_t iddiff = fId - digit->GetId() ;

  if ( iddiff > 0 )
    rv = 1 ;
  else if ( iddiff < 0 )
    rv = -1 ;
  else
    rv = 0 ;

  return rv ;

}

//____________________________________________________________________________
Float_t AliEMCALDigit::GetEta() const
{
  //return pseudorapidity for this digit
  // should be change in EMCALGeometry - 19-nov-04
  Float_t eta=-10., phi=-10.;
  Int_t id = GetId();
  const AliEMCALGeometry *g = AliEMCALGeometry::GetInstance();
  g->EtaPhiFromIndex(id,eta,phi);
  return eta ;
}

//____________________________________________________________________________
Float_t AliEMCALDigit::GetPhi() const
{
  //return phi coordinate of digit
  // should be change in EMCALGeometry - 19-nov-04
  Float_t eta=-10., phi=-10.;
  Int_t id = GetId();
  const AliEMCALGeometry *g = AliEMCALGeometry::GetInstance();
  g->EtaPhiFromIndex(id,eta,phi);
  return phi ;
}

//____________________________________________________________________________
Int_t AliEMCALDigit::GetPrimary(Int_t index) const
{
  // retrieves the primary particle number given its index in the list
  if ( (index <= fNprimary) && (index > 0)){
    return fPrimary[index-1] ;
  }

  return -1 ;
}

//____________________________________________________________________________
Float_t AliEMCALDigit::GetDEPrimary(Int_t index) const
{
  // retrieves the primary particle energy contribution
  // given its index in the list
  if ( (index <= fNprimary) && (index > 0)){
    return fDEPrimary[index-1] ;
  }

  return 0 ;

}

//____________________________________________________________________________
Int_t AliEMCALDigit::GetIparent(Int_t index) const
{
  // retrieves the primary particle number given its index in the list
  if ( index <= fNiparent && index > 0){
    return fIparent[index-1] ;
  }

  return -1 ;

}

//____________________________________________________________________________
Float_t AliEMCALDigit::GetDEParent(Int_t index) const
{
  // retrieves the parent particle energy contribution
  // given its index in the list
  if ( (index <= fNiparent) && (index > 0)){
    return fDEParent[index-1] ;
  }

  return 0;
}

//____________________________________________________________________________
void AliEMCALDigit::ShiftPrimary(Int_t shift){
  //shifts primary number to BIG offset, to separate primary in different TreeK
  Int_t index  ;
  for(index = 0; index <fNprimary; index++ ){
    fPrimary[index] = fPrimary[index]+ shift * 10000000   ;}
  for(index =0; index <fNiparent; index++){
    fIparent[index] = fIparent[index] + shift * 10000000 ;}
}
//____________________________________________________________________________
Bool_t AliEMCALDigit::operator==(AliEMCALDigit const & digit) const
{
  // Two digits are equal if they have the same Id

  if ( fId == digit.fId )
    return kTRUE ;
  else
    return kFALSE ;
}

//____________________________________________________________________________
AliEMCALDigit AliEMCALDigit::operator+(const AliEMCALDigit &digit)
{
  // Adds the amplitude of digits and completes the list of primary particles
  // if amplitude is larger than

  fAmp += digit.fAmp ;
  if(fTime > digit.fTime)
    fTime = digit.fTime ;
  if (digit.fTimeR < fTimeR)
    fTimeR = digit.fTimeR ;

  Int_t max1 = fNprimary ;
  Int_t max2 = fNiparent ;
  Int_t index ;
  for (index = 0 ; index < digit.fNprimary  ; index++){
    Bool_t newPrim = kTRUE ;
    Int_t old ;
    for ( old = 0 ; (old < max1) && newPrim; old++) { //already have this primary?
      if(fPrimary[old] == digit.fPrimary[index]) {
	newPrim = kFALSE;
	fDEPrimary[old] += digit.fDEPrimary[index];
      }
    }
    if (newPrim) {
      if(max1<fNMaxPrimary){
	fPrimary[max1] = digit.fPrimary[index] ;
	fDEPrimary[max1] = digit.fDEPrimary[index] ;
	fNprimary++ ;
	max1++;
      }
      if(fNprimary==fNMaxPrimary) {

	TString mess = " NMaxPrimary  =  " ;
	mess += fNMaxPrimary ;
	mess += " is too small" ;
	Fatal("AliEMCALDigit::Operator+ -->" , mess.Data()) ;

      }
    }
  }

  for (index = 0 ; index < digit.fNiparent ; index++){
    Bool_t newParent = kTRUE ;
    Int_t old ;
    for ( old = 0 ; (old < max2) && newParent; old++) { //already have this primary?
      if(fIparent[old] == digit.fIparent[index]) {
	newParent = kFALSE;
	fDEParent[old] += digit.fDEParent[index];
      }
    }
    if(newParent){
      if(max2<fNMaxiparent) {
	fIparent[max2] = digit.fIparent[index] ;
	fDEParent[max2] = digit.fDEParent[index] ;
	fNiparent++ ;
	max2++;
      }
      if(fNiparent==fNMaxiparent) {

	TString mess = " NMaxiparent  =  " ;
	mess += fNMaxiparent ;
	mess += " is too small" ;
	Fatal("AliEMCALDigit::Operator+ -->", mess.Data()) ;

      }
    }
  }

  return *this ;
}

//____________________________________________________________________________
AliEMCALDigit AliEMCALDigit::operator*(Float_t factor)
{
  // Multiplies the amplitude by a factor

  Float_t tempo = static_cast<Float_t>(fAmp) ;
  tempo *= factor ;
  fAmp = static_cast<Int_t>(TMath::Ceil(tempo)) ;
  for(Int_t i=0; i < fNprimary; i++)
    fDEPrimary[i] *= factor;
  for(Int_t i=0; i < fNiparent; i++)
    fDEParent[i] *= factor;

  return *this ;
}

//____________________________________________________________________________
ostream& operator << ( ostream& out , const AliEMCALDigit & digit)
{
  // Prints the data of the digit

  out << "ID " << digit.fId << " Energy = " << digit.fAmp <<  " Time = " << digit.fTime << endl ;
  Int_t i,j ;
  for(i=0;i<digit.fNprimary;i++)
    out << "Primary " << i+1 << " = " << digit.fPrimary[i]
	<< " : DE " << digit.fDEPrimary[i] << endl ;

  for(j=0;j<digit.fNiparent;j++)
    out << "Iparent " << j+1 << " = " << digit.fIparent[j]
	<< " : DE " << digit.fDEParent[j] << endl ;
  out << "Position in list = " << digit.fIndexInList << endl ;
  return out ;
}

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

/* $Id$ */

//_________________________________________________________________________
//  EMCAL digit:
//      A Digit is the sum of the energy lost in an EMCAL Tower
//      It also stores information on Primary, and enterring particle
//      tracknumbers Digits are created using AliEMCALSDigitizer, followed
//      by AliEMCALDigitizer
//
//*-- Author: Sahal Yacoob (LBL)
// based on : AliPHOSDigit
//__________________________________________________________________________

// --- ROOT system ---
#include <Riostream.h>
#include <TMath.h>

// --- Standard library ---

// --- AliRoot header files ---

#include "AliEMCALDigit.h"
#include "AliEMCALGeometry.h"

ClassImp(AliEMCALDigit)

//____________________________________________________________________________
AliEMCALDigit::AliEMCALDigit() :
  AliDigitNew(),
  fNprimary(0),
  fNMaxPrimary(5),
  fPrimary(0x0),
  fDEPrimary(0x0),
  fNiparent(0),
  fNMaxiparent(5),
  fIparent(0x0),
  fDEParent(0x0),
  fMaxIter(0),
  fTime(0.),
  fTimeR(0.)

{
  // default ctor

  // Need to initialise for reading old files
  fPrimary = new Int_t[fNMaxPrimary] ;
  fDEPrimary = new Float_t[fNMaxPrimary] ;
  fIparent = new Int_t[fNMaxiparent] ;
  fDEParent = new Float_t[fNMaxiparent] ;
  for ( Int_t i = 0; i < fNMaxPrimary ; i++) {
    fPrimary[i]  = -1 ;
    fDEPrimary[i]  = 0 ;
  }

  for ( Int_t i = 0; i < fNMaxiparent ; i++) {
    fIparent[i] = -1 ;
    fDEParent[i] = 0 ;
  }
}

//____________________________________________________________________________
AliEMCALDigit::AliEMCALDigit(Int_t primary, Int_t iparent, Int_t id, Int_t DigEnergy, Float_t time, Int_t index, Float_t dE)
  : AliDigitNew(),
    fNprimary(0),
    fNMaxPrimary(25),
    fPrimary(0x0),
    fDEPrimary(0x0),
    fNiparent(0),
    fNMaxiparent(150),
    fIparent(0x0),
    fDEParent(0x0),
    fMaxIter(5),
    fTime(time),
    fTimeR(time)
{
  // ctor with all data

  // data memebrs of the base class (AliNewDigit)
  fAmp         = DigEnergy ;
  fId          = id ;
  fIndexInList = index ;

  // data members
  fPrimary = new Int_t[fNMaxPrimary] ;
  fDEPrimary = new Float_t[fNMaxPrimary] ;
  fIparent = new Int_t[fNMaxiparent] ;
  fDEParent = new Float_t[fNMaxiparent] ;
  if( primary != -1){
    fNprimary    = 1 ;
    fPrimary[0]  = primary ;
    fDEPrimary[0] = dE ;
    fNiparent   = 1 ;
    fIparent[0] = iparent ;
    fDEParent[0] = dE ;
  }
  else{  //If the contribution of this primary smaller than fDigitThreshold (AliEMCALv1)
    fNprimary    = 0 ;
    fPrimary[0]  = -1 ;
    fDEPrimary[0]  = 0 ;
    fNiparent   = 0 ;
    fIparent[0] = -1 ;
    fDEParent[0]  = 0 ;
  }
  Int_t i ;
  for ( i = 1; i < fNMaxPrimary ; i++) {
    fPrimary[i]  = -1 ;
    fDEPrimary[i]  = 0 ;
  }

  for ( i = 1; i< fNMaxiparent ; i++) {
    fIparent[i] = -1 ;
    fDEParent[i] = 0 ;
  }
}

//____________________________________________________________________________
AliEMCALDigit::AliEMCALDigit(const AliEMCALDigit & digit)
  : AliDigitNew(digit),
    fNprimary(digit.fNprimary),
    fNMaxPrimary(digit.fNMaxPrimary),
    fPrimary(0x0),
    fDEPrimary(0x0),
    fNiparent(digit.fNiparent),
    fNMaxiparent(digit.fNMaxiparent),
    fIparent(0x0),
    fDEParent(0x0),
    fMaxIter(digit.fMaxIter),
    fTime(digit.fTime),
    fTimeR(digit.fTimeR)
{
  // copy ctor

  // data memebrs of the base class (AliNewDigit)
  fAmp         = digit.fAmp ;
  fId          = digit.fId;
  fIndexInList = digit.fIndexInList ;

  // data members
  fPrimary = new Int_t[fNMaxPrimary] ;
  fDEPrimary = new Float_t[fNMaxPrimary] ;
  fIparent = new Int_t[fNMaxiparent] ;
  fDEParent = new Float_t[fNMaxiparent] ;
  Int_t i ;
  for ( i = 0; i < fNMaxPrimary ; i++) {
    fPrimary[i]  = digit.fPrimary[i] ;
    fDEPrimary[i]  = digit.fDEPrimary[i] ;
  }
  Int_t j ;
  for (j = 0; j< fNMaxiparent ; j++) {
    fIparent[j]  = digit.fIparent[j] ;
    fDEParent[j]  = digit.fDEParent[j] ;
  }
}

//____________________________________________________________________________
AliEMCALDigit::~AliEMCALDigit()
{
  // Delete array of primiries if any
    delete [] fPrimary ;
    delete [] fDEPrimary ;
    delete [] fIparent ;
    delete [] fDEParent ;
}

//____________________________________________________________________________
Int_t AliEMCALDigit::Compare(const TObject * obj) const
{
  // Compares two digits with respect to its Id
  // to sort according increasing Id

  Int_t rv ;

  AliEMCALDigit * digit = (AliEMCALDigit *)obj ;

  Int_t iddiff = fId - digit->GetId() ;

  if ( iddiff > 0 )
    rv = 1 ;
  else if ( iddiff < 0 )
    rv = -1 ;
  else
    rv = 0 ;

  return rv ;

}

//____________________________________________________________________________
Float_t AliEMCALDigit::GetEta() const
{
  //return pseudorapidity for this digit
  // should be change in EMCALGeometry - 19-nov-04
  Float_t eta=-10., phi=-10.;
  Int_t id = GetId();
  const AliEMCALGeometry *g = AliEMCALGeometry::GetInstance();
  g->EtaPhiFromIndex(id,eta,phi);
  return eta ;
}

//____________________________________________________________________________
Float_t AliEMCALDigit::GetPhi() const
{
  //return phi coordinate of digit
  // should be change in EMCALGeometry - 19-nov-04
  Float_t eta=-10., phi=-10.;
  Int_t id = GetId();
  const AliEMCALGeometry *g = AliEMCALGeometry::GetInstance();
  g->EtaPhiFromIndex(id,eta,phi);
  return phi ;
}

//____________________________________________________________________________
Int_t AliEMCALDigit::GetPrimary(Int_t index) const
{
  // retrieves the primary particle number given its index in the list
  if ( (index <= fNprimary) && (index > 0)){
    return fPrimary[index-1] ;
  }

  return -1 ;
}

//____________________________________________________________________________
Float_t AliEMCALDigit::GetDEPrimary(Int_t index) const
{
  // retrieves the primary particle energy contribution
  // given its index in the list
  if ( (index <= fNprimary) && (index > 0)){
    return fDEPrimary[index-1] ;
  }

  return 0 ;

}

//____________________________________________________________________________
Int_t AliEMCALDigit::GetIparent(Int_t index) const
{
  // retrieves the primary particle number given its index in the list
  if ( index <= fNiparent && index > 0){
    return fIparent[index-1] ;
  }

  return -1 ;

}

//____________________________________________________________________________
Float_t AliEMCALDigit::GetDEParent(Int_t index) const
{
  // retrieves the parent particle energy contribution
  // given its index in the list
  if ( (index <= fNiparent) && (index > 0)){
    return fDEParent[index-1] ;
  }

  return 0;
}

//____________________________________________________________________________
void AliEMCALDigit::ShiftPrimary(Int_t shift){
  //shifts primary number to BIG offset, to separate primary in different TreeK
  Int_t index  ;
  for(index = 0; index <fNprimary; index++ ){
    fPrimary[index] = fPrimary[index]+ shift * 10000000   ;}
  for(index =0; index <fNiparent; index++){
    fIparent[index] = fIparent[index] + shift * 10000000 ;}
}
//____________________________________________________________________________
Bool_t AliEMCALDigit::operator==(AliEMCALDigit const & digit) const
{
  // Two digits are equal if they have the same Id

  if ( fId == digit.fId )
    return kTRUE ;
  else
    return kFALSE ;
}

//____________________________________________________________________________
AliEMCALDigit AliEMCALDigit::operator+(const AliEMCALDigit &digit)
{
  // Adds the amplitude of digits and completes the list of primary particles
  // if amplitude is larger than

  fAmp += digit.fAmp ;
  if(fTime > digit.fTime)
    fTime = digit.fTime ;
  if (digit.fTimeR < fTimeR)
    fTimeR = digit.fTimeR ;

  Int_t max1 = fNprimary ;
  Int_t max2 = fNiparent ;
  Int_t index ;
  for (index = 0 ; index < digit.fNprimary  ; index++){
    Bool_t newPrim = kTRUE ;
    Int_t old ;
    for ( old = 0 ; (old < max1) && newPrim; old++) { //already have this primary?
      if(fPrimary[old] == digit.fPrimary[index]) {
	newPrim = kFALSE;
	fDEPrimary[old] += digit.fDEPrimary[index];
      }
    }
    if (newPrim) {
      if(max1<fNMaxPrimary){
	fPrimary[max1] = digit.fPrimary[index] ;
	fDEPrimary[max1] = digit.fDEPrimary[index] ;
	fNprimary++ ;
	max1++;
      }
      if(fNprimary==fNMaxPrimary) {

	TString mess = " NMaxPrimary  =  " ;
	mess += fNMaxPrimary ;
	mess += " is too small" ;
	Fatal("AliEMCALDigit::Operator+ -->" , mess.Data()) ;

      }
    }
  }

  for (index = 0 ; index < digit.fNiparent ; index++){
    Bool_t newParent = kTRUE ;
    Int_t old ;
    for ( old = 0 ; (old < max2) && newParent; old++) { //already have this primary?
      if(fIparent[old] == digit.fIparent[index]) {
	newParent = kFALSE;
	fDEParent[old] += digit.fDEParent[index];
      }
    }
    if(newParent){
      if(max2<fNMaxiparent) {
	fIparent[max2] = digit.fIparent[index] ;
	fDEParent[max2] = digit.fDEParent[index] ;
	fNiparent++ ;
	max2++;
      }
      if(fNiparent==fNMaxiparent) {

	TString mess = " NMaxiparent  =  " ;
	mess += fNMaxiparent ;
	mess += " is too small" ;
	Fatal("AliEMCALDigit::Operator+ -->", mess.Data()) ;

      }
    }
  }

  return *this ;
}

//____________________________________________________________________________
AliEMCALDigit AliEMCALDigit::operator*(Float_t factor)
{
  // Multiplies the amplitude by a factor

  Float_t tempo = static_cast<Float_t>(fAmp) ;
  tempo *= factor ;
  fAmp = static_cast<Int_t>(TMath::Ceil(tempo)) ;
  for(Int_t i=0; i < fNprimary; i++)
    fDEPrimary[i] *= factor;
  for(Int_t i=0; i < fNiparent; i++)
    fDEParent[i] *= factor;

  return *this ;
}

//____________________________________________________________________________
ostream& operator << ( ostream& out , const AliEMCALDigit & digit)
{
  // Prints the data of the digit

  out << "ID " << digit.fId << " Energy = " << digit.fAmp <<  " Time = " << digit.fTime << endl ;
  Int_t i,j ;
  for(i=0;i<digit.fNprimary;i++)
    out << "Primary " << i+1 << " = " << digit.fPrimary[i]
	<< " : DE " << digit.fDEPrimary[i] << endl ;

  for(j=0;j<digit.fNiparent;j++)
    out << "Iparent " << j+1 << " = " << digit.fIparent[j]
	<< " : DE " << digit.fDEParent[j] << endl ;
  out << "Position in list = " << digit.fIndexInList << endl ;
  return out ;
}

<|endoftext|>


<commit_before>#include "BBE/BrotBoxEngine.h"
#include <iostream>

#define PERFORMANCETEST 0

#if PERFORMANCETEST
#define AMOUNTOFFRAMES (1000 * 10)
#define AMOUNTOFBATCHES (1000)
#endif

class MyGame : public bbe::Game
{
public:
#if PERFORMANCETEST
	float renderTimes[AMOUNTOFFRAMES * AMOUNTOFBATCHES];
	float cpuTimes[AMOUNTOFFRAMES * AMOUNTOFBATCHES];
	float frameTimes[AMOUNTOFFRAMES * AMOUNTOFBATCHES];

	float avg_renderTimes[AMOUNTOFBATCHES];
	float avg_cpuTimes[AMOUNTOFBATCHES];
	float avg_frameTimes[AMOUNTOFBATCHES];
#endif

#if !PERFORMANCETEST
	bbe::CameraControlNoClip ccnc = bbe::CameraControlNoClip(this);
#endif

	bbe::Random rand;

	bbe::TerrainSingle terrain;		//Terrain Single Draw Call (Tessellation)
	//bbe::Terrain terrain;			//Terrain Multi  Draw Call (Tessellation)
	//bbe::TerrainMesh terrain;		//Meshimplementation

	bbe::PointLight sunLight;

	bool wireframe = false;

#if PERFORMANCETEST
	int frameNumber = 0;
	int batch = 0;
#endif

	MyGame()
		:terrain(8 * 1024, 8 * 1024, "../Third-Party/textures/dryDirt.png", 12)
	{
#if !PERFORMANCETEST
		ccnc.setCameraPos(bbe::Vector3(1000, 1000, 500));
#endif

		terrain.setBaseTextureMult(bbe::Vector2(2, 2));
		terrain.setMaxHeight(350);
		float *weightsGrass = new float[terrain.getWidth() * terrain.getHeight()];
		float *weightsSand  = new float[terrain.getWidth() * terrain.getHeight()];
		for (int i = 0; i < terrain.getHeight(); i++)
		{
			for (int k = 0; k < terrain.getWidth(); k++)
			{
				int index = i * terrain.getWidth() + k;
				float heightValue = (float)terrain.projectOnTerrain(bbe::Vector3(k, i, 0)).z / 350;

				float weightSand = bbe::Math::normalDist(heightValue, 0, 0.3);
				float weightGras = bbe::Math::normalDist(heightValue, 0.5, 0.3);
				float weightStone = bbe::Math::normalDist(heightValue, 1, 0.3);
				float weightSum = weightSand + weightGras + weightStone;

				weightSand /= weightSum;
				weightGras /= weightSum;
				weightStone /= weightSum;

				weightsGrass[index] = weightGras;
				weightsSand[index] = weightSand;
			}
		}
		terrain.addTexture("../Third-Party/textures/sand.png", weightsSand);
		terrain.addTexture("../Third-Party/textures/cf_ter_gcs_01.png", weightsGrass);
		delete[] weightsGrass;
		delete[] weightsSand;
	}

	virtual void onStart() override
	{
		sunLight.setPosition(bbe::Vector3(10000, 20000, 40000));
		sunLight.setLightColor(bbe::Color(1, 1, 0.9f));
		sunLight.setLightStrength(0.9f);
		sunLight.setFalloffMode(bbe::LightFalloffMode::LIGHT_FALLOFF_NONE);

		terrain.setBaseTextureMult(bbe::Vector2(128, 128));
	}

	virtual void update(float timeSinceLastFrame) override
	{
#if !PERFORMANCETEST
		std::cout << "FPS: " << 1 / timeSinceLastFrame << "\n";
		ccnc.update(timeSinceLastFrame);
#endif

		if (isKeyPressed(bbe::Key::I))
		{
			wireframe = !wireframe;
		}

#if PERFORMANCETEST
		if (frameNumber < AMOUNTOFFRAMES)
		{
			frameTimes[frameNumber + batch * AMOUNTOFFRAMES] = timeSinceLastFrame;
		}
#endif
	}
	int height = 2;
	virtual void draw3D(bbe::PrimitiveBrush3D & brush) override
	{
		brush.setFillMode(wireframe ? bbe::FillMode::WIREFRAME : bbe::FillMode::SOLID);

#if !PERFORMANCETEST
		brush.setCamera(ccnc.getCameraPos(), ccnc.getCameraTarget());
#endif

#if PERFORMANCETEST
		float angle = (float)frameNumber / (float)AMOUNTOFFRAMES * bbe::Math::PI * 2;
		bbe::Vector3 center(4 * 1024, 4 * 1024, 0);
		bbe::Vector3 distTo(2 * 1024, 4 * 1024, 0);

		distTo = distTo.rotate(angle, bbe::Vector3(0, 0, 1), center);

		bbe::Vector3 pos = terrain.projectOnTerrain(distTo) + bbe::Vector3(0, 0, height);

		brush.setCamera(pos, center);
#endif

		brush.drawTerrain(terrain);

#if PERFORMANCETEST
		if (frameNumber < AMOUNTOFFRAMES)
		{
			renderTimes[frameNumber + batch * AMOUNTOFFRAMES] = bbe::Profiler::getRenderTime();
			cpuTimes[frameNumber + batch * AMOUNTOFFRAMES] = bbe::Profiler::getCPUTime();
		}
		else if(frameNumber == AMOUNTOFFRAMES)
		{
			float avgRenderTime = 0;
			float avgCpuTime = 0;
			float avgFrameTime = 0;
			for (int i = 3; i < AMOUNTOFFRAMES; i++)
			{
				avgRenderTime += renderTimes[i + batch * AMOUNTOFFRAMES];
				avgCpuTime    += cpuTimes[i + batch * AMOUNTOFFRAMES];
				avgFrameTime  += frameTimes[i + batch * AMOUNTOFFRAMES];
			}
			avgRenderTime /= (AMOUNTOFFRAMES - 3);
			avgCpuTime    /= (AMOUNTOFFRAMES - 3);
			avgFrameTime  /= (AMOUNTOFFRAMES - 3);

			avg_renderTimes[batch] = avgRenderTime;
			avg_cpuTimes[batch]    = avgCpuTime;
			avg_frameTimes[batch]  = avgFrameTime;

			frameNumber = 0;
			std::cout << batch << "\n";
			batch++;
			height++;
			if (batch == AMOUNTOFBATCHES)
			{
				bbe::simpleFile::writeFloatArrToFile(bbe::String("__REALrenderTimes") + height + ".txt", renderTimes, AMOUNTOFBATCHES * AMOUNTOFFRAMES);
				bbe::simpleFile::writeFloatArrToFile(bbe::String("__REALcpuTimes") + height + ".txt", cpuTimes, AMOUNTOFBATCHES * AMOUNTOFFRAMES);
				bbe::simpleFile::writeFloatArrToFile(bbe::String("__REALframeTimes") + height + ".txt", frameTimes, AMOUNTOFBATCHES * AMOUNTOFFRAMES);
				bbe::simpleFile::writeFloatArrToFile(bbe::String("__AVGrenderTimes") + height + ".txt", avg_renderTimes, AMOUNTOFBATCHES);
				bbe::simpleFile::writeFloatArrToFile(bbe::String("__AVGcpuTimes") + height + ".txt", avg_cpuTimes, AMOUNTOFBATCHES);
				bbe::simpleFile::writeFloatArrToFile(bbe::String("__AVGframeTimes") + height + ".txt", avg_frameTimes, AMOUNTOFBATCHES);
				std::exit(0);
			}
			return;
		}

		frameNumber++;
#endif
	}
	virtual void draw2D(bbe::PrimitiveBrush2D & brush) override
	{
	}
	virtual void onEnd() override
	{
	}
};

int main()
{
	bbe::Settings::setAmountOfLightSources(5);
	MyGame *mg = new MyGame();
	mg->start(1280, 720, "3D Test");
	delete mg;

    return 0;
}

<commit_msg>Giving some hint to the user.<commit_after>#include "BBE/BrotBoxEngine.h"
#include <iostream>

#define PERFORMANCETEST 0

#if PERFORMANCETEST
#define AMOUNTOFFRAMES (1000 * 10)
#define AMOUNTOFBATCHES (1000)
#endif

class MyGame : public bbe::Game
{
public:
#if PERFORMANCETEST
	float renderTimes[AMOUNTOFFRAMES * AMOUNTOFBATCHES];
	float cpuTimes[AMOUNTOFFRAMES * AMOUNTOFBATCHES];
	float frameTimes[AMOUNTOFFRAMES * AMOUNTOFBATCHES];

	float avg_renderTimes[AMOUNTOFBATCHES];
	float avg_cpuTimes[AMOUNTOFBATCHES];
	float avg_frameTimes[AMOUNTOFBATCHES];
#endif

#if !PERFORMANCETEST
	bbe::CameraControlNoClip ccnc = bbe::CameraControlNoClip(this);
#endif

	bbe::Random rand;

	bbe::TerrainSingle terrain;		//Terrain Single Draw Call (Tessellation)
	//bbe::Terrain terrain;			//Terrain Multi  Draw Call (Tessellation)
	//bbe::TerrainMesh terrain;		//Meshimplementation

	bbe::PointLight sunLight;

	bool wireframe = false;

#if PERFORMANCETEST
	int frameNumber = 0;
	int batch = 0;
#endif

	MyGame()
		:terrain(8 * 1024, 8 * 1024, "../Third-Party/textures/dryDirt.png", 12)
	{
#if !PERFORMANCETEST
		ccnc.setCameraPos(bbe::Vector3(1000, 1000, 500));
#endif

		terrain.setBaseTextureMult(bbe::Vector2(2, 2));
		terrain.setMaxHeight(350);
		float *weightsGrass = new float[terrain.getWidth() * terrain.getHeight()];
		float *weightsSand  = new float[terrain.getWidth() * terrain.getHeight()];
		for (int i = 0; i < terrain.getHeight(); i++)
		{
			for (int k = 0; k < terrain.getWidth(); k++)
			{
				int index = i * terrain.getWidth() + k;
				float heightValue = (float)terrain.projectOnTerrain(bbe::Vector3(k, i, 0)).z / 350;

				float weightSand = bbe::Math::normalDist(heightValue, 0, 0.3);
				float weightGras = bbe::Math::normalDist(heightValue, 0.5, 0.3);
				float weightStone = bbe::Math::normalDist(heightValue, 1, 0.3);
				float weightSum = weightSand + weightGras + weightStone;

				weightSand /= weightSum;
				weightGras /= weightSum;
				weightStone /= weightSum;

				weightsGrass[index] = weightGras;
				weightsSand[index] = weightSand;
			}
		}
		terrain.addTexture("../Third-Party/textures/sand.png", weightsSand);
		terrain.addTexture("../Third-Party/textures/cf_ter_gcs_01.png", weightsGrass);
		delete[] weightsGrass;
		delete[] weightsSand;
	}

	virtual void onStart() override
	{
		sunLight.setPosition(bbe::Vector3(10000, 20000, 40000));
		sunLight.setLightColor(bbe::Color(1, 1, 0.9f));
		sunLight.setLightStrength(0.9f);
		sunLight.setFalloffMode(bbe::LightFalloffMode::LIGHT_FALLOFF_NONE);

		terrain.setBaseTextureMult(bbe::Vector2(128, 128));
	}

	virtual void update(float timeSinceLastFrame) override
	{
#if !PERFORMANCETEST
		std::cout << "FPS: " << 1 / timeSinceLastFrame << "\n";
		ccnc.update(timeSinceLastFrame);
#endif

		if (isKeyPressed(bbe::Key::I))
		{
			wireframe = !wireframe;
		}

#if PERFORMANCETEST
		if (frameNumber < AMOUNTOFFRAMES)
		{
			frameTimes[frameNumber + batch * AMOUNTOFFRAMES] = timeSinceLastFrame;
		}
#endif
	}
	int height = 2;
	virtual void draw3D(bbe::PrimitiveBrush3D & brush) override
	{
		brush.setFillMode(wireframe ? bbe::FillMode::WIREFRAME : bbe::FillMode::SOLID);

#if !PERFORMANCETEST
		brush.setCamera(ccnc.getCameraPos(), ccnc.getCameraTarget());
#endif

#if PERFORMANCETEST
		float angle = (float)frameNumber / (float)AMOUNTOFFRAMES * bbe::Math::PI * 2;
		bbe::Vector3 center(4 * 1024, 4 * 1024, 0);
		bbe::Vector3 distTo(2 * 1024, 4 * 1024, 0);

		distTo = distTo.rotate(angle, bbe::Vector3(0, 0, 1), center);

		bbe::Vector3 pos = terrain.projectOnTerrain(distTo) + bbe::Vector3(0, 0, height);

		brush.setCamera(pos, center);
#endif

		brush.drawTerrain(terrain);

#if PERFORMANCETEST
		if (frameNumber < AMOUNTOFFRAMES)
		{
			renderTimes[frameNumber + batch * AMOUNTOFFRAMES] = bbe::Profiler::getRenderTime();
			cpuTimes[frameNumber + batch * AMOUNTOFFRAMES] = bbe::Profiler::getCPUTime();
		}
		else if(frameNumber == AMOUNTOFFRAMES)
		{
			float avgRenderTime = 0;
			float avgCpuTime = 0;
			float avgFrameTime = 0;
			for (int i = 3; i < AMOUNTOFFRAMES; i++)
			{
				avgRenderTime += renderTimes[i + batch * AMOUNTOFFRAMES];
				avgCpuTime    += cpuTimes[i + batch * AMOUNTOFFRAMES];
				avgFrameTime  += frameTimes[i + batch * AMOUNTOFFRAMES];
			}
			avgRenderTime /= (AMOUNTOFFRAMES - 3);
			avgCpuTime    /= (AMOUNTOFFRAMES - 3);
			avgFrameTime  /= (AMOUNTOFFRAMES - 3);

			avg_renderTimes[batch] = avgRenderTime;
			avg_cpuTimes[batch]    = avgCpuTime;
			avg_frameTimes[batch]  = avgFrameTime;

			frameNumber = 0;
			std::cout << batch << "\n";
			batch++;
			height++;
			if (batch == AMOUNTOFBATCHES)
			{
				bbe::simpleFile::writeFloatArrToFile(bbe::String("__REALrenderTimes") + height + ".txt", renderTimes, AMOUNTOFBATCHES * AMOUNTOFFRAMES);
				bbe::simpleFile::writeFloatArrToFile(bbe::String("__REALcpuTimes") + height + ".txt", cpuTimes, AMOUNTOFBATCHES * AMOUNTOFFRAMES);
				bbe::simpleFile::writeFloatArrToFile(bbe::String("__REALframeTimes") + height + ".txt", frameTimes, AMOUNTOFBATCHES * AMOUNTOFFRAMES);
				bbe::simpleFile::writeFloatArrToFile(bbe::String("__AVGrenderTimes") + height + ".txt", avg_renderTimes, AMOUNTOFBATCHES);
				bbe::simpleFile::writeFloatArrToFile(bbe::String("__AVGcpuTimes") + height + ".txt", avg_cpuTimes, AMOUNTOFBATCHES);
				bbe::simpleFile::writeFloatArrToFile(bbe::String("__AVGframeTimes") + height + ".txt", avg_frameTimes, AMOUNTOFBATCHES);
				std::exit(0);
			}
			return;
		}

		frameNumber++;
#endif
	}
	virtual void draw2D(bbe::PrimitiveBrush2D & brush) override
	{
	}
	virtual void onEnd() override
	{
	}
};

int main()
{
	std::cout << "Loading. Please wait. This might take a while." << std::endl;
	bbe::Settings::setAmountOfLightSources(5);
	MyGame *mg = new MyGame();
	mg->start(1280, 720, "3D Test");
	delete mg;

    return 0;
}

<|endoftext|>


<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// Run all of our test shell tests.  This is just an entry point
// to kick off gTest's RUN_ALL_TESTS().

#include "base/basictypes.h"

#if defined(OS_WIN)
#include <windows.h>
#include <commctrl.h>
#endif

#include "base/at_exit.h"
#include "base/icu_util.h"
#include "base/message_loop.h"
#include "base/process_util.h"
#include "webkit/tools/test_shell/simple_resource_loader_bridge.h"
#include "webkit/tools/test_shell/test_shell.h"
#include "webkit/tools/test_shell/test_shell_test.h"
#include "testing/gtest/include/gtest/gtest.h"

const char* TestShellTest::kJavascriptDelayExitScript =
  "<script>"
    "window.layoutTestController.waitUntilDone();"
    "window.addEventListener('load', function() {"
    "  var x = document.body.clientWidth;"  // Force a document layout
    "  window.layoutTestController.notifyDone();"
    "});"
  "</script>";

int main(int argc, char* argv[]) {
  process_util::EnableTerminationOnHeapCorruption();
  // Some unittests may use base::Singleton<>, thus we need to instanciate
  // the AtExitManager or else we will leak objects.
  base::AtExitManager at_exit_manager;

#if defined(OS_WIN)
  TestShell::InitLogging(true);  // suppress error dialogs

  // Initialize test shell in non-interactive mode, which will let us load one
  // request than automatically quit.
  TestShell::InitializeTestShell(false);

  // Some of the individual tests wind up calling TestShell::WaitTestFinished
  // which has a timeout in it.  For these tests, we don't care about a timeout
  // so just set it to be a really large number.  This is necessary because
  // when running under Purify, we were hitting those timeouts.
  TestShell::SetFileTestTimeout(USER_TIMER_MAXIMUM);
#endif

  // Allocate a message loop for this thread.  Although it is not used
  // directly, its constructor sets up some necessary state.
  MessageLoop main_message_loop;

  // Load ICU data tables
  icu_util::Initialize();

#if defined(OS_WIN)
  INITCOMMONCONTROLSEX InitCtrlEx;

  InitCtrlEx.dwSize = sizeof(INITCOMMONCONTROLSEX);
  InitCtrlEx.dwICC  = ICC_STANDARD_CLASSES;
  InitCommonControlsEx(&InitCtrlEx);
#endif

  // Run the actual tests
  testing::InitGoogleTest(&argc, argv);
  int result = RUN_ALL_TESTS();

#if defined(OS_WIN)
  TestShell::ShutdownTestShell();
  TestShell::CleanupLogging();
#endif

  return result;
}
<commit_msg>fix bustage, use new api<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// Run all of our test shell tests.  This is just an entry point
// to kick off gTest's RUN_ALL_TESTS().

#include "base/basictypes.h"

#if defined(OS_WIN)
#include <windows.h>
#include <commctrl.h>
#endif

#include "base/at_exit.h"
#include "base/icu_util.h"
#include "base/message_loop.h"
#include "base/process_util.h"
#include "webkit/tools/test_shell/simple_resource_loader_bridge.h"
#include "webkit/tools/test_shell/test_shell.h"
#include "webkit/tools/test_shell/test_shell_test.h"
#include "testing/gtest/include/gtest/gtest.h"

const char* TestShellTest::kJavascriptDelayExitScript =
  "<script>"
    "window.layoutTestController.waitUntilDone();"
    "window.addEventListener('load', function() {"
    "  var x = document.body.clientWidth;"  // Force a document layout
    "  window.layoutTestController.notifyDone();"
    "});"
  "</script>";

int main(int argc, char* argv[]) {
  process_util::EnableTerminationOnHeapCorruption();
  // Some unittests may use base::Singleton<>, thus we need to instanciate
  // the AtExitManager or else we will leak objects.
  base::AtExitManager at_exit_manager;

#if defined(OS_WIN)
  TestShell::InitLogging(true, false);  // suppress error dialogs

  // Initialize test shell in non-interactive mode, which will let us load one
  // request than automatically quit.
  TestShell::InitializeTestShell(false);

  // Some of the individual tests wind up calling TestShell::WaitTestFinished
  // which has a timeout in it.  For these tests, we don't care about a timeout
  // so just set it to be a really large number.  This is necessary because
  // when running under Purify, we were hitting those timeouts.
  TestShell::SetFileTestTimeout(USER_TIMER_MAXIMUM);
#endif

  // Allocate a message loop for this thread.  Although it is not used
  // directly, its constructor sets up some necessary state.
  MessageLoop main_message_loop;

  // Load ICU data tables
  icu_util::Initialize();

#if defined(OS_WIN)
  INITCOMMONCONTROLSEX InitCtrlEx;

  InitCtrlEx.dwSize = sizeof(INITCOMMONCONTROLSEX);
  InitCtrlEx.dwICC  = ICC_STANDARD_CLASSES;
  InitCommonControlsEx(&InitCtrlEx);
#endif

  // Run the actual tests
  testing::InitGoogleTest(&argc, argv);
  int result = RUN_ALL_TESTS();

#if defined(OS_WIN)
  TestShell::ShutdownTestShell();
  TestShell::CleanupLogging();
#endif

  return result;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: XMLTextColumnsExport.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2004-07-13 08:36:14 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

#ifndef _COM_SUN_STAR_TEXT_XTEXTCOLUMNS_HPP_
#include <com/sun/star/text/XTextColumns.hpp>
#endif
#ifndef _COM_SUN_STAR_TEXT_TEXTCOLUMN_HPP_
#include <com/sun/star/text/TextColumn.hpp>
#endif
#ifndef _COM_SUN_STAR_STYLE_VERTICALALIGNMENT_HPP_
#include <com/sun/star/style/VerticalAlignment.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif

#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include "xmluconv.hxx"
#endif
#ifndef _XMLOFF_XMLEXP_HXX
#include "xmlexp.hxx"
#endif

#ifndef _XMLOFF_XMLTEXTCOLUMNSEXPORT_HXX
#include "XMLTextColumnsExport.hxx"
#endif

using namespace ::com::sun::star::style;
using namespace ::com::sun::star::text;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::rtl;
using namespace ::xmloff::token;

XMLTextColumnsExport::XMLTextColumnsExport( SvXMLExport& rExp ) :
    rExport( rExp ),
    sSeparatorLineIsOn(RTL_CONSTASCII_USTRINGPARAM("SeparatorLineIsOn")),
    sSeparatorLineWidth(RTL_CONSTASCII_USTRINGPARAM("SeparatorLineWidth")),
    sSeparatorLineColor(RTL_CONSTASCII_USTRINGPARAM("SeparatorLineColor")),
    sSeparatorLineRelativeHeight(RTL_CONSTASCII_USTRINGPARAM("SeparatorLineRelativeHeight")),
    sSeparatorLineVerticalAlignment(RTL_CONSTASCII_USTRINGPARAM("SeparatorLineVerticalAlignment")),
    sIsAutomatic(RTL_CONSTASCII_USTRINGPARAM("IsAutomatic")),
    sAutomaticDistance(RTL_CONSTASCII_USTRINGPARAM("AutomaticDistance"))
{
}

void XMLTextColumnsExport::exportXML( const Any& rAny )
{
    Reference < XTextColumns > xColumns;
    rAny >>= xColumns;

    Sequence < TextColumn > aColumns = xColumns->getColumns();
    const TextColumn *pColumns = aColumns.getArray();
    sal_Int32 nCount = aColumns.getLength();

    OUStringBuffer sValue;
    GetExport().GetMM100UnitConverter().convertNumber( sValue, nCount );
    GetExport().AddAttribute( XML_NAMESPACE_FO, XML_COLUMN_COUNT,
                              sValue.makeStringAndClear() );

    // handle 'automatic' columns
    Reference < XPropertySet > xPropSet( xColumns, UNO_QUERY );
    if( xPropSet.is() )
    {
        Any aAny = xPropSet->getPropertyValue( sIsAutomatic );
        if ( *(sal_Bool*)aAny.getValue() )
        {
            aAny = xPropSet->getPropertyValue( sAutomaticDistance );
            sal_Int32 nDistance = 0;
            aAny >>= nDistance;
            OUStringBuffer aBuffer;
            GetExport().GetMM100UnitConverter().convertMeasure(
                aBuffer, nDistance );
            GetExport().AddAttribute( XML_NAMESPACE_FO,
                                      XML_COLUMN_GAP,
                                      aBuffer.makeStringAndClear() );
        }
    }

    SvXMLElementExport aElem( GetExport(), XML_NAMESPACE_STYLE, XML_COLUMNS,
                              sal_True, sal_True );

    if( xPropSet.is() )
    {
        Any aAny = xPropSet->getPropertyValue( sSeparatorLineIsOn );
        if( *(sal_Bool *)aAny.getValue() )
        {
            // style:width
            aAny = xPropSet->getPropertyValue( sSeparatorLineWidth );
            sal_Int32 nWidth;
            aAny >>= nWidth;
            GetExport().GetMM100UnitConverter().convertMeasure( sValue,
                                                                nWidth );
            GetExport().AddAttribute( XML_NAMESPACE_STYLE, XML_WIDTH,
                                      sValue.makeStringAndClear() );

            // style:color
            aAny = xPropSet->getPropertyValue( sSeparatorLineColor );
            sal_Int32 nColor;
            aAny >>= nColor;
            GetExport().GetMM100UnitConverter().convertColor( sValue,
                                                              nColor );
            GetExport().AddAttribute( XML_NAMESPACE_STYLE, XML_COLOR,
                                      sValue.makeStringAndClear() );

            // style:height
            aAny = xPropSet->getPropertyValue( sSeparatorLineRelativeHeight );
            sal_Int8 nHeight;
            aAny >>= nHeight;
            GetExport().GetMM100UnitConverter().convertPercent( sValue,
                                                                nHeight );
            GetExport().AddAttribute( XML_NAMESPACE_STYLE, XML_HEIGHT,
                                      sValue.makeStringAndClear() );

            // style:vertical-align
            aAny = xPropSet->getPropertyValue( sSeparatorLineVerticalAlignment );
            VerticalAlignment eVertAlign;
            aAny >>= eVertAlign;

            enum XMLTokenEnum eStr = XML_TOKEN_INVALID;
            switch( eVertAlign )
            {
//          case VerticalAlignment_TOP: eStr = XML_TOP;
            case VerticalAlignment_MIDDLE: eStr = XML_MIDDLE; break;
            case VerticalAlignment_BOTTOM: eStr = XML_BOTTOM; break;
            }

            if( eStr != XML_TOKEN_INVALID)
                GetExport().AddAttribute( XML_NAMESPACE_STYLE,
                                          XML_VERTICAL_ALIGN, eStr );

            // style:column-sep
            SvXMLElementExport aElem( GetExport(), XML_NAMESPACE_STYLE,
                                      XML_COLUMN_SEP,
                                      sal_True, sal_True );
        }
    }

    while( nCount-- )
    {
        // style:rel-width
        GetExport().GetMM100UnitConverter().convertNumber( sValue,
                                                       pColumns->Width );
        sValue.append( (sal_Unicode)'*' );
        GetExport().AddAttribute( XML_NAMESPACE_STYLE, XML_REL_WIDTH,
                                  sValue.makeStringAndClear() );

        // fo:margin-left
        GetExport().GetMM100UnitConverter().convertMeasure( sValue,
                                                       pColumns->LeftMargin );
        GetExport().AddAttribute( XML_NAMESPACE_FO, XML_START_INDENT,
                                       sValue.makeStringAndClear() );

        // fo:margin-right
        GetExport().GetMM100UnitConverter().convertMeasure( sValue,
                                                       pColumns->RightMargin );
        GetExport().AddAttribute( XML_NAMESPACE_FO, XML_END_INDENT,
                                    sValue.makeStringAndClear() );

        // style:column
        SvXMLElementExport aElem( GetExport(), XML_NAMESPACE_STYLE, XML_COLUMN,
                                  sal_True, sal_True );
        pColumns++;
    }
}

<commit_msg>INTEGRATION: CWS ooo19126 (1.6.298); FILE MERGED 2005/09/05 14:40:02 rt 1.6.298.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: XMLTextColumnsExport.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 15:20:24 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

#ifndef _COM_SUN_STAR_TEXT_XTEXTCOLUMNS_HPP_
#include <com/sun/star/text/XTextColumns.hpp>
#endif
#ifndef _COM_SUN_STAR_TEXT_TEXTCOLUMN_HPP_
#include <com/sun/star/text/TextColumn.hpp>
#endif
#ifndef _COM_SUN_STAR_STYLE_VERTICALALIGNMENT_HPP_
#include <com/sun/star/style/VerticalAlignment.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif

#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include "xmluconv.hxx"
#endif
#ifndef _XMLOFF_XMLEXP_HXX
#include "xmlexp.hxx"
#endif

#ifndef _XMLOFF_XMLTEXTCOLUMNSEXPORT_HXX
#include "XMLTextColumnsExport.hxx"
#endif

using namespace ::com::sun::star::style;
using namespace ::com::sun::star::text;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::rtl;
using namespace ::xmloff::token;

XMLTextColumnsExport::XMLTextColumnsExport( SvXMLExport& rExp ) :
    rExport( rExp ),
    sSeparatorLineIsOn(RTL_CONSTASCII_USTRINGPARAM("SeparatorLineIsOn")),
    sSeparatorLineWidth(RTL_CONSTASCII_USTRINGPARAM("SeparatorLineWidth")),
    sSeparatorLineColor(RTL_CONSTASCII_USTRINGPARAM("SeparatorLineColor")),
    sSeparatorLineRelativeHeight(RTL_CONSTASCII_USTRINGPARAM("SeparatorLineRelativeHeight")),
    sSeparatorLineVerticalAlignment(RTL_CONSTASCII_USTRINGPARAM("SeparatorLineVerticalAlignment")),
    sIsAutomatic(RTL_CONSTASCII_USTRINGPARAM("IsAutomatic")),
    sAutomaticDistance(RTL_CONSTASCII_USTRINGPARAM("AutomaticDistance"))
{
}

void XMLTextColumnsExport::exportXML( const Any& rAny )
{
    Reference < XTextColumns > xColumns;
    rAny >>= xColumns;

    Sequence < TextColumn > aColumns = xColumns->getColumns();
    const TextColumn *pColumns = aColumns.getArray();
    sal_Int32 nCount = aColumns.getLength();

    OUStringBuffer sValue;
    GetExport().GetMM100UnitConverter().convertNumber( sValue, nCount );
    GetExport().AddAttribute( XML_NAMESPACE_FO, XML_COLUMN_COUNT,
                              sValue.makeStringAndClear() );

    // handle 'automatic' columns
    Reference < XPropertySet > xPropSet( xColumns, UNO_QUERY );
    if( xPropSet.is() )
    {
        Any aAny = xPropSet->getPropertyValue( sIsAutomatic );
        if ( *(sal_Bool*)aAny.getValue() )
        {
            aAny = xPropSet->getPropertyValue( sAutomaticDistance );
            sal_Int32 nDistance = 0;
            aAny >>= nDistance;
            OUStringBuffer aBuffer;
            GetExport().GetMM100UnitConverter().convertMeasure(
                aBuffer, nDistance );
            GetExport().AddAttribute( XML_NAMESPACE_FO,
                                      XML_COLUMN_GAP,
                                      aBuffer.makeStringAndClear() );
        }
    }

    SvXMLElementExport aElem( GetExport(), XML_NAMESPACE_STYLE, XML_COLUMNS,
                              sal_True, sal_True );

    if( xPropSet.is() )
    {
        Any aAny = xPropSet->getPropertyValue( sSeparatorLineIsOn );
        if( *(sal_Bool *)aAny.getValue() )
        {
            // style:width
            aAny = xPropSet->getPropertyValue( sSeparatorLineWidth );
            sal_Int32 nWidth;
            aAny >>= nWidth;
            GetExport().GetMM100UnitConverter().convertMeasure( sValue,
                                                                nWidth );
            GetExport().AddAttribute( XML_NAMESPACE_STYLE, XML_WIDTH,
                                      sValue.makeStringAndClear() );

            // style:color
            aAny = xPropSet->getPropertyValue( sSeparatorLineColor );
            sal_Int32 nColor;
            aAny >>= nColor;
            GetExport().GetMM100UnitConverter().convertColor( sValue,
                                                              nColor );
            GetExport().AddAttribute( XML_NAMESPACE_STYLE, XML_COLOR,
                                      sValue.makeStringAndClear() );

            // style:height
            aAny = xPropSet->getPropertyValue( sSeparatorLineRelativeHeight );
            sal_Int8 nHeight;
            aAny >>= nHeight;
            GetExport().GetMM100UnitConverter().convertPercent( sValue,
                                                                nHeight );
            GetExport().AddAttribute( XML_NAMESPACE_STYLE, XML_HEIGHT,
                                      sValue.makeStringAndClear() );

            // style:vertical-align
            aAny = xPropSet->getPropertyValue( sSeparatorLineVerticalAlignment );
            VerticalAlignment eVertAlign;
            aAny >>= eVertAlign;

            enum XMLTokenEnum eStr = XML_TOKEN_INVALID;
            switch( eVertAlign )
            {
//          case VerticalAlignment_TOP: eStr = XML_TOP;
            case VerticalAlignment_MIDDLE: eStr = XML_MIDDLE; break;
            case VerticalAlignment_BOTTOM: eStr = XML_BOTTOM; break;
            }

            if( eStr != XML_TOKEN_INVALID)
                GetExport().AddAttribute( XML_NAMESPACE_STYLE,
                                          XML_VERTICAL_ALIGN, eStr );

            // style:column-sep
            SvXMLElementExport aElem( GetExport(), XML_NAMESPACE_STYLE,
                                      XML_COLUMN_SEP,
                                      sal_True, sal_True );
        }
    }

    while( nCount-- )
    {
        // style:rel-width
        GetExport().GetMM100UnitConverter().convertNumber( sValue,
                                                       pColumns->Width );
        sValue.append( (sal_Unicode)'*' );
        GetExport().AddAttribute( XML_NAMESPACE_STYLE, XML_REL_WIDTH,
                                  sValue.makeStringAndClear() );

        // fo:margin-left
        GetExport().GetMM100UnitConverter().convertMeasure( sValue,
                                                       pColumns->LeftMargin );
        GetExport().AddAttribute( XML_NAMESPACE_FO, XML_START_INDENT,
                                       sValue.makeStringAndClear() );

        // fo:margin-right
        GetExport().GetMM100UnitConverter().convertMeasure( sValue,
                                                       pColumns->RightMargin );
        GetExport().AddAttribute( XML_NAMESPACE_FO, XML_END_INDENT,
                                    sValue.makeStringAndClear() );

        // style:column
        SvXMLElementExport aElem( GetExport(), XML_NAMESPACE_STYLE, XML_COLUMN,
                                  sal_True, sal_True );
        pColumns++;
    }
}

<|endoftext|>


<commit_before>// Copyright 2015 Project Vogue. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <vector>

#include "elang/lir/transforms/parallel_copy_expander.h"

#include "base/logging.h"
#include "elang/lir/editor.h"
#include "elang/lir/factory.h"
#include "elang/lir/instructions.h"
#include "elang/lir/literals.h"
#include "elang/lir/target.h"
#include "elang/lir/value.h"

namespace elang {
namespace lir {

namespace {
bool IsImmediate(Value value) {
  return !value.is_physical() && !value.is_virtual() &&
         value.kind != Value::Kind::Argument &&
         value.kind != Value::Kind::Parameter && !value.is_stack_slot();
}
}  // namespace

//////////////////////////////////////////////////////////////////////
//
// ParallelCopyExpander::Task
//
struct ParallelCopyExpander::Task {
  Value output;
  Value input;
};

//////////////////////////////////////////////////////////////////////
//
// ParallelCopyExpander
//
ParallelCopyExpander::ParallelCopyExpander(Factory* factory, Value type)
    : FactoryUser(factory), type_(type) {
}

ParallelCopyExpander::~ParallelCopyExpander() {
}

void ParallelCopyExpander::AddScratch(Value scratch) {
  DCHECK(scratch.is_physical());
  DCHECK(scratch.type == type_.type);
  if (scratch1_.is_void()) {
    DCHECK_NE(scratch1_, scratch);
    scratch1_ = scratch;
    return;
  }
  DCHECK_NE(scratch1_, scratch);
  DCHECK(scratch2_.is_void());
  scratch2_ = scratch;
}

void ParallelCopyExpander::AddTask(Value output, Value input) {
  if (output == input)
    return;
  DCHECK_NE(output, input);
  DCHECK_EQ(output.type, type_.type);
  DCHECK_EQ(input.type, type_.type);
  DCHECK_EQ(output.size, input.size);

  if (!IsImmediate(input))
    dependency_graph_.AddEdge(output, input);
  tasks_.push_back({output, input});
}

void ParallelCopyExpander::EmitCopy(Value output, Value input) {
  if (input.is_physical()) {
    instructions_.push_back(factory()->NewCopyInstruction(output, input));
    return;
  }
  if (IsImmediate(input)) {
    if (output.is_physical() || Target::HasCopyImmediateToMemory(type_)) {
      instructions_.push_back(factory()->NewLiteralInstruction(output, input));
      return;
    }
  }
  if (output.is_physical()) {
    instructions_.push_back(factory()->NewCopyInstruction(output, input));
    return;
  }
  EmitCopy(scratch1_, input);
  EmitCopy(output, scratch1_);
}

ParallelCopyExpander::Task ParallelCopyExpander::EmitSwap(Value output,
                                                          Value input) {
  dependency_graph_.RemoveEdge(output, input);
  if (!output.is_physical() || !input.is_physical()) {
    if (output.is_physical() || input.is_physical()) {
      EmitCopy(output, input);
      return {input, input};
    }
    EmitCopy(scratch1_, input);
    EmitCopy(scratch2_, output);
    EmitCopy(input, scratch2_);
    EmitCopy(output, scratch1_);
    return {scratch2_, input};
  }

  DCHECK(output.is_physical() && input.is_physical());
  if (Target::HasSwapInstruction(type_)) {
    instructions_.push_back(
        factory()->NewPCopyInstruction({output, input}, {input, output}));
    return {input, input};
  }
  EmitCopy(scratch1_, input);
  EmitCopy(input, output);
  EmitCopy(output, scratch1_);
  return {input, input};
}

std::vector<Instruction*> ParallelCopyExpander::Expand() {
  if (!Prepare())
    return {};
  DCHECK(instructions_.empty());
  while (!tasks_.empty()) {
    std::vector<Task> pending_tasks;
    for (auto const& task : tasks_) {
      if (dependency_graph_.HasInEdge(task.output)) {
        pending_tasks.push_back(task);
        continue;
      }
      if (!IsImmediate(task.input))
        dependency_graph_.RemoveEdge(task.output, task.input);
      EmitCopy(task.output, task.input);
    }
    if (pending_tasks.empty())
      break;
    DCHECK_GE(pending_tasks.size(), 2u);

    // Emit swap for one task and rewrite rest of tasks using swapped output.
    auto const swap = pending_tasks.back();
    pending_tasks.pop_back();
    auto const swapped = EmitSwap(swap.output, swap.input);
    tasks_.clear();
    for (auto& task : pending_tasks) {
      if (task.input != swap.output) {
        tasks_.push_back(task);
        continue;
      }
      // Rewrite task to use new input.
      dependency_graph_.RemoveEdge(task.output, task.input);
      if (task.output == swapped.input)
        continue;
      tasks_.push_back({task.output, swapped.output});
      dependency_graph_.AddEdge(task.output, swapped.output);
    }
  }
  return std::move(instructions_);
}

bool ParallelCopyExpander::Prepare() {
  if (scratch2_.is_physical())
    return true;

  auto number_of_scratches = scratch1_.is_physical() ? 1 : 0;
  auto number_of_required_scratches = 0;

  for (auto const& task : tasks_) {
    auto const output = task.output;
    if (output.is_physical()) {
      if (dependency_graph_.HasInEdge(output))
        continue;
      if (scratch1_.is_void()) {
        DCHECK_EQ(number_of_scratches, 0);
        scratch1_ = output;
        number_of_scratches = 1;
        continue;
      }
      // Since, we can do all variation of copy by two scratch registers,
      // we don't need to check rest of tasks.
      DCHECK_EQ(number_of_scratches, 1);
      DCHECK_NE(scratch1_, scratch2_);
      scratch2_ = output;
      return true;
    }

    if (number_of_required_scratches == 2)
      continue;

    auto const input = task.input;
    if (input.is_physical())
      continue;
    if (IsImmediate(input)) {
      if (Target::HasCopyImmediateToMemory(input))
        continue;
      number_of_required_scratches = 1;
      continue;
    }
    if (!dependency_graph_.HasInEdge(output)) {
      number_of_required_scratches = 1;
      continue;
    }
    // Memory rotation requires two scratch registers.
    number_of_required_scratches = 2;
  }

  return number_of_scratches >= number_of_required_scratches;
}

}  // namespace lir
}  // namespace elang
<commit_msg>elang/lir/transform: Change code layout of |ParallelCopyExpander::EmitSwap()| for ease of reading.<commit_after>// Copyright 2015 Project Vogue. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <vector>

#include "elang/lir/transforms/parallel_copy_expander.h"

#include "base/logging.h"
#include "elang/lir/editor.h"
#include "elang/lir/factory.h"
#include "elang/lir/instructions.h"
#include "elang/lir/literals.h"
#include "elang/lir/target.h"
#include "elang/lir/value.h"

namespace elang {
namespace lir {

namespace {
bool IsImmediate(Value value) {
  return !value.is_physical() && !value.is_virtual() &&
         value.kind != Value::Kind::Argument &&
         value.kind != Value::Kind::Parameter && !value.is_stack_slot();
}
}  // namespace

//////////////////////////////////////////////////////////////////////
//
// ParallelCopyExpander::Task
//
struct ParallelCopyExpander::Task {
  Value output;
  Value input;
};

//////////////////////////////////////////////////////////////////////
//
// ParallelCopyExpander
//
ParallelCopyExpander::ParallelCopyExpander(Factory* factory, Value type)
    : FactoryUser(factory), type_(type) {
}

ParallelCopyExpander::~ParallelCopyExpander() {
}

void ParallelCopyExpander::AddScratch(Value scratch) {
  DCHECK(scratch.is_physical());
  DCHECK(scratch.type == type_.type);
  if (scratch1_.is_void()) {
    DCHECK_NE(scratch1_, scratch);
    scratch1_ = scratch;
    return;
  }
  DCHECK_NE(scratch1_, scratch);
  DCHECK(scratch2_.is_void());
  scratch2_ = scratch;
}

void ParallelCopyExpander::AddTask(Value output, Value input) {
  if (output == input)
    return;
  DCHECK_NE(output, input);
  DCHECK_EQ(output.type, type_.type);
  DCHECK_EQ(input.type, type_.type);
  DCHECK_EQ(output.size, input.size);

  if (!IsImmediate(input))
    dependency_graph_.AddEdge(output, input);
  tasks_.push_back({output, input});
}

void ParallelCopyExpander::EmitCopy(Value output, Value input) {
  if (input.is_physical()) {
    instructions_.push_back(factory()->NewCopyInstruction(output, input));
    return;
  }
  if (IsImmediate(input)) {
    if (output.is_physical() || Target::HasCopyImmediateToMemory(type_)) {
      instructions_.push_back(factory()->NewLiteralInstruction(output, input));
      return;
    }
  }
  if (output.is_physical()) {
    instructions_.push_back(factory()->NewCopyInstruction(output, input));
    return;
  }
  EmitCopy(scratch1_, input);
  EmitCopy(output, scratch1_);
}

ParallelCopyExpander::Task ParallelCopyExpander::EmitSwap(Value output,
                                                          Value input) {
  dependency_graph_.RemoveEdge(output, input);

  if (output.is_physical() && input.is_physical()) {
    if (Target::HasSwapInstruction(type_)) {
      instructions_.push_back(
          factory()->NewPCopyInstruction({output, input}, {input, output}));
      return {input, input};
    }
    EmitCopy(scratch1_, input);
    EmitCopy(input, output);
    EmitCopy(output, scratch1_);
    return {input, input};
  }

  if (output.is_physical()) {
    EmitCopy(scratch1_, input);
    EmitCopy(input, output);
    EmitCopy(output, scratch1_);
    return {scratch1_, input};
  }

  if (input.is_physical()) {
    EmitCopy(scratch1_, output);
    EmitCopy(output, input);
    EmitCopy(input, scratch1_);
    return {scratch1_, input};
  }

  EmitCopy(scratch1_, input);
  EmitCopy(scratch2_, output);
  EmitCopy(input, scratch2_);
  EmitCopy(output, scratch1_);
  return {scratch2_, input};
}

std::vector<Instruction*> ParallelCopyExpander::Expand() {
  if (!Prepare())
    return {};
  DCHECK(instructions_.empty());
  while (!tasks_.empty()) {
    std::vector<Task> pending_tasks;
    for (auto const& task : tasks_) {
      if (dependency_graph_.HasInEdge(task.output)) {
        pending_tasks.push_back(task);
        continue;
      }
      if (!IsImmediate(task.input))
        dependency_graph_.RemoveEdge(task.output, task.input);
      EmitCopy(task.output, task.input);
    }
    if (pending_tasks.empty())
      break;
    DCHECK_GE(pending_tasks.size(), 2u);

    // Emit swap for one task and rewrite rest of tasks using swapped output.
    auto const swap = pending_tasks.back();
    pending_tasks.pop_back();
    auto const swapped = EmitSwap(swap.output, swap.input);
    tasks_.clear();
    for (auto& task : pending_tasks) {
      if (task.input != swap.output) {
        tasks_.push_back(task);
        continue;
      }
      // Rewrite task to use new input.
      dependency_graph_.RemoveEdge(task.output, task.input);
      if (task.output == swapped.input)
        continue;
      tasks_.push_back({task.output, swapped.output});
      dependency_graph_.AddEdge(task.output, swapped.output);
    }
  }
  return std::move(instructions_);
}

bool ParallelCopyExpander::Prepare() {
  if (scratch2_.is_physical())
    return true;

  auto number_of_scratches = scratch1_.is_physical() ? 1 : 0;
  auto number_of_required_scratches = 0;

  for (auto const& task : tasks_) {
    auto const output = task.output;
    if (output.is_physical()) {
      if (dependency_graph_.HasInEdge(output))
        continue;
      if (scratch1_.is_void()) {
        DCHECK_EQ(number_of_scratches, 0);
        scratch1_ = output;
        number_of_scratches = 1;
        continue;
      }
      // Since, we can do all variation of copy by two scratch registers,
      // we don't need to check rest of tasks.
      DCHECK_EQ(number_of_scratches, 1);
      DCHECK_NE(scratch1_, scratch2_);
      scratch2_ = output;
      return true;
    }

    if (number_of_required_scratches == 2)
      continue;

    auto const input = task.input;
    if (input.is_physical())
      continue;
    if (IsImmediate(input)) {
      if (Target::HasCopyImmediateToMemory(input))
        continue;
      number_of_required_scratches = 1;
      continue;
    }
    if (!dependency_graph_.HasInEdge(output)) {
      number_of_required_scratches = 1;
      continue;
    }
    // Memory rotation requires two scratch registers.
    number_of_required_scratches = 2;
  }

  return number_of_scratches >= number_of_required_scratches;
}

}  // namespace lir
}  // namespace elang
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: ViewShellImplementation.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: pjunck $ $Date: 2004-10-28 13:27:31 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef SD_VIEW_SHELL_IMPLEMENTATION_HXX
#define SD_VIEW_SHELL_IMPLEMENTATION_HXX

#include "ViewShell.hxx"

namespace sd {

/** This class contains (will contain) the implementation of methods that
    have not be accessible from the outside.
*/
class ViewShell::Implementation
{
public:
    bool mbIsShowingUIControls;
    bool mbIsMainViewShell;
    /// Set to true when the ViewShell::Init() method has been called.
    bool mbIsInitialized;

    Implementation (ViewShell& rViewShell);
    ~Implementation (void);

    /** Process the SID_MODIFY slot.
    */
    void ProcessModifyPageSlot (
        SfxRequest& rRequest,
        SdPage* pCurrentPage,
        PageKind ePageKind);

private:
    ViewShell& mrViewShell;
};

} // end of namespace sd

#endif
<commit_msg>INTEGRATION: CWS impress15 (1.3.66); FILE MERGED 2004/11/01 09:47:29 af 1.3.66.1: #i31283# Added new method GetViewId.<commit_after>/*************************************************************************
 *
 *  $RCSfile: ViewShellImplementation.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2004-11-16 16:35:23 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef SD_VIEW_SHELL_IMPLEMENTATION_HXX
#define SD_VIEW_SHELL_IMPLEMENTATION_HXX

#include "ViewShell.hxx"

namespace sd {

/** This class contains (will contain) the implementation of methods that
    have not be accessible from the outside.
*/
class ViewShell::Implementation
{
public:
    bool mbIsShowingUIControls;
    bool mbIsMainViewShell;
    /// Set to true when the ViewShell::Init() method has been called.
    bool mbIsInitialized;

    Implementation (ViewShell& rViewShell);
    ~Implementation (void);

    /** Process the SID_MODIFY slot.
    */
    void ProcessModifyPageSlot (
        SfxRequest& rRequest,
        SdPage* pCurrentPage,
        PageKind ePageKind);

    /** Determine the view id of the view shell.  This corresponds to the
        view id stored in the SfxViewFrame class.

        We can not use the view of that class because with the introduction
        of the multi pane GUI we do not switch the SfxViewShell anymore when
        switching the view in the center pane.  The view id of the
        SfxViewFrame is thus not modified and we can not set it from the
        outside.

        The view id is still needed for the SFX to determine on start up
        (e.g. after loading a document) which ViewShellBase sub class to
        use.  These sub classes--like OutlineViewShellBase--exist only to be
        used by the SFX as factories.  They only set the initial pane
        configuration, nothing more.

        So what we do here in essence is to return on of the
        ViewShellFactoryIds that can be used to select the factory that
        creates the ViewShellBase subclass with the initial pane
        configuration that has in the center pane a view shell of the same
        type as mrViewShell.
    */
    sal_uInt16 GetViewId (void);

private:
    ViewShell& mrViewShell;
};

} // end of namespace sd

#endif
<|endoftext|>