std::string SignFactory::getLaterByIndex(int inx)
{
    SignMap::iterator iter = m_SignMap.find(inx);
    Sign* pSign = iter->second;
    std::string latter = pSign->getLatter();
    return latter;
}
Exemple #2
0
void RandomScroll::run(Sign &sign, uint8_t layer){

  sign.textChanged = true;
  char random_char = char(' ' + random8(95) );
  sign.pushChar(random_char);
  sign.setCharacters();
}
Exemple #3
0
/**
 * Place a sign at the given coordinates. Ownership of sign has
 * no effect whatsoever except for the colour the sign gets for easy recognition,
 * but everybody is able to rename/remove it.
 * @param tile tile to place sign at
 * @param flags type of operation
 * @param p1 unused
 * @param p2 unused
 * @param text unused
 * @return the cost of this operation or an error
 */
CommandCost CmdPlaceSign(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
	/* Try to locate a new sign */
	if (!Sign::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_SIGNS);

	/* Check sign text length if any */
	if (!StrEmpty(text) && Utf8StringLength(text) >= MAX_LENGTH_SIGN_NAME_CHARS) return CMD_ERROR;

	/* When we execute, really make the sign */
	if (flags & DC_EXEC) {
		Sign *si = new Sign(_current_company);
		int x = TileX(tile) * TILE_SIZE;
		int y = TileY(tile) * TILE_SIZE;

		si->x = x;
		si->y = y;
		si->z = GetSlopeZ(x, y);
		if (!StrEmpty(text)) {
			si->name = strdup(text);
		}
		si->UpdateVirtCoord();
		InvalidateWindowData(WC_SIGN_LIST, 0, 0);
		_new_sign_id = si->index;
	}

	return CommandCost();
}
Exemple #4
0
/**
 * Rename a sign. If the new name of the sign is empty, we assume
 * the user wanted to delete it. So delete it. Ownership of signs
 * has no meaning/effect whatsoever except for eyecandy
 * @param tile unused
 * @param flags type of operation
 * @param p1 index of the sign to be renamed/removed
 * @param p2 unused
 * @param text the new name or an empty string when resetting to the default
 * @return the cost of this operation or an error
 */
