void PhraseTableCreator::EncodeTargetPhrasePREnc(std::vector<std::string>& s,
    std::vector<std::string>& t,
    std::set<AlignPoint>& a,
    size_t ownRank,
    std::ostream& os)
{
  std::vector<unsigned> encodedSymbols(t.size());
  std::vector<unsigned> encodedSymbolsLengths(t.size(), 0);

  ConsistentPhrases cp(s.size(), t.size(), a);
  while(!cp.Empty()) {
    ConsistentPhrases::Phrase p = cp.Pop();

    std::stringstream key1;
    key1 << s[p.i];
    for(int i = p.i+1; i < p.i+p.m; i++)
      key1 << " " << s[i];

    std::stringstream key2;
    key2 << t[p.j];
    for(int i = p.j+1; i < p.j+p.n; i++)
      key2 << " " << t[i];

    int rank = -1;
    std::string key1Str = key1.str(), key2Str = key2.str();
    size_t idx = m_rnkHash[MakeSourceTargetKey(key1Str, key2Str)];
    if(idx != m_rnkHash.GetSize())
      rank = m_ranks[idx];

    if(rank >= 0 && (m_maxRank == 0 || unsigned(rank) < m_maxRank)) {
      if(unsigned(p.m) != s.size() || unsigned(rank) < ownRank) {
        std::stringstream encodedSymbol;
        encodedSymbols[p.j] = EncodePREncSymbol2(p.i-p.j, s.size()-(p.i+p.m), rank);
        encodedSymbolsLengths[p.j] = p.n;

        std::set<AlignPoint> tAlignment;
        for(std::set<AlignPoint>::iterator it = a.begin();
            it != a.end(); it++)
          if(it->first < p.i || it->first >= p.i + p.m
              || it->second < p.j || it->second >= p.j + p.n)
            tAlignment.insert(*it);
        a = tAlignment;
        cp.RemoveOverlap(p);
      }
    }
  }

  std::stringstream encodedTargetPhrase;

  size_t j = 0;
  while(j < t.size()) {
    if(encodedSymbolsLengths[j] > 0) {
      unsigned encodedSymbol = encodedSymbols[j];
      m_symbolCounter.Increase(encodedSymbol);
      os.write((char*)&encodedSymbol, sizeof(encodedSymbol));
      j += encodedSymbolsLengths[j];
    } else {
      unsigned targetSymbolId = GetOrAddTargetSymbolId(t[j]);
      unsigned encodedSymbol = EncodePREncSymbol1(targetSymbolId);
      m_symbolCounter.Increase(encodedSymbol);
      os.write((char*)&encodedSymbol, sizeof(encodedSymbol));
      j++;
    }
  }

  unsigned stopSymbolId = GetTargetSymbolId(m_phraseStopSymbol);
  unsigned encodedSymbol = EncodePREncSymbol1(stopSymbolId);
  os.write((char*)&encodedSymbol, sizeof(encodedSymbol));
  m_symbolCounter.Increase(encodedSymbol);
}
void Task::schedule()
{
  // Is waiting for execution

  // Increment active task count before spawning.
  Kokkos::atomic_increment( m_active_count );

  // spawn in qthread.  must malloc the precondition array and give to qthread.
  // qthread will eventually free this allocation so memory will not be leaked.

  // concern with thread safety of malloc, does this need to be guarded?
  aligned_t ** qprecon = (aligned_t **) malloc( ( m_dep_size + 1 ) * sizeof(aligned_t *) );

  qprecon[0] = reinterpret_cast<aligned_t *>( uintptr_t(m_dep_size) );

  for ( int i = 0 ; i < m_dep_size ; ++i ) {
    qprecon[i+1] = & m_dep[i]->m_qfeb ; // Qthread precondition flag
  }

  if ( m_apply_team && ! m_apply_single ) {
    // If more than one shepherd spawn on a shepherd other than this shepherd
    const int num_shepherd            = qthread_num_shepherds();
    const int num_worker_per_shepherd = qthread_num_workers_local(NO_SHEPHERD);
    const int this_shepherd           = qthread_shep();

    int spawn_shepherd = ( this_shepherd + 1 ) % num_shepherd ;

#if 0
fprintf( stdout
       , "worker(%d.%d) task 0x%.12lx spawning on shepherd(%d) clone(%d)\n"
       , qthread_shep()
       , qthread_worker_local(NULL)
       , reinterpret_cast<unsigned long>(this)
       , spawn_shepherd
       , num_worker_per_shepherd - 1
       );
fflush(stdout);
#endif

    qthread_spawn_cloneable
      ( & Task::qthread_func
      , this
      , 0
      , NULL
      , m_dep_size , qprecon /* dependences */
      , spawn_shepherd
      , unsigned( QTHREAD_SPAWN_SIMPLE | QTHREAD_SPAWN_LOCAL_PRIORITY )
      , num_worker_per_shepherd - 1
      );
  }
  else {
    qthread_spawn( & Task::qthread_func /* function */
                 , this                 /* function argument */
                 , 0
                 , NULL
                 , m_dep_size , qprecon /* dependences */
                 , NO_SHEPHERD
                 , QTHREAD_SPAWN_SIMPLE /* allows optimization for non-blocking task */
                 );
  }
}
示例#3
0
void CCommandProcessor::DisplayCpuLoad ( void )
{
  const uint8_t * lastMinute;
        uint8_t   lastMinuteIndex;

  const uint8_t * lastSecond;
        uint8_t   lastSecondIndex;

  GetCpuLoadStats( &lastMinute, &lastMinuteIndex,
                   &lastSecond, &lastSecondIndex );

  uint32_t minuteAverage = 0;

  for ( unsigned j = 0; j < CPU_LOAD_LONG_PERIOD_SLOT_COUNT; ++j )
  {
    const unsigned index = ( lastMinuteIndex + j ) % CPU_LOAD_LONG_PERIOD_SLOT_COUNT;

    minuteAverage += lastMinute[ index ];
  }

  minuteAverage = minuteAverage * 100 / ( CPU_LOAD_LONG_PERIOD_SLOT_COUNT * 255 );
  assert( minuteAverage <= 100 );

  PrintStr( "CPU load in the last 60 seconds (1 second intervals, oldest to newest):" EOL );

  for ( unsigned j = 0; j < CPU_LOAD_LONG_PERIOD_SLOT_COUNT; ++j )
  {
    const unsigned index = ( lastMinuteIndex + j ) % CPU_LOAD_LONG_PERIOD_SLOT_COUNT;

    const uint32_t val = lastMinute[ index ] * 100 / 255;

    assert( val <= 100 );

    Printf( "%3u %%" EOL, unsigned( val ) );
  }


  uint32_t secondAverage = 0;

  for ( unsigned j = 0; j < CPU_LOAD_SHORT_PERIOD_SLOT_COUNT; ++j )
  {
    const unsigned index = ( lastSecondIndex + j ) % CPU_LOAD_SHORT_PERIOD_SLOT_COUNT;

    secondAverage += lastSecond[ index ];
  }

  secondAverage = secondAverage * 100 / ( CPU_LOAD_SHORT_PERIOD_SLOT_COUNT * 255 );
  assert( secondAverage <= 100 );


  PrintStr( "CPU load in the last second (50 ms intervals, oldest to newest):" EOL );

  for ( unsigned j = 0; j < CPU_LOAD_SHORT_PERIOD_SLOT_COUNT; ++j )
  {
    const unsigned index = ( lastSecondIndex + j ) % CPU_LOAD_SHORT_PERIOD_SLOT_COUNT;

    const uint32_t val = lastSecond[ index ] * 100 / 255;

    assert( val <= 100 );

    Printf( "%2u %%" EOL, unsigned( val ) );
  }

  Printf( "Average CPU load in the last 60 seconds: %2u %%" EOL, unsigned( minuteAverage ) );
  Printf( "Average CPU load in the last    second : %2u %%" EOL, unsigned( secondAverage ) );
}
示例#4
0
CstrBuffer::CstrBuffer(char* data, int len)
  : m_buffer(data), m_len(len), m_cap(len) {
  assert(unsigned(len) < kMaxCap);
}
示例#5
0
  *b = bb & (bb - 1);
  return BSFTable[bsf_index(bb)];
}

