<commit_before>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

 Module:       FGRocket.cpp
 Author:       Jon S. Berndt
 Date started: 09/12/2000
 Purpose:      This module models a rocket engine

 ------------- Copyright (C) 2000  Jon S. Berndt (jon@jsbsim.org) --------------

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

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

 You should have received a copy of the GNU Lesser General Public License along with
 this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 Place - Suite 330, Boston, MA  02111-1307, USA.

 Further information about the GNU Lesser General Public License can also be found on
 the world wide web at http://www.gnu.org.

FUNCTIONAL DESCRIPTION
--------------------------------------------------------------------------------

This class descends from the FGEngine class and models a rocket engine based on
parameters given in the engine config file for this class

HISTORY
--------------------------------------------------------------------------------
09/12/2000  JSB  Created

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
INCLUDES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/

#include <iostream>
#include <sstream>
#include "FGRocket.h"
#include "FGThruster.h"

using namespace std;

namespace JSBSim {

static const char *IdSrc = "$Id: FGRocket.cpp,v 1.29 2013/01/12 21:11:59 jberndt Exp $";
static const char *IdHdr = ID_ROCKET;

/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS IMPLEMENTATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/

FGRocket::FGRocket(FGFDMExec* exec, Element *el, int engine_number, struct Inputs& input)
  : FGEngine(exec, el, engine_number, input), isp_function(0L)
{
  Type = etRocket;
  Element* thrust_table_element = 0;
  ThrustTable = 0L;
  BurnTime = 0.0;
  previousFuelNeedPerTank = 0.0;
  previousOxiNeedPerTank = 0.0;
  PropellantFlowRate = 0.0;
  TotalPropellantExpended = 0.0;
  FuelFlowRate = FuelExpended = 0.0;
  OxidizerFlowRate = OxidizerExpended = 0.0;
  SLOxiFlowMax = SLFuelFlowMax = PropFlowMax = 0.0;
  MxR = 0.0;
  BuildupTime = 0.0;
  It = ItVac = 0.0;
  ThrustVariation = 0.0;
  TotalIspVariation = 0.0;
  VacThrust = 0.0;
  Flameout = false;

  // Defaults
   MinThrottle = 0.0;
   MaxThrottle = 1.0;

  string base_property_name = CreateIndexedPropertyName("propulsion/engine", EngineNumber);

  std::stringstream strEngineNumber;
  strEngineNumber << EngineNumber;

  Element* isp_el = el->FindElement("isp");
  Element* isp_func_el=0;

  bindmodel(); // Bind model properties first, since they might be needed in functions.

  // Specific impulse may be specified as a constant value or as a function - perhaps as a function of mixture ratio.
  if (isp_el) {
    isp_func_el = isp_el->FindElement("function");
    if (isp_func_el) {
      isp_function = new FGFunction(exec->GetPropertyManager(),isp_func_el, strEngineNumber.str());
    } else {
    Isp = el->FindElementValueAsNumber("isp");
    }
  } else {
    throw("Specific Impulse <isp> must be specified for a rocket engine");
  }

  if (el->FindElement("builduptime"))
    BuildupTime = el->FindElementValueAsNumber("builduptime");
  if (el->FindElement("maxthrottle"))
    MaxThrottle = el->FindElementValueAsNumber("maxthrottle");
  if (el->FindElement("minthrottle"))
    MinThrottle = el->FindElementValueAsNumber("minthrottle");

  if (el->FindElement("slfuelflowmax")) {
    SLFuelFlowMax = el->FindElementValueAsNumberConvertTo("slfuelflowmax", "LBS/SEC");
    if (el->FindElement("sloxiflowmax")) {
    SLOxiFlowMax = el->FindElementValueAsNumberConvertTo("sloxiflowmax", "LBS/SEC");
    }
    PropFlowMax = SLOxiFlowMax + SLFuelFlowMax;
    MxR = SLOxiFlowMax/SLFuelFlowMax;
  } else if (el->FindElement("propflowmax")) {
    PropFlowMax = el->FindElementValueAsNumberConvertTo("propflowmax", "LBS/SEC");
    // Mixture ratio may be specified here, but it can also be specified as a function or via property
    if (el->FindElement("mixtureratio")) {
      MxR = el->FindElementValueAsNumber("mixtureratio");
    }
  }

  if (isp_function) Isp = isp_function->GetValue(); // cause Isp function to be executed if present.
  // If there is a thrust table element, this is a solid propellant engine.
  thrust_table_element = el->FindElement("thrust_table");
  if (thrust_table_element) {
    ThrustTable = new FGTable(PropertyManager, thrust_table_element);
    Element* variation_element = el->FindElement("variation");
    if (variation_element) {
      if (variation_element->FindElement("thrust")) {
        ThrustVariation = variation_element->FindElementValueAsNumber("thrust");
      }
      if (variation_element->FindElement("total_isp")) {
        TotalIspVariation = variation_element->FindElementValueAsNumber("total_isp");
      }
    }
  }

  Debug(0);
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

FGRocket::~FGRocket(void)
{
  delete ThrustTable;
  Debug(1);
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

void FGRocket::Calculate(void)
{
  if (FDMExec->IntegrationSuspended()) return;

  RunPreFunctions();

  PropellantFlowRate = (FuelExpended + OxidizerExpended)/in.TotalDeltaT;
  TotalPropellantExpended += FuelExpended + OxidizerExpended;
  // If Isp has been specified as a function, override the value of Isp to that, otherwise
  // assume a constant value is given.
  if (isp_function) Isp = isp_function->GetValue();

  // If there is a thrust table, it is a function of propellant burned. The
  // engine is started when the throttle is advanced to 1.0. After that, it
  // burns without regard to throttle setting.

  if (ThrustTable != 0L) { // Thrust table given -> Solid fuel used

    if ((in.ThrottlePos[EngineNumber] == 1 || BurnTime > 0.0 ) && !Starved) {

      VacThrust = ThrustTable->GetValue(TotalPropellantExpended)
                * (ThrustVariation + 1)
                * (TotalIspVariation + 1);
      if (BurnTime <= BuildupTime && BuildupTime > 0.0) {
        VacThrust *= sin((BurnTime/BuildupTime)*M_PI/2.0);
        // VacThrust *= (1-cos((BurnTime/BuildupTime)*M_PI))/2.0; // 1 - cos approach
      }
      BurnTime += in.TotalDeltaT; // Increment burn time
    } else {
      VacThrust = 0.0;
    }

  } else { // liquid fueled rocket assumed

    if (in.ThrottlePos[EngineNumber] < MinThrottle || Starved) { // Combustion not supported

      PctPower = 0.0; // desired thrust
      Flameout = true;
      VacThrust = 0.0;

    } else { // Calculate thrust

      // PctPower = Throttle / MaxThrottle; // Min and MaxThrottle range from 0.0 to 1.0, normally.

      PctPower = in.ThrottlePos[EngineNumber];
      Flameout = false;
      VacThrust = Isp * PropellantFlowRate;

    }

  } // End thrust calculations

  LoadThrusterInputs();
  It += Thruster->Calculate(VacThrust) * in.TotalDeltaT;
  ItVac += VacThrust * in.TotalDeltaT;

  RunPostFunctions();
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
//
// The FuelFlowRate can be affected by the TotalIspVariation value (settable
// in a config file or via properties). The TotalIspVariation parameter affects
// thrust, but the thrust determines fuel flow rate, so it must be adjusted
// for Total Isp Variation.

double FGRocket::CalcFuelNeed(void)
{
  if (ThrustTable != 0L) {          // Thrust table given - infers solid fuel
    FuelFlowRate = VacThrust/Isp;   // This calculates wdot (weight flow rate in lbs/sec)
    FuelFlowRate /= (1 + TotalIspVariation);
  } else {
    SLFuelFlowMax = PropFlowMax / (1 + MxR);
    FuelFlowRate = SLFuelFlowMax * PctPower;
  }

  FuelExpended = FuelFlowRate * in.TotalDeltaT; // For this time step ...
  return FuelExpended;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

double FGRocket::CalcOxidizerNeed(void)
{
  SLOxiFlowMax = PropFlowMax * MxR / (1 + MxR);
  OxidizerFlowRate = SLOxiFlowMax * PctPower;
  OxidizerExpended = OxidizerFlowRate * in.TotalDeltaT;
  return OxidizerExpended;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

string FGRocket::GetEngineLabels(const string& delimiter)
{
  std::ostringstream buf;

  buf << Name << " Total Impulse (engine " << EngineNumber << " in psf)" << delimiter
      << Name << " Total Vacuum Impulse (engine " << EngineNumber << " in psf)" << delimiter
      << Thruster->GetThrusterLabels(EngineNumber, delimiter);

  return buf.str();
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

string FGRocket::GetEngineValues(const string& delimiter)
{
  std::ostringstream buf;

  buf << It << delimiter
      << ItVac << delimiter
      << Thruster->GetThrusterValues(EngineNumber, delimiter);

  return buf.str();
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// This function should tie properties to rocket engine specific properties
// that are not bound in the base class (FGEngine) code.
//
void FGRocket::bindmodel()
{
  string property_name, base_property_name;
  base_property_name = CreateIndexedPropertyName("propulsion/engine", EngineNumber);

  property_name = base_property_name + "/total-impulse";
  PropertyManager->Tie( property_name.c_str(), this, &FGRocket::GetTotalImpulse);
  property_name = base_property_name + "/vacuum-thrust_lbs";
  PropertyManager->Tie( property_name.c_str(), this, &FGRocket::GetVacThrust);

  if (ThrustTable) { // Solid rocket motor
    property_name = base_property_name + "/thrust-variation_pct";
    PropertyManager->Tie( property_name.c_str(), this, &FGRocket::GetThrustVariation,
                                                       &FGRocket::SetThrustVariation);
    property_name = base_property_name + "/total-isp-variation_pct";
    PropertyManager->Tie( property_name.c_str(), this, &FGRocket::GetTotalIspVariation,
                                                       &FGRocket::SetTotalIspVariation);
  } else { // Liquid rocket motor
    property_name = base_property_name + "/oxi-flow-rate-pps";
    PropertyManager->Tie( property_name.c_str(), this, &FGRocket::GetOxiFlowRate);
    property_name = base_property_name + "/mixture-ratio";
    PropertyManager->Tie( property_name.c_str(), this, &FGRocket::GetMixtureRatio,
                                                       &FGRocket::SetMixtureRatio);
    property_name = base_property_name + "/isp";
    PropertyManager->Tie( property_name.c_str(), this, &FGRocket::GetIsp,
                                                       &FGRocket::SetIsp);
  }
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
//    The bitmasked value choices are as follows:
//    unset: In this case (the default) JSBSim would only print
//       out the normally expected messages, essentially echoing
//       the config files as they are read. If the environment
//       variable is not set, debug_lvl is set to 1 internally
//    0: This requests JSBSim not to output any messages
//       whatsoever.
//    1: This value explicity requests the normal JSBSim
//       startup messages
//    2: This value asks for a message to be printed out when
//       a class is instantiated
//    4: When this value is set, a message is displayed when a
//       FGModel object executes its Run() method
//    8: When this value is set, various runtime state variables
//       are printed out periodically
//    16: When set various parameters are sanity checked and
//       a message is printed out when they go out of bounds

void FGRocket::Debug(int from)
{
  if (debug_lvl <= 0) return;

  if (debug_lvl & 1) { // Standard console startup message output
    if (from == 0) { // Constructor
      cout << "      Engine Name: " << Name << endl;
      cout << "      Vacuum Isp = " << Isp << endl;
      cout << "      Maximum Throttle = " << MaxThrottle << endl;
      cout << "      Minimum Throttle = " << MinThrottle << endl;
      cout << "      Fuel Flow (max) = " << SLFuelFlowMax << endl;
      cout << "      Oxidizer Flow (max) = " << SLOxiFlowMax << endl;
      if (SLFuelFlowMax > 0)
        cout << "      Mixture ratio = " << SLOxiFlowMax/SLFuelFlowMax << endl;
    }
  }
  if (debug_lvl & 2 ) { // Instantiation/Destruction notification
    if (from == 0) cout << "Instantiated: FGRocket" << endl;
    if (from == 1) cout << "Destroyed:    FGRocket" << endl;
  }
  if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects
  }
  if (debug_lvl & 8 ) { // Runtime state variables
  }
  if (debug_lvl & 16) { // Sanity checking
  }
  if (debug_lvl & 64) {
    if (from == 0) { // Constructor
      cout << IdSrc << endl;
      cout << IdHdr << endl;
    }
  }
}
}
<commit_msg>Fixed units text in output<commit_after>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

 Module:       FGRocket.cpp
 Author:       Jon S. Berndt
 Date started: 09/12/2000
 Purpose:      This module models a rocket engine

 ------------- Copyright (C) 2000  Jon S. Berndt (jon@jsbsim.org) --------------

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

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

 You should have received a copy of the GNU Lesser General Public License along with
 this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 Place - Suite 330, Boston, MA  02111-1307, USA.

 Further information about the GNU Lesser General Public License can also be found on
 the world wide web at http://www.gnu.org.

FUNCTIONAL DESCRIPTION
--------------------------------------------------------------------------------

This class descends from the FGEngine class and models a rocket engine based on
parameters given in the engine config file for this class

HISTORY
--------------------------------------------------------------------------------
09/12/2000  JSB  Created

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
INCLUDES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/

#include <iostream>
#include <sstream>
#include "FGRocket.h"
#include "FGThruster.h"

using namespace std;

namespace JSBSim {

static const char *IdSrc = "$Id: FGRocket.cpp,v 1.30 2013/06/10 02:00:11 jberndt Exp $";
static const char *IdHdr = ID_ROCKET;

/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS IMPLEMENTATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/

FGRocket::FGRocket(FGFDMExec* exec, Element *el, int engine_number, struct Inputs& input)
  : FGEngine(exec, el, engine_number, input), isp_function(0L)
{
  Type = etRocket;
  Element* thrust_table_element = 0;
  ThrustTable = 0L;
  BurnTime = 0.0;
  previousFuelNeedPerTank = 0.0;
  previousOxiNeedPerTank = 0.0;
  PropellantFlowRate = 0.0;
  TotalPropellantExpended = 0.0;
  FuelFlowRate = FuelExpended = 0.0;
  OxidizerFlowRate = OxidizerExpended = 0.0;
  SLOxiFlowMax = SLFuelFlowMax = PropFlowMax = 0.0;
  MxR = 0.0;
  BuildupTime = 0.0;
  It = ItVac = 0.0;
  ThrustVariation = 0.0;
  TotalIspVariation = 0.0;
  VacThrust = 0.0;
  Flameout = false;

  // Defaults
   MinThrottle = 0.0;
   MaxThrottle = 1.0;

  string base_property_name = CreateIndexedPropertyName("propulsion/engine", EngineNumber);

  std::stringstream strEngineNumber;
  strEngineNumber << EngineNumber;

  Element* isp_el = el->FindElement("isp");
  Element* isp_func_el=0;

  bindmodel(); // Bind model properties first, since they might be needed in functions.

  // Specific impulse may be specified as a constant value or as a function - perhaps as a function of mixture ratio.
  if (isp_el) {
    isp_func_el = isp_el->FindElement("function");
    if (isp_func_el) {
      isp_function = new FGFunction(exec->GetPropertyManager(),isp_func_el, strEngineNumber.str());
    } else {
    Isp = el->FindElementValueAsNumber("isp");
    }
  } else {
    throw("Specific Impulse <isp> must be specified for a rocket engine");
  }

  if (el->FindElement("builduptime"))
    BuildupTime = el->FindElementValueAsNumber("builduptime");
  if (el->FindElement("maxthrottle"))
    MaxThrottle = el->FindElementValueAsNumber("maxthrottle");
  if (el->FindElement("minthrottle"))
    MinThrottle = el->FindElementValueAsNumber("minthrottle");

  if (el->FindElement("slfuelflowmax")) {
    SLFuelFlowMax = el->FindElementValueAsNumberConvertTo("slfuelflowmax", "LBS/SEC");
    if (el->FindElement("sloxiflowmax")) {
    SLOxiFlowMax = el->FindElementValueAsNumberConvertTo("sloxiflowmax", "LBS/SEC");
    }
    PropFlowMax = SLOxiFlowMax + SLFuelFlowMax;
    MxR = SLOxiFlowMax/SLFuelFlowMax;
  } else if (el->FindElement("propflowmax")) {
    PropFlowMax = el->FindElementValueAsNumberConvertTo("propflowmax", "LBS/SEC");
    // Mixture ratio may be specified here, but it can also be specified as a function or via property
    if (el->FindElement("mixtureratio")) {
      MxR = el->FindElementValueAsNumber("mixtureratio");
    }
  }

  if (isp_function) Isp = isp_function->GetValue(); // cause Isp function to be executed if present.
  // If there is a thrust table element, this is a solid propellant engine.
  thrust_table_element = el->FindElement("thrust_table");
  if (thrust_table_element) {
    ThrustTable = new FGTable(PropertyManager, thrust_table_element);
    Element* variation_element = el->FindElement("variation");
    if (variation_element) {
      if (variation_element->FindElement("thrust")) {
        ThrustVariation = variation_element->FindElementValueAsNumber("thrust");
      }
      if (variation_element->FindElement("total_isp")) {
        TotalIspVariation = variation_element->FindElementValueAsNumber("total_isp");
      }
    }
  }

  Debug(0);
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

FGRocket::~FGRocket(void)
{
  delete ThrustTable;
  Debug(1);
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

void FGRocket::Calculate(void)
{
  if (FDMExec->IntegrationSuspended()) return;

  RunPreFunctions();

  PropellantFlowRate = (FuelExpended + OxidizerExpended)/in.TotalDeltaT;
  TotalPropellantExpended += FuelExpended + OxidizerExpended;
  // If Isp has been specified as a function, override the value of Isp to that, otherwise
  // assume a constant value is given.
  if (isp_function) Isp = isp_function->GetValue();

  // If there is a thrust table, it is a function of propellant burned. The
  // engine is started when the throttle is advanced to 1.0. After that, it
  // burns without regard to throttle setting.

  if (ThrustTable != 0L) { // Thrust table given -> Solid fuel used

    if ((in.ThrottlePos[EngineNumber] == 1 || BurnTime > 0.0 ) && !Starved) {

      VacThrust = ThrustTable->GetValue(TotalPropellantExpended)
                * (ThrustVariation + 1)
                * (TotalIspVariation + 1);
      if (BurnTime <= BuildupTime && BuildupTime > 0.0) {
        VacThrust *= sin((BurnTime/BuildupTime)*M_PI/2.0);
        // VacThrust *= (1-cos((BurnTime/BuildupTime)*M_PI))/2.0; // 1 - cos approach
      }
      BurnTime += in.TotalDeltaT; // Increment burn time
    } else {
      VacThrust = 0.0;
    }

  } else { // liquid fueled rocket assumed

    if (in.ThrottlePos[EngineNumber] < MinThrottle || Starved) { // Combustion not supported

      PctPower = 0.0; // desired thrust
      Flameout = true;
      VacThrust = 0.0;

    } else { // Calculate thrust

      // PctPower = Throttle / MaxThrottle; // Min and MaxThrottle range from 0.0 to 1.0, normally.

      PctPower = in.ThrottlePos[EngineNumber];
      Flameout = false;
      VacThrust = Isp * PropellantFlowRate;

    }

  } // End thrust calculations

  LoadThrusterInputs();
  It += Thruster->Calculate(VacThrust) * in.TotalDeltaT;
  ItVac += VacThrust * in.TotalDeltaT;

  RunPostFunctions();
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
//
// The FuelFlowRate can be affected by the TotalIspVariation value (settable
// in a config file or via properties). The TotalIspVariation parameter affects
// thrust, but the thrust determines fuel flow rate, so it must be adjusted
// for Total Isp Variation.

double FGRocket::CalcFuelNeed(void)
{
  if (ThrustTable != 0L) {          // Thrust table given - infers solid fuel
    FuelFlowRate = VacThrust/Isp;   // This calculates wdot (weight flow rate in lbs/sec)
    FuelFlowRate /= (1 + TotalIspVariation);
  } else {
    SLFuelFlowMax = PropFlowMax / (1 + MxR);
    FuelFlowRate = SLFuelFlowMax * PctPower;
  }

  FuelExpended = FuelFlowRate * in.TotalDeltaT; // For this time step ...
  return FuelExpended;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

double FGRocket::CalcOxidizerNeed(void)
{
  SLOxiFlowMax = PropFlowMax * MxR / (1 + MxR);
  OxidizerFlowRate = SLOxiFlowMax * PctPower;
  OxidizerExpended = OxidizerFlowRate * in.TotalDeltaT;
  return OxidizerExpended;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

string FGRocket::GetEngineLabels(const string& delimiter)
{
  std::ostringstream buf;

  buf << Name << " Total Impulse (engine " << EngineNumber << " in lbf)" << delimiter
      << Name << " Total Vacuum Impulse (engine " << EngineNumber << " in lbf)" << delimiter
      << Thruster->GetThrusterLabels(EngineNumber, delimiter);

  return buf.str();
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

string FGRocket::GetEngineValues(const string& delimiter)
{
  std::ostringstream buf;

  buf << It << delimiter
      << ItVac << delimiter
      << Thruster->GetThrusterValues(EngineNumber, delimiter);

  return buf.str();
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// This function should tie properties to rocket engine specific properties
// that are not bound in the base class (FGEngine) code.
//
void FGRocket::bindmodel()
{
  string property_name, base_property_name;
  base_property_name = CreateIndexedPropertyName("propulsion/engine", EngineNumber);

  property_name = base_property_name + "/total-impulse";
  PropertyManager->Tie( property_name.c_str(), this, &FGRocket::GetTotalImpulse);
  property_name = base_property_name + "/vacuum-thrust_lbs";
  PropertyManager->Tie( property_name.c_str(), this, &FGRocket::GetVacThrust);

  if (ThrustTable) { // Solid rocket motor
    property_name = base_property_name + "/thrust-variation_pct";
    PropertyManager->Tie( property_name.c_str(), this, &FGRocket::GetThrustVariation,
                                                       &FGRocket::SetThrustVariation);
    property_name = base_property_name + "/total-isp-variation_pct";
    PropertyManager->Tie( property_name.c_str(), this, &FGRocket::GetTotalIspVariation,
                                                       &FGRocket::SetTotalIspVariation);
  } else { // Liquid rocket motor
    property_name = base_property_name + "/oxi-flow-rate-pps";
    PropertyManager->Tie( property_name.c_str(), this, &FGRocket::GetOxiFlowRate);
    property_name = base_property_name + "/mixture-ratio";
    PropertyManager->Tie( property_name.c_str(), this, &FGRocket::GetMixtureRatio,
                                                       &FGRocket::SetMixtureRatio);
    property_name = base_property_name + "/isp";
    PropertyManager->Tie( property_name.c_str(), this, &FGRocket::GetIsp,
                                                       &FGRocket::SetIsp);
  }
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
//    The bitmasked value choices are as follows:
//    unset: In this case (the default) JSBSim would only print
//       out the normally expected messages, essentially echoing
//       the config files as they are read. If the environment
//       variable is not set, debug_lvl is set to 1 internally
//    0: This requests JSBSim not to output any messages
//       whatsoever.
//    1: This value explicity requests the normal JSBSim
//       startup messages
//    2: This value asks for a message to be printed out when
//       a class is instantiated
//    4: When this value is set, a message is displayed when a
//       FGModel object executes its Run() method
//    8: When this value is set, various runtime state variables
//       are printed out periodically
//    16: When set various parameters are sanity checked and
//       a message is printed out when they go out of bounds

void FGRocket::Debug(int from)
{
  if (debug_lvl <= 0) return;

  if (debug_lvl & 1) { // Standard console startup message output
    if (from == 0) { // Constructor
      cout << "      Engine Name: " << Name << endl;
      cout << "      Vacuum Isp = " << Isp << endl;
      cout << "      Maximum Throttle = " << MaxThrottle << endl;
      cout << "      Minimum Throttle = " << MinThrottle << endl;
      cout << "      Fuel Flow (max) = " << SLFuelFlowMax << endl;
      cout << "      Oxidizer Flow (max) = " << SLOxiFlowMax << endl;
      if (SLFuelFlowMax > 0)
        cout << "      Mixture ratio = " << SLOxiFlowMax/SLFuelFlowMax << endl;
    }
  }
  if (debug_lvl & 2 ) { // Instantiation/Destruction notification
    if (from == 0) cout << "Instantiated: FGRocket" << endl;
    if (from == 1) cout << "Destroyed:    FGRocket" << endl;
  }
  if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects
  }
  if (debug_lvl & 8 ) { // Runtime state variables
  }
  if (debug_lvl & 16) { // Sanity checking
  }
  if (debug_lvl & 64) {
    if (from == 0) { // Constructor
      cout << IdSrc << endl;
      cout << IdHdr << endl;
    }
  }
}
}
<|endoftext|>


<commit_before>#include "scanner/api/kernel.h"
#include "scanner/api/op.h"
#include "scanner/util/memory.h"

namespace scanner {

class DiscardKernel : public BatchedKernel {
 public:
  DiscardKernel(const KernelConfig& config)
    : BatchedKernel(config),
      device_(config.devices[0]),
      work_item_size_(config.work_item_size) {}

  void execute(const BatchedColumns& input_columns,
               BatchedColumns& output_columns) override {
    i32 input_count = (i32)num_rows(input_columns[0]);
    u8* output_block = new_block_buffer(device_, 1, input_count);
    for (i32 i = 0; i < input_count; ++i) {
      insert_element(output_columns[0], output_block, 1);
    }
  }

 private:
  DeviceHandle device_;
  i32 work_item_size_;
};

REGISTER_OP(Discard).input("ignore").output("dummy");

REGISTER_OP(DiscardFrame).frame_input("ignore").output("dummy");

REGISTER_KERNEL(Discard, DiscardKernel).device(DeviceType::CPU).num_devices(1);

REGISTER_KERNEL(Discard, DiscardKernel).device(DeviceType::GPU).num_devices(1);

REGISTER_KERNEL(DiscardFrame, DiscardKernel)
    .device(DeviceType::CPU)
    .num_devices(1);

REGISTER_KERNEL(DiscardFrame, DiscardKernel)
    .device(DeviceType::GPU)
    .num_devices(1);
}
<commit_msg>Support batching on discard kernel<commit_after>#include "scanner/api/kernel.h"
#include "scanner/api/op.h"
#include "scanner/util/memory.h"

namespace scanner {

class DiscardKernel : public BatchedKernel {
 public:
  DiscardKernel(const KernelConfig& config)
    : BatchedKernel(config),
      device_(config.devices[0]),
      work_item_size_(config.work_item_size) {}

  void execute(const BatchedColumns& input_columns,
               BatchedColumns& output_columns) override {
    i32 input_count = (i32)num_rows(input_columns[0]);
    u8* output_block = new_block_buffer(device_, 1, input_count);
    for (i32 i = 0; i < input_count; ++i) {
      insert_element(output_columns[0], output_block, 1);
    }
  }

 private:
  DeviceHandle device_;
  i32 work_item_size_;
};

REGISTER_OP(Discard).input("ignore").output("dummy");

REGISTER_OP(DiscardFrame).frame_input("ignore").output("dummy");

REGISTER_KERNEL(Discard, DiscardKernel).device(DeviceType::CPU).num_devices(1);

REGISTER_KERNEL(Discard, DiscardKernel).device(DeviceType::GPU).num_devices(1);

REGISTER_KERNEL(DiscardFrame, DiscardKernel)
    .device(DeviceType::CPU)
    .batch()
    .num_devices(1);

REGISTER_KERNEL(DiscardFrame, DiscardKernel)
    .device(DeviceType::GPU)
    .batch()
    .num_devices(1);
}
<|endoftext|>


<commit_before>/*
    Copyright (C) 2014 Alexandr Akulich <akulichalexander@gmail.com>

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
    LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
    OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
    WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

*/

#ifndef CTELEGRAMCONNECTION_HPP
#define CTELEGRAMCONNECTION_HPP

#include <QObject>
#include <QByteArray>
#include <QVector>
#include <QMap>
#include <QStringList>

#include "TLTypes.hpp"
#include "crypto-rsa.hpp"
#include "crypto-aes.hpp"

class CAppInformation;
class CTelegramStream;
class CTelegramTransport;

class CTelegramConnection : public QObject
{
    Q_OBJECT
public:
    enum AuthState {
        AuthStateNone,
        AuthStatePqRequested,
        AuthStateDhRequested,
        AuthStateDhGenerationResultRequested,
        AuthStateSuccess,
        AuthStateSignedIn
    };

    enum DeltaTimeHeuristicState {
        DeltaTimeIsOk,
        DeltaTimeCorrectionForward,
        DeltaTimeCorrectionBackward,
    };

    explicit CTelegramConnection(const CAppInformation *appInfo, QObject *parent = 0);

    void setDcInfo(const TLDcOption &newDcInfo);

    inline TLDcOption dcInfo() const { return m_dcInfo; }

    void connectToDc();

    bool isConnected() const;

    static quint64 formatTimeStamp(qint64 timeInMs);
    static inline quint64 formatClientTimeStamp(qint64 timeInMs) { return formatTimeStamp(timeInMs) & ~quint64(3); }

    static quint64 timeStampToMSecsSinceEpoch(quint64 ts);

    void initAuth();
    void getConfiguration();

    void requestPhoneStatus(const QString &phoneNumber);
    void requestPhoneCode(const QString &phoneNumber);
    void signIn(const QString &phoneNumber, const QString &authCode);
    void signUp(const QString &phoneNumber, const QString &authCode, const QString &firstName, const QString &lastName);

    void requestContacts();
    void getFile(const TLInputFileLocation &location, quint32 fileId);

    void addContacts(const QStringList &phoneNumbers, bool replace);

    void sendMessage(const TLInputPeer &peer, const QString &message);

    AuthState authState() { return m_authState; }

    void requestPqAuthorization();
    bool answerPqAuthorization(const QByteArray &payload);
    void requestDhParameters();
    bool answerDh(const QByteArray &payload);
    void requestDhGenerationResult();
    bool processServersDHAnswer(const QByteArray &payload);

    inline TLNumber128 clientNonce() const { return m_clientNonce; }
    inline TLNumber128 serverNonce() const { return m_serverNonce; }

    inline quint64 pq() const { return m_pq; }
    inline quint64 p() const { return m_p; }
    inline quint64 q() const { return m_q; }

    inline quint64 serverPublicFingersprint() const { return m_serverPublicFingersprint; }

    inline QByteArray authKey() const { return m_authKey; }
    void setAuthKey(const QByteArray &newAuthKey);
    inline quint64 authId() const { return m_authId; }

    inline quint64 serverSalt() const { return m_serverSalt; }
    void setServerSalt(const quint64 salt) { m_serverSalt = salt; }
    inline quint64 sessionId() const { return m_sessionId; }

    inline QVector<TLDcOption> dcConfiguration() const { return m_dcConfiguration; }

    inline qint32 deltaTime() const { return m_deltaTime; }
    void setDeltaTime(const qint32 delta) { m_deltaTime = delta; }

    void processRedirectedPackage(const QByteArray &data);

signals:
    void wantedActiveDcChanged(int dc);
    void newRedirectedPackage(const QByteArray &data, int dc);

    void selfPhoneReceived(const QString &phoneNumber);
    void authStateChanged(int dc, int state);
    void actualDcIdReceived(int dc, int newDcId);
    void dcConfigurationReceived(int dc);
    void phoneStatusReceived(const QString &phone, bool registered, bool invited);
    void phoneCodeRequired();
    void phoneCodeIsInvalid();
    void usersReceived(const QVector<TLUser> &users);
    void usersAdded(const QVector<TLUser> &users);
    void fileReceived(const TLUploadFile &file, quint32 fileId);

    void updatesReceived(const TLUpdates &update);

private slots:
    void whenConnected();
    void whenReadyRead();

protected:
    void processRpcQuery(const QByteArray &data);

    void processSessionCreated(CTelegramStream &stream);
    void processContainer(CTelegramStream &stream);
    void processRpcResult(CTelegramStream &stream);
    void processGzipPacked(CTelegramStream &stream);
    bool processRpcError(CTelegramStream &stream, quint64 id, TLValue request);

    void processMessageAck(CTelegramStream &stream);
    void processIgnoredMessageNotification(CTelegramStream &stream);

    TLValue processHelpGetConfig(CTelegramStream &stream, quint64 id);
    TLValue processContactsGetContacts(CTelegramStream &stream, quint64 id);
    TLValue processContactsImportContacts(CTelegramStream &stream, quint64 id);
    TLValue processAuthCheckPhone(CTelegramStream &stream, quint64 id);
    TLValue processAuthSendCode(CTelegramStream &stream, quint64 id);
    TLValue processAuthSign(CTelegramStream &stream, quint64 id);
    TLValue processUploadGetFile(CTelegramStream &stream, quint64 id);
    TLValue processMessagesSendMessage(CTelegramStream &stream, quint64 id);

    bool processErrorSeeOther(const QString errorMessage, quint64 id);

    TLValue processUpdate(CTelegramStream &stream);

    SAesKey generateTmpAesKey() const;
    SAesKey generateClientToServerAesKey(const QByteArray &messageKey) const;
    SAesKey generateServerToClientAesKey(const QByteArray &messageKey) const;

    SAesKey generateAesKey(const QByteArray &messageKey, int xValue) const;

    void insertInitConnection(QByteArray *data) const;

    quint64 sendPlainPackage(const QByteArray &buffer);
    quint64 sendEncryptedPackage(const QByteArray &buffer);
    void setTransport(CTelegramTransport *newTransport);

    void setAuthState(AuthState newState);

    quint64 newMessageId();

    const CAppInformation *m_appInfo;

    QMap<quint64, QByteArray> m_submittedPackages; // <message id, package data>
    QMap<quint64, quint32> m_requestedFilesIds; // <message id, file id>

    CTelegramTransport *m_transport;

    AuthState m_authState;

    QByteArray m_authKey;
    quint64 m_authId;
    quint64 m_authKeyAuxHash;
    quint64 m_serverSalt;
    quint64 m_receivedServerSalt;
    quint64 m_sessionId;
    quint64 m_lastMessageId;
    quint32 m_sequenceNumber;
    quint32 m_contentRelatedMessages;

    qint32 m_deltaTime;
    DeltaTimeHeuristicState m_deltaTimeHeuristicState;

    TLNumber128 m_clientNonce;
    TLNumber128 m_serverNonce;
    TLNumber256 m_newNonce;

    quint64 m_pq;
    quint32 m_p;
    quint32 m_q;

    quint64 m_serverPublicFingersprint;
    SRsaKey m_rsaKey;
    SAesKey m_tmpAesKey;

    quint32 m_g;
    QByteArray m_dhPrime;
    QByteArray m_gA;
    QByteArray m_b;

    quint64 m_authRetryId;

    TLDcOption m_dcInfo;

    QVector<TLDcOption> m_dcConfiguration;

    QString m_authCodeHash;

};

inline SAesKey CTelegramConnection::generateClientToServerAesKey(const QByteArray &messageKey) const
{
    return generateAesKey(messageKey, 0);
}

inline SAesKey CTelegramConnection::generateServerToClientAesKey(const QByteArray &messageKey) const
{
    return generateAesKey(messageKey, 8);
}

#endif // CTELEGRAMCONNECTION_HPP
<commit_msg>Fixed compilation.<commit_after>/*
    Copyright (C) 2014 Alexandr Akulich <akulichalexander@gmail.com>

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
    LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
    OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
    WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

*/

#ifndef CTELEGRAMCONNECTION_HPP
#define CTELEGRAMCONNECTION_HPP

#include <QObject>
#include <QByteArray>
#include <QVector>
#include <QMap>
#include <QStringList>

#include "TLTypes.hpp"
#include "crypto-rsa.hpp"
#include "crypto-aes.hpp"

class CAppInformation;
class CTelegramStream;
class CTelegramTransport;

class CTelegramConnection : public QObject
{
    Q_OBJECT
public:
    enum AuthState {
        AuthStateNone,
        AuthStatePqRequested,
        AuthStateDhRequested,
        AuthStateDhGenerationResultRequested,
        AuthStateSuccess,
        AuthStateSignedIn
    };

    enum DeltaTimeHeuristicState {
        DeltaTimeIsOk,
        DeltaTimeCorrectionForward,
        DeltaTimeCorrectionBackward,
    };

    explicit CTelegramConnection(const CAppInformation *appInfo, QObject *parent = 0);

    void setDcInfo(const TLDcOption &newDcInfo);

    inline TLDcOption dcInfo() const { return m_dcInfo; }

    void connectToDc();

    bool isConnected() const;

    static quint64 formatTimeStamp(qint64 timeInMs);
    static inline quint64 formatClientTimeStamp(qint64 timeInMs) { return formatTimeStamp(timeInMs) & ~quint64(3); }

    static quint64 timeStampToMSecsSinceEpoch(quint64 ts);

    void initAuth();
    void getConfiguration();

    void requestPhoneStatus(const QString &phoneNumber);
    void requestPhoneCode(const QString &phoneNumber);
    void signIn(const QString &phoneNumber, const QString &authCode);
    void signUp(const QString &phoneNumber, const QString &authCode, const QString &firstName, const QString &lastName);

    void requestContacts();
    void getFile(const TLInputFileLocation &location, quint32 fileId);

    void addContacts(const QStringList &phoneNumbers, bool replace);

    void sendMessage(const TLInputPeer &peer, const QString &message);

    AuthState authState() { return m_authState; }

    void requestPqAuthorization();
    bool answerPqAuthorization(const QByteArray &payload);
    void requestDhParameters();
    bool answerDh(const QByteArray &payload);
    void requestDhGenerationResult();
    bool processServersDHAnswer(const QByteArray &payload);

    inline TLNumber128 clientNonce() const { return m_clientNonce; }
    inline TLNumber128 serverNonce() const { return m_serverNonce; }

    inline quint64 pq() const { return m_pq; }
    inline quint64 p() const { return m_p; }
    inline quint64 q() const { return m_q; }

    inline quint64 serverPublicFingersprint() const { return m_serverPublicFingersprint; }

    inline QByteArray authKey() const { return m_authKey; }
    void setAuthKey(const QByteArray &newAuthKey);
    inline quint64 authId() const { return m_authId; }

    inline quint64 serverSalt() const { return m_serverSalt; }
    void setServerSalt(const quint64 salt) { m_serverSalt = salt; }
    inline quint64 sessionId() const { return m_sessionId; }

    inline QVector<TLDcOption> dcConfiguration() const { return m_dcConfiguration; }

    inline qint32 deltaTime() const { return m_deltaTime; }
    void setDeltaTime(const qint32 delta) { m_deltaTime = delta; }

    void processRedirectedPackage(const QByteArray &data);

signals:
    void wantedActiveDcChanged(int dc);
    void newRedirectedPackage(const QByteArray &data, int dc);

    void selfPhoneReceived(const QString &phoneNumber);
    void authStateChanged(int dc, int state);
    void actualDcIdReceived(int dc, int newDcId);
    void dcConfigurationReceived(int dc);
    void phoneStatusReceived(const QString &phone, bool registered, bool invited);
    void phoneCodeRequired();
    void phoneCodeIsInvalid();
    void usersReceived(const QVector<TLUser> &users);
    void usersAdded(const QVector<TLUser> &users);
    void fileReceived(const TLUploadFile &file, quint32 fileId);

    void updatesReceived(const TLUpdates &update);

private slots:
    void whenConnected();
    void whenReadyRead();

protected:
    void processRpcQuery(const QByteArray &data);

    void processSessionCreated(CTelegramStream &stream);
    void processContainer(CTelegramStream &stream);
    void processRpcResult(CTelegramStream &stream);
    void processGzipPacked(CTelegramStream &stream);
    bool processRpcError(CTelegramStream &stream, quint64 id, TLValue request);

    void processMessageAck(CTelegramStream &stream);
    void processIgnoredMessageNotification(CTelegramStream &stream);

    TLValue processHelpGetConfig(CTelegramStream &stream, quint64 id);
    TLValue processContactsGetContacts(CTelegramStream &stream, quint64 id);
    TLValue processContactsImportContacts(CTelegramStream &stream, quint64 id);
    TLValue processAuthCheckPhone(CTelegramStream &stream, quint64 id);
    TLValue processAuthSendCode(CTelegramStream &stream, quint64 id);
    TLValue processAuthSign(CTelegramStream &stream, quint64 id);
    TLValue processUploadGetFile(CTelegramStream &stream, quint64 id);
    TLValue processMessagesSendMessage(CTelegramStream &stream, quint64 id);

    bool processErrorSeeOther(const QString errorMessage, quint64 id);

    TLValue processUpdate(CTelegramStream &stream, bool *ok);

    SAesKey generateTmpAesKey() const;
    SAesKey generateClientToServerAesKey(const QByteArray &messageKey) const;
    SAesKey generateServerToClientAesKey(const QByteArray &messageKey) const;

    SAesKey generateAesKey(const QByteArray &messageKey, int xValue) const;

    void insertInitConnection(QByteArray *data) const;

    quint64 sendPlainPackage(const QByteArray &buffer);
    quint64 sendEncryptedPackage(const QByteArray &buffer);
    void setTransport(CTelegramTransport *newTransport);

    void setAuthState(AuthState newState);

    quint64 newMessageId();

    const CAppInformation *m_appInfo;

    QMap<quint64, QByteArray> m_submittedPackages; // <message id, package data>
    QMap<quint64, quint32> m_requestedFilesIds; // <message id, file id>

    CTelegramTransport *m_transport;

    AuthState m_authState;

    QByteArray m_authKey;
    quint64 m_authId;
    quint64 m_authKeyAuxHash;
    quint64 m_serverSalt;
    quint64 m_receivedServerSalt;
    quint64 m_sessionId;
    quint64 m_lastMessageId;
    quint32 m_sequenceNumber;
    quint32 m_contentRelatedMessages;

    qint32 m_deltaTime;
    DeltaTimeHeuristicState m_deltaTimeHeuristicState;

    TLNumber128 m_clientNonce;
    TLNumber128 m_serverNonce;
    TLNumber256 m_newNonce;

    quint64 m_pq;
    quint32 m_p;
    quint32 m_q;

    quint64 m_serverPublicFingersprint;
    SRsaKey m_rsaKey;
    SAesKey m_tmpAesKey;

    quint32 m_g;
    QByteArray m_dhPrime;
    QByteArray m_gA;
    QByteArray m_b;

    quint64 m_authRetryId;

    TLDcOption m_dcInfo;

    QVector<TLDcOption> m_dcConfiguration;

    QString m_authCodeHash;

};

inline SAesKey CTelegramConnection::generateClientToServerAesKey(const QByteArray &messageKey) const
{
    return generateAesKey(messageKey, 0);
}

inline SAesKey CTelegramConnection::generateServerToClientAesKey(const QByteArray &messageKey) const
{
    return generateAesKey(messageKey, 8);
}

#endif // CTELEGRAMCONNECTION_HPP
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: jvmargs.cxx,v $
 *
 *  $Revision: 1.16 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 07:59:29 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include "jvmargs.hxx"
#include <rtl/ustring.hxx>

#define OUSTR(x) rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( x ))

using namespace rtl;

namespace stoc_javavm {

JVM::JVM() throw()//: _enabled(sal_False)
{
}

void JVM::pushProp(const OUString & property)
{
    sal_Int32 index = property.indexOf((sal_Unicode)'=');
    if(index > 0)
    {
        OUString left = property.copy(0, index).trim();
        OUString right(property.copy(index + 1).trim());
        _props.push_back(property);
    }
    else
    { // no '=', could be -X
        _props.push_back(property);
    }
}

const ::std::vector< ::rtl::OUString > & JVM::getProperties() const
{
    return _props;
}

}
<commit_msg>INTEGRATION: CWS pchfix02 (1.16.36); FILE MERGED 2006/09/01 17:41:13 kaib 1.16.36.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: jvmargs.cxx,v $
 *
 *  $Revision: 1.17 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 17:31:17 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

#include "jvmargs.hxx"
#include <rtl/ustring.hxx>

#define OUSTR(x) rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( x ))

using namespace rtl;

namespace stoc_javavm {

JVM::JVM() throw()//: _enabled(sal_False)
{
}

void JVM::pushProp(const OUString & property)
{
    sal_Int32 index = property.indexOf((sal_Unicode)'=');
    if(index > 0)
    {
        OUString left = property.copy(0, index).trim();
        OUString right(property.copy(index + 1).trim());
        _props.push_back(property);
    }
    else
    { // no '=', could be -X
        _props.push_back(property);
    }
}

const ::std::vector< ::rtl::OUString > & JVM::getProperties() const
{
    return _props;
}

}
<|endoftext|>


<commit_before>/***********************************************************************************************************************
 **
 ** Copyright (c) 2011, 2014 ETH Zurich
 ** All rights reserved.
 **
 ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
 ** following conditions are met:
 **
 **    * Redistributions of source code must retain the above copyright notice, this list of conditions and the
 **      following disclaimer.
 **    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
 **      following disclaimer in the documentation and/or other materials provided with the distribution.
 **    * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
 **      derived from this software without specific prior written permission.
 **
 **
 ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 **
 **********************************************************************************************************************/

#include "StringComponents.h"

#include "ModelBase/src/nodes/Node.h"
#include "../expression_editor/CompoundObjectDescriptor.h"

#include "OOModel/src/allOOModelNodes.h"

namespace OOInteraction {

QMap<int, QStringList(*)(Model::Node* node)>& StringComponents::componentFunctions()
{
	static QMap<int, QStringList(*)(Model::Node* node)> funcs;
	return funcs;
}

StringComponents::StringComponents(Model::Node* node) : node_{node}
{}

StringComponents::~StringComponents()
{}

QStringList StringComponents::components()
{
	//if (!node_) return QStringList{};
	Q_ASSERT(node_);

	auto iter = componentFunctions().find(node_->typeId());
	if (iter != componentFunctions().end()) return iter.value()(node_);
	if (auto listNode = DCast<Model::List>(node_)) return c( list(listNode) );

	throw OOInteractionException{"No string component function registered for node of type " + node_->typeName()};
}

QString StringComponents::stringForNode(Model::Node* node)
{
	QString res = componentsForNode(node).join("");
	if (res.isNull()) res = "";
	return res;
}

QStringList StringComponents::componentsForNode(Model::Node* node)
{
	if (!node) return QStringList{};
	else return StringComponents{node}.components();
}

StringComponents::Optional StringComponents::list(Model::List* listNode)
{
	QStringList result;
	if (!listNode) return result;

	for (int i=0; i< listNode->size(); ++i)
		result << stringForNode(listNode->at<Model::Node>(i));

	return result;
}

StringComponents::Optional StringComponents::list(Model::List* listNode, const QString& prefix,
		const QString& separator, const QString& postfix, bool nothingIfEmpty, bool collapse)
{
	if (nothingIfEmpty && listNode->size() == 0)
		return Optional{};

	QStringList list;
	list << prefix;
	for (int i=0; i< listNode->size(); ++i)
	{
		if (i>0) list << separator;
		list << stringForNode(listNode->at<Model::Node>(i));
	}
	list << postfix;

	if (collapse) return list.join("");
	else return list;
}

using namespace OOModel;
void StringComponents::initConversions()
{
	// Types
	add<ArrayTypeExpression>([](ArrayTypeExpression* e){ return c( Optional{e->typeExpression(), AUTO}, "[]"); });
	add<ReferenceTypeExpression>([](ReferenceTypeExpression* e){ return c( Optional{e->typeExpression(), AUTO}, "&"); });
	add<PointerTypeExpression>([](PointerTypeExpression* e){ return c( Optional{e->typeExpression(), AUTO}, "*"); });
	add<ClassTypeExpression>([](ClassTypeExpression* e){ return c( Optional{e->typeExpression(), AUTO} ); });
	add<PrimitiveTypeExpression>([](PrimitiveTypeExpression* e){ return c(
		choose(e->typeValue(),
			PrimitiveTypeExpression::PrimitiveTypes::INT, "int",
			PrimitiveTypeExpression::PrimitiveTypes::LONG, "long",
			PrimitiveTypeExpression::PrimitiveTypes::UNSIGNED_INT, "uint",
			PrimitiveTypeExpression::PrimitiveTypes::UNSIGNED_LONG, "ulong",
			PrimitiveTypeExpression::PrimitiveTypes::FLOAT, "float",
			PrimitiveTypeExpression::PrimitiveTypes::DOUBLE, "double",
			PrimitiveTypeExpression::PrimitiveTypes::BOOLEAN, "bool",
			PrimitiveTypeExpression::PrimitiveTypes::CHAR, "char",
			PrimitiveTypeExpression::PrimitiveTypes::VOID, "void")
	); });
	add<TypeQualifierExpression>([](TypeQualifierExpression* e ){ return c(
			choose(e->qualifier(),
					TypeQualifierExpression::Qualifier::CONST, "const",
					TypeQualifierExpression::Qualifier::VOLATILE, "volatile"),
			" ", e->typeExpression() ); });
	add<AutoTypeExpression>([](AutoTypeExpression* ){ return c( "auto" ); });
	add<FunctionTypeExpression>([](FunctionTypeExpression* e){ return c( "[]",
			list(e->arguments(), "(", ",", ")", false, true),
			Optional{"->", e->results()->size() > 0},
			list(e->results(), "(", ",", ")", true, true)
	);});

	// Operators
	add<AssignmentExpression>([](AssignmentExpression* e){ return c(
		QString{}, e->left(), choose(e->op(),
			AssignmentExpression::ASSIGN, "=",
			AssignmentExpression::PLUS_ASSIGN, "+=",
			AssignmentExpression::MINUS_ASSIGN, "-=",
			AssignmentExpression::TIMES_ASSIGN, "*=",
			AssignmentExpression::DIVIDE_ASSIGN, "/=",
			AssignmentExpression::BIT_AND_ASSIGN, "&=",
			AssignmentExpression::BIT_OR_ASSIGN, "|=",
			AssignmentExpression::BIT_XOR_ASSIGN, "^=",
			AssignmentExpression::REMAINDER_ASSIGN, "%=",
			AssignmentExpression::LEFT_SHIFT_ASSIGN, "<<=",
			AssignmentExpression::RIGHT_SHIFT_SIGNED_ASSIGN, ">>=",
			AssignmentExpression::RIGHT_SHIFT_UNSIGNED_ASSIGN, ">>>="),
		e->right(), QString{}
	); });
	add<BinaryOperation>([](BinaryOperation* e){ return c(
		QString{}, e->left(), choose(e->op(),
			BinaryOperation::TIMES, "*",
			BinaryOperation::DIVIDE, "/",
			BinaryOperation::REMAINDER, "%",
			BinaryOperation::PLUS, "+",
			BinaryOperation::MINUS, "-",
			BinaryOperation::LEFT_SHIFT, "<<",
			BinaryOperation::RIGHT_SHIFT_SIGNED, ">>",
			BinaryOperation::RIGHT_SHIFT_UNSIGNED, ">>>",
			BinaryOperation::LESS, "<",
			BinaryOperation::GREATER, ">",
			BinaryOperation::LESS_EQUALS, "<=",
			BinaryOperation::GREATER_EQUALS, ">=",
			BinaryOperation::EQUALS, "==",
			BinaryOperation::NOT_EQUALS, "!=",
			BinaryOperation::XOR, "^",
			BinaryOperation::AND, "&",
			BinaryOperation::OR, "|",
			BinaryOperation::CONDITIONAL_AND, "&&",
			BinaryOperation::CONDITIONAL_OR, "||",
			BinaryOperation::ARRAY_INDEX, "["),
		e->right(),
		e->op() == OOModel::BinaryOperation::ARRAY_INDEX ? "]" : QString{}
	); });
	add<UnaryOperation>([](UnaryOperation* e){ return c(
		choose(e->op(),
			UnaryOperation::PREINCREMENT, "++",
			UnaryOperation::PREDECREMENT, "--",
			UnaryOperation::POSTINCREMENT, Optional{},
			UnaryOperation::POSTDECREMENT, Optional{},
			UnaryOperation::PLUS, "+",
			UnaryOperation::MINUS, "-",
			UnaryOperation::NOT, "!",
			UnaryOperation::COMPLEMENT, "~",
			UnaryOperation::PARENTHESIS, "(",
			UnaryOperation::DEREFERENCE, "*",
			UnaryOperation::ADDRESSOF, "&"),
		e->operand(),
		choose(e->op(),
			UnaryOperation::PREINCREMENT, Optional{},
			UnaryOperation::PREDECREMENT, Optional{},
			UnaryOperation::POSTINCREMENT, "++",
			UnaryOperation::POSTDECREMENT, "--",
			UnaryOperation::PLUS, Optional{},
			UnaryOperation::MINUS, Optional{},
			UnaryOperation::NOT, Optional{},
			UnaryOperation::COMPLEMENT, Optional{},
			UnaryOperation::PARENTHESIS, ")",
			UnaryOperation::DEREFERENCE, Optional{},
			UnaryOperation::ADDRESSOF, Optional{})
	); });
	add<TypeTraitExpression>([](TypeTraitExpression* e){ return c(
			choose( static_cast<int>(e->typeTraitKind()),
				static_cast<int>(TypeTraitExpression::TypeTraitKind::SizeOf), "sizeof",
				static_cast<int>(TypeTraitExpression::TypeTraitKind::AlignOf), "alignof",
				static_cast<int>(TypeTraitExpression::TypeTraitKind::TypeId), "typeid"),
			"(",
			e->operand(),
			")"
	); });

	// Literals
	add<BooleanLiteral>([](BooleanLiteral* e){ return c( e->value() ? "true" : "false" ); });
	add<IntegerLiteral>([](IntegerLiteral* e){ return c( e->value() ); });
	add<FloatLiteral>([](FloatLiteral* e){ return c( e->value() ); });
	add<NullLiteral>([](NullLiteral*){ return c( "null" ); });
	add<StringLiteral>([](StringLiteral* e){ return c( "\"", e->value(), "\"" ); });
	add<CharacterLiteral>([](CharacterLiteral* e){ return c( "'", e->value(), "'" ); });

	// Misc
	add<CastExpression>([](CastExpression* e){ return c( "(", e->castType(), ")", e->expr() ); });
	add<InstanceOfExpression>(
			[](InstanceOfExpression* e){ return c( e->expr(), " ", "instanceof", " ", e->typeExpression() ); });
	add<CommaExpression>([](CommaExpression* e){ return c( QString{}, e->left(), ",", e->right(), QString{} ); });
	add<ConditionalExpression>([](ConditionalExpression* e){ return c(
		QString{}, e->condition(), "?", e->trueExpression(), ":", e->falseExpression(), QString{} ); });
	add<SuperExpression>([](SuperExpression* ){ return c( "super" ); });
	add<ThisExpression>([](ThisExpression* ){ return c( "this" ); });
	add<GlobalScopeExpression>([](GlobalScopeExpression* ){ return c( "::" ); });
	add<ThrowExpression>([](ThrowExpression* e ){ return c( "throw", " ", e->expr() ); });
	add<TypeNameOperator>([](TypeNameOperator* e ){ return c( "typename", " ", e->typeExpression() ); });
	add<DeleteExpression>([](DeleteExpression* e ){ return c( e->isArray() ? "delete[]":"delete", " ", e->expr() ); });
	add<VariableDeclarationExpression>([](VariableDeclarationExpression* e ){ return c( e->decl()->typeExpression(), " ",
			e->decl()->name(), Optional{"=", e->decl()->initialValue()}, Optional{e->decl()->initialValue()}); });

	add<LambdaExpression>([](LambdaExpression* e ){ return c( CompoundObjectDescriptor::storeExpression(e)); });

	add<ArrayInitializer>([](ArrayInitializer* e){ return c( list(e->values(), "{", ",", "}", false, false) ); });

	add<MethodCallExpression>([](MethodCallExpression* e){ return c(
		e->callee(), list(e->arguments(), "(", ",", ")", false, true) ); });

	add<MetaCallExpression>([](MetaCallExpression* e){ return c( "#",
		e->callee(), list(e->arguments(), "(", ",", ")", false, true) ); });

	add<NewExpression>([](NewExpression* e){ return c( "new", " ",
			Optional{ (e->dimensions()->size() > 0 || !e->initializer()) ? e->newType() : nullptr, AUTO},
			list(e->dimensions(), "[", ",", "]", true, true), Optional{e->initializer(), AUTO} ); });

	add<ReferenceExpression>([](ReferenceExpression* e){ return c(
		Optional{e->prefix(), AUTO}, Optional{
						(e->memberKind() == ReferenceExpression::MemberKind::Dot ? "." :
						 e->memberKind() == ReferenceExpression::MemberKind::Pointer ? "->" :
						 e->memberKind() == ReferenceExpression::MemberKind::Static ? "::" : "::template"),
						e->prefix()}, e->name(),
		list(e->typeArguments(), "<", ",", ">", true, true) ); });

	add<OOReference>([](OOReference* e){ return c( e->name() ); });

	// Flexible input expressions
	add<EmptyExpression>([](EmptyExpression*){ return c( "" ); });
	add<ErrorExpression>([](ErrorExpression* e){ return c(
		Optional{e->prefix(), !e->prefix().isEmpty()}, e->arg(), Optional{e->postfix(), !e->postfix().isEmpty()} ); });
	add<UnfinishedOperator>([](UnfinishedOperator* e)
	{
		QStringList result;

		for (int i=0; i< e->operands()->size(); ++i)
		{
			QString delim = e->delimiters()->at(i)->get();

			result << delim << stringForNode(e->operands()->at(i));
		}

		if (e->delimiters()->size() > e->operands()->size())
		{
			QString delim = e->delimiters()->last()->get();
			result << delim;
		}

		// Insert spaces on the insdie of the result to make sure they don't stick to each other
		int i = 0;
		int lastNonEmpty = -1;
		while (i<result.size())
		{
			if (!result[i].isEmpty())
			{
				if (lastNonEmpty >= 0)
				{
					result.insert(lastNonEmpty + 1, " ");
					++i;
				}
				lastNonEmpty = i;
			}
			++i;
		}

		return result;
	});
}

}
<commit_msg>Add a clarification comment<commit_after>/***********************************************************************************************************************
 **
 ** Copyright (c) 2011, 2014 ETH Zurich
 ** All rights reserved.
 **
 ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
 ** following conditions are met:
 **
 **    * Redistributions of source code must retain the above copyright notice, this list of conditions and the
 **      following disclaimer.
 **    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
 **      following disclaimer in the documentation and/or other materials provided with the distribution.
 **    * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
 **      derived from this software without specific prior written permission.
 **
 **
 ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 **
 **********************************************************************************************************************/

#include "StringComponents.h"

#include "ModelBase/src/nodes/Node.h"
#include "../expression_editor/CompoundObjectDescriptor.h"

#include "OOModel/src/allOOModelNodes.h"

namespace OOInteraction {

QMap<int, QStringList(*)(Model::Node* node)>& StringComponents::componentFunctions()
{
	static QMap<int, QStringList(*)(Model::Node* node)> funcs;
	return funcs;
}

StringComponents::StringComponents(Model::Node* node) : node_{node}
{}

StringComponents::~StringComponents()
{}

QStringList StringComponents::components()
{
	//if (!node_) return QStringList{};
	Q_ASSERT(node_);

	auto iter = componentFunctions().find(node_->typeId());
	if (iter != componentFunctions().end()) return iter.value()(node_);
	if (auto listNode = DCast<Model::List>(node_)) return c( list(listNode) );

	throw OOInteractionException{"No string component function registered for node of type " + node_->typeName()};
}

QString StringComponents::stringForNode(Model::Node* node)
{
	QString res = componentsForNode(node).join("");
	if (res.isNull()) res = "";
	return res;
}

QStringList StringComponents::componentsForNode(Model::Node* node)
{
	if (!node) return QStringList{};
	else return StringComponents{node}.components();
}

StringComponents::Optional StringComponents::list(Model::List* listNode)
{
	QStringList result;
	if (!listNode) return result;

	for (int i=0; i< listNode->size(); ++i)
		result << stringForNode(listNode->at<Model::Node>(i));

	return result;
}

StringComponents::Optional StringComponents::list(Model::List* listNode, const QString& prefix,
		const QString& separator, const QString& postfix, bool nothingIfEmpty, bool collapse)
{
	if (nothingIfEmpty && listNode->size() == 0)
		return Optional{};

	QStringList list;
	list << prefix;
	for (int i=0; i< listNode->size(); ++i)
	{
		if (i>0) list << separator;
		list << stringForNode(listNode->at<Model::Node>(i));
	}
	list << postfix;

	if (collapse) return list.join("");
	else return list;
}

using namespace OOModel;
void StringComponents::initConversions()
{
	// Types
	add<ArrayTypeExpression>([](ArrayTypeExpression* e){ return c( Optional{e->typeExpression(), AUTO}, "[]"); });
	add<ReferenceTypeExpression>([](ReferenceTypeExpression* e){ return c( Optional{e->typeExpression(), AUTO}, "&"); });
	add<PointerTypeExpression>([](PointerTypeExpression* e){ return c( Optional{e->typeExpression(), AUTO}, "*"); });
	add<ClassTypeExpression>([](ClassTypeExpression* e){ return c( Optional{e->typeExpression(), AUTO} ); });
	add<PrimitiveTypeExpression>([](PrimitiveTypeExpression* e){ return c(
		choose(e->typeValue(),
			PrimitiveTypeExpression::PrimitiveTypes::INT, "int",
			PrimitiveTypeExpression::PrimitiveTypes::LONG, "long",
			PrimitiveTypeExpression::PrimitiveTypes::UNSIGNED_INT, "uint",
			PrimitiveTypeExpression::PrimitiveTypes::UNSIGNED_LONG, "ulong",
			PrimitiveTypeExpression::PrimitiveTypes::FLOAT, "float",
			PrimitiveTypeExpression::PrimitiveTypes::DOUBLE, "double",
			PrimitiveTypeExpression::PrimitiveTypes::BOOLEAN, "bool",
			PrimitiveTypeExpression::PrimitiveTypes::CHAR, "char",
			PrimitiveTypeExpression::PrimitiveTypes::VOID, "void")
	); });
	add<TypeQualifierExpression>([](TypeQualifierExpression* e ){ return c(
			choose(e->qualifier(),
					TypeQualifierExpression::Qualifier::CONST, "const",
					TypeQualifierExpression::Qualifier::VOLATILE, "volatile"),
			" ", e->typeExpression() ); });
	add<AutoTypeExpression>([](AutoTypeExpression* ){ return c( "auto" ); });
	add<FunctionTypeExpression>([](FunctionTypeExpression* e){ return c( "[]",
			list(e->arguments(), "(", ",", ")", false, true),
			Optional{"->", e->results()->size() > 0},
			list(e->results(), "(", ",", ")", true, true)
	);});

	// Operators
	add<AssignmentExpression>([](AssignmentExpression* e){ return c(
		QString{}, e->left(), choose(e->op(),
			AssignmentExpression::ASSIGN, "=",
			AssignmentExpression::PLUS_ASSIGN, "+=",
			AssignmentExpression::MINUS_ASSIGN, "-=",
			AssignmentExpression::TIMES_ASSIGN, "*=",
			AssignmentExpression::DIVIDE_ASSIGN, "/=",
			AssignmentExpression::BIT_AND_ASSIGN, "&=",
			AssignmentExpression::BIT_OR_ASSIGN, "|=",
			AssignmentExpression::BIT_XOR_ASSIGN, "^=",
			AssignmentExpression::REMAINDER_ASSIGN, "%=",
			AssignmentExpression::LEFT_SHIFT_ASSIGN, "<<=",
			AssignmentExpression::RIGHT_SHIFT_SIGNED_ASSIGN, ">>=",
			AssignmentExpression::RIGHT_SHIFT_UNSIGNED_ASSIGN, ">>>="),
		e->right(), QString{}
	); });
	add<BinaryOperation>([](BinaryOperation* e){ return c(
		QString{}, e->left(), choose(e->op(),
			BinaryOperation::TIMES, "*",
			BinaryOperation::DIVIDE, "/",
			BinaryOperation::REMAINDER, "%",
			BinaryOperation::PLUS, "+",
			BinaryOperation::MINUS, "-",
			BinaryOperation::LEFT_SHIFT, "<<",
			BinaryOperation::RIGHT_SHIFT_SIGNED, ">>",
			BinaryOperation::RIGHT_SHIFT_UNSIGNED, ">>>",
			BinaryOperation::LESS, "<",
			BinaryOperation::GREATER, ">",
			BinaryOperation::LESS_EQUALS, "<=",
			BinaryOperation::GREATER_EQUALS, ">=",
			BinaryOperation::EQUALS, "==",
			BinaryOperation::NOT_EQUALS, "!=",
			BinaryOperation::XOR, "^",
			BinaryOperation::AND, "&",
			BinaryOperation::OR, "|",
			BinaryOperation::CONDITIONAL_AND, "&&",
			BinaryOperation::CONDITIONAL_OR, "||",
			BinaryOperation::ARRAY_INDEX, "["),
		e->right(),
		e->op() == OOModel::BinaryOperation::ARRAY_INDEX ? "]" : QString{}
	); });
	add<UnaryOperation>([](UnaryOperation* e){ return c(
		choose(e->op(),
			UnaryOperation::PREINCREMENT, "++",
			UnaryOperation::PREDECREMENT, "--",
			UnaryOperation::POSTINCREMENT, Optional{},
			UnaryOperation::POSTDECREMENT, Optional{},
			UnaryOperation::PLUS, "+",
			UnaryOperation::MINUS, "-",
			UnaryOperation::NOT, "!",
			UnaryOperation::COMPLEMENT, "~",
			UnaryOperation::PARENTHESIS, "(",
			UnaryOperation::DEREFERENCE, "*",
			UnaryOperation::ADDRESSOF, "&"),
		e->operand(),
		choose(e->op(),
			UnaryOperation::PREINCREMENT, Optional{},
			UnaryOperation::PREDECREMENT, Optional{},
			UnaryOperation::POSTINCREMENT, "++",
			UnaryOperation::POSTDECREMENT, "--",
			UnaryOperation::PLUS, Optional{},
			UnaryOperation::MINUS, Optional{},
			UnaryOperation::NOT, Optional{},
			UnaryOperation::COMPLEMENT, Optional{},
			UnaryOperation::PARENTHESIS, ")",
			UnaryOperation::DEREFERENCE, Optional{},
			UnaryOperation::ADDRESSOF, Optional{})
	); });
	add<TypeTraitExpression>([](TypeTraitExpression* e){ return c(
			choose( static_cast<int>(e->typeTraitKind()),
				static_cast<int>(TypeTraitExpression::TypeTraitKind::SizeOf), "sizeof",
				static_cast<int>(TypeTraitExpression::TypeTraitKind::AlignOf), "alignof",
				static_cast<int>(TypeTraitExpression::TypeTraitKind::TypeId), "typeid"),
			"(",
			e->operand(),
			")"
	); });

	// Literals
	add<BooleanLiteral>([](BooleanLiteral* e){ return c( e->value() ? "true" : "false" ); });
	add<IntegerLiteral>([](IntegerLiteral* e){ return c( e->value() ); });
	add<FloatLiteral>([](FloatLiteral* e){ return c( e->value() ); });
	add<NullLiteral>([](NullLiteral*){ return c( "null" ); });
	add<StringLiteral>([](StringLiteral* e){ return c( "\"", e->value(), "\"" ); });
	add<CharacterLiteral>([](CharacterLiteral* e){ return c( "'", e->value(), "'" ); });

	// Misc
	add<CastExpression>([](CastExpression* e){ return c( "(", e->castType(), ")", e->expr() ); });
	add<InstanceOfExpression>(
			[](InstanceOfExpression* e){ return c( e->expr(), " ", "instanceof", " ", e->typeExpression() ); });
	add<CommaExpression>([](CommaExpression* e){ return c( QString{}, e->left(), ",", e->right(), QString{} ); });
	add<ConditionalExpression>([](ConditionalExpression* e){ return c(
		QString{}, e->condition(), "?", e->trueExpression(), ":", e->falseExpression(), QString{} ); });
	add<SuperExpression>([](SuperExpression* ){ return c( "super" ); });
	add<ThisExpression>([](ThisExpression* ){ return c( "this" ); });
	add<GlobalScopeExpression>([](GlobalScopeExpression* ){ return c( "::" ); });
	add<ThrowExpression>([](ThrowExpression* e ){ return c( "throw", " ", e->expr() ); });
	add<TypeNameOperator>([](TypeNameOperator* e ){ return c( "typename", " ", e->typeExpression() ); });
	add<DeleteExpression>([](DeleteExpression* e ){ return c( e->isArray() ? "delete[]":"delete", " ", e->expr() ); });
	add<VariableDeclarationExpression>([](VariableDeclarationExpression* e ){ return c( e->decl()->typeExpression(), " ",
			e->decl()->name(), Optional{"=", e->decl()->initialValue()}, Optional{e->decl()->initialValue()}); });

	add<LambdaExpression>([](LambdaExpression* e ){ return c( CompoundObjectDescriptor::storeExpression(e)); });

	add<ArrayInitializer>([](ArrayInitializer* e){ return c( list(e->values(), "{", ",", "}", false, false) ); });

	add<MethodCallExpression>([](MethodCallExpression* e){ return c(
		e->callee(), list(e->arguments(), "(", ",", ")", false, true) ); });

	add<MetaCallExpression>([](MetaCallExpression* e){ return c( "#",
		e->callee(), list(e->arguments(), "(", ",", ")", false, true) ); });

	add<NewExpression>([](NewExpression* e){ return c( "new", " ",
			Optional{ (e->dimensions()->size() > 0 || !e->initializer()) ? e->newType() : nullptr, AUTO},
			list(e->dimensions(), "[", ",", "]", true, true), Optional{e->initializer(), AUTO} ); });

	add<ReferenceExpression>([](ReferenceExpression* e){ return c(
		Optional{e->prefix(), AUTO}, Optional{
						(e->memberKind() == ReferenceExpression::MemberKind::Dot ? "." :
						 e->memberKind() == ReferenceExpression::MemberKind::Pointer ? "->" :
						 e->memberKind() == ReferenceExpression::MemberKind::Static ? "::" : "::template"),
						e->prefix()}, e->name(),
		list(e->typeArguments(), "<", ",", ">", true, true) ); });

	add<OOReference>([](OOReference* e){ return c( e->name() ); });

	// Flexible input expressions
	add<EmptyExpression>([](EmptyExpression*){ return c( "" ); });
	add<ErrorExpression>([](ErrorExpression* e){ return c(
		Optional{e->prefix(), !e->prefix().isEmpty()}, e->arg(), Optional{e->postfix(), !e->postfix().isEmpty()} ); });
	add<UnfinishedOperator>([](UnfinishedOperator* e)
	{
		QStringList result;

		for (int i=0; i< e->operands()->size(); ++i)
		{
			QString delim = e->delimiters()->at(i)->get();

			result << delim << stringForNode(e->operands()->at(i));
		}

		if (e->delimiters()->size() > e->operands()->size())
		{
			QString delim = e->delimiters()->last()->get();
			result << delim;
		}

		// Insert spaces on the insdie of the result to make sure they don't stick to each other
		// E.g. when typing 'delete new foo'
		int i = 0;
		int lastNonEmpty = -1;
		while (i<result.size())
		{
			if (!result[i].isEmpty())
			{
				if (lastNonEmpty >= 0)
				{
					result.insert(lastNonEmpty + 1, " ");
					++i;
				}
				lastNonEmpty = i;
			}
			++i;
		}

		return result;
	});
}

}
<|endoftext|>


<commit_before><commit_msg>CEQU - Crucial Equation.cpp<commit_after><|endoftext|>


<commit_before>#include <vector>

#include "base/basictypes.h"
#include "base/logging.h"
#include "gfx/gl_lost_manager.h"

std::vector<GfxResourceHolder *> *holders;

static bool inLost;

void register_gl_resource_holder(GfxResourceHolder *holder) {
	if (inLost) {
		FLOG("BAD: Should not call register_gl_resource_holder from lost path");
		return;
	}
	if (holders) {
		holders->push_back(holder);
	} else {
		WLOG("GL resource holder not initialized, cannot register resource");
	}
}

void unregister_gl_resource_holder(GfxResourceHolder *holder) {
	if (inLost) {
		FLOG("BAD: Should not call unregister_gl_resource_holder from lost path");
		return;
	}
	if (holders) {
		for (size_t i = 0; i < holders->size(); i++) {
			if ((*holders)[i] == holder) {
				holders->erase(holders->begin() + i);
				return;
			}
		}
		WLOG("unregister_gl_resource_holder: Resource not registered");
	} else {
		WLOG("GL resource holder not initialized or already shutdown, cannot unregister resource");
	}
}

void gl_lost() {
	inLost = true;
	if (!holders) {
		WLOG("GL resource holder not initialized, cannot process lost request");
		inLost = false;
		return;
	}

	// TODO: We should really do this when we get the context back, not during gl_lost...
	ILOG("gl_lost() restoring %i items:", (int)holders->size());
	for (size_t i = 0; i < holders->size(); i++) {
		ILOG("GLLost(%i / %i, %p)", (int)(i + 1), (int) holders->size(), (*holders)[i]);
		(*holders)[i]->GLLost();
	}
	ILOG("gl_lost() completed restoring %i items:", (int)holders->size());
	inLost = false;
}

void gl_lost_manager_init() {
	if (holders) {
		FLOG("Double GL lost manager init");
		// Dead here (FLOG), no need to delete holders
	}
	holders = new std::vector<GfxResourceHolder *>();
}

void gl_lost_manager_shutdown() {
	if (!holders) {
		FLOG("Lost manager already shutdown");
	}
	delete holders;
	holders = 0;
}
<commit_msg>Log an error if lost manager exits with objects still registered<commit_after>#include <vector>

#include "base/basictypes.h"
#include "base/logging.h"
#include "gfx/gl_lost_manager.h"

std::vector<GfxResourceHolder *> *holders;

static bool inLost;

void register_gl_resource_holder(GfxResourceHolder *holder) {
	if (inLost) {
		FLOG("BAD: Should not call register_gl_resource_holder from lost path");
		return;
	}
	if (holders) {
		holders->push_back(holder);
	} else {
		WLOG("GL resource holder not initialized, cannot register resource");
	}
}

void unregister_gl_resource_holder(GfxResourceHolder *holder) {
	if (inLost) {
		FLOG("BAD: Should not call unregister_gl_resource_holder from lost path");
		return;
	}
	if (holders) {
		for (size_t i = 0; i < holders->size(); i++) {
			if ((*holders)[i] == holder) {
				holders->erase(holders->begin() + i);
				return;
			}
		}
		WLOG("unregister_gl_resource_holder: Resource not registered");
	} else {
		WLOG("GL resource holder not initialized or already shutdown, cannot unregister resource");
	}
}

void gl_lost() {
	inLost = true;
	if (!holders) {
		WLOG("GL resource holder not initialized, cannot process lost request");
		inLost = false;
		return;
	}

	// TODO: We should really do this when we get the context back, not during gl_lost...
	ILOG("gl_lost() restoring %i items:", (int)holders->size());
	for (size_t i = 0; i < holders->size(); i++) {
		ILOG("GLLost(%i / %i, %p)", (int)(i + 1), (int) holders->size(), (*holders)[i]);
		(*holders)[i]->GLLost();
	}
	ILOG("gl_lost() completed restoring %i items:", (int)holders->size());
	inLost = false;
}

void gl_lost_manager_init() {
	if (holders) {
		FLOG("Double GL lost manager init");
		// Dead here (FLOG), no need to delete holders
	}
	holders = new std::vector<GfxResourceHolder *>();
}

void gl_lost_manager_shutdown() {
	if (!holders) {
		FLOG("Lost manager already shutdown");
	} else if (holders->size() > 0) {
		ELOG("Lost manager shutdown with %i objects still registered", (int)holders->size());
	}

	delete holders;
	holders = 0;
}
<|endoftext|>


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

/******************************************************************************
 * Dependencies
 ******************************************************************************/

#include "loggingevent.h"

#include <QtCore/QBuffer>
#include <QtCore/QByteArray>
#include <QtCore/QDataStream>
#include <QtCore/QDebug>
#include <QtCore/QMutex>
#include <QtCore/QThread>
#include "helpers/datetime.h"
#include "helpers/initialisationhelper.h"
#include "logger.h"
#include "mdc.h"
#include "ndc.h"

namespace Log4Qt
{

	/**************************************************************************
	 * Declarations
	 **************************************************************************/

	LOG4QT_GLOBAL_STATIC(QMutex, sequence_guard)

	/**************************************************************************
	 * C helper functions
	 **************************************************************************/

	/**************************************************************************
	 * Class implementation: LoggingEvent
	 **************************************************************************/

	LoggingEvent::LoggingEvent() :
		mLevel(Level::NULL_INT),
	    mpLogger(0),
	    mMessage(),
	    mNdc(NDC::peek()),
	    mProperties(MDC::context()),
	    mSequenceNumber(nextSequenceNumber()),
	    mThreadName(),
	    mTimeStamp(DateTime::currentDateTime().toMilliSeconds())
	{
		setThreadNameToCurrent();
	}

	LoggingEvent::LoggingEvent(const Logger *pLogger,
	                           Level level,
	                           const QString &rMessage) :
	    mLevel(level),
	    mpLogger(pLogger),
	    mMessage(rMessage),
	    mNdc(NDC::peek()),
	    mProperties(MDC::context()),
	    mSequenceNumber(nextSequenceNumber()),
	    mThreadName(),
	    mTimeStamp(DateTime::currentDateTime().toMilliSeconds())
	{
		setThreadNameToCurrent();
	}

	LoggingEvent::LoggingEvent(const Logger *pLogger,
	                           Level level,
	                           const QString &rMessage,
	                           qint64 timeStamp) :
	    mLevel(level),
	    mpLogger(pLogger),
	    mMessage(rMessage),
	    mNdc(NDC::peek()),
	    mProperties(MDC::context()),
	    mSequenceNumber(nextSequenceNumber()),
	    mThreadName(),
	    mTimeStamp(timeStamp)
	{
		setThreadNameToCurrent();
	}

	LoggingEvent::LoggingEvent(const Logger *pLogger,
	                           Level level,
	                           const QString &rMessage,
	                           const QString &rNdc,
	                           const QHash<QString, QString> &rProperties,
	                           const QString &rThreadName,
	                           qint64 timeStamp) :
	    mLevel(level),
	    mpLogger(pLogger),
	    mMessage(rMessage),
	    mNdc(rNdc),
	    mProperties(rProperties),
	    mSequenceNumber(nextSequenceNumber()),
	    mThreadName(rThreadName),
	    mTimeStamp(timeStamp)
	{
	}

	QString LoggingEvent::loggerName() const
	{
		if (mpLogger)
			return mpLogger->name();
		else
			return QString();
	}

	QString LoggingEvent::toString() const
	{
	    return level().toString() + QLatin1Char(':') + message();
	}

	qint64 LoggingEvent::sequenceCount()
	{
	    QMutexLocker locker(sequence_guard());

	    return msSequenceCount;
	}

	qint64 LoggingEvent::startTime()
	{
		return InitialisationHelper::startTime();
	}

	void LoggingEvent::setThreadNameToCurrent()
	{
		if (QThread::currentThread())
			mThreadName = QThread::currentThread()->objectName();
	}

	qint64 LoggingEvent::nextSequenceNumber()
	{
	    QMutexLocker locker(sequence_guard());

	    return ++msSequenceCount;
	}

	qint64 LoggingEvent::msSequenceCount = 0;

	/**************************************************************************
	 * Implementation: Operators, Helper
	 **************************************************************************/

#ifndef QT_NO_DATASTREAM
    QDataStream &operator<<(QDataStream &rStream, const LoggingEvent &rLoggingEvent)
    {
        QBuffer buffer;
        buffer.open(QIODevice::WriteOnly);
        QDataStream stream(&buffer);

        // version
        quint16 version = 0;
        stream << version;
        // version 0 data
        stream << rLoggingEvent.mLevel
               << rLoggingEvent.loggerName()
               << rLoggingEvent.mMessage
               << rLoggingEvent.mNdc
               << rLoggingEvent.mProperties
               << rLoggingEvent.mSequenceNumber
               << rLoggingEvent.mThreadName
               << rLoggingEvent.mTimeStamp;

        buffer.close();
        rStream << buffer.buffer();
        return rStream;
    }

    QDataStream &operator>>(QDataStream &rStream, LoggingEvent &rLoggingEvent)
    {
        QByteArray array;
        rStream >> array;
        QBuffer buffer(&array);
        buffer.open(QIODevice::ReadOnly);
        QDataStream stream(&buffer);

        // version
        quint16 version;
        stream >> version;
        // Version 0 data
        QString logger;
        stream >> rLoggingEvent.mLevel
               >> logger
               >> rLoggingEvent.mMessage
               >> rLoggingEvent.mNdc
               >> rLoggingEvent.mProperties
               >> rLoggingEvent.mSequenceNumber
               >> rLoggingEvent.mThreadName
               >> rLoggingEvent.mTimeStamp;
        if (logger.isEmpty())
            rLoggingEvent.mpLogger = 0;
        else
            rLoggingEvent.mpLogger = Logger::logger(logger);

        buffer.close();
        return rStream;
    }
#endif // QT_NO_DATASTREAM

#ifndef QT_NO_DEBUG_STREAM
	QDebug operator<<(QDebug debug,
	                  const LoggingEvent &rLoggingEvent)
	{
	    QString logger;
	    if (rLoggingEvent.logger() != 0)
	        logger = rLoggingEvent.logger()->name();

	    debug.nospace() << "LoggingEvent("
	        << "level:" << rLoggingEvent.level().toString() << " "
	        << "logger:" << logger << " "
	        << "message:" << rLoggingEvent.message() << " "
	        << "sequencenumber:" << rLoggingEvent.sequenceNumber() << " "
	        << "threadname:" << rLoggingEvent.threadName() << " "
	        << "timestamp:" << rLoggingEvent.timeStamp()
	        	<< "(" << DateTime::fromMilliSeconds(rLoggingEvent.timeStamp()) << ")"
	        << "sequenceCount:" << rLoggingEvent.sequenceCount()
	        << ")";
	    return debug.space();
	}
#endif // QT_NO_DEBUG_STREAM

} // namespace Log4Qt
<commit_msg>If object name is not defined for thread use thread ID instead if object name for thread identification<commit_after>/******************************************************************************
 *
 * package:     Log4Qt
 * file:        loggingevent.cpp
 * created:     September 2007
 * author:      Martin Heinrich
 *
 *
 * Copyright 2007 Martin Heinrich
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *****************************************************************************/

/******************************************************************************
 * Dependencies
 ******************************************************************************/

#include "loggingevent.h"

#include <QtCore/QBuffer>
#include <QtCore/QByteArray>
#include <QtCore/QDataStream>
#include <QtCore/QDebug>
#include <QtCore/QMutex>
#include <QtCore/QThread>
#include "helpers/datetime.h"
#include "helpers/initialisationhelper.h"
#include "logger.h"
#include "mdc.h"
#include "ndc.h"

namespace Log4Qt
{

	/**************************************************************************
	 * Declarations
	 **************************************************************************/

	LOG4QT_GLOBAL_STATIC(QMutex, sequence_guard)

	/**************************************************************************
	 * C helper functions
	 **************************************************************************/

	/**************************************************************************
	 * Class implementation: LoggingEvent
	 **************************************************************************/

	LoggingEvent::LoggingEvent() :
		mLevel(Level::NULL_INT),
	    mpLogger(0),
	    mMessage(),
	    mNdc(NDC::peek()),
	    mProperties(MDC::context()),
	    mSequenceNumber(nextSequenceNumber()),
	    mThreadName(),
	    mTimeStamp(DateTime::currentDateTime().toMilliSeconds())
	{
		setThreadNameToCurrent();
	}

	LoggingEvent::LoggingEvent(const Logger *pLogger,
	                           Level level,
	                           const QString &rMessage) :
	    mLevel(level),
	    mpLogger(pLogger),
	    mMessage(rMessage),
	    mNdc(NDC::peek()),
	    mProperties(MDC::context()),
	    mSequenceNumber(nextSequenceNumber()),
	    mThreadName(),
	    mTimeStamp(DateTime::currentDateTime().toMilliSeconds())
	{
		setThreadNameToCurrent();
	}

	LoggingEvent::LoggingEvent(const Logger *pLogger,
	                           Level level,
	                           const QString &rMessage,
	                           qint64 timeStamp) :
	    mLevel(level),
	    mpLogger(pLogger),
	    mMessage(rMessage),
	    mNdc(NDC::peek()),
	    mProperties(MDC::context()),
	    mSequenceNumber(nextSequenceNumber()),
	    mThreadName(),
	    mTimeStamp(timeStamp)
	{
		setThreadNameToCurrent();
	}

	LoggingEvent::LoggingEvent(const Logger *pLogger,
	                           Level level,
	                           const QString &rMessage,
	                           const QString &rNdc,
	                           const QHash<QString, QString> &rProperties,
	                           const QString &rThreadName,
	                           qint64 timeStamp) :
	    mLevel(level),
	    mpLogger(pLogger),
	    mMessage(rMessage),
	    mNdc(rNdc),
	    mProperties(rProperties),
	    mSequenceNumber(nextSequenceNumber()),
	    mThreadName(rThreadName),
	    mTimeStamp(timeStamp)
	{
	}

	QString LoggingEvent::loggerName() const
	{
		if (mpLogger)
			return mpLogger->name();
		else
			return QString();
	}

	QString LoggingEvent::toString() const
	{
	    return level().toString() + QLatin1Char(':') + message();
	}

	qint64 LoggingEvent::sequenceCount()
	{
	    QMutexLocker locker(sequence_guard());

	    return msSequenceCount;
	}

	qint64 LoggingEvent::startTime()
	{
		return InitialisationHelper::startTime();
	}

	void LoggingEvent::setThreadNameToCurrent()
	{
		if (QThread::currentThread())
		{
			mThreadName = QThread::currentThread()->objectName();
			// if object name is not set use thread id for thead identification
			if (mThreadName.isEmpty())
				mThreadName = QString("0x%0").arg(QThread::currentThreadId(),4,16);
		}
	}

	qint64 LoggingEvent::nextSequenceNumber()
	{
	    QMutexLocker locker(sequence_guard());

	    return ++msSequenceCount;
	}

	qint64 LoggingEvent::msSequenceCount = 0;

	/**************************************************************************
	 * Implementation: Operators, Helper
	 **************************************************************************/

#ifndef QT_NO_DATASTREAM
    QDataStream &operator<<(QDataStream &rStream, const LoggingEvent &rLoggingEvent)
    {
        QBuffer buffer;
        buffer.open(QIODevice::WriteOnly);
        QDataStream stream(&buffer);

        // version
        quint16 version = 0;
        stream << version;
        // version 0 data
        stream << rLoggingEvent.mLevel
               << rLoggingEvent.loggerName()
               << rLoggingEvent.mMessage
               << rLoggingEvent.mNdc
               << rLoggingEvent.mProperties
               << rLoggingEvent.mSequenceNumber
               << rLoggingEvent.mThreadName
               << rLoggingEvent.mTimeStamp;

        buffer.close();
        rStream << buffer.buffer();
        return rStream;
    }

    QDataStream &operator>>(QDataStream &rStream, LoggingEvent &rLoggingEvent)
    {
        QByteArray array;
        rStream >> array;
        QBuffer buffer(&array);
        buffer.open(QIODevice::ReadOnly);
        QDataStream stream(&buffer);

        // version
        quint16 version;
        stream >> version;
        // Version 0 data
        QString logger;
        stream >> rLoggingEvent.mLevel
               >> logger
               >> rLoggingEvent.mMessage
               >> rLoggingEvent.mNdc
               >> rLoggingEvent.mProperties
               >> rLoggingEvent.mSequenceNumber
               >> rLoggingEvent.mThreadName
               >> rLoggingEvent.mTimeStamp;
        if (logger.isEmpty())
            rLoggingEvent.mpLogger = 0;
        else
            rLoggingEvent.mpLogger = Logger::logger(logger);

        buffer.close();
        return rStream;
    }
#endif // QT_NO_DATASTREAM

#ifndef QT_NO_DEBUG_STREAM
	QDebug operator<<(QDebug debug,
	                  const LoggingEvent &rLoggingEvent)
	{
	    QString logger;
	    if (rLoggingEvent.logger() != 0)
	        logger = rLoggingEvent.logger()->name();

	    debug.nospace() << "LoggingEvent("
	        << "level:" << rLoggingEvent.level().toString() << " "
	        << "logger:" << logger << " "
	        << "message:" << rLoggingEvent.message() << " "
	        << "sequencenumber:" << rLoggingEvent.sequenceNumber() << " "
	        << "threadname:" << rLoggingEvent.threadName() << " "
	        << "timestamp:" << rLoggingEvent.timeStamp()
	        	<< "(" << DateTime::fromMilliSeconds(rLoggingEvent.timeStamp()) << ")"
	        << "sequenceCount:" << rLoggingEvent.sequenceCount()
	        << ")";
	    return debug.space();
	}
#endif // QT_NO_DEBUG_STREAM

} // namespace Log4Qt
<|endoftext|>