inline reverse_iterator rend() { return reverse_iterator(begin()); }
void C4GraphCollection::Update() const { // update all child graphs for (const_iterator i = begin(); i != end(); ++i) (*i)->Update(); }
void C4GraphCollection::SetMultiplier(ValueType fToVal) { if (fMultiplier = fToVal) for (iterator i = begin(); i != end(); ++i) (*i)->SetMultiplier(fToVal); }
bool RAS_MeshSlot::Split(bool force) { list<RAS_MeshSlot*>::iterator jit; RAS_MeshSlot *target = m_joinSlot; RAS_DisplayArrayList::iterator it, jt; iterator mit; size_t i, found0 = 0, found1 = 0; if (target && (force || !Equals(target))) { m_joinSlot = NULL; for (jit=target->m_joinedSlots.begin(); jit!=target->m_joinedSlots.end(); jit++) { if (*jit == this) { target->m_joinedSlots.erase(jit); found0 = 1; break; } } if (!found0) abort(); for (it=m_displayArrays.begin(); it!=m_displayArrays.end(); it++) { found1 = 0; for (jt=target->m_displayArrays.begin(); jt!=target->m_displayArrays.end(); jt++) { if (*jt == *it) { target->m_displayArrays.erase(jt); target->m_endarray--; found1 = 1; break; } } if (!found1) abort(); } if (target->m_displayArrays.empty() == false) { target->m_endvertex = target->m_displayArrays.back()->m_vertex.size(); target->m_endindex = target->m_displayArrays.back()->m_index.size(); } else { target->m_endvertex = 0; target->m_endindex = 0; } MT_Matrix4x4 ntransform = m_joinInvTransform.inverse().transposed(); ntransform[0][3] = ntransform[1][3] = ntransform[2][3] = 0.0f; for (begin(mit); !end(mit); next(mit)) for (i=mit.startvertex; i<mit.endvertex; i++) mit.vertex[i].Transform(m_joinInvTransform, ntransform); if (target->m_DisplayList) { target->m_DisplayList->Release(); target->m_DisplayList = NULL; } return true; } return false; }
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; }
template <typename PointInT, typename PointNT, typename PointOutT> Eigen::MatrixXf pcl::computeRSD (boost::shared_ptr<const pcl::PointCloud<PointInT> > &surface, boost::shared_ptr<const pcl::PointCloud<PointNT> > &normals, const std::vector<int> &indices, double max_dist, int nr_subdiv, double plane_radius, PointOutT &radii, bool compute_histogram) { // Check if the full histogram has to be saved or not Eigen::MatrixXf histogram; if (compute_histogram) histogram = Eigen::MatrixXf::Zero (nr_subdiv, nr_subdiv); // Check if enough points are provided or not if (indices.size () < 2) { radii.r_max = 0; radii.r_min = 0; return histogram; } // Initialize minimum and maximum angle values in each distance bin std::vector<std::vector<double> > min_max_angle_by_dist (nr_subdiv); min_max_angle_by_dist[0].resize (2); min_max_angle_by_dist[0][0] = min_max_angle_by_dist[0][1] = 0.0; for (int di=1; di<nr_subdiv; di++) { min_max_angle_by_dist[di].resize (2); min_max_angle_by_dist[di][0] = +DBL_MAX; min_max_angle_by_dist[di][1] = -DBL_MAX; } // Compute distance by normal angle distribution for points std::vector<int>::const_iterator i, begin (indices.begin()), end (indices.end()); for(i = begin+1; i != end; ++i) { // compute angle between the two lines going through normals (disregard orientation!) double cosine = normals->points[*i].normal[0] * normals->points[*begin].normal[0] + normals->points[*i].normal[1] * normals->points[*begin].normal[1] + normals->points[*i].normal[2] * normals->points[*begin].normal[2]; if (cosine > 1) cosine = 1; if (cosine < -1) cosine = -1; double angle = acos (cosine); if (angle > M_PI/2) angle = M_PI - angle; /// \note: orientation is neglected! // Compute point to point distance double dist = sqrt ((surface->points[*i].x - surface->points[*begin].x) * (surface->points[*i].x - surface->points[*begin].x) + (surface->points[*i].y - surface->points[*begin].y) * (surface->points[*i].y - surface->points[*begin].y) + (surface->points[*i].z - surface->points[*begin].z) * (surface->points[*i].z - surface->points[*begin].z)); if (dist > max_dist) continue; /// \note: we neglect points that are outside the specified interval! // compute bins and increase int bin_d = (int) floor (nr_subdiv * dist / max_dist); if (compute_histogram) { int bin_a = std::min (nr_subdiv-1, (int) floor (nr_subdiv * angle / (M_PI/2))); histogram(bin_a, bin_d)++; } // update min-max values for distance bins if (min_max_angle_by_dist[bin_d][0] > angle) min_max_angle_by_dist[bin_d][0] = angle; if (min_max_angle_by_dist[bin_d][1] < angle) min_max_angle_by_dist[bin_d][1] = angle; } // Estimate radius from min and max lines double Amint_Amin = 0, Amint_d = 0; double Amaxt_Amax = 0, Amaxt_d = 0; for (int di=0; di<nr_subdiv; di++) { // combute the members of A'*A*r = A'*D if (min_max_angle_by_dist[di][1] >= 0) { double p_min = min_max_angle_by_dist[di][0]; double p_max = min_max_angle_by_dist[di][1]; double f = (di+0.5)*max_dist/nr_subdiv; Amint_Amin += p_min * p_min; Amint_d += p_min * f; Amaxt_Amax += p_max * p_max; Amaxt_d += p_max * f; } } float min_radius = Amint_Amin == 0 ? plane_radius : std::min (Amint_d/Amint_Amin, plane_radius); float max_radius = Amaxt_Amax == 0 ? plane_radius : std::min (Amaxt_d/Amaxt_Amax, plane_radius); // Small correction of the systematic error of the estimation (based on analysis with nr_subdiv_ = 5) min_radius *= 1.1; max_radius *= 0.9; if (min_radius < max_radius) { radii.r_min = min_radius; radii.r_max = max_radius; } else { radii.r_max = min_radius; radii.r_min = max_radius; } return histogram; }
void UARTClass::begin(const uint32_t dwBaudRate) { begin(dwBaudRate, Mode_8N1); }
bool ZoneDatabase::GetTradeRecipe(uint32 recipe_id, uint8 c_type, uint32 some_id, uint32 char_id, DBTradeskillRecipe_Struct *spec) { // make where clause segment for container(s) std::string containers; if (some_id == 0) containers = StringFormat("= %u", c_type); // world combiner so no item number else containers = StringFormat("IN (%u,%u)", c_type, some_id); // container in inventory std::string query = StringFormat("SELECT tr.id, tr.tradeskill, tr.skillneeded, " "tr.trivial, tr.nofail, tr.replace_container, " "tr.name, tr.must_learn, tr.quest, crl.madecount " "FROM tradeskill_recipe AS tr " "INNER JOIN tradeskill_recipe_entries AS tre " "ON tr.id = tre.recipe_id " "LEFT JOIN (SELECT recipe_id, madecount " "FROM char_recipe_list WHERE char_id = %u) AS crl " "ON tr.id = crl.recipe_id " "WHERE tr.id = %lu AND tre.item_id %s AND tr.enabled " "GROUP BY tr.id", char_id, (unsigned long)recipe_id, containers.c_str()); auto results = QueryDatabase(query); if (!results.Success()) { Log.Out(Logs::General, Logs::Error, "Error in GetTradeRecipe, query: %s", query.c_str()); Log.Out(Logs::General, Logs::Error, "Error in GetTradeRecipe, error: %s", results.ErrorMessage().c_str()); return false; } if(results.RowCount() != 1) return false;//just not found i guess.. auto row = results.begin(); spec->tradeskill = (SkillUseTypes)atoi(row[1]); spec->skill_needed = (int16)atoi(row[2]); spec->trivial = (uint16)atoi(row[3]); spec->nofail = atoi(row[4]) ? true : false; spec->replace_container = atoi(row[5]) ? true : false; spec->name = row[6]; spec->must_learn = (uint8)atoi(row[7]); spec->quest = atoi(row[8]) ? true : false; if (row[9] == nullptr) { spec->has_learnt = false; spec->madecount = 0; } else { spec->has_learnt = true; spec->madecount = (uint32)atoul(row[9]); } spec->recipe_id = recipe_id; //Pull the on-success items... query = StringFormat("SELECT item_id,successcount FROM tradeskill_recipe_entries " "WHERE successcount > 0 AND recipe_id = %u", recipe_id); results = QueryDatabase(query); if (!results.Success()) { return false; } if(results.RowCount() < 1) { Log.Out(Logs::General, Logs::Error, "Error in GetTradeRecept success: no success items returned"); return false; } spec->onsuccess.clear(); for(auto row = results.begin(); row != results.end(); ++row) { uint32 item = (uint32)atoi(row[0]); uint8 num = (uint8) atoi(row[1]); spec->onsuccess.push_back(std::pair<uint32,uint8>(item, num)); } spec->onfail.clear(); //Pull the on-fail items... query = StringFormat("SELECT item_id, failcount FROM tradeskill_recipe_entries " "WHERE failcount > 0 AND recipe_id = %u", recipe_id); results = QueryDatabase(query); if (results.Success()) for(auto row = results.begin(); row != results.end(); ++row) { uint32 item = (uint32)atoi(row[0]); uint8 num = (uint8) atoi(row[1]); spec->onfail.push_back(std::pair<uint32,uint8>(item, num)); } spec->salvage.clear(); // Don't bother with the query if TS is nofail if (spec->nofail) return true; // Pull the salvage list query = StringFormat("SELECT item_id, salvagecount " "FROM tradeskill_recipe_entries " "WHERE salvagecount > 0 AND recipe_id = %u", recipe_id); results = QueryDatabase(query); if (results.Success()) for(auto row = results.begin(); row != results.begin(); ++row) { uint32 item = (uint32)atoi(row[0]); uint8 num = (uint8)atoi(row[1]); spec->salvage.push_back(std::pair<uint32,uint8>(item, num)); } return true; }
void Object::HandleAutoCombine(Client* user, const RecipeAutoCombine_Struct* rac) { //get our packet ready, gotta send one no matter what... EQApplicationPacket* outapp = new EQApplicationPacket(OP_RecipeAutoCombine, sizeof(RecipeAutoCombine_Struct)); RecipeAutoCombine_Struct *outp = (RecipeAutoCombine_Struct *)outapp->pBuffer; outp->object_type = rac->object_type; outp->some_id = rac->some_id; outp->unknown1 = rac->unknown1; outp->recipe_id = rac->recipe_id; outp->reply_code = 0xFFFFFFF5; //default fail. //ask the database for the recipe to make sure it exists... DBTradeskillRecipe_Struct spec; if (!database.GetTradeRecipe(rac->recipe_id, rac->object_type, rac->some_id, user->CharacterID(), &spec)) { Log.Out(Logs::General, Logs::Error, "Unknown recipe for HandleAutoCombine: %u\n", rac->recipe_id); user->QueuePacket(outapp); safe_delete(outapp); return; } // Character hasn't learnt the recipe yet. // This shouldn't happen. if ((spec.must_learn&0xf) && !spec.has_learnt) { // Made up message for the client. Just giving a DNC is the other option. user->Message(4, "You need to learn how to combine these first."); user->QueuePacket(outapp); safe_delete(outapp); return; } //pull the list of components std::string query = StringFormat("SELECT tre.item_id, tre.componentcount " "FROM tradeskill_recipe_entries AS tre " "WHERE tre.componentcount > 0 AND tre.recipe_id = %u", rac->recipe_id); auto results = database.QueryDatabase(query); if (!results.Success()) { user->QueuePacket(outapp); safe_delete(outapp); return; } if(results.RowCount() < 1) { Log.Out(Logs::General, Logs::Error, "Error in HandleAutoCombine: no components returned"); user->QueuePacket(outapp); safe_delete(outapp); return; } if(results.RowCount() > 10) { Log.Out(Logs::General, Logs::Error, "Error in HandleAutoCombine: too many components returned (%u)", results.RowCount()); user->QueuePacket(outapp); safe_delete(outapp); return; } uint32 items[10]; memset(items, 0, sizeof(items)); uint8 counts[10]; memset(counts, 0, sizeof(counts)); //search for all the items in their inventory Inventory& user_inv = user->GetInv(); uint8 count = 0; uint8 needcount = 0; std::list<int> MissingItems; uint8 needItemIndex = 0; for (auto row = results.begin(); row != results.end(); ++row, ++needItemIndex) { uint32 item = (uint32)atoi(row[0]); uint8 num = (uint8) atoi(row[1]); needcount += num; //because a HasItem on items with num > 1 only returns the //last-most slot... the results of this are useless to us //when we go to delete them because we cannot assume it is in a single stack. if (user_inv.HasItem(item, num, invWherePersonal) != INVALID_INDEX) count += num; else MissingItems.push_back(item); //dont start deleting anything until we have found it all. items[needItemIndex] = item; counts[needItemIndex] = num; } //make sure we found it all... if(count != needcount) { user->QueuePacket(outapp); safe_delete(outapp); user->Message_StringID(MT_Skills, TRADESKILL_MISSING_COMPONENTS); for(std::list<int>::iterator it = MissingItems.begin(); it != MissingItems.end(); ++it) { const Item_Struct* item = database.GetItem(*it); if(item) user->Message_StringID(MT_Skills, TRADESKILL_MISSING_ITEM, item->Name); } return; } //now we know they have everything... //remove all the items from the players inventory, with updates... int16 slot; for(uint8 r = 0; r < results.RowCount(); r++) { if(items[r] == 0 || counts[r] == 0) continue; //skip empties, could prolly break here //we have to loop here to delete 1 at a time in case its in multiple stacks. for(uint8 k = 0; k < counts[r]; k++) { slot = user_inv.HasItem(items[r], 1, invWherePersonal); if (slot == INVALID_INDEX) { //WTF... I just checked this above, but just to be sure... //we cant undo the previous deletes without a lot of work. //so just call it quits, this shouldent ever happen anyways. user->QueuePacket(outapp); safe_delete(outapp); return; } const ItemInst* inst = user_inv.GetItem(slot); if (inst && !inst->IsStackable()) user->DeleteItemInInventory(slot, 0, true); else user->DeleteItemInInventory(slot, 1, true); } } //otherwise, we found it all... outp->reply_code = 0x00000000; //success for finding it... user->QueuePacket(outapp); safe_delete(outapp); //now actually try to make something... bool success = user->TradeskillExecute(&spec); if (success) { if (!spec.has_learnt && ((spec.must_learn & 0x10) != 0x10)) { user->Message_StringID(4, TRADESKILL_LEARN_RECIPE, spec.name.c_str()); } database.UpdateRecipeMadecount(spec.recipe_id, user->CharacterID(), spec.madecount+1); } //TODO: find in-pack containers in inventory, make sure they are really //there, and then use that slot to handle replace_container too. if(success && spec.replace_container) { // user->DeleteItemInInventory(in_combine->container_slot, 0, true); } if (success) parse->EventPlayer(EVENT_COMBINE_SUCCESS, user, spec.name.c_str(), spec.recipe_id); else parse->EventPlayer(EVENT_COMBINE_FAILURE, user, spec.name.c_str(), spec.recipe_id); }
void SetList::sortByKey() { qSort(begin(), end(), CompareFunctor()); }
bool ZoneDatabase::GetTradeRecipe(const ItemInst* container, uint8 c_type, uint32 some_id, uint32 char_id, DBTradeskillRecipe_Struct *spec) { if (container == nullptr) return false; std::string containers;// make where clause segment for container(s) if (some_id == 0) containers = StringFormat("= %u", c_type); // world combiner so no item number else containers = StringFormat("IN (%u,%u)", c_type, some_id); // container in inventory //Could prolly watch for stacks in this loop and handle them properly... //just increment sum and count accordingly bool first = true; std::string buf2; uint32 count = 0; uint32 sum = 0; for (uint8 i = 0; i < 10; i++) { // <watch> TODO: need to determine if this is bound to world/item container size const ItemInst* inst = container->GetItem(i); if (!inst) continue; const Item_Struct* item = GetItem(inst->GetItem()->ID); if (!item) continue; if(first) { buf2 += StringFormat("%d", item->ID); first = false; } else buf2 += StringFormat(",%d", item->ID); sum += item->ID; count++; } if(count == 0) return false; //no items == no recipe std::string query = StringFormat("SELECT tre.recipe_id " "FROM tradeskill_recipe_entries AS tre " "INNER JOIN tradeskill_recipe AS tr ON (tre.recipe_id = tr.id) " "WHERE tr.enabled AND (( tre.item_id IN(%s) AND tre.componentcount > 0) " "OR ( tre.item_id %s AND tre.iscontainer=1 ))" "GROUP BY tre.recipe_id HAVING sum(tre.componentcount) = %u " "AND sum(tre.item_id * tre.componentcount) = %u", buf2.c_str(), containers.c_str(), count, sum); auto results = QueryDatabase(query); if (!results.Success()) { Log.Out(Logs::General, Logs::Error, "Error in GetTradeRecipe search, query: %s", query.c_str()); Log.Out(Logs::General, Logs::Error, "Error in GetTradeRecipe search, error: %s", results.ErrorMessage().c_str()); return false; } if (results.RowCount() > 1) { //multiple recipes, partial match... do an extra query to get it exact. //this happens when combining components for a smaller recipe //which is completely contained within another recipe first = true; uint32 index = 0; buf2 = ""; for (auto row = results.begin(); row != results.end(); ++row, ++index) { uint32 recipeid = (uint32)atoi(row[0]); if(first) { buf2 += StringFormat("%u", recipeid); first = false; } else buf2 += StringFormat(",%u", recipeid); //length limit on buf2 if(index == 214) { //Maximum number of recipe matches (19 * 215 = 4096) Log.Out(Logs::General, Logs::Error, "GetTradeRecipe warning: Too many matches. Unable to search all recipe entries. Searched %u of %u possible entries.", index + 1, results.RowCount()); break; } } query = StringFormat("SELECT tre.recipe_id " "FROM tradeskill_recipe_entries AS tre " "WHERE tre.recipe_id IN (%s) " "GROUP BY tre.recipe_id HAVING sum(tre.componentcount) = %u " "AND sum(tre.item_id * tre.componentcount) = %u", buf2.c_str(), count, sum); results = QueryDatabase(query); if (!results.Success()) { Log.Out(Logs::General, Logs::Error, "Error in GetTradeRecipe, re-query: %s", query.c_str()); Log.Out(Logs::General, Logs::Error, "Error in GetTradeRecipe, error: %s", results.ErrorMessage().c_str()); return false; } } if (results.RowCount() < 1) return false; if(results.RowCount() > 1) { //The recipe is not unique, so we need to compare the container were using. uint32 containerId = 0; if(some_id) //Standard container containerId = some_id; else if(c_type)//World container containerId = c_type; else //Invalid container return false; query = StringFormat("SELECT tre.recipe_id " "FROM tradeskill_recipe_entries AS tre " "WHERE tre.recipe_id IN (%s) " "AND tre.item_id = %u;", buf2.c_str(), containerId); results = QueryDatabase(query); if (!results.Success()) { Log.Out(Logs::General, Logs::Error, "Error in GetTradeRecipe, re-query: %s", query.c_str()); Log.Out(Logs::General, Logs::Error, "Error in GetTradeRecipe, error: %s", results.ErrorMessage().c_str()); return false; } if(results.RowCount() == 0) { //Recipe contents matched more than 1 recipe, but not in this container Log.Out(Logs::General, Logs::Error, "Combine error: Incorrect container is being used!"); return false; } if (results.RowCount() > 1) //Recipe contents matched more than 1 recipe in this container Log.Out(Logs::General, Logs::Error, "Combine error: Recipe is not unique! %u matches found for container %u. Continuing with first recipe match.", results.RowCount(), containerId); } auto row = results.begin(); uint32 recipe_id = (uint32)atoi(row[0]); //Right here we verify that we actually have ALL of the tradeskill components.. //instead of part which is possible with experimentation. //This is here because something's up with the query above.. it needs to be rethought out bool has_components = true; query = StringFormat("SELECT item_id, componentcount " "FROM tradeskill_recipe_entries " "WHERE recipe_id = %i AND componentcount > 0", recipe_id); results = QueryDatabase(query); if (!results.Success()) { return GetTradeRecipe(recipe_id, c_type, some_id, char_id, spec); } if (results.RowCount() == 0) return GetTradeRecipe(recipe_id, c_type, some_id, char_id, spec); for (auto row = results.begin(); row != results.end(); ++row) { int ccnt = 0; for(int x = MAIN_BEGIN; x < EmuConstants::MAP_WORLD_SIZE; x++) { const ItemInst* inst = container->GetItem(x); if(!inst) continue; const Item_Struct* item = GetItem(inst->GetItem()->ID); if (!item) continue; if(item->ID == atoi(row[0])) ccnt++; } if(ccnt != atoi(row[1])) return false; } return GetTradeRecipe(recipe_id, c_type, some_id, char_id, spec); }
ostream& operator << (ostream& os, const logstring& lstr) { return (os << string{begin(lstr), end(lstr)}); }
iterator end() const { difference_type d = thrust::distance(first, last); return begin() + (d/lead*rows) + (d % lead); }
inline const_reverse_iterator rend() const { return const_reverse_iterator(begin()); }
void CZonePlacer::placeZones(const CMapGenOptions * mapGenOptions, CRandomGenerator * rand) { logGlobal->infoStream() << "Starting zone placement"; int width = mapGenOptions->getWidth(); int height = mapGenOptions->getHeight(); auto zones = gen->getZones(); bool underground = mapGenOptions->getHasTwoLevels(); //gravity-based algorithm const float gravityConstant = 4e-3; const float stiffnessConstant = 4e-3; float zoneScale = 1.0f / std::sqrt(zones.size()); //zones starts small and then inflate. placing more zones is more difficult const float inflateModifier = 1.02; /* let's assume we try to fit N circular zones with radius = size on a map formula: sum((prescaler*n)^2)*pi = WH prescaler = sqrt((WH)/(sum(n^2)*pi)) */ std::vector<std::pair<TRmgTemplateZoneId, CRmgTemplateZone*>> zonesVector (zones.begin(), zones.end()); assert (zonesVector.size()); RandomGeneratorUtil::randomShuffle(zonesVector, *rand); TRmgTemplateZoneId firstZone = zones.begin()->first; //we want lowest ID here bool undergroundFlag = false; std::vector<float> totalSize = { 0, 0 }; //make sure that sum of zone sizes on surface and uderground match size of the map const float radius = 0.4f; const float pi2 = 6.28f; for (auto zone : zonesVector) { //even distribution for surface / underground zones. Surface zones always have priority. int level = 0; if (underground) //only then consider underground zones { if (zone.first == firstZone) { level = 0; } else { level = undergroundFlag; undergroundFlag = !undergroundFlag; //toggle underground on/off } } totalSize[level] += (zone.second->getSize() * zone.second->getSize()); float randomAngle = rand->nextDouble(0, pi2); zone.second->setCenter(float3(0.5f + std::sin(randomAngle) * radius, 0.5f + std::cos(randomAngle) * radius, level)); //place zones around circle } //prescale zones std::vector<float> prescaler = { 0, 0 }; for (int i = 0; i < 2; i++) prescaler[i] = sqrt((width * height) / (totalSize[i] * 3.14f)); float mapSize = sqrt (width * height); for (auto zone : zones) { zone.second->setSize (zone.second->getSize() * prescaler[zone.second->getCenter().z]); } //gravity-based algorithm. connected zones attract, intersceting zones and map boundaries push back //remember best solution float bestTotalDistance = 1e10; float bestTotalOverlap = 1e10; //float bestRatio = 1e10; std::map<CRmgTemplateZone *, float3> bestSolution; const int maxDistanceMovementRatio = zones.size() * zones.size(); //experimental - the more zones, the greater total distance expected auto getDistance = [](float distance) -> float { return (distance ? distance * distance : 1e-6); }; std::map <CRmgTemplateZone *, float3> forces; std::map <CRmgTemplateZone *, float> distances; std::map <CRmgTemplateZone *, float> overlaps; while (zoneScale < 1) //until zones reach their desired size and fill the map tightly { for (auto zone : zones) { float3 forceVector(0,0,0); float3 pos = zone.second->getCenter(); float totalDistance = 0; //attract connected zones for (auto con : zone.second->getConnections()) { auto otherZone = zones[con]; float3 otherZoneCenter = otherZone->getCenter(); float distance = pos.dist2d (otherZoneCenter); float minDistance = (zone.second->getSize() + otherZone->getSize())/mapSize * zoneScale; //scale down to (0,1) coordinates if (distance > minDistance) { //WARNING: compiler used to 'optimize' that line so it never actually worked forceVector += (((otherZoneCenter - pos)*(pos.z == otherZoneCenter.z ? (minDistance/distance) : 1)/ getDistance(distance))) * gravityConstant; //positive value totalDistance += (distance - minDistance); } } distances[zone.second] = totalDistance; float totalOverlap = 0; //separate overlaping zones for (auto otherZone : zones) { float3 otherZoneCenter = otherZone.second->getCenter(); //zones on different levels don't push away if (zone == otherZone || pos.z != otherZoneCenter.z) continue; float distance = pos.dist2d (otherZoneCenter); float minDistance = (zone.second->getSize() + otherZone.second->getSize())/mapSize * zoneScale; if (distance < minDistance) { forceVector -= (((otherZoneCenter - pos)*(minDistance/(distance ? distance : 1e-3))) / getDistance(distance)) * stiffnessConstant; //negative value totalOverlap += (minDistance - distance) / (zoneScale * zoneScale); //overlapping of small zones hurts us more } } //move zones away from boundaries //do not scale boundary distance - zones tend to get squashed float size = zone.second->getSize() / mapSize; auto pushAwayFromBoundary = [&forceVector, pos, &getDistance, size, stiffnessConstant, &totalOverlap](float x, float y) { float3 boundary = float3 (x, y, pos.z); float distance = pos.dist2d(boundary); totalOverlap += distance; //overlapping map boundaries is wrong as well forceVector -= (boundary - pos) * (size - distance) / getDistance(distance) * stiffnessConstant; //negative value }; if (pos.x < size) { pushAwayFromBoundary(0, pos.y); } if (pos.x > 1-size) { pushAwayFromBoundary(1, pos.y); } if (pos.y < size) { pushAwayFromBoundary(pos.x, 0); } if (pos.y > 1-size) { pushAwayFromBoundary(pos.x, 1); } overlaps[zone.second] = totalOverlap; forceVector.z = 0; //operator - doesn't preserve z coordinate :/ forces[zone.second] = forceVector; } //update positions for (auto zone : forces) { zone.first->setCenter (zone.first->getCenter() + zone.second); } //now perform drastic movement of zone that is completely not linked float maxRatio = 0; CRmgTemplateZone * misplacedZone = nullptr; float totalDistance = 0; float totalOverlap = 0; for (auto zone : distances) //find most misplaced zone { totalDistance += zone.second; float overlap = overlaps[zone.first]; totalOverlap += overlap; float ratio = (zone.second + overlap) / forces[zone.first].mag(); //if distance to actual movement is long, the zone is misplaced if (ratio > maxRatio) { maxRatio = ratio; misplacedZone = zone.first; } } logGlobal->traceStream() << boost::format("Total distance between zones in this iteration: %2.4f, Total overlap: %2.4f, Worst misplacement/movement ratio: %3.2f") % totalDistance % totalOverlap % maxRatio; //save best solution before drastic jump if (totalDistance + totalOverlap < bestTotalDistance + bestTotalOverlap) { bestTotalDistance = totalDistance; bestTotalOverlap = totalOverlap; //if (maxRatio < bestRatio) //{ // bestRatio = maxRatio; for (auto zone : zones) bestSolution[zone.second] = zone.second->getCenter(); } if (maxRatio > maxDistanceMovementRatio) { CRmgTemplateZone * targetZone = nullptr; float3 ourCenter = misplacedZone->getCenter(); if (totalDistance > totalOverlap) { //find most distant zone that should be attracted and move inside it float maxDistance = 0; for (auto con : misplacedZone->getConnections()) { auto otherZone = zones[con]; float distance = otherZone->getCenter().dist2dSQ(ourCenter); if (distance > maxDistance) { maxDistance = distance; targetZone = otherZone; } } float3 vec = targetZone->getCenter() - ourCenter; float newDistanceBetweenZones = (std::max(misplacedZone->getSize(), targetZone->getSize())) * zoneScale / mapSize; logGlobal->traceStream() << boost::format("Trying to move zone %d %s towards %d %s. Old distance %f") % misplacedZone->getId() % ourCenter() % targetZone->getId() % targetZone->getCenter()() % maxDistance; logGlobal->traceStream() << boost::format("direction is %s") % vec(); misplacedZone->setCenter(targetZone->getCenter() - vec.unitVector() * newDistanceBetweenZones); //zones should now overlap by half size logGlobal->traceStream() << boost::format("New distance %f") % targetZone->getCenter().dist2d(misplacedZone->getCenter()); } else { float maxOverlap = 0; for (auto otherZone : zones) { float3 otherZoneCenter = otherZone.second->getCenter(); if (otherZone.second == misplacedZone || otherZoneCenter.z != ourCenter.z) continue; float distance = otherZoneCenter.dist2dSQ(ourCenter); if (distance > maxOverlap) { maxOverlap = distance; targetZone = otherZone.second; } } float3 vec = ourCenter - targetZone->getCenter(); float newDistanceBetweenZones = (misplacedZone->getSize() + targetZone->getSize()) * zoneScale / mapSize; logGlobal->traceStream() << boost::format("Trying to move zone %d %s away from %d %s. Old distance %f") % misplacedZone->getId() % ourCenter() % targetZone->getId() % targetZone->getCenter()() % maxOverlap; logGlobal->traceStream() << boost::format("direction is %s") % vec(); misplacedZone->setCenter(targetZone->getCenter() + vec.unitVector() * newDistanceBetweenZones); //zones should now be just separated logGlobal->traceStream() << boost::format("New distance %f") % targetZone->getCenter().dist2d(misplacedZone->getCenter()); } } zoneScale *= inflateModifier; //increase size of zones so they } logGlobal->traceStream() << boost::format("Best fitness reached: total distance %2.4f, total overlap %2.4f") % bestTotalDistance % bestTotalOverlap; for (auto zone : zones) //finalize zone positions { zone.second->setPos (cords (bestSolution[zone.second])); logGlobal->traceStream() << boost::format ("Placed zone %d at relative position %s and coordinates %s") % zone.first % zone.second->getCenter() % zone.second->getPos(); } }
void Client::SendTradeskillDetails(uint32 recipe_id) { //pull the list of components std::string query = StringFormat("SELECT tre.item_id,tre.componentcount,i.icon,i.Name " "FROM tradeskill_recipe_entries AS tre " "LEFT JOIN items AS i ON tre.item_id = i.id " "WHERE tre.componentcount > 0 AND tre.recipe_id = %u", recipe_id); auto results = database.QueryDatabase(query); if (!results.Success()) { return; } if(results.RowCount() < 1) { Log.Out(Logs::General, Logs::Error, "Error in SendTradeskillDetails: no components returned"); return; } if(results.RowCount() > 10) { Log.Out(Logs::General, Logs::Error, "Error in SendTradeskillDetails: too many components returned (%u)", results.RowCount()); return; } //biggest this packet can ever be: // 64 * 10 + 8 * 10 + 4 + 4 * 10 = 764 char *buf = new char[775]; //dynamic so we can just give it to EQApplicationPacket uint8 r,k; uint32 *header = (uint32 *) buf; //Hell if I know why this is in the wrong byte order.... *header = htonl(recipe_id); char *startblock = buf; startblock += sizeof(uint32); uint32 *ffff_start = (uint32 *) startblock; //fill in the FFFF's as if there were 0 items for(r = 0; r < 10; r++) { // world:item container size related? *ffff_start = 0xFFFFFFFF; ffff_start++; } char * datastart = (char *) ffff_start; char * cblock = (char *) ffff_start; uint32 *itemptr; uint32 *iconptr; uint32 len; uint32 datalen = 0; uint8 count = 0; for(auto row = results.begin(); row != results.end(); ++row) { //watch for references to items which are not in the //items table, which the left join will make nullptr... if(row[2] == nullptr || row[3] == nullptr) continue; uint32 item = (uint32)atoi(row[0]); uint8 num = (uint8) atoi(row[1]); uint32 icon = (uint32) atoi(row[2]); const char *name = row[3]; len = strlen(name); if(len > 63) len = 63; //Hell if I know why these are in the wrong byte order.... item = htonl(item); icon = htonl(icon); //if we get more than 10 items, just start skipping them... for(k = 0; k < num && count < 10; k++) { // world:item container size related? itemptr = (uint32 *) cblock; cblock += sizeof(uint32); datalen += sizeof(uint32); iconptr = (uint32 *) cblock; cblock += sizeof(uint32); datalen += sizeof(uint32); *itemptr = item; *iconptr = icon; strncpy(cblock, name, len); cblock[len] = '\0'; //just making sure. cblock += len + 1; //get the null datalen += len + 1; //get the null count++; } } //now move the item data over top of the FFFFs uint8 dist = sizeof(uint32) * (10 - count); startblock += dist; memmove(startblock, datastart, datalen); uint32 total = sizeof(uint32) + dist + datalen; EQApplicationPacket* outapp = new EQApplicationPacket(OP_RecipeDetails); outapp->size = total; outapp->pBuffer = (uchar*) buf; QueuePacket(outapp); DumpPacket(outapp); safe_delete(outapp); }
void Fleet::MovementPhase() { //Logger().debugStream() << "Fleet::MovementPhase this: " << this->Name() << " id: " << this->ID(); m_arrived_this_turn = false; m_arrival_starlane = UniverseObject::INVALID_OBJECT_ID; int prev_prev_system = m_prev_system; Empire* empire = Empires().Lookup(this->Owner()); // if owner of fleet can resupply ships at the location of this fleet, then // resupply all ships in this fleet if (empire && empire->FleetOrResourceSupplyableAtSystem(this->SystemID())) for (Fleet::const_iterator ship_it = this->begin(); ship_it != this->end(); ++ship_it) if (Ship* ship = GetObject<Ship>(*ship_it)) ship->Resupply(); System* current_system = GetObject<System>(SystemID()); System* const initial_system = current_system; std::list<MovePathNode> move_path = this->MovePath(); std::list<MovePathNode>::const_iterator it = move_path.begin(); std::list<MovePathNode>::const_iterator next_it = it; if (next_it != move_path.end()) ++next_it; // is the ship stuck in a system for a whole turn? if (current_system) { // in a system. if there is no system after the current one in the // path, or the current and next nodes have the same system id, that // is an actual system, then won't be moving this turn. if ((next_it == move_path.end()) || (it->object_id != INVALID_OBJECT_ID && it->object_id == next_it->object_id) ) { // fuel regeneration for ships in stationary fleet if (this->FinalDestinationID() == UniverseObject::INVALID_OBJECT_ID || this->FinalDestinationID() == this->SystemID()) { for (Fleet::const_iterator ship_it = this->begin(); ship_it != this->end(); ++ship_it) { if (Ship* ship = GetObject<Ship>(*ship_it)) if (Meter* fuel_meter = ship->UniverseObject::GetMeter(METER_FUEL)) { fuel_meter->AddToCurrent(0.1001); fuel_meter->BackPropegate(); } } } return; } } // if fleet not moving, nothing more to do. if (move_path.empty() || move_path.size() == 1) { //Logger().debugStream() << "Fleet::MovementPhase: Fleet move path is empty or has only one entry. doing nothing"; return; } //Logger().debugStream() << "Fleet::MovementPhase move path:"; //for (std::list<MovePathNode>::const_iterator it = move_path.begin(); it != move_path.end(); ++it) // Logger().debugStream() << "... (" << it->x << ", " << it->y << ") at object id: " << it->object_id << " eta: " << it->eta << (it->turn_end ? " (end of turn)" : " (during turn)"); // move fleet in sequence to MovePathNodes it can reach this turn double fuel_consumed = 0.0; for (it = move_path.begin(); it != move_path.end(); ++it) { next_it = it; ++next_it; System* system = GetObject<System>(it->object_id); //Logger().debugStream() << "... node " << (system ? system->Name() : "no system"); // is this system the last node reached this turn? either it's an end of turn node, // or there are no more nodes after this one on path bool node_is_next_stop = (it->turn_end || next_it == move_path.end()); if (system) { // node is a system. explore system for all owners of this fleet if (empire) empire->AddExploredSystem(it->object_id); prev_prev_system = m_prev_system; m_prev_system = system->ID(); // passing a system, so update previous system of this fleet bool resupply_here = empire ? empire->FleetOrResourceSupplyableAtSystem(system->ID()) : false; // if this system can provide supplies, reset consumed fuel and refuel ships if (resupply_here) { //Logger().debugStream() << " ... node has fuel supply. consumed fuel for movement reset to 0 and fleet resupplied"; fuel_consumed = 0.0; for (Fleet::const_iterator ship_it = this->begin(); ship_it != this->end(); ++ship_it) { Ship* ship = GetObject<Ship>(*ship_it); assert(ship); ship->Resupply(); } } if (node_is_next_stop) { // is system the last node reached this turn? system->Insert(this); // fleet ends turn at this node. insert fleet into system current_system = system; //Logger().debugStream() << "... ... inserted fleet into system"; break; } else { // fleet will continue past this system this turn. //Logger().debugStream() << "... ... moved fleet to system (not inserted)"; if (!resupply_here) { fuel_consumed += 1.0; //Logger().debugStream() << "... ... consuming 1 unit of fuel to continue moving. total fuel consumed now: " << fuel_consumed; } else { //Logger().debugStream() << "... ... not consuming fuel to depart resupply system"; } } } else { // node is not a system. if (node_is_next_stop) { // node is not a system, but is it the last node reached this turn? MoveTo(it->x, it->y); // fleet ends turn at this node. move fleet here //Logger().debugStream() << "... ... moved fleet to position"; break; } } } //Logger().debugStream() << "Fleet::MovementPhase rest of move path:"; //for (std::list<MovePathNode>::const_iterator it2 = it; it2 != move_path.end(); ++it2) // Logger().debugStream() << "... (" << it2->x << ", " << it2->y << ") at object id: " << it2->object_id << " eta: " << it2->eta << (it2->turn_end ? " (end of turn)" : " (during turn)"); // update next system if (m_moving_to != SystemID() && next_it != move_path.end() && it != move_path.end()) { // there is another system later on the path to aim for. find it for (; next_it != move_path.end(); ++next_it) { if (GetObject<System>(next_it->object_id)) { //Logger().debugStream() << "___ setting m_next_system to " << next_it->object_id; m_next_system = next_it->object_id; break; } } } else { // no more systems on path m_arrived_this_turn = current_system != initial_system; m_arrival_starlane = prev_prev_system; m_moving_to = m_next_system = m_prev_system = UniverseObject::INVALID_OBJECT_ID; } // consume fuel from ships in fleet if (fuel_consumed > 0.0) { for (const_iterator ship_it = begin(); ship_it != end(); ++ship_it) if (Ship* ship = GetObject<Ship>(*ship_it)) if (Meter* meter = ship->UniverseObject::GetMeter(METER_FUEL)) { meter->AddToCurrent(-fuel_consumed); meter->BackPropegate(); } } }
bool VACVariable::averaging() { Cost Top = wcsp->getUb(); bool change = false; EnumeratedVariable* x; EnumeratedVariable* y; Constraint* ctr = NULL; ConstraintList::iterator itc = getConstrs()->begin(); if (itc != getConstrs()->end()) ctr = (*itc).constr; while (ctr) { if (ctr->isBinary() && !ctr->isSep()) { BinaryConstraint* bctr = (BinaryConstraint*)ctr; x = (EnumeratedVariable*)bctr->getVarDiffFrom((Variable*)this); for (iterator it = begin(); it != end(); ++it) { Cost cu = getCost(*it); Cost cmin = Top; for (iterator itx = x->begin(); itx != x->end(); ++itx) { Cost cbin = bctr->getCost(this, x, *it, *itx); if (cbin < cmin) cmin = cbin; } assert(cmin < Top); Double mean = to_double(cmin + cu) / 2.; Double extc = to_double(cu) - mean; if (abs(extc) >= 1) { Cost costi = (Long)extc; for (iterator itx = x->begin(); itx != x->end(); ++itx) { bctr->addcost(this, x, *it, *itx, costi); } if (mean > to_double(cu)) project(*it, -costi); else extend(*it, costi); change = true; } } } else if (ctr->isTernary() && !ctr->isSep()) { TernaryConstraint* tctr = (TernaryConstraint*)ctr; x = (EnumeratedVariable*)tctr->getVar(0); if (x == this) x = (EnumeratedVariable*)tctr->getVar(1); y = (EnumeratedVariable*)tctr->getVarDiffFrom((Variable*)this, (Variable*)x); for (iterator it = begin(); it != end(); ++it) { Cost cu = getCost(*it); Cost cmin = Top; for (iterator itx = x->begin(); itx != x->end(); ++itx) { for (iterator ity = y->begin(); ity != y->end(); ++ity) { Cost ctern = tctr->getCost(this, x, y, *it, *itx, *ity); if (ctern < cmin) cmin = ctern; } } assert(cmin < Top); Double mean = to_double(cmin + cu) / 2.; Double extc = to_double(cu) - mean; if (abs(extc) >= 1) { Cost costi = (Long)extc; for (iterator itx = x->begin(); itx != x->end(); ++itx) { for (iterator ity = y->begin(); ity != y->end(); ++ity) { tctr->addCost(this, x, y, *it, *itx, *ity, costi); } } if (mean > to_double(cu)) project(*it, -costi); else extend(*it, costi); change = true; } } } else if (ctr->isNary() && !ctr->isSep()) { NaryConstraint* nctr = (NaryConstraint*)ctr; for (iterator it = begin(); it != end(); ++it) { Cost cu = getCost(*it); Cost cmin = Top; int tindex = nctr->getIndex(this); String tuple; Cost cost; Long nbtuples = 0; nctr->first(); while (nctr->next(tuple, cost)) { nbtuples++; if (toValue(tuple[tindex] - CHAR_FIRST) == (*it) && cost < cmin) cmin = cost; } if (nctr->getDefCost() < cmin && nbtuples < nctr->getDomainSizeProduct() / getDomainSize()) cmin = nctr->getDefCost(); // assert(cmin < Top); Double mean = to_double(cmin + cu) / 2.; Double extc = to_double(cu) - mean; if (abs(extc) >= 1) { Cost costi = (Cost)extc; nctr->addtoTuples(this, *it, costi); if (mean > to_double(cu)) project(*it, -costi); else extend(*it, costi); change = true; } } } ++itc; if (itc != getConstrs()->end()) ctr = (*itc).constr; else ctr = NULL; } return change; }
int main(int argc, char** argv) { std::cout << "hello world" << std::endl; std::random_device rand{}; auto input_dim = 2u; auto output_dim = 1u; auto batch_size = 4u; std::vector<neu::cpu_vector> cpu_input = { {0.f, 0.f}, {1.f, 0.f}, {0.f, 1.f}, {1.f, 1.f} }; std::vector<neu::cpu_vector> cpu_teach = { {0.f}, {1.f}, {1.f}, {0.f} }; neu::gpu_vector input; for(auto const& cpui : cpu_input) { input.insert(input.end(), cpui.begin(), cpui.end()); } neu::gpu_vector teach; for(auto const& cput : cpu_teach) { teach.insert(teach.end(), cput.begin(), cput.end()); } auto layers = std::make_tuple( neu::make_full_connected_layer(input_dim, 3, batch_size, neu::rectifier(), neu::adagrad(input_dim*3, 3, 0.1f)), neu::make_full_connected_layer(3, output_dim, batch_size, neu::sigmoid(), neu::adagrad(3*output_dim, output_dim, 0.1f)) ); std::uniform_real_distribution<> bin{-1.f,1.f}; neu::tuple_foreach(layers, [&rand, &bin](auto& l){ l.init_weight_randomly([&rand, &bin]() { return bin(rand); }); }); for(auto i = 0u; i < 1000u; ++i) { neu::feedforward_x(layers, input); const auto y = neu::layer_get_y(neu::tuple_back(layers)); neu::gpu_vector errors(y.size()); boost::compute::transform(y.begin(), y.end(), teach.begin(), errors.begin(), boost::compute::minus<neu::scalar>()); neu::feedback_delta(layers, errors); neu::update_delta_weight(layers, input); neu::update_weight(layers); neu::gpu_vector squared_errors(errors.size()); boost::compute::transform(errors.begin(), errors.end(), errors.begin(), squared_errors.begin(), boost::compute::multiplies<neu::scalar>()); auto error_sum = boost::compute::accumulate( squared_errors.begin(), squared_errors.end(), 0.0f); if(i%100 == 0) { std::cout << i << ":" << error_sum << std::endl; } } neu::print(teach); std::cout << "\n"; auto y = std::get<std::tuple_size<decltype(layers)>::value-1>(layers).get_y(); neu::print(y); std::cout << std::endl; }
void CPUUncontrolledApproximation::perform() { const auto &ctx = kernel->context(); auto &stateModel = kernel->getCPUKernelStateModel(); auto nl = stateModel.getNeighborList(); auto &data = nl->data(); const auto &box = ctx.boxSize().data(); const auto &pbc = ctx.periodicBoundaryConditions().data(); if (ctx.recordReactionsWithPositions()) { kernel->getCPUKernelStateModel().reactionRecords().clear(); } if (ctx.recordReactionCounts()) { stateModel.resetReactionCounts(); } // gather events std::vector<std::promise<std::size_t>> n_events_promises(kernel->getNThreads()); std::vector<event_promise_t> promises(kernel->getNThreads()); { auto &pool = kernel->pool(); std::vector<std::function<void(std::size_t)>> executables; executables.reserve(kernel->getNThreads()); std::size_t grainSize = data.size() / kernel->getNThreads(); std::size_t nlGrainSize = nl->nCells() / kernel->getNThreads(); auto it = data.cbegin(); std::size_t it_nl = 0; for (auto i = 0U; i < kernel->getNThreads()-1 ; ++i) { auto itNext = std::min(it+grainSize, data.cend()); auto nlNext = std::min(it_nl + nlGrainSize, nl->nCells()); auto bounds_nl = std::make_tuple(it_nl, nlNext); pool.push(findEvents, it, itNext, bounds_nl, kernel, timeStep(), false, std::cref(*nl), std::ref(promises.at(i)), std::ref(n_events_promises.at(i))); it = itNext; it_nl = nlNext; } pool.push(findEvents, it, data.cend(), std::make_tuple(it_nl, nl->nCells()), kernel, timeStep(), false, std::cref(*nl), std::ref(promises.back()), std::ref(n_events_promises.back())); } // collect events std::vector<event_t> events; { std::size_t n_events = 0; for (auto &&f : n_events_promises) { n_events += f.get_future().get(); } events.reserve(n_events); for (auto &&f : promises) { auto eventUpdate = std::move(f.get_future().get()); auto mBegin = std::make_move_iterator(eventUpdate.begin()); auto mEnd = std::make_move_iterator(eventUpdate.end()); events.insert(events.end(), mBegin, mEnd); } } // shuffle reactions std::shuffle(events.begin(), events.end(), std::mt19937(std::random_device()())); // execute reactions { data_t::EntriesUpdate newParticles{}; std::vector<data_t::size_type> decayedEntries{}; // todo better conflict detection? for (auto it = events.begin(); it != events.end(); ++it) { auto &event = *it; if (event.cumulativeRate == 0) { auto entry1 = event.idx1; if (event.nEducts == 1) { auto reaction = ctx.reactions().order1ByType(event.t1)[event.reactionIndex]; if (ctx.recordReactionsWithPositions()) { record_t record; record.id = reaction->id(); performReaction(&data, ctx, entry1, entry1, newParticles, decayedEntries, reaction, &record); bcs::fixPosition(record.where, box, pbc); kernel->getCPUKernelStateModel().reactionRecords().push_back(record); } else { performReaction(&data, ctx, entry1, entry1, newParticles, decayedEntries, reaction, nullptr); } if (ctx.recordReactionCounts()) { auto &counts = stateModel.reactionCounts(); counts.at(reaction->id())++; } for (auto _it2 = it + 1; _it2 != events.end(); ++_it2) { if (_it2->idx1 == entry1 || _it2->idx2 == entry1) { _it2->cumulativeRate = 1; } } } else { auto reaction = ctx.reactions().order2ByType(event.t1, event.t2)[event.reactionIndex]; if (ctx.recordReactionsWithPositions()) { record_t record; record.id = reaction->id(); performReaction(&data, ctx, entry1, event.idx2, newParticles, decayedEntries, reaction, &record); bcs::fixPosition(record.where, box, pbc); kernel->getCPUKernelStateModel().reactionRecords().push_back(record); } else { performReaction(&data, ctx, entry1, event.idx2, newParticles, decayedEntries, reaction, nullptr); } if (ctx.recordReactionCounts()) { auto &counts = stateModel.reactionCounts(); counts.at(reaction->id())++; } for (auto _it2 = it + 1; _it2 != events.end(); ++_it2) { if (_it2->idx1 == entry1 || _it2->idx2 == entry1 || _it2->idx1 == event.idx2 || _it2->idx2 == event.idx2) { _it2->cumulativeRate = 1; } } } } } data.update(std::make_pair(std::move(newParticles), std::move(decayedEntries))); } }
bool RAS_MeshSlot::Join(RAS_MeshSlot *target, MT_Scalar distance) { RAS_DisplayArrayList::iterator it; iterator mit; size_t i; // verify if we can join if (m_joinSlot || (m_joinedSlots.empty() == false) || target->m_joinSlot) return false; if (!Equals(target)) return false; MT_Vector3 co(&m_OpenGLMatrix[12]); MT_Vector3 targetco(&target->m_OpenGLMatrix[12]); if ((co - targetco).length() > distance) return false; MT_Matrix4x4 mat(m_OpenGLMatrix); MT_Matrix4x4 targetmat(target->m_OpenGLMatrix); targetmat.invert(); MT_Matrix4x4 transform = targetmat*mat; // m_mesh, clientobj m_joinSlot = target; m_joinInvTransform = transform; m_joinInvTransform.invert(); target->m_joinedSlots.push_back(this); MT_Matrix4x4 ntransform = m_joinInvTransform.transposed(); ntransform[0][3] = ntransform[1][3] = ntransform[2][3] = 0.0f; for (begin(mit); !end(mit); next(mit)) for (i=mit.startvertex; i<mit.endvertex; i++) mit.vertex[i].Transform(transform, ntransform); /* We know we'll need a list at least this big, reserve in advance */ target->m_displayArrays.reserve(target->m_displayArrays.size() + m_displayArrays.size()); for (it=m_displayArrays.begin(); it!=m_displayArrays.end(); it++) { target->m_displayArrays.push_back(*it); target->m_endarray++; target->m_endvertex = target->m_displayArrays.back()->m_vertex.size(); target->m_endindex = target->m_displayArrays.back()->m_index.size(); } if (m_DisplayList) { m_DisplayList->Release(); m_DisplayList = NULL; } if (target->m_DisplayList) { target->m_DisplayList->Release(); target->m_DisplayList = NULL; } return true; #if 0 return false; #endif }
boolean CREST::begin(const char* host) { return begin(host, 80, false); }
ViewElementList::~ViewElementList() { for (iterator i = begin(); i != end(); ++i) { delete (*i); } }
void StubCodeDesc::print_on(outputStream* st) const { st->print(group()); st->print("::"); st->print(name()); st->print(" [" INTPTR_FORMAT ", " INTPTR_FORMAT "[ (%d bytes)", begin(), end(), size_in_bytes()); }
int C4GraphCollection::GetSeriesCount() const { int iCount = 0; for (const_iterator i = begin(); i != end(); ++i) iCount += (*i)->GetSeriesCount(); return iCount; }
range_safe_iterator_t<Rng> operator()(Rng &&rng, V const &val, P proj = P{}) const { return (*this)(begin(rng), end(rng), val, std::move(proj)); }
void C4GraphCollection::SetAverageTime(int iToTime) { if (iCommonAvgTime = iToTime) for (iterator i = begin(); i != end(); ++i) (*i)->SetAverageTime(iToTime); }
typedef rx::resource<std::vector<int>> resource; WHEN("created by scope"){ auto res = w.start( [&]() { return rx::observable<>:: scope( [&](){ return resource(rxu::to_vector({1, 2, 3, 4, 5})); }, [&](resource r){ auto msg = std::vector<rxsc::test::messages<int>::recorded_type>(); int time = 10; auto values = r.get(); std::for_each(values.begin(), values.end(), [&](int &v){ msg.push_back(on.next(time, v)); time += 10; }); msg.push_back(on.completed(time)); xs.reset(sc.make_cold_observable(msg)); return xs.get(); } ) // forget type to workaround lambda deduction bug on msvc 2013 .as_dynamic(); } ); THEN("the output stops on completion"){ auto required = rxu::to_vector({
LambdaDataReaderListener<TempSensorType> listener; listener.data_available = [](DataReader<TempSensorType>& dr) { auto samples = dr.read(); std::for_each(samples.begin(), samples.end(), [](const Sample<TempSensorType>& s) { std::cout << s.data() << std::endl; }); }; dr.listener(&listener, StatusMask::data_available());
inline const_iterator cbegin() const { return begin(); }