Square msb(Bitboard b) {

  unsigned b32;
  int result = 0;

  if (b > 0xFFFFFFFF)
  {
      b >>= 32;
      result = 32;
  }

  b32 = unsigned(b);

  if (b32 > 0xFFFF)
  {
      b32 >>= 16;
      result += 16;
  }

  if (b32 > 0xFF)
  {
      b32 >>= 8;
      result += 8;
  }

  return (Square)(result + MS1BTable[b32]);
}
示例#6
0
Tokens jsonnet_lex(const std::string &filename, const char *input)
{
    unsigned long line_number = 1;
    const char *line_start = input;

    Tokens r;

    const char *c = input;

    Fodder fodder;
    bool fresh_line = true;  // Are we tokenizing from the beginning of a new line?

    while (*c!='\0') {
        Token::Kind kind;
        std::string data;
        std::string string_block_indent;
        std::string string_block_term_indent;

        unsigned new_lines, indent;
        lex_ws(c, new_lines, indent, line_start, line_number);

        // If it's the end of the file, discard final whitespace.
        if (*c == '\0')
            break;

        if (new_lines > 0) {
            // Otherwise store whitespace in fodder.
            unsigned blanks = new_lines - 1;
            fodder.emplace_back(FodderElement::LINE_END, blanks, indent, EMPTY);
            fresh_line = true;
        }

        Location begin(line_number, c - line_start + 1);

        switch (*c) {

            // The following operators should never be combined with subsequent symbols.
            case '{':
            kind = Token::BRACE_L;
            c++;
            break;

            case '}':
            kind = Token::BRACE_R;
            c++;
            break;

            case '[':
            kind = Token::BRACKET_L;
            c++;
            break;

            case ']':
            kind = Token::BRACKET_R;
            c++;
            break;

            case ',':
            kind = Token::COMMA;
            c++;
            break;

            case '.':
            kind = Token::DOT;
            c++;
            break;

            case '(':
            kind = Token::PAREN_L;
            c++;
            break;

            case ')':
            kind = Token::PAREN_R;
            c++;
            break;

            case ';':
            kind = Token::SEMICOLON;
            c++;
            break;

            // Numeric literals.
            case '0': case '1': case '2': case '3': case '4':
            case '5': case '6': case '7': case '8': case '9':
            kind = Token::NUMBER;
            data = lex_number(c, filename, begin);
            break;

            // String literals.
            case '"': {
                c++;
                for (; ; ++c) {
                    if (*c == '\0') {
                        throw StaticError(filename, begin, "Unterminated string");
                    }
                    if (*c == '"') {
                        break;
                    }
                    if (*c == '\\' && *(c+1) != '\0') {
                        data += *c;
                        ++c;
                    }
                    if (*c == '\n') {
                        // Maintain line/column counters.
                        line_number++;
                        line_start = c+1;
                    }
                    data += *c;
                }
                c++;  // Advance beyond the ".
                kind = Token::STRING_DOUBLE;
            }
            break;

            // String literals.
            case '\'': {
                c++;
                for (; ; ++c) {
                    if (*c == '\0') {
                        throw StaticError(filename, begin, "Unterminated string");
                    }
                    if (*c == '\'') {
                        break;
                    }
                    if (*c == '\\' && *(c+1) != '\0') {
                        data += *c;
                        ++c;
                    }
                    if (*c == '\n') {
                        // Maintain line/column counters.
                        line_number++;
                        line_start = c+1;
                    }
                    data += *c;
                }
                c++;  // Advance beyond the '.
                kind = Token::STRING_SINGLE;
            }
            break;

            // Keywords
            default:
            if (is_identifier_first(*c)) {
                std::string id;
                for (; is_identifier(*c); ++c)
                    id += *c;
                if (id == "assert") {
                    kind = Token::ASSERT;
                } else if (id == "else") {
                    kind = Token::ELSE;
                } else if (id == "error") {
                    kind = Token::ERROR;
                } else if (id == "false") {
                    kind = Token::FALSE;
                } else if (id == "for") {
                    kind = Token::FOR;
                } else if (id == "function") {
                    kind = Token::FUNCTION;
                } else if (id == "if") {
                    kind = Token::IF;
                } else if (id == "import") {
                    kind = Token::IMPORT;
                } else if (id == "importstr") {
                    kind = Token::IMPORTSTR;
                } else if (id == "in") {
                    kind = Token::IN;
                } else if (id == "local") {
                    kind = Token::LOCAL;
                } else if (id == "null") {
                    kind = Token::NULL_LIT;
                } else if (id == "self") {
                    kind = Token::SELF;
                } else if (id == "super") {
                    kind = Token::SUPER;
                } else if (id == "tailstrict") {
                    kind = Token::TAILSTRICT;
                } else if (id == "then") {
                    kind = Token::THEN;
                } else if (id == "true") {
                    kind = Token::TRUE;
                } else {
                    // Not a keyword, must be an identifier.
                    kind = Token::IDENTIFIER;
                }
                data = id;

            } else if (is_symbol(*c) || *c == '#') {

                // Single line C++ and Python style comments.
                if (*c == '#' || (*c == '/' && *(c+1) == '/')) {
                    std::vector<std::string> comment(1);
                    unsigned blanks;
                    unsigned indent;
                    lex_until_newline(c, comment[0], blanks, indent, line_start, line_number);
                    auto kind = fresh_line ? FodderElement::PARAGRAPH : FodderElement::LINE_END;
                    fodder.emplace_back(kind, blanks, indent, comment);
                    fresh_line = true;
                    continue;  // We've not got a token, just fodder, so keep scanning.
                }

                // Multi-line C style comment.
                if (*c == '/' && *(c+1) == '*') {

                    unsigned margin = c - line_start;
 
                    const char *initial_c = c;
                    c += 2;  // Avoid matching /*/: skip the /* before starting the search for */.

                    while (!(*c == '*' && *(c+1) == '/')) {
                        if (*c == '\0') {
                            auto msg = "Multi-line comment has no terminating */.";
                            throw StaticError(filename, begin, msg);
                        }
                        if (*c == '\n') {
                            // Just keep track of the line / column counters.
                            line_number++;
                            line_start = c+1;
                        }
                        ++c;
                    }
                    c += 2;  // Move the pointer to the char after the closing '/'.

                    std::string comment(initial_c, c - initial_c);  // Includes the "/*" and "*/".

                    // Lex whitespace after comment
                    unsigned new_lines_after, indent_after;
                    lex_ws(c, new_lines_after, indent_after, line_start, line_number);
                    std::vector<std::string> lines;
                    if (comment.find('\n') >= comment.length()) {
                        // Comment looks like /* foo */
                        lines.push_back(comment);
                        fodder.emplace_back(FodderElement::INTERSTITIAL, 0, 0, lines);
                        if (new_lines_after > 0) {
                            fodder.emplace_back(FodderElement::LINE_END, new_lines_after - 1,
                                                indent_after, EMPTY);
                            fresh_line = true;
                        }
                    } else {
                        lines = line_split(comment, margin);
                        assert(lines[0][0] == '/');
                        // Little hack to support PARAGRAPHs with * down the LHS:
                        // Add a space to lines that start with a '*'
                        bool all_star = true;
                        for (auto &l : lines) {
                            if (l[0] != '*')
                                all_star = false;
                        }
                        if (all_star) {
                            for (auto &l : lines) {
                                if (l[0] == '*') l = " " + l;
                            }
                        }
                        if (new_lines_after == 0) {
                            // Ensure a line end after the paragraph.
                            new_lines_after = 1;
                            indent_after = 0;
                        }
                        if (!fresh_line)
                            // Ensure a line end before the comment.
                            fodder.emplace_back(FodderElement::LINE_END, 0, 0, EMPTY);
                        fodder.emplace_back(FodderElement::PARAGRAPH, new_lines_after - 1,
                                            indent_after, lines);
                        fresh_line = true;
                    }
                    continue;  // We've not got a token, just fodder, so keep scanning.
                }

                // Text block
                if (*c == '|' && *(c+1) == '|' && *(c+2) == '|' && *(c+3) == '\n') {
                    std::stringstream block;
                    c += 4; // Skip the "|||\n"
                    line_number++;
                    // Skip any blank lines at the beginning of the block.
                    while (*c == '\n') {
                        line_number++;
                        ++c;
                        block << '\n';
                    }
                    line_start = c;
                    const char *first_line = c;
                    int ws_chars = whitespace_check(first_line, c);
                    string_block_indent = std::string(first_line, ws_chars);
                    if (ws_chars == 0) {
                        auto msg = "Text block's first line must start with whitespace.";
                        throw StaticError(filename, begin, msg);
                    }
                    while (true) {
                        assert(ws_chars > 0);
                        // Read up to the \n
                        for (c = &c[ws_chars]; *c != '\n' ; ++c) {
                            if (*c == '\0')
                                throw StaticError(filename, begin, "Unexpected EOF");
                            block << *c;
                        }
                        // Add the \n
                        block << '\n';
                        ++c;
                        line_number++;
                        line_start = c;
                        // Skip any blank lines
                        while (*c == '\n') {
                            line_number++;
                            ++c;
                            block << '\n';
                        }
                        // Examine next line
                        ws_chars = whitespace_check(first_line, c);
                        if (ws_chars == 0) {
                            // End of text block
                            // Skip over any whitespace
                            while (*c == ' ' || *c == '\t') {
                                string_block_term_indent += *c;
                                ++c;
                            }
                            // Expect |||
                            if (!(*c == '|' && *(c+1) == '|' && *(c+2) == '|')) {
                                auto msg = "Text block not terminated with |||";
                                throw StaticError(filename, begin, msg);
                            }
                            c += 3;  // Leave after the last |
                            data = block.str();
                            kind = Token::STRING_BLOCK;
                            break;  // Out of the while loop.
                        }
                    }

                    break;  // Out of the switch.
                }

                const char *operator_begin = c;
                for (; is_symbol(*c) ; ++c) {
                    // Not allowed // in operators
                    if (*c == '/' && *(c+1) == '/') break;
                    // Not allowed /* in operators
                    if (*c == '/' && *(c+1) == '*') break;
                    // Not allowed ||| in operators
                    if (*c == '|' && *(c+1) == '|' && *(c+2) == '|') break;
                }
                // Not allowed to end with a + - ~ ! unless a single char.
                // So, wind it back if we need to (but not too far).
                while (c > operator_begin + 1
                       && (*(c-1) == '+' || *(c-1) == '-' || *(c-1) == '~' || *(c-1) == '!')) {
                    c--;
                }
                data += std::string(operator_begin, c);
                if (data == "$") {
                    kind = Token::DOLLAR;
                    data = "";
                } else {
                    kind = Token::OPERATOR;
                }
            } else {
                std::stringstream ss;
                ss << "Could not lex the character ";
                auto uc = (unsigned char)(*c);
                if (*c < 32)
                    ss << "code " << unsigned(uc);
                else
                    ss << "'" << *c << "'";
                throw StaticError(filename, begin, ss.str());
            }
        }

        Location end(line_number, c - line_start);
        r.emplace_back(kind, fodder, data, string_block_indent, string_block_term_indent,
                       LocationRange(filename, begin, end));
        fodder.clear();
        fresh_line = false;
    }

    Location end(line_number, c - line_start + 1);
    r.emplace_back(Token::END_OF_FILE, fodder, "", "", "", LocationRange(filename, end, end));
    return r;
}
示例#7
0
std::string new_artifact()
{
    if (one_in(2)) { // Generate a "tool" artifact

        it_artifact_tool *art = new it_artifact_tool();
        int form = rng(ARTTOOLFORM_NULL + 1, NUM_ARTTOOLFORMS - 1);

        artifact_tool_form_datum *info = &(artifact_tool_form_data[form]);
        art->create_name(info->name);
        art->color = info->color;
        art->sym = info->sym;
        art->materials.push_back(info->material);
        art->volume = rng(info->volume_min, info->volume_max);
        art->weight = rng(info->weight_min, info->weight_max);
        // Set up the basic weapon type
        artifact_weapon_datum *weapon = &(artifact_weapon_data[info->base_weapon]);
        art->melee_dam = rng(weapon->bash_min, weapon->bash_max);
        art->melee_cut = rng(weapon->cut_min, weapon->cut_max);
        art->m_to_hit = rng(weapon->to_hit_min, weapon->to_hit_max);
        if( weapon->tag != "" ) {
            art->item_tags.insert(weapon->tag);
        }
        // Add an extra weapon perhaps?
        if (one_in(2)) {
            int select = rng(0, 2);
            if (info->extra_weapons[select] != ARTWEAP_NULL) {
                weapon = &(artifact_weapon_data[ info->extra_weapons[select] ]);
                art->volume += weapon->volume;
                art->weight += weapon->weight;
                art->melee_dam += rng(weapon->bash_min, weapon->bash_max);
                art->melee_cut += rng(weapon->cut_min, weapon->cut_max);
                art->m_to_hit += rng(weapon->to_hit_min, weapon->to_hit_max);
                if( weapon->tag != "" ) {
                    art->item_tags.insert(weapon->tag);
                }
                std::stringstream newname;
                newname << weapon->adjective << " " << info->name;
                art->create_name(newname.str());
            }
        }
        // CHOP is a sword, STAB is a dagger
        if( art->item_tags.count( "CHOP" ) > 0 ) {
            art->item_tags.insert( "SHEATH_SWORD" );
        }
        if( art->item_tags.count( "STAB" ) > 0 ) {
            art->item_tags.insert( "SHEATH_KNIFE" );
        }
        art->description = string_format(
                               _("This is the %s.\nIt is the only one of its kind.\nIt may have unknown powers; try activating them."),
                               art->nname(1).c_str());

        // Finally, pick some powers
        art_effect_passive passive_tmp = AEP_NULL;
        art_effect_active active_tmp = AEA_NULL;
        int num_good = 0, num_bad = 0, value = 0;
        std::vector<art_effect_passive> good_effects = fill_good_passive();
        std::vector<art_effect_passive> bad_effects = fill_bad_passive();

        // Wielded effects first
        while (!good_effects.empty() && !bad_effects.empty() &&
               num_good < 3 && num_bad < 3 &&
               (num_good < 1 || num_bad < 1 || one_in(num_good + 1) ||
                one_in(num_bad + 1) || value > 1)) {
            if (value < 1 && one_in(2)) { // Good
                int index = rng(0, good_effects.size() - 1);
                passive_tmp = good_effects[index];
                good_effects.erase(good_effects.begin() + index);
                num_good++;
            } else if (!bad_effects.empty()) { // Bad effect
                int index = rng(0, bad_effects.size() - 1);
                passive_tmp = bad_effects[index];
                bad_effects.erase(bad_effects.begin() + index);
                num_bad++;
            }
            value += passive_effect_cost[passive_tmp];
            art->effects_wielded.push_back(passive_tmp);
        }
        // Next, carried effects; more likely to be just bad
        num_good = 0;
        num_bad = 0;
        value = 0;
        good_effects = fill_good_passive();
        bad_effects = fill_bad_passive();
        while (one_in(2) && !good_effects.empty() && !bad_effects.empty() &&
               num_good < 3 && num_bad < 3 &&
               ((num_good > 2 && one_in(num_good + 1)) || num_bad < 1 ||
                one_in(num_bad + 1) || value > 1)) {
            if (value < 1 && one_in(3)) { // Good
                int index = rng(0, good_effects.size() - 1);
                passive_tmp = good_effects[index];
                good_effects.erase(good_effects.begin() + index);
                num_good++;
            } else { // Bad effect
                int index = rng(0, bad_effects.size() - 1);
                passive_tmp = bad_effects[index];
                bad_effects.erase(bad_effects.begin() + index);
                num_bad++;
            }
            value += passive_effect_cost[passive_tmp];
            art->effects_carried.push_back(passive_tmp);
        }
        // Finally, activated effects; not necessarily good or bad
        num_good = 0;
        num_bad = 0;
        value = 0;
        art->def_charges = 0;
        art->max_charges = 0;
        std::vector<art_effect_active> good_a_effects = fill_good_active();
        std::vector<art_effect_active> bad_a_effects = fill_bad_active();
        while (!good_a_effects.empty() && !bad_a_effects.empty() &&
               num_good < 3 && num_bad < 3 &&
               (value > 3 || (num_bad > 0 && num_good == 0) ||
                !one_in(3 - num_good) || !one_in(3 - num_bad))) {
            if (!one_in(3) && value <= 1) { // Good effect
                int index = rng(0, good_a_effects.size() - 1);
                active_tmp = good_a_effects[index];
                good_a_effects.erase(good_a_effects.begin() + index);
                num_good++;
                value += active_effect_cost[active_tmp];
            } else { // Bad effect
                int index = rng(0, bad_a_effects.size() - 1);
                active_tmp = bad_a_effects[index];
                bad_a_effects.erase(bad_a_effects.begin() + index);
                num_bad++;
                value += active_effect_cost[active_tmp];
            }
            art->effects_activated.push_back(active_tmp);
            art->max_charges += rng(1, 3);
        }
        art->def_charges = art->max_charges;
        art->rand_charges.push_back(art->max_charges);
        // If we have charges, pick a recharge mechanism
        if (art->max_charges > 0) {
            art->charge_type = art_charge( rng(ARTC_NULL + 1, NUM_ARTCS - 1) );
        }
        if (one_in(8) && num_bad + num_good >= 4) {
            art->charge_type = ARTC_NULL;    // 1 in 8 chance that it can't recharge!
        }
        item_controller->add_item_type( art );
        return art->id;
    } else { // Generate an armor artifact

        it_artifact_armor *art = new it_artifact_armor();
        int form = rng(ARTARMFORM_NULL + 1, NUM_ARTARMFORMS - 1);
        artifact_armor_form_datum *info = &(artifact_armor_form_data[form]);

        art->create_name(info->name);
        art->sym = '['; // Armor is always [
        art->color = info->color;
        art->materials.push_back(info->material);
        art->volume = info->volume;
        art->weight = info->weight;
        art->melee_dam = info->melee_bash;
        art->melee_cut = info->melee_cut;
        art->m_to_hit = info->melee_hit;
        art->covers = info->covers;
        art->encumber = info->encumb;
        art->coverage = info->coverage;
        art->thickness = info->thickness;
        art->env_resist = info->env_resist;
        art->warmth = info->warmth;
        art->storage = info->storage;
        std::stringstream description;
        description << string_format(info->plural ?
                                     _("This is the %s.\nThey are the only ones of their kind.") :
                                     _("This is the %s.\nIt is the only one of its kind."),
                                     art->nname(1).c_str());

        // Modify the armor further
        if (!one_in(4)) {
            int index = rng(0, 4);
            if (info->available_mods[index] != ARMORMOD_NULL) {
                artifact_armor_mod mod = info->available_mods[index];
                artifact_armor_form_datum *modinfo = &(artifact_armor_mod_data[mod]);
                if (modinfo->volume >= 0 || art->volume > unsigned(abs(modinfo->volume))) {
                    art->volume += modinfo->volume;
                } else {
                    art->volume = 1;
                }

                if (modinfo->weight >= 0 || art->weight > unsigned(abs(modinfo->weight))) {
                    art->weight += modinfo->weight;
                } else {
                    art->weight = 1;
                }

                art->encumber += modinfo->encumb;

                if (modinfo->coverage > 0 || art->coverage > abs(modinfo->coverage)) {
                    art->coverage += modinfo->coverage;
                } else {
                    art->coverage = 0;
                }

                if (modinfo->thickness > 0 || art->thickness > abs(modinfo->thickness)) {
                    art->thickness += modinfo->thickness;
                } else {
                    art->thickness = 0;
                }

                if (modinfo->env_resist > 0 || art->env_resist > abs(modinfo->env_resist)) {
                    art->env_resist += modinfo->env_resist;
                } else {
                    art->env_resist = 0;
                }
                art->warmth += modinfo->warmth;

                if (modinfo->storage > 0 || art->storage > abs(modinfo->storage)) {
                    art->storage += modinfo->storage;
                } else {
                    art->storage = 0;
                }

                description << string_format(info->plural ?
                                             _("\nThey are %s") :
                                             _("\nIt is %s"),
                                             modinfo->name.c_str());
            }
        }

        art->description = description.str();

        // Finally, pick some effects
        int num_good = 0, num_bad = 0, value = 0;
        art_effect_passive passive_tmp = AEP_NULL;
        std::vector<art_effect_passive> good_effects = fill_good_passive();
        std::vector<art_effect_passive> bad_effects = fill_bad_passive();

        while (!good_effects.empty() && !bad_effects.empty() &&
               num_good < 3 && num_bad < 3 &&
               (num_good < 1 || one_in(num_good * 2) || value > 1 ||
                (num_bad < 3 && !one_in(3 - num_bad)))) {
            if (value < 1 && one_in(2)) { // Good effect
                int index = rng(0, good_effects.size() - 1);
                passive_tmp = good_effects[index];
                good_effects.erase(good_effects.begin() + index);
                num_good++;
            } else { // Bad effect
                int index = rng(0, bad_effects.size() - 1);
                passive_tmp = bad_effects[index];
                bad_effects.erase(bad_effects.begin() + index);
                num_bad++;
            }
            value += passive_effect_cost[passive_tmp];
            art->effects_worn.push_back(passive_tmp);
        }
        item_controller->add_item_type( art );
        return art->id;
    }
}
示例#8
0
/**
 * Whenever a hazard collides with an entity, this function resolves the effect
 * Called by HazardManager
 *
 * Returns false on miss
 */