CommandCost CmdRenameSign(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
	Sign *si = Sign::GetIfValid(p1);
	if (si == NULL) return CMD_ERROR;

	/* Rename the signs when empty, otherwise remove it */
	if (!StrEmpty(text)) {
		if (Utf8StringLength(text) >= MAX_LENGTH_SIGN_NAME_CHARS) return CMD_ERROR;

		if (flags & DC_EXEC) {
			/* Delete the old name */
			free(si->name);
			/* Assign the new one */
			si->name = strdup(text);
			si->owner = _current_company;

			si->UpdateVirtCoord();
			InvalidateWindowData(WC_SIGN_LIST, 0, 1);
		}
	} else { // Delete sign
		if (flags & DC_EXEC) {
			si->sign.MarkDirty();
			delete si;

			InvalidateWindowData(WC_SIGN_LIST, 0, 0);
		}
	}

	return CommandCost();
}
Exemple #5
0
/** Update the coordinates of all signs */
void UpdateAllSignVirtCoords()
{
	Sign *si;

	FOR_ALL_SIGNS(si) {
		si->UpdateVirtCoord();
	}
}
Exemple #6
0
Sign* Sign::create(cocos2d::Vec2* points, int nbrPoints, std::string spriteFile)
{
	Sign * node = new Sign();
	if (node) {
		node->init(points, nbrPoints, spriteFile);
		node->autorelease();
		return node;
	}
	CC_SAFE_DELETE(node);
	return NULL;
}
void RandomLetters::run(Sign &sign, EffectData &data, uint8_t layer){

  sign.textChanged = true;
  uint8_t letters_count = sign.letterCount();
  char random_char;

  for(uint8_t i=0; i < letters_count; i++){
    random_char = ' ' + random(95);
    sign.letter(i) -> setChar(random_char);
  }

}
RETCODE World::EntityLoad_Sign(hQBSP qbsp, const EntityParse & entityDat)
{
	hTXT txt;
	int r,g,b,a;

	//create new sign
	Sign *newObj = new Sign; assert(newObj);

	///////////////////////////////////////////////////////
	//load up the common stuff
	EntityLoad_CommonObject(qbsp, entityDat, dynamic_cast<Object *>(newObj));

	const char *pStr;

	///////////////////////////////////////////////////////
	//load image
	pStr = entityDat.GetVal("image");

	if(pStr)
	{
		string imgPath = GAMEFOLDER;
		imgPath += "\\";
		imgPath += pStr;

		txt = TextureCreate(0, imgPath.c_str(), false, 0);
	}

	///////////////////////////////////////////////////////
	//get color
	pStr = entityDat.GetVal("color");

	if(pStr)
	{
		sscanf(pStr, "%d %d %d %d", &r,&g,&b,&a);
	}

	if(txt)
	{
		float sX = (SCRN_W/2) - (TextureGetWidth(txt)/2);
		float sY = (SCRN_H/2) - (TextureGetHeight(txt)/2);
		float eX = sX + TextureGetWidth(txt);
		float eY = sY + TextureGetHeight(txt);

		sX /= SCRN_W; sY /= SCRN_H;
		eX /= SCRN_W; eY /= SCRN_H;

		newObj->SetImageDisplay(ImageDisplayAdd(txt, sX,sY,eX,eY, r,g,b,a));
		TextureDestroy(&txt);
	}

	return RETCODE_SUCCESS;
}
Exemple #9
0
void WavePixels::run(Sign &sign, EffectData &data, uint8_t ci){
  uint16_t angle = (millis() % cycleTime[ci])*UINT16_MAX/cycleTime[ci];

  int16_t delta_hue = hueA[ci] * sin16(angle)/UINT16_MAX;
  uint16_t seg_count = sign.segmentCount();

  bool on = (ci == 0);

  for(uint8_t i=0; i < seg_count; i++){
    Segment *curr_seg = sign.segments[i];

    if(curr_seg -> isOn == on){
      curr_seg -> setColor(color[ci]);
      delta_hue = -delta_hue;
      int16_t hue_add = delta_hue;

      uint8_t pixel_count = curr_seg -> pixelCount();

      for(uint8_t j = 0; j < pixel_count; j++ ){
        Pixel *currPixel = curr_seg -> pixels[j];
        currPixel -> addHue16(hue_add);
        hue_add += delta_hue;
      }
    }
  }

}
Exemple #10
0
int main (int argc, char * argv[])
{
    QApplication app(argc,argv);

    Signfactory sf;
    Sign *s = sf.createSign("/");
    s->setA(1);s->setB(0);
    try{
        qDebug()<<s->getResult();
    }
    catch(...)
    {}
    delete s;

#ifdef use_origin
    std::shared_ptr<caculate> c(new caculate);
#else
    QSharedPointer<caculate> c(new caculate);
#endif
    c->show();

    return app.exec();
}
Exemple #11
0
void RainbowSegment::run(Sign &sign, uint8_t layer){
  if( sign.textChanged ){ this -> signWasUpdated(sign);}
  uint8_t segment_count = sign.segmentCount();
  CHSV curr_color = color[layer];

  if(changeOnBeat && sign.onBeat){
    color[layer].hue += beatStep[layer];
  }

  for(uint8_t i=0; i<segment_count; i++){
    Segment* curr_segment = sign.segments[i];
    curr_segment -> setColor(layer, curr_color);
    curr_color.hue += hueStep[layer];
  }

}
Exemple #12
0
void Scrolling::run(Sign &sign, EffectData &data, uint8_t layer){
  if(beatIdx++ % numBeats > 0){ return;}

  sign.textChanged = true;

  char word[4];
  if(randomLetterIdx >= 0){
    this->setRandomLetter(word);
  }else{
    for(uint8_t i=0; i< LETTERS_COUNT; i++){
      uint8_t idx = (beatIdx+i) % charCount;
      word[i] = buffer[idx];
    }
  }

  sign.setWord( String( word ) );
}
 inline
 UnitVector3d
 operator*(Sign sign, const UnitVector3d& unitVector) {
     return UnitVector3d(sign.value() * unitVector.components());
 }