bool Entity::takeHit(const Hazard &h) {

	//check if this enemy should be affected by this hazard based on the category
	if(!powers->powers[h.power_index].target_categories.empty() && !stats.hero) {
		//the power has a target category requirement, so if it doesnt match, dont continue
		bool match_found = false;
		for (unsigned int i=0; i<stats.categories.size(); i++) {
			if(std::find(powers->powers[h.power_index].target_categories.begin(), powers->powers[h.power_index].target_categories.end(), stats.categories[i]) != powers->powers[h.power_index].target_categories.end()) {
				match_found = true;
			}
		}
		if(!match_found)
			return false;
	}

	//if the target is already dead, they cannot be hit
	if ((stats.cur_state == ENEMY_DEAD || stats.cur_state == ENEMY_CRITDEAD) && !stats.hero)
		return false;

	if(stats.cur_state == AVATAR_DEAD && stats.hero)
		return false;

	//if the target is an enemy and they are not already in combat, activate a beacon to draw other enemies into battle
	if (!stats.in_combat && !stats.hero && !stats.hero_ally) {
		stats.join_combat = true;
		stats.in_combat = true;
		powers->activate(stats.power_index[BEACON], &stats, stats.pos); //emit beacon
	}

	// exit if it was a beacon (to prevent stats.targeted from being set)
	if (powers->powers[h.power_index].beacon) return false;

	// prepare the combat text
	CombatText *combat_text = comb;

	// if it's a miss, do nothing
	int accuracy = h.accuracy;
	if(powers->powers[h.power_index].mod_accuracy_mode == STAT_MODIFIER_MODE_MULTIPLY)
		accuracy = accuracy * powers->powers[h.power_index].mod_accuracy_value / 100;
	else if(powers->powers[h.power_index].mod_accuracy_mode == STAT_MODIFIER_MODE_ADD)
		accuracy += powers->powers[h.power_index].mod_accuracy_value;
	else if(powers->powers[h.power_index].mod_accuracy_mode == STAT_MODIFIER_MODE_ABSOLUTE)
		accuracy = powers->powers[h.power_index].mod_accuracy_value;

	int avoidance = 0;
	if(!powers->powers[h.power_index].trait_avoidance_ignore) {
		avoidance = stats.get(STAT_AVOIDANCE);
		if (stats.effects.triggered_block) avoidance *= 2;
	}

	int true_avoidance = 100 - (accuracy + 25 - avoidance);
	//if we are using an absolute accuracy, offset the constant 25 added to the accuracy
	if(powers->powers[h.power_index].mod_accuracy_mode == STAT_MODIFIER_MODE_ABSOLUTE)
		true_avoidance += 25;
	clampFloor(true_avoidance, MIN_AVOIDANCE);
	clampCeil(true_avoidance, MAX_AVOIDANCE);

	if (percentChance(true_avoidance)) {
		combat_text->addMessage(msg->get("miss"), stats.pos, COMBAT_MESSAGE_MISS);
		return false;
	}

	// calculate base damage
	int dmg = randBetween(h.dmg_min, h.dmg_max);

	if(powers->powers[h.power_index].mod_damage_mode == STAT_MODIFIER_MODE_MULTIPLY)
		dmg = dmg * powers->powers[h.power_index].mod_damage_value_min / 100;
	else if(powers->powers[h.power_index].mod_damage_mode == STAT_MODIFIER_MODE_ADD)
		dmg += powers->powers[h.power_index].mod_damage_value_min;
	else if(powers->powers[h.power_index].mod_damage_mode == STAT_MODIFIER_MODE_ABSOLUTE)
		dmg = randBetween(powers->powers[h.power_index].mod_damage_value_min, powers->powers[h.power_index].mod_damage_value_max);

	// apply elemental resistance
	if (h.trait_elemental >= 0 && unsigned(h.trait_elemental) < stats.vulnerable.size()) {
		unsigned i = h.trait_elemental;
		int vulnerable = stats.vulnerable[i];
		clampFloor(vulnerable,MIN_RESIST);
		if (stats.vulnerable[i] < 100)
			clampCeil(vulnerable,MAX_RESIST);
		dmg = (dmg * vulnerable) / 100;
	}

	if (!h.trait_armor_penetration) { // armor penetration ignores all absorption
		// substract absorption from armor
		int absorption = randBetween(stats.get(STAT_ABS_MIN), stats.get(STAT_ABS_MAX));

		if (stats.effects.triggered_block) {
			absorption += absorption + stats.get(STAT_ABS_MAX); // blocking doubles your absorb amount
		}

		if (absorption > 0 && dmg > 0) {
			int abs = absorption;
			if ((abs*100)/dmg < MIN_BLOCK)
				absorption = (dmg * MIN_BLOCK) /100;
			if ((abs*100)/dmg > MAX_BLOCK)
				absorption = (dmg * MAX_BLOCK) /100;
			if ((abs*100)/dmg < MIN_ABSORB && !stats.effects.triggered_block)
				absorption = (dmg * MIN_ABSORB) /100;
			if ((abs*100)/dmg > MAX_ABSORB && !stats.effects.triggered_block)
				absorption = (dmg * MAX_ABSORB) /100;

			// Sometimes, the absorb limits cause absorbtion to drop to 1
			// This could be confusing to a player that has something with an absorb of 1 equipped
			// So we round absorption up in this case
			if (absorption == 0) absorption = 1;
		}

		dmg = dmg - absorption;
		if (dmg <= 0) {
			dmg = 0;
			if (h.trait_elemental < 0) {
				if (stats.effects.triggered_block && MAX_BLOCK < 100) dmg = 1;
				else if (!stats.effects.triggered_block && MAX_ABSORB < 100) dmg = 1;
			}
			else {
				if (MAX_RESIST < 100) dmg = 1;
			}
			play_sfx_block = true;
			if (activeAnimation->getName() == "block")
				resetActiveAnimation();
		}
	}

	// check for crits
	int true_crit_chance = h.crit_chance;

	if(powers->powers[h.power_index].mod_crit_mode == STAT_MODIFIER_MODE_MULTIPLY)
		true_crit_chance = true_crit_chance * powers->powers[h.power_index].mod_crit_value / 100;
	else if(powers->powers[h.power_index].mod_crit_mode == STAT_MODIFIER_MODE_ADD)
		true_crit_chance += powers->powers[h.power_index].mod_crit_value;
	else if(powers->powers[h.power_index].mod_crit_mode == STAT_MODIFIER_MODE_ABSOLUTE)
		true_crit_chance = powers->powers[h.power_index].mod_crit_value;

	if (stats.effects.stun || stats.effects.speed < 100)
		true_crit_chance += h.trait_crits_impaired;

	bool crit = percentChance(true_crit_chance);
	if (crit) {
		dmg = dmg + h.dmg_max;
		if(!stats.hero)
			mapr->shaky_cam_ticks = MAX_FRAMES_PER_SEC/2;
	}

	if(stats.hero)
		combat_text->addMessage(dmg, stats.pos, COMBAT_MESSAGE_TAKEDMG);
	else {
		if(crit)
			combat_text->addMessage(dmg, stats.pos, COMBAT_MESSAGE_CRIT);
		else
			combat_text->addMessage(dmg, stats.pos, COMBAT_MESSAGE_GIVEDMG);
	}

	// temporarily save the current HP for calculating HP/MP steal on final blow
	int prev_hp = stats.hp;

	// apply damage
	stats.takeDamage(dmg);

	// after effects
	if (dmg > 0) {

		// damage always breaks stun
		stats.effects.removeEffectType(EFFECT_STUN);

		if (stats.hp > 0) {
			powers->effect(&stats, h.src_stats, h.power_index,h.source_type);
		}

		if (!stats.effects.immunity) {
			if (h.hp_steal != 0) {
				int steal_amt = (std::min(dmg, prev_hp) * h.hp_steal) / 100;
				if (steal_amt == 0) steal_amt = 1;
				combat_text->addMessage(msg->get("+%d HP",steal_amt), h.src_stats->pos, COMBAT_MESSAGE_BUFF);
				h.src_stats->hp = std::min(h.src_stats->hp + steal_amt, h.src_stats->get(STAT_HP_MAX));
			}
			if (h.mp_steal != 0) {
				int steal_amt = (std::min(dmg, prev_hp) * h.mp_steal) / 100;
				if (steal_amt == 0) steal_amt = 1;
				combat_text->addMessage(msg->get("+%d MP",steal_amt), h.src_stats->pos, COMBAT_MESSAGE_BUFF);
				h.src_stats->mp = std::min(h.src_stats->mp + steal_amt, h.src_stats->get(STAT_MP_MAX));
			}
		}
	}

	// post effect power
	if (h.post_power > 0 && dmg > 0) {
		powers->activate(h.post_power, h.src_stats, stats.pos);
	}

	// loot
	if (dmg > 0 && !h.loot.empty()) {
		for (unsigned i=0; i<h.loot.size(); i++) {
			powers->loot.push_back(h.loot[i]);
			powers->loot.back().x = (int)stats.pos.x;
			powers->loot.back().y = (int)stats.pos.y;
		}
	}

	// interrupted to new state
	if (dmg > 0) {
		bool chance_poise = percentChance(stats.get(STAT_POISE));

		if(stats.hp <= 0) {
			stats.effects.triggered_death = true;
			if(stats.hero)
				stats.cur_state = AVATAR_DEAD;
			else {
				doRewards(h.source_type);
				if (crit)
					stats.cur_state = ENEMY_CRITDEAD;
				else
					stats.cur_state = ENEMY_DEAD;
				mapr->collider.unblock(stats.pos.x,stats.pos.y);
			}
		}
		// don't go through a hit animation if stunned
		else if (!stats.effects.stun && !chance_poise) {
			play_sfx_hit = true;

			if(!chance_poise && stats.cooldown_hit_ticks == 0) {
				if(stats.hero)
					stats.cur_state = AVATAR_HIT;
				else
					stats.cur_state = ENEMY_HIT;
				stats.cooldown_hit_ticks = stats.cooldown_hit;

				if (stats.untransform_on_hit)
					stats.transform_duration = 0;
			}
			// roll to see if the enemy's ON_HIT power is casted
			if (percentChance(stats.power_chance[ON_HIT])) {
				powers->activate(stats.power_index[ON_HIT], &stats, stats.pos);
			}
		}
		// just play the hit sound
		else
			play_sfx_hit = true;
	}

	return true;
}
示例#9
0
bool TestImporter::parseDDSG( QString filename )
{
    QString outputPrefix = fileInDirectory( m_outputDirectory, "Test Importer" );

    FileStream edgesData( outputPrefix + "_mapped_edges" );
    FileStream routingCoordinatesData( outputPrefix + "_routing_coordinates" );
    FileStream edgePathsData( outputPrefix + "_paths" );
    FileStream wayRefsData( outputPrefix + "_way_refs" );
    FileStream wayTypesData( outputPrefix + "_way_types" );
    FileStream penaltyData( outputPrefix + "_penalties" );
    FileStream boundingBoxData( outputPrefix + "_bounding_box" );

    if ( !edgesData.open( QIODevice::WriteOnly ) )
        return false;
    if ( !routingCoordinatesData.open( QIODevice::WriteOnly ) )
        return false;
    if ( !edgePathsData.open( QIODevice::WriteOnly ) )
        return false;
    if ( !wayRefsData.open( QIODevice::WriteOnly ) )
        return false;
    if ( !wayTypesData.open( QIODevice::WriteOnly ) )
        return false;
    if ( !penaltyData.open( QIODevice::WriteOnly ) )
        return false;
    if ( !boundingBoxData.open( QIODevice::WriteOnly ) )
        return false;

    QFile ddsgFile( filename );
    if ( !openQFile( &ddsgFile, QIODevice::ReadOnly ) )
        return false;
    QTextStream inputStream( &ddsgFile );

    QString id;
    inputStream >> id;
    if ( id != "d" ) {
        qCritical() << "Not a ddsg file";
        return false;
    }

    wayRefsData << "";
    wayTypesData << "";

    unsigned nodes;
    unsigned edges;
    inputStream >> nodes >> edges;
    std::vector< SimpleEdge > simpleEdges;
    qDebug() << "Test Importer:" << "reading" << nodes << " nodes and" << edges << "edges";
    for ( unsigned i = 0; i < edges; i++ ) {
        unsigned from;
        unsigned to;
        unsigned weight;
        unsigned direction;
        inputStream >> from >> to >> weight >> direction;
        if ( direction == 3 )
            continue;
        if ( from == to )
            continue;
        SimpleEdge newEdge;
        newEdge.source = from;
        newEdge.target = to;
        newEdge.bidirectional = direction == 1;
        newEdge.distance = weight / 10.0;
        newEdge.forward = direction == 1 || direction == 0;
        newEdge.backward = direction == 2 || direction == 0;
        if ( from > to ) {
            std::swap( newEdge.source, newEdge.target );
            std::swap( newEdge.forward, newEdge.backward );
        }
        simpleEdges.push_back( newEdge );
    }

    std::sort( simpleEdges.begin(), simpleEdges.end(), SimpleEdge::sortToMerge );
    unsigned edgesLeft = 1;
    for ( unsigned i = 1; i < simpleEdges.size(); i++ ) {
        SimpleEdge& edge = simpleEdges[i];
        SimpleEdge& otherEdge = simpleEdges[edgesLeft - 1];
        simpleEdges[edgesLeft++] = edge;
        if ( edge.source != otherEdge.source )
            continue;
        if ( edge.target != otherEdge.target )
            continue;
        if ( edge.distance != otherEdge.distance )
            continue;
        edgesLeft--;
        otherEdge.forward |= edge.forward;
        otherEdge.backward |= edge.backward;
    }
    simpleEdges.resize( edgesLeft );

    unsigned biEdges = 0;
    for ( unsigned i = 0; i < simpleEdges.size(); i++ ) {
        if ( !simpleEdges[i].forward ) {
            std::swap( simpleEdges[i].source, simpleEdges[i].target );
            std::swap( simpleEdges[i].forward, simpleEdges[i].backward );
        }
        simpleEdges[i].bidirectional = simpleEdges[i].forward && simpleEdges[i].backward;
        biEdges += simpleEdges[i].bidirectional ? 1 : 0;
        assert( simpleEdges[i].forward );
    }

    qDebug() << "Test Importer:" << biEdges << "bidirectional edges";
    qDebug() << "Test Importer:" << edges - biEdges * 2 << "unidirectional edges";
    qDebug() << "Test Importer:" << edges - edgesLeft << "edges removed";

    std::sort( simpleEdges.begin(), simpleEdges.end() );

    std::vector< char > in( nodes, 0 );
    std::vector< char > out( nodes, 0 );
    std::vector< char > bi( nodes, 0 );
    qDebug() << "Test Importer:" << "writing" << simpleEdges.size() << "edges";
    for ( unsigned i = 0; i < simpleEdges.size(); i++ ) {
        edgesData << simpleEdges[i].source << simpleEdges[i].target << simpleEdges[i].bidirectional << simpleEdges[i].distance;
        edgesData << unsigned( 0 ) << unsigned( 0 ) << unsigned ( 0 ); // name
        edgesData << unsigned( 0 ) << unsigned( 0 ); // path
        edgesData << unsigned( 0 ) << unsigned( 0 ); // address
        edgesData << qint8( out[simpleEdges[i].source]++ ) << qint8( in[simpleEdges[i].target]++ );
        if ( simpleEdges[i].bidirectional ) {
            in[simpleEdges[i].source]++;
            out[simpleEdges[i].target]++;
            bi[simpleEdges[i].source]++;
            bi[simpleEdges[i].target]++;
            assert( in[simpleEdges[i].source] == out[simpleEdges[i].source] );
            assert( in[simpleEdges[i].target] == out[simpleEdges[i].target] );
        }
    }

    long long penalties = 0;
    long long uturns = 0;
    qDebug() << "Test Importer:" << "forbid uturns:" << m_settings.forbidUTurn;
    qDebug() << "Test Importer:" << "uturn penalty:" << m_settings.uTurnPenalty;
    for ( unsigned i = 0; i < nodes; i++ ) {
        routingCoordinatesData << unsigned( 0 ) << unsigned( 0 );
        penaltyData << unsigned( in[i] ) << unsigned( out[i] );
        for ( int from = 0; from < in[i]; from++ ) {
            for ( int to = 0; to < out[i]; to++ ) {
                double penalty = 0;
                if ( from == to && from < bi[i] ) {
                    uturns++;
                    if ( m_settings.forbidUTurn )
                        penalty = -1;
                    else
                        penalty = m_settings.uTurnPenalty;
                }
                penaltyData << penalty;
                penalties++;
            }
        }
    }
    qDebug() << "Test Importer:" << "wrote" << penalties << "penalties";
    qDebug() << "Test Importer:" << uturns << "uturns";

    return true;
}
示例#10
0
void TestAARHUD::UpdateHighDetailData(int baseWidth, float& curYPos)
{
   if (*mHUDState == HUDState::MAXIMUM)
   {
      char clin[HUDCONTROLMAXTEXTSIZE]; // general buffer to print
      char lastTagStr[HUDCONTROLMAXTEXTSIZE];
      char numTagsStr[HUDCONTROLMAXTEXTSIZE];
      char lastFrameStr[HUDCONTROLMAXTEXTSIZE];
      char numFramesStr[HUDCONTROLMAXTEXTSIZE];

      // Determine num tags, num frames, etc...
      if (dtGame::LogStateEnumeration::LOGGER_STATE_IDLE == mLogController->GetLastKnownStatus().GetStateEnum())
      {
         snprintf(numTagsStr, HUDCONTROLMAXTEXTSIZE, "Num Tags: NA");
         snprintf(lastTagStr, HUDCONTROLMAXTEXTSIZE, "  (Last: NA)");
         snprintf(numFramesStr, HUDCONTROLMAXTEXTSIZE, "Num Frames: NA");
         snprintf(lastFrameStr, HUDCONTROLMAXTEXTSIZE, "  (Last: NA)");
      }
      else // compute data needed for both LOGGER_STATE_PLAYBACK or LOGGER_STATE_RECORD
      {
         // TAGS - num tags and last tag
         const std::vector<dtGame::LogTag> tags = mLogController->GetLastKnownTagList();
         snprintf(numTagsStr, HUDCONTROLMAXTEXTSIZE, "Num Tags: %u", unsigned(tags.size()));
         if (tags.size() > 0)
         {
            snprintf(lastTagStr, HUDCONTROLMAXTEXTSIZE, "  (Last: None)");
            for (unsigned int i = 0; i < tags.size(); i ++)
            {
               const dtGame::LogTag tag = tags[i];
               //double tagTime = tags[i].GetSimTimeStamp();
               //double simTime = mClientGM->GetSimulationTime();

               if (tags[i].GetSimTimeStamp() <= GetGameManager()->GetSimulationTime())
               {
                  std::string temp = (tags[i]).GetName();
                  snprintf(lastTagStr, HUDCONTROLMAXTEXTSIZE, " (%s)", temp.c_str());//(tags[tags.size()-1]).GetName());
               }
            }
         }
         else
         {
            snprintf(lastTagStr, HUDCONTROLMAXTEXTSIZE, " (----)");
         }

         // FRAMES - num frames and last frame
         const std::vector<dtGame::LogKeyframe> frames = mLogController->GetLastKnownKeyframeList();
         snprintf(numFramesStr, HUDCONTROLMAXTEXTSIZE, "Num Frames: %u", unsigned(frames.size()));
         if (frames.size() > 0)
         {
            snprintf(lastFrameStr, HUDCONTROLMAXTEXTSIZE, "  (Last: None)");
            for (unsigned int i = 0; i < frames.size(); i ++)
            {
               if (frames[i].GetSimTimeStamp() <= GetGameManager()->GetSimulationTime())
               {
                  std::string temp = (frames[i]).GetName();
                  snprintf(lastFrameStr, HUDCONTROLMAXTEXTSIZE, " (%s)", temp.c_str());
               }
            }
         }
         else
         {
            snprintf(lastFrameStr, HUDCONTROLMAXTEXTSIZE, " (----)");
         }
      }

      // Num Messages
      snprintf(clin, HUDCONTROLMAXTEXTSIZE, "Num Msgs: %lu", mLogController->GetLastKnownStatus().GetNumMessages());
      curYPos += (mTextHeight + 2) * 2;
      UpdateStaticText(mNumMessagesText, clin, -1.0f, -1.0f, -1.0f, baseWidth, curYPos);

      // Record Duration
      snprintf(clin, HUDCONTROLMAXTEXTSIZE, "Duration: %.2f", mLogController->GetLastKnownStatus().GetCurrentRecordDuration());
      curYPos += mTextHeight + 2;
      UpdateStaticText(mRecordDurationText, clin, -1.0f, -1.0f, -1.0f, baseWidth, curYPos);

      // Number of Tags
      curYPos += mTextHeight + 2;
      UpdateStaticText(mNumTagsText, numTagsStr, -1.0f, -1.0f, -1.0f, baseWidth, curYPos);

      // Last Tag
      curYPos += mTextHeight + 2;
      UpdateStaticText(mLastTagText, lastTagStr, -1.0f, -1.0f, -1.0f, baseWidth, curYPos);

      // Num Frames
      curYPos += mTextHeight + 2;
      UpdateStaticText(mNumFramesText, numFramesStr, -1.0f, -1.0f, -1.0f, baseWidth, curYPos);

      // Num Frames
      curYPos += mTextHeight + 2;
      UpdateStaticText(mLastFrameText, lastFrameStr, -1.0f, -1.0f, -1.0f, baseWidth, curYPos);

      // Current Log
      snprintf(clin, HUDCONTROLMAXTEXTSIZE, "LogFile: %s", mLogController->GetLastKnownStatus().GetLogFile().c_str());
      curYPos += mTextHeight + 2;
      UpdateStaticText(mCurLogText, clin, -1.0f, -1.0f, -1.0f, baseWidth, curYPos);

      // Current Map
      snprintf(clin, HUDCONTROLMAXTEXTSIZE, "CurMap: %s", mLogController->GetLastKnownStatus().GetActiveMaps()[0].c_str());
      curYPos += mTextHeight + 2;
      UpdateStaticText(mCurMapText, clin, -1.0f, -1.0f, -1.0f, baseWidth, curYPos);
   }
}
示例#11
0
void NextCommand::execute(const Arguments& args, NSDebuggingContext::Context& ctx)
{
    mili::assert_throw<NSCommon::InvalidArgumentNumbers>(0u == args.size() || args.size() == unsigned(NumberOfArgs));

    const auto instanceNmbr = (args.size() == 0u) ? ctx.getCurrentInstance() : mili::from_string<NSCommon::InstanceId>(args[InstanceNumber]);
    const auto instance = ctx.getInstance(instanceNmbr).lock();
    mili::assert_throw<NSCommon::InstanceNoLongerAlive>(bool(instance));

    auto nextTermination = instance->next();
    nextTermination.wait();
}
示例#12
0
 void LoadValueEnum(unsigned i, T value) {
   LoadValueEnum(i, unsigned(value));
 }