//invoke only once
void SignFactory::fillSignMap()
{
    int soundType = SIGN_SOUND_DEFAULT;
    //latters 
    for(int i=0;i<LETTERS_LENGTH;i++)
    {
        char stringSignName[20] = { 0 };
        sprintf(stringSignName,"%s%d.png",LatterfileNameByRez.c_str(), i);
        Sign* pSign = Sign::create(stringSignName);
        pSign->setAnchorPoint(Vec2(0.0,0.0));        
        //char ch = m_LatersStr[i-1];
        std::string latter = pUT->int_to_string(i);
        pSign->setLatterInx((i));
        pSign->setLatter(latter);
        pSign->setTag(sign_tags::LETTER_SIGH);

        if(soundType == IS_FALSE)
        {
            char stringSignSoundName[50] = { 0 };
            sprintf(stringSignSoundName,"%s/%s%d.mp3",lang_sound.c_str(),
                                                      sLetterfileSounds_fnt_to_slc.c_str(),
                                                      i);

			//std::string stringSignSoundName ="x";
            std::string stdstringSignSoundName(stringSignSoundName);
            pSign->setFontToSolutionSound(stdstringSignSoundName);
            pSign->setSolutionToFontSound(core::Settings::getInstance()->getSoundManager()
                                                .soundEffectClick_FromSolutionToFont);

			//delete stringSignSoundName;
        }
        else
        {
            pSign->setSolutionToFontSound(core::Settings::getInstance()->getSoundManager()
                                                .soundEffectClick_FromSolutionToFont);
            pSign->setFontToSolutionSound(core::Settings::getInstance()->getSoundManager()
                                                .soundEffectClick_FromSolutionToFont);
        }



        pSign->retain();         
        m_SignMap.insert(std::pair<int, Sign*>((i),pSign));
        //m_SignToNumMap.insert(std::pair<std::string,int>(latter,(i-1)));
         
    }
    //image container
    Sign* pSignContainer = Sign::create(LatterContainerfileNameByRez);
    pSignContainer->setAnchorPoint(Vec2(0.0,0.0)); 
    pSignContainer->setLatterInx(sign_tags::CONTAINER_SIGH);
    pSignContainer->retain();
    m_SignMap.insert(std::pair<int, Sign*>(sign_tags::CONTAINER_SIGH,pSignContainer));
    
    

    //line break
    Sign* pSignLineBreak = Sign::create(LatterContainerfileNameByRez);
    pSignLineBreak->setAnchorPoint(Vec2(0.0,0.0)); 
    pSignLineBreak->setLatterInx(sign_tags::SEPERATOR_SIGH);
    pSignLineBreak->retain();
    m_SignMap.insert(std::pair<int, Sign*>(sign_tags::SEPERATOR_SIGH,pSignLineBreak));


    //scalefactor
    Sign* SignTest = getSign(1);
    Size LatterOrigSize = SignTest->getBoundingBox().size;
    // must be set first TODO fix this... 
    float winWidth =  m_Parent->pFontSelectionContainer->visibleSize.width;
    float locallatterScaleFactor = pUT->getScaleFactorBasedOnWinWidth(winWidth,LatterOrigSize);
    setLatterScaleFactor(locallatterScaleFactor);
    //SignTest->setScale(getLatterScaleFactor());
    pUT->setSignScalefactor(SignTest);
    setLatterScalledSize(SignTest->getBoundingBox().size);
}
void SymplecticRungeKuttaNyströmIntegrator<Position, order, time_reversible,
                                           evaluations, composition>::Solve(
    IntegrationProblem<ODE> const& problem,
    Time const& step) const {
  using Displacement = typename ODE::Displacement;
  using Velocity = typename ODE::Velocity;
  using Acceleration = typename ODE::Acceleration;

  // Argument checks.
  CHECK_NOTNULL(problem.initial_state);
  int const dimension = problem.initial_state->positions.size();
  CHECK_EQ(dimension, problem.initial_state->velocities.size());
  CHECK_NE(Time(), step);
  Sign const integration_direction = Sign(step);
  if (integration_direction.Positive()) {
    // Integrating forward.
    CHECK_LT(problem.initial_state->time.value, problem.t_final);
  } else {
    // Integrating backward.
    CHECK_GT(problem.initial_state->time.value, problem.t_final);
  }

  typename ODE::SystemState current_state = *problem.initial_state;

  // Time step.
  Time const& h = step;
  Time const abs_h = integration_direction * h;
  // Current time.  This is a non-const reference whose purpose is to make the
  // equations more readable.
  DoublePrecision<Instant>& t = current_state.time;

  // Position increment.
  std::vector<Displacement> Δq(dimension);
  // Velocity increment.
  std::vector<Velocity> Δv(dimension);
  // Current position.  This is a non-const reference whose purpose is to make
  // the equations more readable.
  std::vector<DoublePrecision<Position>>& q = current_state.positions;
  // Current velocity.  This is a non-const reference whose purpose is to make
  // the equations more readable.
  std::vector<DoublePrecision<Velocity>>& v = current_state.velocities;

  // Current Runge-Kutta-Nyström stage.
  std::vector<Position> q_stage(dimension);
  // Accelerations at the current stage.
  std::vector<Acceleration> g(dimension);

  // The first full stage of the step, i.e. the first stage where
  // exp(bᵢ h B) exp(aᵢ h A) must be entirely computed.
  // Always 0 in the non-FSAL kBA case, always 1 in the kABA case since b₀ = 0,
  // means the first stage is only exp(a₀ h A), and 1 after the first step
  // in the kBAB case, since the last right-hand-side evaluation can be used for
  // exp(bᵢ h B).
  int first_stage = composition == kABA ? 1 : 0;

  while (abs_h <= Abs((problem.t_final - t.value) - t.error)) {
    std::fill(Δq.begin(), Δq.end(), Displacement{});
    std::fill(Δv.begin(), Δv.end(), Velocity{});

    if (first_stage == 1) {
      for (int k = 0; k < dimension; ++k) {
        if (composition == kBAB) {
          // exp(b₀ h B)
          Δv[k] += h * b_[0] * g[k];
        }
        // exp(a₀ h A)
        Δq[k] += h * a_[0] * (v[k].value + Δv[k]);
      }
    }

    for (int i = first_stage; i < stages_; ++i) {
      for (int k = 0; k < dimension; ++k) {
        q_stage[k] = q[k].value + Δq[k];
      }
      problem.equation.compute_acceleration(t.value + c_[i] * h, q_stage, &g);
      for (int k = 0; k < dimension; ++k) {
        // exp(bᵢ h B)
        Δv[k] += h * b_[i] * g[k];
        // exp(aᵢ h A)
        Δq[k] += h * a_[i] * (v[k].value + Δv[k]);
      }
    }

    if (composition == kBAB) {
      first_stage = 1;
    }

    // Increment the solution.
    t.Increment(h);
    for (int k = 0; k < dimension; ++k) {
      q[k].Increment(Δq[k]);
      v[k].Increment(Δv[k]);
    }
    problem.append_state(current_state);
  }
}
Exemple #16
0
Status EmbeddedExplicitRungeKuttaNyströmIntegrator<Position,
                                                   higher_order,
                                                   lower_order,
                                                   stages,
                                                   first_same_as_last>::