示例#13
0
 void functional(typename enable_if< O <= unsigned(4) >::type* = 0) {
 }
示例#14
0
bool MCCrypt_rsa_op(bool p_encrypt, RSA_KEYTYPE p_key_type, const char *p_message_in, uint32_t p_message_in_length,
			const char *p_key, uint32_t p_key_length, const char *p_passphrase,
			char *&r_message_out, uint32_t &r_message_out_length, char *&r_result, uint32_t &r_error)
{
	bool t_success = true;
	EVP_PKEY *t_key = NULL;
	RSA *t_rsa = NULL;
	int32_t t_rsa_size;
	uint8_t *t_output_buffer = NULL;
	int32_t t_output_length;

	if (!InitSSLCrypt())
	{
		t_success = false;
		MCCStringClone("error: ssl library initialization failed", r_result);
	}

	if (t_success)
	{
		if (!load_pem_key(p_key, p_key_length, p_key_type, p_passphrase, t_key))
		{
			t_success = false;
			MCCStringClone("error: invalid key", r_result);
		}
	}

	if (t_success)
	{
		t_rsa = EVP_PKEY_get1_RSA(t_key);
		if (t_rsa == NULL)
		{
			t_success = false;
			MCCStringClone("error: not an RSA key", r_result);
		}
	}

	if (t_success)
	{
		t_rsa_size = RSA_size(t_rsa);
		if (!MCMemoryAllocate(t_rsa_size, t_output_buffer))
		{
			t_success = false;
			r_error = EE_NO_MEMORY;
		}
	}
	int (*t_rsa_func)(int, const unsigned char*, unsigned char*, RSA*, int) = NULL;
	if (t_success)
	{
		if (p_encrypt)
		{
			if (p_key_type == RSAKEY_PRIVKEY)
				t_rsa_func = RSA_private_encrypt;
			else
				t_rsa_func = RSA_public_encrypt;
			if (p_message_in_length >= unsigned(t_rsa_size - 11))
			{
				t_success = false;
				MCCStringClone("error: message too large", r_result);
			}
		}
		else
		{
			if (p_key_type == RSAKEY_PRIVKEY)
				t_rsa_func = RSA_private_decrypt;
			else
				t_rsa_func = RSA_public_decrypt;
			if (p_message_in_length != t_rsa_size)
			{
				t_success = false;
				MCCStringClone("error: invalid message size", r_result);
			}
		}
	}
	if (t_success)
	{
		t_output_length = t_rsa_func(p_message_in_length, (const uint8_t*)p_message_in, t_output_buffer, t_rsa, RSA_PKCS1_PADDING);
		if (t_output_length < 0)
		{
			t_success = false;
			MCCStringClone("error: SSL operation failed", r_result);
		}
	}

	if (t_rsa != NULL)
		RSA_free(t_rsa);
	if (t_key != NULL)
		EVP_PKEY_free(t_key);

	if (t_success)
	{
		r_message_out = (char*)t_output_buffer;
		r_message_out_length = t_output_length;
	}
	else
	{
		uint32_t t_err;
		t_err = ERR_get_error();
		if (t_err)
		{
			const char *t_ssl_error = ERR_reason_error_string(t_err);
			MCCStringAppendFormat(r_result, " (SSL error: %s)", t_ssl_error);
		}
		MCMemoryDeallocate(t_output_buffer);
	}

	return t_success;
}
inline KernelProfilingInfoMask operator|(KernelProfilingInfoMask a, KernelProfilingInfoMask b) { return KernelProfilingInfoMask(unsigned(a) | unsigned(b)); }
inline ImageOperandsMask operator|(ImageOperandsMask a, ImageOperandsMask b) { return ImageOperandsMask(unsigned(a) | unsigned(b)); }
示例#17
0
bool DFInstanceLinux::find_running_copy(bool connect_anyway) {
    // find PID of DF
    TRACE << "attempting to find running copy of DF by executable name";
    QProcess *proc = new QProcess(this);
    QStringList args;
    args << "dwarfort.exe"; // 0.31.04 and earlier
    args << "Dwarf_Fortress"; // 0.31.05+
    proc->start("pidof", args);
    proc->waitForFinished(1000);
    if (proc->exitCode() == 0) { //found it
        QByteArray out = proc->readAllStandardOutput();
        QStringList str_pids = QString(out).split(" ");
        str_pids.sort();
        if(str_pids.count() > 1){
            m_pid = QInputDialog::getItem(0, tr("Warning"),tr("Multiple Dwarf Fortress processes found, please choose the process to use."),str_pids,str_pids.count()-1,false).toInt();
        }else{
            m_pid = str_pids.at(0).toInt();
        }

        m_memory_file.setFileName(QString("/proc/%1/mem").arg(m_pid));

        TRACE << "USING PID:" << m_pid;
    } else {
        QMessageBox::warning(0, tr("Warning"),
                             tr("Unable to locate a running copy of Dwarf "
                                "Fortress, are you sure it's running?"));
        LOGW << "can't find running copy";
        m_is_ok = false;
        return m_is_ok;
    }

    m_inject_addr = unsigned(-1);
    m_alloc_start = 0;
    m_alloc_end = 0;

    map_virtual_memory();

    //qDebug() << "LOWEST ADDR:" << hex << lowest_addr;


    //DUMP LIST OF MEMORY RANGES
    /*
    QPair<uint, uint> tmp_pair;
    foreach(tmp_pair, m_regions) {
        LOGD << "RANGE start:" << hex << tmp_pair.first << "end:" << tmp_pair.second;
    }*/

    VIRTADDR m_base_addr = read_addr(m_lowest_address + 0x18);
    LOGD << "base_addr:" << m_base_addr << "HEX" << hex << m_base_addr;
    m_is_ok = m_base_addr > 0;

    uint checksum = calculate_checksum();
    LOGI << "DF's checksum is" << hexify(checksum);
    if (m_is_ok) {
        m_layout = get_memory_layout(hexify(checksum).toLower(), !connect_anyway);
    }

    //Get dwarf fortress directory
    m_df_dir = QDir(QFileInfo(QString("/proc/%1/cwd").arg(m_pid)).symLinkTarget());
    LOGI << "Dwarf fortress path:" << m_df_dir.absolutePath();

    return m_is_ok || connect_anyway;
}
inline FPFastMathModeMask operator|(FPFastMathModeMask a, FPFastMathModeMask b) { return FPFastMathModeMask(unsigned(a) | unsigned(b)); }
示例#19
0
//---------------------------------------------------------
char recoding_snp_data_under_coding_and_strand(char set2_val_, gtps_container *Set2, gtps_container *Set1, unsigned snp_in_set2, unsigned snp_in_set1, std::map<char, char*>* coding_polymorphism_map_, std::map<char, char> *alleleID_reverse_, unsigned *snp_position_error, char* snp_set2_codding_error, char* snp_set1_codding_error, int *error_amount_, unsigned *found_error_amount_snp, unsigned *snp_error_counter, bool forcestrand, std::map<std::string, std::string> *complemetntary)		
{
//here is coding_polymorphism_map_->first = alleleID, coding_polymorphism_map_->second="name"
unsigned set2_val = unsigned(set2_val_);

char coding2_val=Set2->get_coding(snp_in_set2),
		 coding1_val=Set1->get_coding(snp_in_set1); 

std::string coding2=(*coding_polymorphism_map_)[coding2_val],
						coding1=(*coding_polymorphism_map_)[coding1_val];


CI iter=complemetntary->find(coding2);
bool two_nucl_is_complement=false;

if(iter != complemetntary->end())
{
two_nucl_is_complement=true;
}


//char coding2 = coding_set2_origin,
//		 coding1 = coding_set1_origin;
//
//std::string coding1=(*coding_polymorphism_map_)[coding_set1_origin],
//  					coding2=(*coding_polymorphism_map_)[coding_set2_origin];
										 
char coding2_inverse_tmp[3] = {coding2[1], coding2[0], '\0'};
std::string coding2_inverse(coding2_inverse_tmp);

std::string coding2_fliped = (*coding_polymorphism_map_)[alleleID_reverse_->find(coding2_val)->second];


char coding2_fliped_inverse_tmp[3] = {coding2_fliped[1], coding2_fliped[0], '\0'};
std::string coding2_fliped_inverse(coding2_fliped_inverse_tmp);					





char strand2 = Set2->get_strand(snp_in_set2);
char strand1 = Set1->get_strand(snp_in_set1);


//start



if(forcestrand)
	{
	if(strand1!=0 && strand2!=0)
		{
		FORCESTRAND:
		if(strand1 != strand2)
			{
			coding2 = coding2_fliped;
			}
		

		if(coding1 == coding2)
	 		{
			return set2_val;
			}
		else
	 		{
			if(coding1 == coding2_inverse)
				{
				return inverse_genotype(set2_val);
				}
			else
				{
				coding_error(snp_in_set1,
									coding1_val, coding2_val,
									snp_error_counter,
			 						snp_position_error,
								 	snp_set2_codding_error,
								 	snp_set1_codding_error,
									found_error_amount_snp,
									error_amount_);
				return 0; 	
				}	
			}
		}
	else
		{
		goto NOFORCESTRAND; //a komu seichas legko?
		}

	}
else
	{
	if(two_nucl_is_complement)
		{
		if(strand1!=0 && strand2!=0)
			{
			goto FORCESTRAND;
			}
		else
			{
			coding_error(snp_in_set1,
									coding1_val, coding2_val,
									snp_error_counter,
			 						snp_position_error,
								 	snp_set2_codding_error,
								 	snp_set1_codding_error,
									found_error_amount_snp,
									error_amount_);
			return 0;
			}
		}
	else
		{
//		std::cout<<"NOFORCESTRAND\n";
		NOFORCESTRAND:
		if(coding1 == coding2)
			{
//			std::cout<<"coding1 == coding2\n";
			return set2_val;
			}
		else
			{
			if(coding1 == coding2_inverse)
				{
//				std::cout<<"coding1 == coding2_inverse\n";
				return inverse_genotype(set2_val);
				}	
			else
				{
				if(coding1 == coding2_fliped)
					{
//					std::cout<<"coding1 == coding2_fliped\n";
					return set2_val;
					}
				else
					{
					if(coding1 == coding2_fliped_inverse)
						{
//						std::cout<<"coding1 == coding2_fliped_inverse\n";
						return inverse_genotype(set2_val);
						}
					else
						{
//						std::cout<<"error\n";
					coding_error(snp_in_set1,
											coding1_val, coding2_val,
											snp_error_counter,
											snp_position_error,
											snp_set2_codding_error,
											snp_set1_codding_error,
											found_error_amount_snp,
											error_amount_);
						return 0;
						}
					}
				}
			}
		}

	}



//}




//}




//}



//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

/*


//recode in coding in accordance with strand
if(strand1 != strand2 &&
	 (user_want_to_look_at_strand || two_nucl_is_complement) &&
	 strand1 != 0 &&
	 strand2 != 0)
	{
	made_strand_flip = true;
	coding_set2 = alleleID_reverse_->find(Set2->get_coding(snp_in_set2))->second;
	}
else
	{
	coding_set2 = coding_set2_origin;
	}




char *coding_set2_name;



if(coding_set1 != coding_set2)
	{
	//check wether is coding really same. For example coding_set1="AG" and coding_set2="GA" <- realy it is same polymorphism.
	coding_set2_name = (*coding_polymorphism_map_)[coding_set2];
	char coding_set2_name_new[3] = {coding_set2_name[1], coding_set2_name[0], '\0'};


	if(std::string(coding_set1_name) == std::string(coding_set2_name_new))
		 { 
				switch(set1_val)
					{
					case 1:
							set1_val=3;
							break;
					case 3:
							set1_val=1;
							break;
					default:
							break;
					}

		 }
		else
			{
			if(!made_strand_flip && strand1 != strand2)
		 		{
				coding_set2 = alleleID_reverse_->find(Set2->get_coding(snp_in_set2))->second;
				} //flip strand if we have not done it yet	
			
			if(coding_set1 == coding_set2) {return char(set1_val);}
			coding_set2_name = (*coding_polymorphism_map_)[coding_set2];
			char coding_set2_name_new[3] = {coding_set2_name[1], coding_set2_name[0], '\0'};

	
			if(std::string(coding_set1_name) == std::string(coding_set2_name_new))	
				{
				switch(set1_val)
					{
					case 1:
							set1_val=3;
							break;
					case 3:
							set1_val=1;
							break;
					default:
							break;
					}
				}
			else
				{
				std::ostringstream error_stream;

				if(*snp_error_counter == 0)
					{
					snp_position_error[*snp_error_counter] = snp_in_set1;
					snp_set1_codding_error[*snp_error_counter] = coding_set1_origin; 
					snp_set2_codding_error[*snp_error_counter] = coding_set2_origin;
		 			(*snp_error_counter)++;
					*found_error_amount_snp = *snp_error_counter;
					}
				else if(snp_position_error[*snp_error_counter-1] != snp_in_set1)
					{
					snp_position_error[*snp_error_counter] = snp_in_set1;
					snp_set1_codding_error[*snp_error_counter] = coding_set1_origin; 
					snp_set2_codding_error[*snp_error_counter] = coding_set2_origin;
			 		(*snp_error_counter)++;
					*found_error_amount_snp = *snp_error_counter;
					}

				if(*snp_error_counter >= *error_amount_)
					{	
					Rprintf("ID:Error: Too many errors while merging sets (see error table). Change error_amount value to increase error-table size.\n");
					*error_amount_=-1;
					return char();
					}

				}
	

		}
	}
return char(set1_val);
*/
}
inline SelectionControlMask operator|(SelectionControlMask a, SelectionControlMask b) { return SelectionControlMask(unsigned(a) | unsigned(b)); }
示例#21
0
CstrBuffer::CstrBuffer(int cap)
  : m_buffer((char*)safe_malloc(cap + 1)), m_len(0), m_cap(cap) {
  assert(unsigned(cap) <= kMaxCap);
}
inline LoopControlMask operator|(LoopControlMask a, LoopControlMask b) { return LoopControlMask(unsigned(a) | unsigned(b)); }
示例#23
0
文件: Task.cpp 项目: Advi42/XCSoar
static int
l_task_index(lua_State *L)
{
  const char *name = lua_tostring(L, 2);
  if (name == nullptr)
    return 0;
  else if (StringIsEqual(name, "bearing")) {
    const TaskStats &task_stats = CommonInterface::Calculated().task_stats;
    const GeoVector &vector_remaining = task_stats.current_leg.vector_remaining;
    if (!task_stats.task_valid || !vector_remaining.IsValid() ||
        vector_remaining.distance <= 10) {
      return 0;
    }
    Lua::Push(L, vector_remaining.bearing);
  } else if (StringIsEqual(name, "bearing_diff")) {
      const NMEAInfo &basic = CommonInterface::Basic();
      const TaskStats &task_stats = CommonInterface::Calculated().task_stats;
      const GeoVector &vector_remaining = task_stats.current_leg.vector_remaining;
      if (!basic.track_available || !task_stats.task_valid ||
          !vector_remaining.IsValid() || vector_remaining.distance <= 10) {
        return 0;
      }      
      Lua::Push(L, vector_remaining.bearing - basic.track);
  } else if (StringIsEqual(name, "radial")) {
      const TaskStats &task_stats = CommonInterface::Calculated().task_stats;
      const GeoVector &vector_remaining = task_stats.current_leg.vector_remaining;
      if (!task_stats.task_valid || !vector_remaining.IsValid() ||
          vector_remaining.distance <= 10) {
        return 0;
      }
      Lua::Push(L, vector_remaining.bearing.Reciprocal());
  } else if (StringIsEqual(name, "next_distance")) {
      const TaskStats &task_stats = CommonInterface::Calculated().task_stats;
      const GeoVector &vector_remaining = task_stats.current_leg.vector_remaining;
      if (!task_stats.task_valid || !vector_remaining.IsValid()) 
        return 0;
     
      Lua::Push(L, vector_remaining.distance);
  } else if (StringIsEqual(name, "next_distance_nominal")) {
      const auto way_point = protected_task_manager != nullptr
          ? protected_task_manager->GetActiveWaypoint() : NULL;

      if (!way_point) return 0;
      const NMEAInfo &basic = CommonInterface::Basic();
      const TaskStats &task_stats = CommonInterface::Calculated().task_stats;

      if (!task_stats.task_valid || !basic.location_available) return 0;

      const GeoVector vector(basic.location, way_point->location);

      if (!vector.IsValid()) return 0;
      Lua::Push(L, vector.distance);
  } else if (StringIsEqual(name, "next_ete")) {
      const TaskStats &task_stats = CommonInterface::Calculated().task_stats;
      if (!task_stats.task_valid || !task_stats.current_leg.IsAchievable()) 
        return 0; 
      assert(task_stats.current_leg.time_remaining_now >= 0);

      Lua::Push(L, task_stats.current_leg.time_remaining_now);
  } else if (StringIsEqual(name, "next_eta")) {
      const auto &task_stats = CommonInterface::Calculated().task_stats;
      const BrokenTime &now_local = CommonInterface::Calculated().date_time_local;

      if (!task_stats.task_valid || !task_stats.current_leg.IsAchievable() ||
          !now_local.IsPlausible()) {
        return 0;
      }

      const BrokenTime t = now_local +
      unsigned(task_stats.current_leg.solution_remaining.time_elapsed);
      float time = t.hour + (float)(t.second/60);

      Lua::Push(L, time);
  } else if (StringIsEqual(name, "next_altitude_diff")) {    
      const auto &task_stats = CommonInterface::Calculated().task_stats;
      const auto &next_solution = task_stats.current_leg.solution_remaining;

      if (!task_stats.task_valid || !next_solution.IsAchievable())
        return 0;

      const auto &settings = CommonInterface::GetComputerSettings();
      auto altitude_difference = next_solution.SelectAltitudeDifference(settings.task.glide);
      Lua::Push(L, altitude_difference);
  } else if (StringIsEqual(name, "nextmc0_altitude_diff")) {
      const TaskStats &task_stats = CommonInterface::Calculated().task_stats;
      if (!task_stats.task_valid || !task_stats.current_leg.solution_mc0.IsAchievable())
        return 0;

      const auto &settings = CommonInterface::GetComputerSettings();
      auto altitude_difference = task_stats.current_leg.solution_mc0.SelectAltitudeDifference(settings.task.glide);
      Lua::Push(L, altitude_difference);
  } else if (StringIsEqual(name, "next_altitude_require")) {
      const auto &task_stats = CommonInterface::Calculated().task_stats;
      const auto &next_solution = task_stats.current_leg.solution_remaining;
      if (!task_stats.task_valid || !next_solution.IsAchievable()) 
        return 0;

      Lua::Push(L, next_solution.GetRequiredAltitude());
  } else if (StringIsEqual(name, "next_altitude_arrival")) {
      const auto &basic = CommonInterface::Basic();
      const auto &task_stats = CommonInterface::Calculated().task_stats;
      const auto next_solution = task_stats.current_leg.solution_remaining;
      if (!basic.NavAltitudeAvailable() ||
          !task_stats.task_valid || !next_solution.IsAchievable()) {
        return 0;
      }

      Lua::Push(L, next_solution.GetArrivalAltitude(basic.nav_altitude));
  } else if (StringIsEqual(name, "next_gr")) {
      if (!CommonInterface::Calculated().task_stats.task_valid) 
        return 0;

      auto gradient = CommonInterface::Calculated().task_stats.current_leg.gradient;
      if (gradient <= 0) 
        return 0;     
      if (::GradientValid(gradient)) 
        Lua::Push(L, gradient);
      else 
        return 0;         
  } else if (StringIsEqual(name, "final_distance")) {
      const auto &calculated = CommonInterface::Calculated();
      const TaskStats &task_stats = calculated.task_stats;

      if (!task_stats.task_valid ||
          !task_stats.current_leg.vector_remaining.IsValid() ||
          !task_stats.total.remaining.IsDefined()) {
        return 0;
      }

      Lua::Push(L, task_stats.total.remaining.GetDistance());
  } else if (StringIsEqual(name, "final_ete")) {
      const TaskStats &task_stats = CommonInterface::Calculated().task_stats;

      if (!task_stats.task_valid || !task_stats.total.IsAchievable()) 
        return 0;
      assert(task_stats.total.time_remaining_now >= 0);

      Lua::Push(L, task_stats.total.time_remaining_now);
  } else if (StringIsEqual(name, "final_eta")) {
      const TaskStats &task_stats = CommonInterface::Calculated().task_stats;
      const BrokenTime &now_local = CommonInterface::Calculated().date_time_local;

      if (!task_stats.task_valid || !task_stats.total.IsAchievable() ||
          !now_local.IsPlausible()) 
        return 0;    

      const BrokenTime t = now_local +
        unsigned(task_stats.total.solution_remaining.time_elapsed);

      float time = t.hour + (float)(t.minute/60);
      Lua::Push(L, time);
  } else if (StringIsEqual(name, "final_altitude_diff")) {
      const TaskStats &task_stats = CommonInterface::Calculated().task_stats;
      const auto &settings = CommonInterface::GetComputerSettings();
      if (!task_stats.task_valid || !task_stats.total.solution_remaining.IsAchievable())
        return 0;
      auto altitude_difference =
        task_stats.total.solution_remaining.SelectAltitudeDifference(settings.task.glide);

      Lua::Push(L, altitude_difference);
  } else if (StringIsEqual(name, "finalmc0_altitude_diff")) {
      const TaskStats &task_stats = CommonInterface::Calculated().task_stats;
      const auto &settings = CommonInterface::GetComputerSettings();
      if (!task_stats.task_valid || !task_stats.total.solution_mc0.IsAchievable())
        return 0;
      auto altitude_difference =
        task_stats.total.solution_mc0.SelectAltitudeDifference(settings.task.glide);

      Lua::Push(L, altitude_difference);
  } else if (StringIsEqual(name, "final_altitude_require")) {
      const TaskStats &task_stats = CommonInterface::Calculated().task_stats;
      if (!task_stats.task_valid ||
          !task_stats.total.solution_remaining.IsOk()) {
        return 0;
      }
   
      Lua::Push(L, task_stats.total.solution_remaining.GetRequiredAltitude());
  } else if (StringIsEqual(name, "task_speed")) {
      const TaskStats &task_stats = CommonInterface::Calculated().task_stats;
      if (!task_stats.task_valid || !task_stats.total.travelled.IsDefined()) 
        return 0;

      Lua::Push(L, task_stats.total.travelled.GetSpeed());
  } else if (StringIsEqual(name, "task_speed_achieved")) {
      const TaskStats &task_stats = CommonInterface::Calculated().task_stats;
      if (!task_stats.task_valid || !task_stats.total.remaining_effective.IsDefined()) 
        return 0;

      Lua::Push(L, task_stats.total.remaining_effective.GetSpeed());
  } else if (StringIsEqual(name, "task_speed_instant")) {
      const TaskStats &task_stats = CommonInterface::Calculated().task_stats;
      if (!task_stats.task_valid)
        return -1;

      Lua::Push(L, task_stats.inst_speed_fast);
  } else if (StringIsEqual(name, "task_speed_hour")) {
      const WindowStats &window = CommonInterface::Calculated().task_stats.last_hour;
      if (window.duration < 0)
        return 0;

      Lua::Push(L, window.speed);
  } else if (StringIsEqual(name, "final_gr")) {
      const TaskStats &task_stats = CommonInterface::Calculated().task_stats;
      if (!task_stats.task_valid) 
        return 0;

      auto gradient = task_stats.total.gradient;

      if (gradient <= 0)
        return 0;
      if (::GradientValid(gradient))
        Lua::Push(L, gradient);
      else
        return 0;
  } else if (StringIsEqual(name, "aat_time")) {
      const auto &calculated = CommonInterface::Calculated();
      const TaskStats &task_stats = calculated.ordered_task_stats;
      const CommonStats &common_stats = calculated.common_stats;

      if (!task_stats.has_targets || !task_stats.total.IsAchievable()) 
        return 0;

      Lua::Push(L, common_stats.aat_time_remaining);
  } else if (StringIsEqual(name, "aat_time_delta")) {
      const auto &calculated = CommonInterface::Calculated();
      const TaskStats &task_stats = calculated.ordered_task_stats;
      const CommonStats &common_stats = calculated.common_stats;
      if (!task_stats.has_targets || !task_stats.total.IsAchievable()) 
        return 0;
   
      assert(task_stats.total.time_remaining_start >= 0);

      auto diff = task_stats.total.time_remaining_start -
        common_stats.aat_time_remaining;

      Lua::Push(L, diff);
  } else if (StringIsEqual(name, "aat_distance")) {
      const auto &calculated = CommonInterface::Calculated();
      const TaskStats &task_stats = calculated.ordered_task_stats;

      if (!task_stats.has_targets || !task_stats.total.planned.IsDefined()) 
        return 0;
       
      Lua::Push(L, task_stats.total.planned.GetDistance());
  } else if (StringIsEqual(name, "aat_distance_max")) {
      const auto &calculated = CommonInterface::Calculated();
      const TaskStats &task_stats = calculated.ordered_task_stats;

      if (!task_stats.has_targets) 
        return 0;

      Lua::Push(L, task_stats.distance_max);
  } else if (StringIsEqual(name, "aat_distance_min")) {
      const auto &calculated = CommonInterface::Calculated();
      const TaskStats &task_stats = calculated.ordered_task_stats;

      if (!task_stats.has_targets) 
        return 0;

      Lua::Push(L, task_stats.distance_min);
  } else if (StringIsEqual(name, "aat_speed")) {
      const auto &calculated = CommonInterface::Calculated();
      const TaskStats &task_stats = calculated.ordered_task_stats;
      const CommonStats &common_stats = calculated.common_stats;

      if (!task_stats.has_targets || common_stats.aat_speed_target <= 0) 
        return 0;

      Lua::Push(L, common_stats.aat_speed_target);
  } else if (StringIsEqual(name, "aat_speed_max")) {
      const auto &calculated = CommonInterface::Calculated();
      const TaskStats &task_stats = calculated.ordered_task_stats;
      const CommonStats &common_stats = calculated.common_stats;

      if (!task_stats.has_targets || common_stats.aat_speed_max <= 0) 
        return 0;

      Lua::Push(L, common_stats.aat_speed_max);
  } else if (StringIsEqual(name, "aat_speed_min")) {
      const auto &calculated = CommonInterface::Calculated();
      const TaskStats &task_stats = calculated.ordered_task_stats;
      const CommonStats &common_stats = calculated.common_stats;

      if (!task_stats.has_targets ||
        !task_stats.task_valid || common_stats.aat_speed_min <= 0) 
        return 0;
    
      Lua::Push(L, common_stats.aat_speed_min);
  } else if (StringIsEqual(name, "time_under_max_height")) {
      const auto &calculated = CommonInterface::Calculated();
      const auto &task_stats = calculated.ordered_task_stats;
      const auto &common_stats = calculated.common_stats;
      const double maxheight = protected_task_manager->GetOrderedTaskSettings().start_constraints.max_height;

      if (!task_stats.task_valid || maxheight <= 0
          || !protected_task_manager
          || common_stats.TimeUnderStartMaxHeight <= 0) {
        return 0;
      }
      const int time = (int)(CommonInterface::Basic().time -
      common_stats.TimeUnderStartMaxHeight);

      Lua::Push(L, time);
  } else if (StringIsEqual(name, "next_etevmg")) {
      const NMEAInfo &basic = CommonInterface::Basic();
      const TaskStats &task_stats = CommonInterface::Calculated().task_stats;

      if (!basic.ground_speed_available || !task_stats.task_valid ||
          !task_stats.current_leg.remaining.IsDefined()) {  
        return 0;
      }
      const auto d = task_stats.current_leg.remaining.GetDistance();
      const auto v = basic.ground_speed;

      if (!task_stats.task_valid ||
          d <= 0 ||
          v <= 0) {
        return 0;
      }
   
      Lua::Push(L, d/v);
  } else if (StringIsEqual(name, "final_etevmg")) {
      const NMEAInfo &basic = CommonInterface::Basic();
      const TaskStats &task_stats = CommonInterface::Calculated().task_stats;

      if (!basic.ground_speed_available || !task_stats.task_valid ||
          !task_stats.total.remaining.IsDefined()) {
        return 0;
      }
      const auto d = task_stats.total.remaining.GetDistance();
      const auto v = basic.ground_speed;

      if (!task_stats.task_valid ||
          d <= 0 ||
          v <= 0) {
        return 0;
      }
 
      Lua::Push(L, d/v);
  } else if (StringIsEqual(name, "cruise_efficiency")) {
      const TaskStats &task_stats = CommonInterface::Calculated().task_stats;
      if (!task_stats.task_valid || !task_stats.start.task_started) 
        return 0;

      Lua::Push(L, task_stats.cruise_efficiency);
  } else
    return 0;

  return 1;
}
inline FunctionControlMask operator|(FunctionControlMask a, FunctionControlMask b) { return FunctionControlMask(unsigned(a) | unsigned(b)); }
示例#25
0
文件: TASReso.cpp 项目: t-weber/takin
bool TASReso::SetHKLE(t_real h, t_real k, t_real l, t_real E)
{
	static const t_real s_dPlaneDistTolerance = std::cbrt(tl::get_epsilon<t_real>());

	ResoResults& resores = m_res[0];

	//std::cout << "UB = " << m_opts.matUB << std::endl;
	//std::cout << h << " " << k << " " << l << ", " << E << std::endl;
	if(m_opts.matUB.size1() < 3 || m_opts.matUB.size2() < 3)
	{
		const char* pcErr = "Invalid UB matrix.";
		tl::log_err(pcErr);
		resores.strErr = pcErr;
		resores.bOk = false;
		return false;
	}

	t_vec vecHKLE;
	if(m_opts.matUB.size1() == 3)
		vecHKLE = tl::make_vec({h, k, l});
	else
		vecHKLE = tl::make_vec({h, k, l, E});

	t_vec vecQ = ublas::prod(m_opts.matUB, vecHKLE);
	if(vecQ.size() > 3)
		vecQ.resize(3, true);

	m_tofreso.Q = m_reso.Q = ublas::norm_2(vecQ) / angs;
	m_tofreso.E = m_reso.E = E * meV;

	//tl::log_info("kfix = ", m_dKFix, ", E = ", E, ", Q = ", vecQ);
	wavenumber kother = tl::get_other_k(m_reso.E, m_dKFix/angs, m_bKiFix);
	//tl::log_info("kother = ", t_real(kother*angs));
	if(m_bKiFix)
	{
		m_tofreso.ki = m_reso.ki = m_dKFix / angs;
		m_tofreso.kf = m_reso.kf = kother;
	}
	else
	{
		m_tofreso.ki = m_reso.ki = kother;
		m_tofreso.kf = m_reso.kf = m_dKFix / angs;
	}

	m_reso.thetam = units::abs(tl::get_mono_twotheta(m_reso.ki, m_reso.mono_d, /*m_reso.dmono_sense>=0.*/1)*t_real(0.5));
	m_reso.thetaa = units::abs(tl::get_mono_twotheta(m_reso.kf, m_reso.ana_d, /*m_reso.dana_sense>=0.*/1)*t_real(0.5));
	m_tofreso.twotheta = m_reso.twotheta = units::abs(tl::get_sample_twotheta(m_reso.ki, m_reso.kf, m_reso.Q, 1));

	//tl::log_info("thetam = ", tl::r2d(m_reso.thetam/rads));
	//tl::log_info("thetaa = ", tl::r2d(m_reso.thetaa/rads));
	//tl::log_info("twothetas = ", tl::r2d(m_reso.twotheta/rads));

	m_tofreso.angle_ki_Q = m_reso.angle_ki_Q = tl::get_angle_ki_Q(m_reso.ki, m_reso.kf, m_reso.Q, /*m_reso.dsample_sense>=0.*/1);
	m_tofreso.angle_kf_Q = m_reso.angle_kf_Q = tl::get_angle_kf_Q(m_reso.ki, m_reso.kf, m_reso.Q, /*m_reso.dsample_sense>=0.*/1);

	//tl::log_info("kiQ = ", tl::r2d(m_reso.angle_ki_Q/rads));
	//m_reso.angle_ki_Q = units::abs(m_reso.angle_ki_Q);
	//m_reso.angle_kf_Q = units::abs(m_reso.angle_kf_Q);


	if(m_foc != ResoFocus::FOC_UNCHANGED)
	{
		if((unsigned(m_foc) & unsigned(ResoFocus::FOC_MONO_FLAT)) != 0)		// flat mono
			m_reso.bMonoIsCurvedH = m_reso.bMonoIsCurvedV = 0;
		if((unsigned(m_foc) & unsigned(ResoFocus::FOC_MONO_H)) != 0)		// optimally curved mono (h)
			m_reso.bMonoIsCurvedH = m_reso.bMonoIsOptimallyCurvedH = 1;
		if((unsigned(m_foc) & unsigned(ResoFocus::FOC_MONO_V)) != 0)		// optimally curved mono (v)
			m_reso.bMonoIsCurvedV = m_reso.bMonoIsOptimallyCurvedV = 1;

		if((unsigned(m_foc) & unsigned(ResoFocus::FOC_ANA_FLAT)) != 0)		// flat ana
			m_reso.bAnaIsCurvedH = m_reso.bAnaIsCurvedV = 0;
		if((unsigned(m_foc) & unsigned(ResoFocus::FOC_ANA_H)) != 0)			// optimally curved ana (h)
			m_reso.bAnaIsCurvedH = m_reso.bAnaIsOptimallyCurvedH = 1;
		if((unsigned(m_foc) & unsigned(ResoFocus::FOC_ANA_V)) != 0)			// optimally curved ana (v)
			m_reso.bAnaIsCurvedV = m_reso.bAnaIsOptimallyCurvedV = 1;

		//tl::log_info("Mono focus (h,v): ", m_reso.bMonoIsOptimallyCurvedH, ", ", m_reso.bMonoIsOptimallyCurvedV);
		//tl::log_info("Ana focus (h,v): ", m_reso.bAnaIsOptimallyCurvedH, ", ", m_reso.bAnaIsOptimallyCurvedV);

		// remove collimators
		/*if(m_reso.bMonoIsCurvedH)
		{
			m_reso.coll_h_pre_mono = 99999. * rads;
			m_reso.coll_h_pre_sample = 99999. * rads;
		}
		if(m_reso.bMonoIsCurvedV)
		{
			m_reso.coll_v_pre_mono = 99999. * rads;
			m_reso.coll_v_pre_sample = 99999. * rads;
		}
		if(m_reso.bAnaIsCurvedH)
		{
			m_reso.coll_h_post_sample = 99999. * rads;
			m_reso.coll_h_post_ana = 99999. * rads;
		}
		if(m_reso.bAnaIsCurvedV)
		{
			m_reso.coll_v_post_sample = 99999. * rads;
			m_reso.coll_v_post_ana = 99999. * rads;
		}*/
	}


	/*tl::log_info("thetam = ", m_reso.thetam);
	tl::log_info("thetaa = ", m_reso.thetaa);
	tl::log_info("2theta = ", m_reso.twotheta);*/

	if(std::fabs(vecQ[2]) > s_dPlaneDistTolerance)
	{
		tl::log_err("Position Q = (", h, " ", k, " ", l, "),",
			" E = ", E, " meV not in scattering plane.");

		resores.strErr = "Not in scattering plane.";
		resores.bOk = false;
		return false;
	}

	vecQ.resize(2, true);
	m_opts.dAngleQVec0 = -tl::vec_angle(vecQ);
	//tl::log_info("angle Q vec0 = ", m_opts.dAngleQVec0);
	//tl::log_info("calc r0: ", m_reso.bCalcR0);

	for(ResoResults& resores_cur : m_res)
	{
		// if only one sample position is requested, don't randomise
		if(m_res.size() > 1)
		{
			/*m_reso.pos_x = tl::rand_real(-t_real(m_reso.sample_w_q*0.5/cm),
				t_real(m_reso.sample_w_q*0.5/cm)) * cm;
			m_reso.pos_y = tl::rand_real(-t_real(m_reso.sample_w_perpq*0.5/cm),
				t_real(m_reso.sample_w_perpq*0.5/cm)) * cm;
			m_reso.pos_z = tl::rand_real(-t_real(m_reso.sample_h*0.5/cm),
				t_real(m_reso.sample_h*0.5/cm)) * cm;*/

			m_reso.pos_x = tl::rand_norm(t_real(0),
				t_real(tl::get_FWHM2SIGMA<t_real>()*m_reso.sample_w_q/cm)) * cm;
			m_reso.pos_y = tl::rand_norm(t_real(0),
				t_real(tl::get_FWHM2SIGMA<t_real>()*m_reso.sample_w_perpq/cm)) * cm;
			m_reso.pos_z = tl::rand_norm(t_real(0),
				t_real(tl::get_FWHM2SIGMA<t_real>()*m_reso.sample_h/cm)) * cm;
		}

		// calculate resolution at (hkl) and E
		if(m_algo == ResoAlgo::CN)
		{
			//tl::log_info("Algorithm: Cooper-Nathans (TAS)");
			resores_cur = calc_cn(m_reso);
		}
		else if(m_algo == ResoAlgo::POP)
		{
			//tl::log_info("Algorithm: Popovici (TAS)");
			resores_cur = calc_pop(m_reso);
		}
		else if(m_algo == ResoAlgo::ECK)
		{
			//tl::log_info("Algorithm: Eckold-Sobolev (TAS)");
			resores_cur = calc_eck(m_reso);
		}
		else if(m_algo == ResoAlgo::VIOL)
		{
			//tl::log_info("Algorithm: Violini (TOF)");
			m_reso.flags &= ~CALC_R0;
			resores_cur = calc_viol(m_tofreso);
		}
		else
		{
			const char* pcErr = "Unknown algorithm selected.";
			tl::log_err(pcErr);
			resores_cur.strErr = pcErr;
			resores_cur.bOk = false;
			return false;
		}

		if(!resores_cur.bOk)
		{
			tl::log_err("Error calculating resolution: ", resores_cur.strErr);
			tl::log_debug("R0: ", resores_cur.dR0);
			tl::log_debug("res: ", resores_cur.reso);
		}
	}

	return resores.bOk;
}
inline MemorySemanticsMask operator|(MemorySemanticsMask a, MemorySemanticsMask b) { return MemorySemanticsMask(unsigned(a) | unsigned(b)); }
示例#27
0
void OsamaAI::performAttack(GameGridLayer* playerGrid)
{
    //For test purposes
    readTestValues();
    //fillTheSetAndTest(this->pointsSet);
    //this->pointsSet.clear();

    //insertPointAndFillAdjacentPoints({5,5}, 4, ShipOrientation::vertical);

    switch(state)
    {
        case State::searching:
        {
            Point2D<int> point; //{ rand()%10, rand() % 10};
            if(reverseIt!=hitPoints.end()) {
                point = {reverseIt->x, reverseIt->y };
                reverseIt++;
            } else
            {
                point = { rand()%10, rand()%10 };
            }

            //Osama do not hit a cells that are boundary to destroyed ships
            while (doesIntersectsWithBoundary(point)) {
                point = {rand()%10, rand()%10}; //generate new coordinates
            }

            if(!playerGrid->isCellTested(point.x, point.y)) {
                CellState cellState = memoryMatrix[point.x][point.y] = playerGrid->hitCell(point.x, point.y);
                pointsSet.insert(point);

                switch(cellState)
                {
                    case CellState::Hit:
                    {
                        if(point.x==0)
                            usedDirections.insert(Direction::left);
                        if(point.y==0)
                            usedDirections.insert(Direction::down);
                        if(point.x==9)
                            usedDirections.insert(Direction::right);
                        if(point.y==9)
                            usedDirections.insert(Direction::up);
                        m_originalShot = point;
                        shotsCount = 1;
                        shotsVector.push_back(point);
                        state = State::discoveringDirection; //transitionate to a new state
                    }
                    break;

                    case CellState::Destroyed:
                        //write ship coord and boundary into a set
                        //it's and 1 deck ship otherwise we should hit from another state
                        usedDirections.clear();
                        insertPointAndFillAdjacentPoints(point, 1, ShipOrientation::horizontal);
                        break;
                    default: pointsSet.insert(point);
                }
            }
        }
        break;

        //We're moving to that state if we have discovered a ship
        case State::discoveringDirection:
        {
            const Point2D<int> lastShot = shotsVector.back();
            std::set<Direction> allDirections {Direction::up, Direction::down, Direction::left, Direction::right};

            std::set<Direction> unusedDirections;

            std::vector<Direction> vec1 (begin(usedDirections), end(usedDirections));
            std::vector<Direction> vec2 (begin(allDirections ), end(allDirections ));

            std::sort(begin(vec1), end(vec1), [](const Direction& d1, const Direction& d2)
                      { return (static_cast<int>(d1) < static_cast<int>(d2)); });
            std::sort(begin(vec2), end(vec2), [](const Direction& d1, const Direction& d2)
                      { return (static_cast<int>(d1) < static_cast<int>(d2)); });
            std::set_symmetric_difference(begin(vec1), end(vec1), begin(vec2),
                                end  (vec2), inserter(unusedDirections,
                                                      unusedDirections.begin()));

            std::vector<Direction> unusedDirectionsShuffled(begin(unusedDirections), end(unusedDirections));
            std::srand(unsigned(std::time(0)));
            std::random_shuffle(begin(unusedDirectionsShuffled), end(unusedDirectionsShuffled));

            for(Direction direction: unusedDirectionsShuffled) {
                Point2D<int> vector{0,0};
                this->choosenDirection = direction;
                switch(direction)
                {
                    case Direction::up:
                        vector = {0,1};
                        break;
                    case Direction::down:
                        vector = {0,-1};
                        break;
                    case Direction::left:
                        vector = {-1,0};
                        break;
                    case Direction::right:
                        vector = {1,0};
                        break;
                }
                Point2D<int> newShot = lastShot + vector;
                CellState cellState = CellState::Empty;

                if(!doesIntersectsWithBoundary(newShot)) {
                    cellState = playerGrid->hitCell(newShot.x, newShot.y);
                    pointsSet.insert(newShot);
                }
                else
                {
                    //change the direction and hit
                    continue;
                }
                if(cellState==CellState::Hit)
                {
                    //right direction was choosen. continue to destroy ship in that direction
                    shotsCount++;
                    shotsVector.push_back(newShot);
                    state = State::destroyingShip;
                    break;
                }
                else if(cellState==CellState::Destroyed) {
                    //we destroyed a ship with that shot.
                    //store him in a matrix
                    //store it bounds

                    shotsCount++;

                    ShipOrientation shipOrientation;

                    if(direction==Direction::up||direction==Direction::down)
                        shipOrientation = ShipOrientation::vertical;
                    else
                        shipOrientation = ShipOrientation::horizontal;

                    insertPointAndFillAdjacentPoints(m_originalShot, shotsCount, shipOrientation);
                    state = State::searching;
                    shotsCount = 0;
                    usedDirections.clear();
                    break;
                }
                else if(cellState==CellState::Miss)
                {
                    //store used direction so we won't hit there again
                    usedDirections.insert(direction);
                    break;
                }
            }
            
        }
        break;

        case State::destroyingShip:
        {
            Point2D<int> vector{0,0};
            const Point2D<int> lastShot = shotsVector.back();
            switch(choosenDirection)
            {
                case Direction::up:
                    vector = {0,1};
                    break;
                case Direction::down:
                    vector = {0,-1};
                    break;
                case Direction::left:
                    vector = {-1,0};
                    break;
                case Direction::right:
                    vector = {1,0};
                    break;
            }
            Point2D<int> newShot = lastShot + vector;
            shotsVector.push_back(newShot);
            if(isShotExceedsBoundary(newShot + vector))
            {
                state = State::discoveringDirection;
                usedDirections.insert(choosenDirection);
                shotsVector.push_back(m_originalShot);
            }
            auto cellState = playerGrid->hitCell(newShot.x, newShot.y);
            switch(cellState)
            {
                case CellState::Miss:
                    usedDirections.insert(choosenDirection);
                    if(choosenDirection==Direction::up||choosenDirection==Direction::down)
                    {
                        usedDirections.insert(Direction::left);
                        usedDirections.insert(Direction::right);
                    } else {
                        usedDirections.insert(Direction::up);
                        usedDirections.insert(Direction::down);
                    }

                    shotsVector.push_back(m_originalShot);
                    pointsSet.insert(newShot);
                    state = State::discoveringDirection;
                    break;
                case CellState::Hit:
                    shotsCount++;
                    pointsSet.insert(newShot);
                    break;
                case CellState::Destroyed:
                    shotsCount++;
                    ShipOrientation shipOrientation;

                    if(choosenDirection==Direction::up||choosenDirection==Direction::down)
                        shipOrientation = ShipOrientation::vertical;
                    else
                        shipOrientation = ShipOrientation::horizontal;

                    insertPointAndFillAdjacentPoints(m_originalShot, shotsCount, shipOrientation);
                    shotsCount = 0;
                    usedDirections.clear();

                    state = State::searching; //Osama destroyed the ship
                    break;
                default: break;
            }
        }
        break;

    }



}
inline MemoryAccessMask operator|(MemoryAccessMask a, MemoryAccessMask b) { return MemoryAccessMask(unsigned(a) | unsigned(b)); }
示例#29
0
void CCommandProcessor::ParseCommand ( const char * const cmdBegin,
                                       const uint64_t currentTime )
{
  const char * const cmdEnd = SkipCharsNotInSet( cmdBegin, SPACE_AND_TAB );
  assert( cmdBegin != cmdEnd );

  const char * const paramBegin = SkipCharsInSet( cmdEnd, SPACE_AND_TAB );

  bool extraParamsFound = false;

  if ( IsCmd( cmdBegin, cmdEnd, CMDNAME_QUESTION_MARK, true, false, &extraParamsFound ) ||
       IsCmd( cmdBegin, cmdEnd, CMDNAME_HELP, false, false, &extraParamsFound ) )
  {
    PrintStr( "This console is similar to the Bus Pirate console." EOL );
    PrintStr( "Commands longer than 1 character are case insensitive." EOL );
    PrintStr( "WARNING: If a command takes too long to run, the watchdog may reset the board." EOL );
    PrintStr( "Commands are:" EOL );

    Printf( "  %s, %s: Show this help text." EOL, CMDNAME_QUESTION_MARK, CMDNAME_HELP );
    Printf( "  %s: Show version information." EOL, CMDNAME_I );
    Printf( "  %s: Test USB transfer speed." EOL, CMDNAME_USBSPEEDTEST );
    Printf( "  %s: Show JTAG pin status (read as inputs)." EOL, CMDNAME_JTAGPINS );
    Printf( "  %s: Test JTAG shift speed. WARNING: Do NOT connect any JTAG device." EOL, CMDNAME_JTAGSHIFTSPEEDTEST );
    Printf( "  %s: Exercises malloc()." EOL, CMDNAME_MALLOCTEST );
    Printf( "  %s: Exercises C++ exceptions." EOL, CMDNAME_CPP_EXCEPTION_TEST );
    Printf( "  %s: Shows memory usage." EOL, CMDNAME_MEMORY_USAGE );
    Printf( "  %s" EOL, CMDNAME_CPU_LOAD );
    Printf( "  %s" EOL, CMDNAME_UPTIME );
    Printf( "  %s" EOL, CMDNAME_RESET );
    Printf( "  %s" EOL, CMDNAME_RESET_CAUSE );
    Printf( "  %s <addr> <byte count>" EOL, CMDNAME_PRINT_MEMORY );
    Printf( "  %s <milliseconds>" EOL, CMDNAME_BUSY_WAIT );
    Printf( "  %s <command|protocol>" EOL, CMDNAME_SIMULATE_ERROR );

    return;
  }

  if ( IsCmd( cmdBegin, cmdEnd, CMDNAME_I, true, false, &extraParamsFound ) )
  {
    #ifndef NDEBUG
      const char buildType[] = "Debug build";
    #else
      const char buildType[] = "Release build";
    #endif

    Printf( "JtagDue %s" EOL, PACKAGE_VERSION );
    Printf( "%s, compiler version %s" EOL, buildType, __VERSION__ );
    Printf( "Watchdog %s" EOL, ENABLE_WDT ? "enabled" : "disabled" );

    return;
  }


  if ( IsCmd( cmdBegin, cmdEnd, CMDNAME_RESET, false, false, &extraParamsFound ) )
  {
    // This message does not reach the other side, we would need to add some delay.
    //   UsbPrint( txBuffer, "Resetting the board..." EOL );
    __disable_irq();
    // Note that this message always goes to the serial port console,
    // even if the user is connected over USB. It might be possible to send
    // it over USB and then wait for the outgoing buffer to be empty.
    SerialSyncWriteStr( "Resetting the board..." EOL );
    SerialWaitForDataSent();
    ResetBoard( ENABLE_WDT );
    assert( false );  // We should never reach this point.
    return;
  }


  if ( IsCmd( cmdBegin, cmdEnd, CMDNAME_CPU_LOAD, false, false, &extraParamsFound ) )
  {
    if ( ENABLE_CPU_SLEEP )
      PrintStr( "CPU load statistics not available." EOL );
    else
      DisplayCpuLoad();

    return;
  }


  if ( IsCmd( cmdBegin, cmdEnd, CMDNAME_UPTIME, false, false, &extraParamsFound ) )
  {
    char buffer[ CONVERT_TO_DEC_BUF_SIZE ];
    Printf( "Uptime: %s seconds." EOL, convert_unsigned_to_dec_th( GetUptime() / 1000, buffer, ',' ) );
    return;
  }


  if ( IsCmd( cmdBegin, cmdEnd, CMDNAME_RESET_CAUSE, false, false, &extraParamsFound ) )
  {
    DisplayResetCause();
    return;
  }


  if ( IsCmd( cmdBegin, cmdEnd, CMDNAME_PRINT_MEMORY, false, true, &extraParamsFound ) )
  {
    PrintMemory( paramBegin );
    return;
  }


  if ( IsCmd( cmdBegin, cmdEnd, CMDNAME_BUSY_WAIT, false, true, &extraParamsFound ) )
  {
    BusyWait( paramBegin );
    return;
  }


  if ( IsCmd( cmdBegin, cmdEnd, CMDNAME_USBSPEEDTEST, false, true, &extraParamsFound ) )
  {
    ProcessUsbSpeedTestCmd( paramBegin, currentTime );
    return;
  }


  if ( IsCmd( cmdBegin, cmdEnd, CMDNAME_JTAGPINS, false, false, &extraParamsFound ) )
  {
    PrintJtagPinStatus();
    return;
  }

  if ( IsCmd( cmdBegin, cmdEnd, CMDNAME_JTAGSHIFTSPEEDTEST, false, false, &extraParamsFound ) )
  {
    if ( !IsNativeUsbPort() )
      throw std::runtime_error( "This command is only available on the 'Native' USB port." );


    // Fill the Rx buffer with some test data.
    assert( m_rxBuffer != NULL );

    m_rxBuffer->Reset();
    for ( uint32_t i = 0; !m_rxBuffer->IsFull(); ++i )
    {
      m_rxBuffer->WriteElem( CUsbRxBuffer::ElemType( i ) );
    }


    // If the mode is set to MODE_HIZ, you cannot see the generated signal with the oscilloscope.
    // Note also that the built-in pull-ups on the Atmel ATSAM3X8 are too weak (between 50 and 100 KOhm,
    // yields too slow a rising time) to be of any use.

    const bool oldPullUps = GetJtagPullups();
    SetJtagPullups( false );

    const JtagPinModeEnum oldMode = GetJtagPinMode();
    SetJtagPinMode ( MODE_JTAG );


    // Each JTAG transfer needs 2 bits in the Rx buffer, TMS and TDI,
    // but produces only 1 bit, TDO.
    const uint32_t jtagByteCount = m_rxBuffer->GetElemCount() / 2;

    const uint16_t bitCount = jtagByteCount * 8;

    // Shift all JTAG data through several times.

    const uint64_t startTime = GetUptime();
    const uint32_t iterCount = 50;

    for ( uint32_t i = 0; i < iterCount; ++i )
    {
      // We hope that this will not clear the buffer contents.
      assert( m_rxBuffer != NULL );
      assert( m_txBuffer != NULL );

      m_rxBuffer->Reset();
      m_rxBuffer->CommitWrittenElements( jtagByteCount * 2 );

      m_txBuffer->Reset();

      ShiftJtagData( m_rxBuffer,
                     m_txBuffer,
                     bitCount );

      assert( m_txBuffer->GetElemCount() == jtagByteCount );
    }

    const uint64_t finishTime = GetUptime();
    const uint32_t elapsedTime = uint32_t( finishTime - startTime );

    m_rxBuffer->Reset();
    m_txBuffer->Reset();
    const unsigned kBitsPerSec = unsigned( uint64_t(bitCount) * iterCount * 1000 / elapsedTime / 1024 );

    SetJtagPinMode( oldMode );
    SetJtagPullups( oldPullUps );

    // I am getting 221 KiB/s with GCC 4.7.3 and optimisation level "-O3".
    Printf( EOL "Finished JTAG shift speed test, throughput %u Kbits/s (%u KiB/s)." EOL,
               kBitsPerSec, kBitsPerSec / 8 );

    return;
  }


  if ( IsCmd( cmdBegin, cmdEnd, CMDNAME_MALLOCTEST, false, false, &extraParamsFound ) )
  {
    PrintStr( "Allocalling memory..." EOL );

    volatile uint32_t * const volatile mallocTest = (volatile uint32_t *) malloc(123);
    *mallocTest = 123;

    PrintStr( "Releasing memory..." EOL );

    free( const_cast< uint32_t * >( mallocTest ) );

    PrintStr( "Test finished." EOL );

    return;
  }


  if ( IsCmd( cmdBegin, cmdEnd, CMDNAME_CPP_EXCEPTION_TEST, false, false, &extraParamsFound ) )
  {
    try
    {
      PrintStr( "Throwing integer exception..." EOL );
      throw 123;
      PrintStr( "Throw did not work." EOL );
      assert( false );
    }
    catch ( ... )
    {
      PrintStr( "Caught integer exception." EOL );
    }
    PrintStr( "Test finished." EOL );

    return;
  }


  if ( IsCmd( cmdBegin, cmdEnd, CMDNAME_SIMULATE_ERROR, false, true, &extraParamsFound ) )
  {
    SimulateError( paramBegin );
    return;
  }


  if ( IsCmd( cmdBegin, cmdEnd, CMDNAME_MEMORY_USAGE, false, false, &extraParamsFound ) )
  {
    const unsigned heapSize = unsigned( GetHeapEndAddr() - uintptr_t( &_end ) );

    Printf( "Partitions: malloc heap: %u bytes, free: %u bytes, stack: %u bytes." EOL,
               heapSize,
               GetStackStartAddr() - GetHeapEndAddr(),
               STACK_SIZE );

    Printf( "Used stack (estimated): %u from %u bytes." EOL,
               unsigned( GetStackSizeUsageEstimate() ),
               STACK_SIZE );

    const struct mallinfo mi = mallinfo();
    const unsigned heapSizeAccordingToNewlib = unsigned( mi.arena );

    Printf( "Heap: %u allocated from %u bytes." EOL,
               unsigned( mi.uordblks ),
               unsigned( mi.arena ) );

    assert( heapSize == heapSizeAccordingToNewlib );
    UNUSED_IN_RELEASE( heapSizeAccordingToNewlib );

    return;
  }

  if ( extraParamsFound )
    Printf( "Command \"%.*s\" does not take any parameters." EOL, cmdEnd - cmdBegin, cmdBegin );
  else
    Printf( "Unknown command \"%.*s\"." EOL, cmdEnd - cmdBegin, cmdBegin );
}
示例#30
0
  //}}}
  //{{{
  //------------------------------------------------------------------------
  unsigned vcgen_contour::vertex(double* x, double* y)
  {
      unsigned cmd = path_cmd_line_to;
      while(!is_stop(cmd))
      {
          switch(m_status)
          {
          case initial:
              rewind(0);

          case ready:
              if(m_src_vertices.size() < 2 + unsigned(m_closed != 0))
              {
                  cmd = path_cmd_stop;
                  break;
              }
              m_status = outline;
              cmd = path_cmd_move_to;
              m_src_vertex = 0;
              m_out_vertex = 0;

          case outline:
              if(m_src_vertex >= m_src_vertices.size())
              {
                  m_status = end_poly;
                  break;
              }
              m_stroker.calc_join(m_out_vertices,
                                  m_src_vertices.prev(m_src_vertex),
                                  m_src_vertices.curr(m_src_vertex),
                                  m_src_vertices.next(m_src_vertex),
                                  m_src_vertices.prev(m_src_vertex).dist,
                                  m_src_vertices.curr(m_src_vertex).dist);
              ++m_src_vertex;
              m_status = out_vertices;
              m_out_vertex = 0;

          case out_vertices:
              if(m_out_vertex >= m_out_vertices.size())
              {
                  m_status = outline;
              }
              else
              {
                  const point_d& c = m_out_vertices[m_out_vertex++];
                  *x = c.x;
                  *y = c.y;
                  return cmd;
              }
              break;

          case end_poly:
              if(!m_closed) return path_cmd_stop;
              m_status = stop;
              return path_cmd_end_poly | path_flags_close | path_flags_ccw;

          case stop:
              return path_cmd_stop;
          }
      }
      return cmd;
  }