Instance::Solve(Instant const& t_final) {
  using Displacement = typename ODE::Displacement;
  using Velocity = typename ODE::Velocity;
  using Acceleration = typename ODE::Acceleration;

  auto const& a = integrator_.a_;
  auto const& b_hat = integrator_.b_hat_;
  auto const& b_prime_hat = integrator_.b_prime_hat_;
  auto const& b = integrator_.b_;
  auto const& b_prime = integrator_.b_prime_;
  auto const& c = integrator_.c_;

  auto& current_state = this->current_state_;
  auto& append_state = this->append_state_;
  auto& adaptive_step_size = this->adaptive_step_size_;
  auto const& equation = this->equation_;

  // |current_state| gets updated as the integration progresses to allow
  // restartability.

  // State before the last, truncated step.
  std::experimental::optional<typename ODE::SystemState> final_state;

  // Argument checks.
  int const dimension = current_state.positions.size();
  Sign const integration_direction =
      Sign(adaptive_step_size.first_time_step);
  if (integration_direction.Positive()) {
    // Integrating forward.
    CHECK_LT(current_state.time.value, t_final);
  } else {
    // Integrating backward.
    CHECK_GT(current_state.time.value, t_final);
  }

  // Time step.
  Time h = adaptive_step_size.first_time_step;
  // Current time.  This is a non-const reference whose purpose is to make the
  // equations more readable.
  DoublePrecision<Instant>& t = current_state.time;

  // Position increment (high-order).
  std::vector<Displacement> Δq_hat(dimension);
  // Velocity increment (high-order).
  std::vector<Velocity> Δv_hat(dimension);
  // Current position.  This is a non-const reference whose purpose is to make
  // the equations more readable.
  std::vector<DoublePrecision<Position>>& q_hat = current_state.positions;
  // Current velocity.  This is a non-const reference whose purpose is to make
  // the equations more readable.
  std::vector<DoublePrecision<Velocity>>& v_hat = current_state.velocities;

  // Difference between the low- and high-order approximations.
  typename ODE::SystemStateError error_estimate;
  error_estimate.position_error.resize(dimension);
  error_estimate.velocity_error.resize(dimension);

  // Current Runge-Kutta-Nyström stage.
  std::vector<Position> q_stage(dimension);
  // Accelerations at each stage.
  // TODO(egg): this is a rectangular container, use something more appropriate.
  std::vector<std::vector<Acceleration>> g(stages);
  for (auto& g_stage : g) {
    g_stage.resize(dimension);
  }

  bool at_end = false;
  double tolerance_to_error_ratio;

  // The first stage of the Runge-Kutta-Nyström iteration.  In the FSAL case,
  // |first_stage == 1| after the first step, since the first RHS evaluation has
  // already occured in the previous step.  In the non-FSAL case and in the
  // first step of the FSAL case, |first_stage == 0|.
  int first_stage = 0;

  // The number of steps already performed.
  std::int64_t step_count = 0;

  // No step size control on the first step.
  goto runge_kutta_nyström_step;

  while (!at_end) {
    // Compute the next step with decreasing step sizes until the error is
    // tolerable.
    do {
      // Adapt step size.
      // TODO(egg): find out whether there's a smarter way to compute that root,
      // especially since we make the order compile-time.
      h *= adaptive_step_size.safety_factor *
               std::pow(tolerance_to_error_ratio, 1.0 / (lower_order + 1));
      // TODO(egg): should we check whether it vanishes in double precision
      // instead?
      if (t.value + (t.error + h) == t.value) {
        return Status(termination_condition::VanishingStepSize,
                      "At time " + DebugString(t.value) +
                          ", step size is effectively zero.  Singularity or "
                          "stiff system suspected.");
      }

    runge_kutta_nyström_step:
      // Termination condition.
      Time const time_to_end = (t_final - t.value) - t.error;
      at_end = integration_direction * h >= integration_direction * time_to_end;
      if (at_end) {
        // The chosen step size will overshoot.  Clip it to just reach the end,
        // and terminate if the step is accepted.
        h = time_to_end;
        final_state = current_state;
      }

      // Runge-Kutta-Nyström iteration; fills |g|.
      for (int i = first_stage; i < stages; ++i) {
        Instant const t_stage = t.value + c[i] * h;
        for (int k = 0; k < dimension; ++k) {
          Acceleration Σj_a_ij_g_jk{};
          for (int j = 0; j < i; ++j) {
            Σj_a_ij_g_jk += a[i][j] * g[j][k];
          }
          q_stage[k] = q_hat[k].value +
                           h * (c[i] * v_hat[k].value + h * Σj_a_ij_g_jk);
        }
        equation.compute_acceleration(t_stage, q_stage, g[i]);
      }

      // Increment computation and step size control.
      for (int k = 0; k < dimension; ++k) {
        Acceleration Σi_b_hat_i_g_ik{};
        Acceleration Σi_b_i_g_ik{};
        Acceleration Σi_b_prime_hat_i_g_ik{};
        Acceleration Σi_b_prime_i_g_ik{};
        // Please keep the eight assigments below aligned, they become illegible
        // otherwise.
        for (int i = 0; i < stages; ++i) {
          Σi_b_hat_i_g_ik       += b_hat[i] * g[i][k];
          Σi_b_i_g_ik           += b[i] * g[i][k];
          Σi_b_prime_hat_i_g_ik += b_prime_hat[i] * g[i][k];
          Σi_b_prime_i_g_ik     += b_prime[i] * g[i][k];
        }
        // The hat-less Δq and Δv are the low-order increments.
        Δq_hat[k]               = h * (h * (Σi_b_hat_i_g_ik) + v_hat[k].value);
        Displacement const Δq_k = h * (h * (Σi_b_i_g_ik) + v_hat[k].value);
        Δv_hat[k]               = h * Σi_b_prime_hat_i_g_ik;
        Velocity const Δv_k     = h * Σi_b_prime_i_g_ik;

        error_estimate.position_error[k] = Δq_k - Δq_hat[k];
        error_estimate.velocity_error[k] = Δv_k - Δv_hat[k];
      }
      tolerance_to_error_ratio =
          adaptive_step_size.tolerance_to_error_ratio(h, error_estimate);
    } while (tolerance_to_error_ratio < 1.0);

    if (first_same_as_last) {
      using std::swap;
      swap(g.front(), g.back());
      first_stage = 1;
    }

    // Increment the solution with the high-order approximation.
    t.Increment(h);
    for (int k = 0; k < dimension; ++k) {
      q_hat[k].Increment(Δq_hat[k]);
      v_hat[k].Increment(Δv_hat[k]);
    }
    append_state(current_state);
    ++step_count;
    if (step_count == adaptive_step_size.max_steps && !at_end) {
      return Status(termination_condition::ReachedMaximalStepCount,
                    "Reached maximum step count " +
                        std::to_string(adaptive_step_size.max_steps) +
                        " at time " + DebugString(t.value) +
                        "; requested t_final is " + DebugString(t_final) +
                        ".");
    }
  }
  // The resolution is restartable from the last non-truncated state.
  CHECK(final_state);
  current_state = *final_state;
  return Status(termination_condition::Done, "");
}
Exemple #17
0
/**
testing.
*/
int mainCryptopp(const char* encryptPath, const char* decryptPath)
{
    printf("/***************************************************************************\n");
    printf("C++ crypto, wrap cryptopp interface, reference to www.cryptopp.com\n");
    printf("[email protected] 2006-5-25\n");
    printf("***************************************************************************/\n");

    // base64 testing.
    {
        printf("\n=======================base64=====================\n");
        // input data.
        const char * indata = "bsmith is a good guy.";
        int inlen = (int)strlen(indata);
        printf("inlen=%d\n", inlen);
        printf("indata(hex)=");
        dump(indata, inlen);
        
        // encoding ...
        int maxoutlen = Base64::getCipherLen(inlen);
        printf("maxoutlen=%d\n", maxoutlen);
        char * outdata = new char[maxoutlen];
        int outlen = Base64::encode(indata, inlen, outdata);
        printf("outlen=%d\n", outlen);
        printf("outdata(hex)=");
        dump(outdata, outlen);
        // encoded base64 string.
        char * outstr = new char[outlen+1];
        memcpy(outstr, outdata, outlen);
        outstr[outlen] = 0x00;
        printf("outstr=%s\n", outstr);

        // decoding ...
        int maxinlen = Base64::getPlainLen(outlen);
        printf("maxinlen=%d\n", maxinlen);
        char * orgdata = new char[maxinlen];
        int orglen = Base64::decode(outdata, outlen, orgdata);
        printf("orglen=%d\n", orglen);
        printf("orgdata(hex)=");
        dump(orgdata, orglen);

        delete[] outdata;
        delete[] outstr;
        delete[] orgdata;
    }

    // base16 testing.
    {
        printf("\n=======================base16=====================\n");
        // input data.
        const char * indata = "bsmith is a good guy.";
        int inlen = (int)strlen(indata);
        printf("inlen=%d\n", inlen);
        printf("indata(hex)=");
        dump(indata, inlen);
        
        // encoding ...
        int maxoutlen = Base16::getCipherLen(inlen);
        printf("maxoutlen=%d\n", maxoutlen);
        char * outdata = new char[maxoutlen];
        int outlen = Base16::encode(indata, inlen, outdata);
        printf("outlen=%d\n", outlen);
        printf("outdata(hex)=");
        dump(outdata, outlen);
        // encoded base16 string.
        char * outstr = new char[outlen+1];
        memcpy(outstr, outdata, outlen);
        outstr[outlen] = 0x00;
        printf("outstr=%s\n", outstr);

        // decoding ...
        int maxinlen = Base16::getPlainLen(outlen);
        printf("maxinlen=%d\n", maxinlen);
        char * orgdata = new char[maxinlen];
        int orglen = Base16::decode(outdata, outlen, orgdata);
        printf("orglen=%d\n", orglen);
        printf("orgdata(hex)=");
        dump(orgdata, orglen);

        delete[] outdata;
        delete[] outstr;
        delete[] orgdata;
    }

    // RSA testing.
    {
        printf("\n=======================RSA PKCS #1=====================\n");
        // key
        // N factor in RSA, aslo called modulus.
        const char * N = "90755611487566208138950675092879865387596685014726501531250157258482495478524769456222913843665634824684037468817980814231054856125127115894189385717148934026931120932481402379431731629550862846041784305274651476086892165805223719552575599962253392248079811268061946102234935422772131475340988882825043233323";
        // e factor in RSA, aslo called public exponent.
        const char * e = "65537";
        // d factor in RSA, aslo called private exponent
        const char * d = "17790520481266507102264359414044396762660094486842415203197747383916331528947124726552875080482359744765793816651732601742929364124685415229452844016482477236658413327331659722342187036963943428678684677279032263501011143882814728160215380051287503219732737197808611144507720521201393129692996926599975297921";

        // input data.
        const char * indata = "bsmith is a good guy.";
        int inlen = (int)strlen(indata);
        printf("inlen=%d\n", inlen);
        printf("indata(hex)=");
        dump(indata, inlen);

        // init RSA public key encryptor.
        RSA enc;
        enc.initPublicKey(N, e);

        // encrypt.
        int maxoutlen = enc.getCipherLen(inlen);
        printf("maxoutlen=%d\n", maxoutlen);
        char * outdata = new char[maxoutlen];
        int outlen = enc.encrypt(indata, inlen, outdata);
        printf("outlen=%d\n", outlen);
        printf("outdata(hex)=");
        dump(outdata, outlen);

        // init private for RSA decryptor.
        RSA dec;
        dec.initPrivateKey(N, e, d);

        // decrypt.
        int maxinlen = dec.getPlainLen(outlen);
        printf("maxinlen=%d\n", maxinlen);
        char * orgdata = new char[maxinlen];
        int orglen = dec.decrypt(outdata, outlen, orgdata);
        printf("orglen=%d\n", orglen);
        printf("orgdata(hex)=");
        dump(orgdata, orglen);

        delete[] outdata;
        delete[] orgdata;
    }

    // AES/CBC/PKCS5Padding testing.
    {
        printf("\n=======================AES/CBC/PKCS5Padding=====================\n");
        // key
        const char * key = "0123456789abcdef";
        // iv
        const char * iv = "fedcba9876543210";

        // init AES.
        AES aes;
        aes.init(key, 16, iv);

        // input data.
        // const char * indata = "bsmith is a good guy.";
        // const char * indata = "bsmith.";
        const char * indata = "I am a good guy.";
        int inlen = (int)strlen(indata);
        printf("inlen=%d\n", inlen);
        printf("indata(hex)=");
        dump(indata, inlen);

        // encrypt.
        int maxoutlen = aes.getCipherLen(inlen);
        printf("maxoutlen=%d\n", maxoutlen);
        char * outdata = new char[maxoutlen];
        int outlen = 0;
        {
            outlen = aes.encrypt(indata, inlen, outdata);
            printf("outlen=%d\n", outlen);
            printf("outdata(hex)=");
            dump(outdata, outlen);
        }
        {
            outlen = aes.encrypt(indata, inlen, outdata);
            printf("outlen=%d\n", outlen);
            printf("outdata(hex)=");
            dump(outdata, outlen);
        }

        // decrypt.
        int maxinlen = aes.getPlainLen(outlen);
        printf("maxinlen=%d\n", maxinlen);
        char * orgdata = new char[maxinlen];
        {
            
            int orglen = aes.decrypt(outdata, outlen, orgdata);
            printf("orglen=%d\n", orglen);
            printf("orgdata(hex)=");
            dump(orgdata, orglen);
        }
        {
            int orglen = aes.decrypt(outdata, outlen, orgdata);
            printf("orglen=%d\n", orglen);
            printf("orgdata(hex)=");
            dump(orgdata, orglen);
        }

        delete[] outdata;
        delete[] orgdata;

    }

    // SHA1 testing.
    {
        printf("\n=======================SHA1=====================\n");

        SHA1 sha1;

        // input data.
        const char * indata = "bsmith is a good guy.";
        int inlen = (int)strlen(indata);
        printf("inlen=%d\n", inlen);
        printf("indata(hex)=");
        dump(indata, inlen);
        
        // one time digest.
        {
            char * outdata = new char[sha1.getCipherLen(inlen)];
            int outlen = sha1.digest(indata, inlen, outdata);
            printf("outlen=%d\n", outlen);
            printf("outdata(hex)=");
            dump(outdata, outlen);

            delete[] outdata;
        }

        // serval times
        {
            char * outdata = new char[sha1.getCipherLen(inlen)];
            sha1.update(indata, 5);
            sha1.update(indata+5, inlen-5);
            int outlen = sha1.final(outdata);
            printf("outlen=%d\n", outlen);
            printf("outdata(hex)=");
            dump(outdata, outlen);

            delete[] outdata;
        }

        // one time digest.
        {
            char * outdata = new char[sha1.getCipherLen(inlen)];
            int outlen = sha1.digest(indata, inlen, outdata);
            printf("outlen=%d\n", outlen);
            printf("outdata(hex)=");
            dump(outdata, outlen);

            delete[] outdata;
        }

        // serval times
        {
            char * outdata = new char[sha1.getCipherLen(inlen)];
            sha1.update(indata, 5);
            sha1.update(indata+5, inlen-5);
            int outlen = sha1.final(outdata);
            printf("outlen=%d\n", outlen);
            printf("outdata(hex)=");
            dump(outdata, outlen);

            delete[] outdata;
        }
    }

    // RSA-SHA1 Sign testing.
    {
        printf("\n=======================RSA-SHA1 Sign=====================\n");

        // key
        // N factor in RSA, aslo called modulus.
        const char * N = "90755611487566208138950675092879865387596685014726501531250157258482495478524769456222913843665634824684037468817980814231054856125127115894189385717148934026931120932481402379431731629550862846041784305274651476086892165805223719552575599962253392248079811268061946102234935422772131475340988882825043233323";
        // e factor in RSA, aslo called public exponent.
        const char * e = "65537";
        // d factor in RSA, aslo called private exponent
        const char * d = "17790520481266507102264359414044396762660094486842415203197747383916331528947124726552875080482359744765793816651732601742929364124685415229452844016482477236658413327331659722342187036963943428678684677279032263501011143882814728160215380051287503219732737197808611144507720521201393129692996926599975297921";

        // input data.
        const char * indata = "bsmith is a good guy.";
        int inlen = (int)strlen(indata);
        printf("inlen=%d\n", inlen);
        printf("indata(hex)=");
        dump(indata, inlen);

        Sign sign;
        // private key for signer.
        sign.initPrivateKey(N, e, d);

        // sign.
        int maxoutlen = sign.getCipherLen(inlen);
        printf("maxoutlen=%d\n", maxoutlen);
        char * outdata = new char[maxoutlen];
        int outlen = sign.sign(indata, inlen, outdata);
        printf("outlen=%d\n", outlen);
        printf("outdata(hex)=");
        dump(outdata, outlen);

        // public key for verifier.
        sign.initPublicKey(N, e);

        // verify.
        {
            bool res = sign.verify(indata, inlen, outdata, outlen);
            printf("result <?> true : %s\n", res?"true":"false");
        }
        
        // another data.
        const char * indata1 = "bsmith is not a good guy.";
        int inlen1 = (int)strlen(indata1);
        {
            bool res = sign.verify(indata1, inlen1, outdata, outlen);
            printf("result <?> false : %s\n", res?"true":"false");
        }

        delete[] outdata;
    }

    //printf("press any key to exit!");
    //getchar();
    
    {
        //my test
        unsigned long decryptSize = 0;
        char* decryptBuffer = (char*)getFileData(decryptPath, &decryptSize);
        
        unsigned long encryptSize = 0;
        char* encryptBuffer = (char*)getFileData(encryptPath, &encryptSize);
        
        printf("decryptBuffer(hex)=");
        dump(decryptBuffer, decryptSize);
        
        // key
        const char * key = "0123456789abcdef";
        // iv
        const char * iv = "fedcba9876543210";
        
        // init AES.
        AES aes;
        aes.init(key, 16, iv);
        {
            // decrypt.
            int maxinlen = aes.getPlainLen(encryptSize);
            char * orgdata = new char[maxinlen];
            {
                int orglen = aes.decrypt(encryptBuffer, encryptSize, orgdata);
                printf("decryptWithCrypto++(hex)=");
                dump(orgdata, orglen);
            }
            delete [] orgdata;
        }
        
        printf("encryptBuffer(hex)=");
        dump(encryptBuffer, encryptSize);
        
        {
            // encrypt.
            int maxoutlen = aes.getCipherLen(decryptSize);
            char * outdata = new char[maxoutlen];
            int outlen = 0;
            {
                outlen = aes.encrypt(decryptBuffer, decryptSize, outdata);
                printf("encryptWithCrypto++(hex)=");
                dump(outdata, outlen);
            }
            delete [] outdata;
        }
        
        delete [] decryptBuffer;
        delete [] encryptBuffer;
        
        
    }

    return 0;
}
 inline
 UnitVector3d
 operator*(const UnitVector3d& unitVector, Sign sign) {
     return UnitVector3d(unitVector.components() * sign.value());
 }
inline std::string DebugString(Sign const& sign) {
  return sign.Negative() ? "-" : "+";
}