hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
6413561ec480c8c1d73fd18b7fbf6f54b98eee64
2,869
cpp
C++
problems/uva/uva259.cpp
phogbinh/cp
41a86550e14571c8f54bbec9579060647e77209c
[ "MIT" ]
null
null
null
problems/uva/uva259.cpp
phogbinh/cp
41a86550e14571c8f54bbec9579060647e77209c
[ "MIT" ]
null
null
null
problems/uva/uva259.cpp
phogbinh/cp
41a86550e14571c8f54bbec9579060647e77209c
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef vector<int> vi; #define LOCAL #define MAX_V 50 #define V 38 #define INF ( int )10E9 enum { UNVISITED = 0, VISITED }; string str; int totalAppsCount; int res[MAX_V][MAX_V]; int s = 0, t = 37; int mf, f; vi p; void reset() { totalAppsCount = 0; memset(res, 0, sizeof res); } void construct() { char app = str[0]; int appVertex = app - 'A' + 1; res[0][appVertex] = str[1] - '0'; // app count totalAppsCount += res[0][appVertex]; //printf("app %c, vertex %d, count: %d\n", app, appVertex, res[0][appVertex]); for (int i = 3; i < str.length() - 1; ++i) { int computerVertex = str[i] - '0' + 27; //printf("computer vertex #%d: %d\n", i - 3, computerVertex); res[appVertex][computerVertex] = INF; } //printf("\n"); } void augment(int v, int minEdge) { if (v==s) { f = minEdge; return; } else if (p[v]!=-1) { augment(p[v], min(minEdge, res[p[v]][v])); res[p[v]][v] -= f; res[v][p[v]] += f; } } void printResidualCapacities() { //for () } void output() { for (int computerVertex = 27; computerVertex <= 36; ++computerVertex) res[computerVertex][t] = 1; printResidualCapacities(); mf = 0; while (true) { f = 0; vi visit(V, UNVISITED); visit[s] = VISITED; queue<int> q; q.push(s); p.assign(V, -1); while (!q.empty()) { int u = q.front(); q.pop(); if (u==t) break; for (int v = 0; v < V; ++v) if (res[u][v] > 0 && visit[v] == UNVISITED) visit[v] = VISITED, q.push(v), p[v] = u; } augment(t, INF); if (f == 0) break; mf += f; } //printf("total apps count: %d, mf: %d\n", totalAppsCount, mf); if (totalAppsCount != mf) { printf("!\n"); return; } for (int computerVertex = 27; computerVertex <= 36; ++computerVertex) { int assignment = -1; for (int appVertex = 1; appVertex <= 26; ++appVertex) if (res[computerVertex][appVertex]==1) { //printf("comp: %d, app: %d\n", computerVertex, appVertex); assignment = appVertex; break; } if (assignment == -1) printf("_"); else printf("%c", assignment - 1 + 'A'); } printf("\n"); } int main() { #ifdef LOCAL freopen("in", "r", stdin); #endif int cnt = 0; reset(); while (getline(cin, str)) { //printf("#%d: %s|\n", ++cnt, str.c_str()); if (str.length()==0) { output(); reset(); continue; // next job description } construct(); } output(); // Do 1 last time return 0; }
20.941606
101
0.47961
[ "vector" ]
641507e789c33a35242a28b361654d669562ac99
1,338
cpp
C++
454_4Sum_II.cpp
AvadheshChamola/LeetCode
b0edabfa798c4e204b015f4c367bfc5acfbd8277
[ "MIT" ]
null
null
null
454_4Sum_II.cpp
AvadheshChamola/LeetCode
b0edabfa798c4e204b015f4c367bfc5acfbd8277
[ "MIT" ]
null
null
null
454_4Sum_II.cpp
AvadheshChamola/LeetCode
b0edabfa798c4e204b015f4c367bfc5acfbd8277
[ "MIT" ]
null
null
null
/* 454. 4Sum II Medium Given four integer arrays nums1, nums2, nums3, and nums4 all of length n, return the number of tuples (i, j, k, l) such that: 0 <= i, j, k, l < n nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0 Example 1: Input: nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2] Output: 2 Explanation: The two tuples are: 1. (0, 0, 0, 1) -> nums1[0] + nums2[0] + nums3[0] + nums4[1] = 1 + (-2) + (-1) + 2 = 0 2. (1, 1, 0, 0) -> nums1[1] + nums2[1] + nums3[0] + nums4[0] = 2 + (-1) + (-1) + 0 = 0 Example 2: Input: nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0] Output: 1 Constraints: n == nums1.length n == nums2.length n == nums3.length n == nums4.length 1 <= n <= 200 -228 <= nums1[i], nums2[i], nums3[i], nums4[i] <= 228 */ class Solution { public: int fourSumCount(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3, vector<int>& nums4) { unordered_map<int,int> abmap; for(auto a:nums1){ for(auto b:nums2){ ++abmap[a+b]; } } int count=0; for(auto a:nums3){ for(auto b:nums4){ auto it=abmap.find(-1*(a+b)); if(it!=abmap.end()){ count+=it->second; } } } return count; } };
26.76
125
0.488789
[ "vector" ]
641c39d45b1b5896ae079870d8840ba51bbfd1c3
2,762
hpp
C++
QuantExt/qle/models/cdsoptionhelper.hpp
mrslezak/Engine
c46ff278a2c5f4162db91a7ab500a0bb8cef7657
[ "BSD-3-Clause" ]
335
2016-10-07T16:31:10.000Z
2022-03-02T07:12:03.000Z
QuantExt/qle/models/cdsoptionhelper.hpp
mrslezak/Engine
c46ff278a2c5f4162db91a7ab500a0bb8cef7657
[ "BSD-3-Clause" ]
59
2016-10-31T04:20:24.000Z
2022-01-03T16:39:57.000Z
QuantExt/qle/models/cdsoptionhelper.hpp
mrslezak/Engine
c46ff278a2c5f4162db91a7ab500a0bb8cef7657
[ "BSD-3-Clause" ]
180
2016-10-08T14:23:50.000Z
2022-03-28T10:43:05.000Z
/* Copyright (C) 2017 Quaternion Risk Management Ltd All rights reserved. This file is part of ORE, a free-software/open-source library for transparent pricing and risk analysis - http://opensourcerisk.org ORE is free software: you can redistribute it and/or modify it under the terms of the Modified BSD License. You should have received a copy of the license along with this program. The license is also available online at <http://opensourcerisk.org> This program is distributed on the basis that it will form a useful contribution to risk analytics and model standardisation, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ /*! \file models/cdsoptionhelper.hpp \brief cds option calibration helper \ingroup models */ #ifndef quantext_cdsoptionhelper_hpp #define quantext_cdsoptionhelper_hpp #include <qle/instruments/cdsoption.hpp> #include <qle/instruments/creditdefaultswap.hpp> #include <ql/models/calibrationhelper.hpp> #include <ql/quotes/simplequote.hpp> namespace QuantExt { using namespace QuantLib; //! CDS option helper /*! \ingroup models */ class CdsOptionHelper : public BlackCalibrationHelper { public: CdsOptionHelper( const Date& exerciseDate, const Handle<Quote>& volatility, const Protection::Side side, const Schedule& schedule, const BusinessDayConvention paymentConvention, const DayCounter& dayCounter, const Handle<DefaultProbabilityTermStructure>& probability, const Real recoveryRate, const Handle<YieldTermStructure>& termStructure, const Rate spread = Null<Rate>(), const Rate upfront = Null<Rate>(), const bool settlesAccrual = true, const CreditDefaultSwap::ProtectionPaymentTime proteectionPaymentTime = CreditDefaultSwap::ProtectionPaymentTime::atDefault, const Date protectionStart = Date(), const Date upfrontDate = Date(), const boost::shared_ptr<Claim>& claim = boost::shared_ptr<Claim>(), const BlackCalibrationHelper::CalibrationErrorType errorType = BlackCalibrationHelper::RelativePriceError); virtual void addTimesTo(std::list<Time>& times) const {} virtual Real modelValue() const; virtual Real blackPrice(Volatility volatility) const; boost::shared_ptr<CreditDefaultSwap> underlying() const { return cds_; } boost::shared_ptr<QuantExt::CdsOption> option() const { return option_; } private: Handle<YieldTermStructure> termStructure_; boost::shared_ptr<CreditDefaultSwap> cds_; boost::shared_ptr<QuantExt::CdsOption> option_; boost::shared_ptr<SimpleQuote> blackVol_; boost::shared_ptr<PricingEngine> blackEngine_; }; } // namespace QuantExt #endif
39.457143
115
0.763215
[ "model" ]
6420a8ca74b8f90783a5947f7c6272d882b2688b
6,491
cpp
C++
objects/objcomposite.cpp
lukas-ke/faint-graphics-editor
33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf
[ "Apache-2.0" ]
10
2016-12-28T22:06:31.000Z
2021-05-24T13:42:30.000Z
objects/objcomposite.cpp
lukas-ke/faint-graphics-editor
33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf
[ "Apache-2.0" ]
4
2015-10-09T23:55:10.000Z
2020-04-04T08:09:22.000Z
objects/objcomposite.cpp
lukas-ke/faint-graphics-editor
33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf
[ "Apache-2.0" ]
null
null
null
// -*- coding: us-ascii-unix -*- // Copyright 2012 Lukas Kemmer // // Licensed under the Apache License, Version 2.0 (the "License"); you // may not use this file except in compliance with the License. You // may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the License. #include <algorithm> #include <cassert> #include <cmath> // fabs #include <iterator> // back_inserter #include <numeric> // accumulate #include "geo/int-rect.hh" #include "geo/measure.hh" // bounding_rect #include "geo/pathpt.hh" #include "geo/rect.hh" #include "geo/scale.hh" #include "geo/tri.hh" #include "objects/objcomposite.hh" #include "objects/standard-object.hh" #include "text/utf8-string.hh" #include "util/object-util.hh" #include "util/setting-id.hh" #include "util/type-util.hh" namespace faint{ static void update_objects(const Tri& tri, const Tri& origTri, const objects_t& objects, const std::vector<Tri>& objTris) { Adj a = get_adj(origTri, tri); coord ht = std::fabs(origTri.P2().y - origTri.P1().y); for (size_t objNum = 0; objNum != objects.size(); objNum++){ Tri temp = objTris[objNum]; Point p0(temp.P0()); Point p1(temp.P1()); Point p2(temp.P2()); if (a.scale_x != 0 && ht != 0){ // Cannot skew objects scaled to nothing or with a height of zero. p0.x += a.skew * (fabs(ht - p0.y) / ht) / a.scale_x; p1.x += a.skew * (fabs(ht - p1.y) / ht) / a.scale_x; p2.x += a.skew * (fabs(ht - p2.y) / ht) / a.scale_x; } temp = translated(Tri(p0, p1, p2), origTri.P0().x + a.tr_x, origTri.P0().y + a.tr_y); temp = scaled(temp, Scale(a.scale_x, a.scale_y), tri.P3()); temp = rotated(temp, tri.GetAngle(), tri.P3()); objects[objNum]->SetTri(temp); } } class ObjComposite : public StandardObject{ public: ObjComposite(const objects_t& objects, Ownership ownership) : m_objects(objects), m_ownership(ownership) { m_settings.Set(ts_AlignedResize, false); assert(!objects.empty()); for (const auto obj : m_objects){ m_objTris.push_back(obj->GetTri()); } SetTri(tri_from_rect(bounding_rect(m_objects))); m_origTri = GetTri(); for (Tri& objTri : m_objTris){ objTri = Tri(objTri.P0() - m_origTri.P0(), objTri.P1() - m_origTri.P0(), objTri.P2() - m_origTri.P0()); } update_objects(GetTri(), m_origTri, m_objects, m_objTris); } ~ObjComposite(){ if (m_ownership == Ownership::OWNER){ for (Object* obj : m_objects){ delete obj; } } } void Draw(FaintDC& dc, ExpressionContext& ctx) override{ for (Object* obj : m_objects){ obj->Draw(dc, ctx); } } void DrawMask(FaintDC& dc, ExpressionContext& ctx) override{ for (Object* obj : m_objects){ obj->DrawMask(dc, ctx); } } IntRect GetRefreshRect() const override{ assert(!m_objects.empty()); IntRect r(m_objects[0]->GetRefreshRect()); for (size_t i = 1; i != m_objects.size(); i++){ r = bounding_rect(r, m_objects[i]->GetRefreshRect()); } return r; } utf8_string GetType() const override{ return "Group"; } Object* Clone() const override{ return new ObjComposite(*this); } coord GetArea() const override{ return std::accumulate(begin(m_objects), end(m_objects), 0.0, [](auto v, auto obj){ return v + obj->GetArea(); }); } int GetObjectCount() const override{ return resigned(m_objects.size()); } Object* GetObject(int index) override{ return m_objects[to_size_t(index)]; } std::vector<PathPt> GetPath(const ExpressionContext& ctx) const override{ std::vector<PathPt> path; for (Object* object : m_objects){ std::vector<PathPt> subPath(object->GetPath(ctx)); for (PathPt pt : subPath){ path.push_back(pt); } } return path; } const Object* GetObject(int index) const override{ return m_objects[to_size_t(index)]; } std::vector<Point> GetSnappingPoints() const override{ // Fixme: Why only top left? return { bounding_rect(m_tri).TopLeft() }; } Tri GetTri() const override{ return m_tri; } // Fixme: This is probably horrendously slow for complex groups std::vector<Point> GetAttachPoints() const override{ std::vector<Point> points; for (const Object* obj : m_objects){ std::vector<Point> current(obj->GetAttachPoints()); std::copy(begin(current), end(current), std::back_inserter(points)); } return points; } Optional<CmdFuncs> PixelSnapFunc(){ std::vector<CmdFunc> doFuncs; std::vector<CmdFunc> undoFuncs; for (Object* obj : m_objects){ obj->PixelSnapFunc().IfSet( [&](const CmdFuncs& f){ doFuncs.push_back(f.Do); undoFuncs.push_back(f.Undo); }); } if (doFuncs.empty()){ return {}; } return {CmdFuncs( [doFuncs = std::move(doFuncs), this](){ for (const auto& f : doFuncs){ f(); } SetTri(tri_from_rect(bounding_rect(m_objects))); }, [oldTri = m_tri, undoFuncs = std::move(undoFuncs), this](){ for (const auto& f : undoFuncs){ f(); } SetTri(oldTri); })}; } void SetTri(const Tri& tri) override{ assert(valid(tri)); m_tri = tri; update_objects(m_tri, m_origTri, m_objects, m_objTris); } private: ObjComposite(const ObjComposite& other) : StandardObject(other.GetSettings()), m_tri(other.m_tri), m_origTri(other.m_origTri), m_objTris(other.m_objTris), m_ownership(Ownership::OWNER) { for (const Object* obj : other.m_objects){ m_objects.push_back(obj->Clone()); } } objects_t m_objects; Tri m_tri; Tri m_origTri; std::vector<Tri> m_objTris; Ownership m_ownership; }; Object* create_composite_object_raw(const objects_t& objects, Ownership owner){ return new ObjComposite(objects, owner); } ObjectPtr create_composite_object(const objects_t& objects, Ownership owner){ return std::make_unique<ObjComposite>(objects, owner); } bool is_composite(const Object& obj){ return is_type<ObjComposite>(obj); } } // namespace
26.711934
80
0.640733
[ "object", "vector" ]
64217504578ec01bda4538ab040e389ab5cdad8f
5,306
cc
C++
core/graphics/measure.cc
jbeals12/clip
8a987d1ee92290d7724db040094050d5e41e5013
[ "Apache-2.0" ]
null
null
null
core/graphics/measure.cc
jbeals12/clip
8a987d1ee92290d7724db040094050d5e41e5013
[ "Apache-2.0" ]
null
null
null
core/graphics/measure.cc
jbeals12/clip
8a987d1ee92290d7724db040094050d5e41e5013
[ "Apache-2.0" ]
null
null
null
/** * This file is part of the "clip" project * Copyright (c) 2018 Paul Asmuth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "measure.h" #include <assert.h> #include <iostream> namespace clip { Measure::Measure() : Measure(Unit::UNIT, 0) {} Measure::Measure(Unit u, double v) : unit(u), value(v) {} Measure::operator double() const { return value; } Measure from_unit(double v) { return Measure(Unit::UNIT, v); } Measure from_px(double v) { return Measure(Unit::PX, v); } Measure from_pt(double v) { return Measure(Unit::PT, v); } Measure from_pt(double v, double dpi) { return Measure(Unit::UNIT, (v / 72.0) * dpi); } Measure from_em(double v, double font_size) { return Measure(Unit::UNIT, v * font_size); } Measure from_em(double v) { return Measure(Unit::REM, v); } Measure from_user(double v) { return Measure(Unit::USER, v); } Measure from_rel(double v) { return Measure(Unit::REL, v); } ReturnCode parse_measure( const std::string& s, Measure* measure) { double value; size_t unit_pos; try { value = std::stod(s, &unit_pos); } catch (... ) { return errorf(ERROR, "invalid number: '{}'", s); } if (unit_pos == s.size()) { *measure = from_user(value); return OK; } auto unit = s.substr(unit_pos); if (unit == "px") { *measure = from_px(value); return OK; } if (unit == "pt") { *measure = from_pt(value); return OK; } if (unit == "em" || unit == "rem") { *measure = from_em(value); return OK; } if (unit == "%") { *measure = from_rel(value / 100.0); return OK; } if (unit == "rel") { *measure = from_rel(value); return OK; } return errorf( ERROR, "invalid unit: '{}', expected one of 'px', 'pt', 'em', 'rem', 'rel' or '%'", unit); } Measure measure_or(const Measure& primary, const Measure& fallback) { if (primary == 0) { return fallback; } else { return primary; } } void convert_units( const std::vector<UnitConverter>& converters, Measure* begin, Measure* end) { assert(begin <= end); for (auto cur = begin; cur != end; ++cur) { for (const auto& c : converters) { c(cur); } } } void convert_unit( const std::vector<UnitConverter>& converters, Measure* measure) { for (const auto& c : converters) { c(measure); } } void convert_unit_typographic( double dpi, Measure font_size, Measure* measure) { switch (font_size.unit) { case Unit::PT: font_size.value = (double(font_size) / 72.0) * dpi; break; case Unit::UNIT: break; } switch (measure->unit) { case Unit::PT: measure->value = (measure->value / 72.0) * dpi; measure->unit = Unit::UNIT; break; case Unit::REM: measure->value = measure->value * font_size; measure->unit = Unit::UNIT; break; } } void convert_unit_relative( double range, Measure* measure) { switch (measure->unit) { case Unit::REL: measure->unit = Unit::UNIT; measure->value = measure->value * range; break; } } void convert_unit_user( std::function<double (double)> converter, Measure* measure) { switch (measure->unit) { case Unit::USER: measure->unit = Unit::REL; measure->value = converter(measure->value); break; } } void measure_normalize(const MeasureConv& conv, Measure* measure) { double parent_size = 0; switch (conv.parent_size.unit) { case Unit::PT: parent_size = (double(conv.parent_size) / 72.0) * conv.dpi; break; case Unit::REM: case Unit::REL: parent_size = 0; break; case Unit::UNIT: case Unit::PX: case Unit::USER: parent_size = double(conv.parent_size); break; } double font_size = 0; switch (conv.font_size.unit) { case Unit::PT: font_size = (double(conv.font_size) / 72.0) * conv.dpi; break; case Unit::REM: font_size = 0; break; case Unit::REL: font_size = parent_size * double(conv.font_size); break; case Unit::UNIT: case Unit::PX: case Unit::USER: font_size = double(conv.font_size); break; } switch (measure->unit) { case Unit::PT: measure->value = (measure->value / 72.0) * conv.dpi; measure->unit = Unit::UNIT; break; case Unit::REM: measure->value = measure->value * font_size; measure->unit = Unit::UNIT; break; case Unit::REL: measure->value = measure->value * parent_size; measure->unit = Unit::UNIT; break; case Unit::UNIT: case Unit::PX: case Unit::USER: measure->unit = Unit::UNIT; break; } } void measure_normalizev( const MeasureConv& conv, Measure* begin, Measure* end) { for (; begin != end; ++begin) { measure_normalize(conv, begin); } } } // namespace clip
21.224
82
0.607802
[ "vector" ]
642233db3f8f8cc7eedb39787a8240076628d0ef
5,905
cpp
C++
deform_control/external_libs/OpenSceneGraph-2.8.5/applications/osgviewer/osgviewer.cpp
UM-ARM-Lab/mab_ms
f199f05b88060182cfbb47706bd1ff3479032c43
[ "BSD-2-Clause" ]
3
2018-08-20T12:12:43.000Z
2021-06-06T09:43:27.000Z
deform_control/external_libs/OpenSceneGraph-2.8.5/applications/osgviewer/osgviewer.cpp
UM-ARM-Lab/mab_ms
f199f05b88060182cfbb47706bd1ff3479032c43
[ "BSD-2-Clause" ]
null
null
null
deform_control/external_libs/OpenSceneGraph-2.8.5/applications/osgviewer/osgviewer.cpp
UM-ARM-Lab/mab_ms
f199f05b88060182cfbb47706bd1ff3479032c43
[ "BSD-2-Clause" ]
1
2022-03-31T03:12:23.000Z
2022-03-31T03:12:23.000Z
/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This application is open source and may be redistributed and/or modified * freely and without restriction, both in commericial and non commericial applications, * as long as this copyright notice is maintained. * * This application is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ #include <osgDB/ReadFile> #include <osgUtil/Optimizer> #include <osg/CoordinateSystemNode> #include <osg/Switch> #include <osgText/Text> #include <osgViewer/Viewer> #include <osgViewer/ViewerEventHandlers> #include <osgGA/TrackballManipulator> #include <osgGA/FlightManipulator> #include <osgGA/DriveManipulator> #include <osgGA/KeySwitchMatrixManipulator> #include <osgGA/StateSetManipulator> #include <osgGA/AnimationPathManipulator> #include <osgGA/TerrainManipulator> #include <iostream> int main(int argc, char** argv) { // use an ArgumentParser object to manage the program arguments. osg::ArgumentParser arguments(&argc,argv); arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName()); arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the standard OpenSceneGraph example which loads and visualises 3d models."); arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ..."); arguments.getApplicationUsage()->addCommandLineOption("--image <filename>","Load an image and render it on a quad"); arguments.getApplicationUsage()->addCommandLineOption("--dem <filename>","Load an image/DEM and render it on a HeightField"); arguments.getApplicationUsage()->addCommandLineOption("--login <url> <username> <password>","Provide authentication information for http file access."); osgViewer::Viewer viewer(arguments); unsigned int helpType = 0; if ((helpType = arguments.readHelpType())) { arguments.getApplicationUsage()->write(std::cout, helpType); return 1; } // report any errors if they have occurred when parsing the program arguments. if (arguments.errors()) { arguments.writeErrorMessages(std::cout); return 1; } if (arguments.argc()<=1) { arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION); return 1; } std::string url, username, password; while(arguments.read("--login",url, username, password)) { if (!osgDB::Registry::instance()->getAuthenticationMap()) { osgDB::Registry::instance()->setAuthenticationMap(new osgDB::AuthenticationMap); osgDB::Registry::instance()->getAuthenticationMap()->addAuthenticationDetails( url, new osgDB::AuthenticationDetails(username, password) ); } } // set up the camera manipulators. { osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator; keyswitchManipulator->addMatrixManipulator( '1', "Trackball", new osgGA::TrackballManipulator() ); keyswitchManipulator->addMatrixManipulator( '2', "Flight", new osgGA::FlightManipulator() ); keyswitchManipulator->addMatrixManipulator( '3', "Drive", new osgGA::DriveManipulator() ); keyswitchManipulator->addMatrixManipulator( '4', "Terrain", new osgGA::TerrainManipulator() ); std::string pathfile; char keyForAnimationPath = '5'; while (arguments.read("-p",pathfile)) { osgGA::AnimationPathManipulator* apm = new osgGA::AnimationPathManipulator(pathfile); if (apm || !apm->valid()) { unsigned int num = keyswitchManipulator->getNumMatrixManipulators(); keyswitchManipulator->addMatrixManipulator( keyForAnimationPath, "Path", apm ); keyswitchManipulator->selectMatrixManipulator(num); ++keyForAnimationPath; } } viewer.setCameraManipulator( keyswitchManipulator.get() ); } // add the state manipulator viewer.addEventHandler( new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()) ); // add the thread model handler viewer.addEventHandler(new osgViewer::ThreadingHandler); // add the window size toggle handler viewer.addEventHandler(new osgViewer::WindowSizeHandler); // add the stats handler viewer.addEventHandler(new osgViewer::StatsHandler); // add the help handler viewer.addEventHandler(new osgViewer::HelpHandler(arguments.getApplicationUsage())); // add the record camera path handler viewer.addEventHandler(new osgViewer::RecordCameraPathHandler); // add the LOD Scale handler viewer.addEventHandler(new osgViewer::LODScaleHandler); // add the screen capture handler viewer.addEventHandler(new osgViewer::ScreenCaptureHandler); // load the data osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles(arguments); if (!loadedModel) { std::cout << arguments.getApplicationName() <<": No data loaded" << std::endl; return 1; } // any option left unread are converted into errors to write out later. arguments.reportRemainingOptionsAsUnrecognized(); // report any errors if they have occurred when parsing the program arguments. if (arguments.errors()) { arguments.writeErrorMessages(std::cout); return 1; } // optimize the scene graph, remove redundant nodes and state etc. osgUtil::Optimizer optimizer; optimizer.optimize(loadedModel.get()); viewer.setSceneData( loadedModel.get() ); viewer.realize(); return viewer.run(); }
37.138365
164
0.696528
[ "render", "object", "model", "3d" ]
6427f7e04fab9595002ef102e06221ba685c23a4
18,681
cpp
C++
third_party/WebKit/Source/core/frame/FrameSerializer.cpp
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
1
2020-09-15T08:43:34.000Z
2020-09-15T08:43:34.000Z
third_party/WebKit/Source/core/frame/FrameSerializer.cpp
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/core/frame/FrameSerializer.cpp
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (C) 2011 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "core/frame/FrameSerializer.h" #include "core/HTMLNames.h" #include "core/InputTypeNames.h" #include "core/css/CSSFontFaceRule.h" #include "core/css/CSSFontFaceSrcValue.h" #include "core/css/CSSImageValue.h" #include "core/css/CSSImportRule.h" #include "core/css/CSSRuleList.h" #include "core/css/CSSStyleDeclaration.h" #include "core/css/CSSStyleRule.h" #include "core/css/CSSValueList.h" #include "core/css/StylePropertySet.h" #include "core/css/StyleRule.h" #include "core/css/StyleSheetContents.h" #include "core/dom/Document.h" #include "core/dom/Element.h" #include "core/dom/Text.h" #include "core/editing/serializers/MarkupAccumulator.h" #include "core/fetch/FontResource.h" #include "core/fetch/ImageResource.h" #include "core/frame/LocalFrame.h" #include "core/html/HTMLFrameElementBase.h" #include "core/html/HTMLImageElement.h" #include "core/html/HTMLInputElement.h" #include "core/html/HTMLLinkElement.h" #include "core/html/HTMLMetaElement.h" #include "core/html/HTMLStyleElement.h" #include "core/html/ImageDocument.h" #include "core/style/StyleFetchedImage.h" #include "core/style/StyleImage.h" #include "platform/SerializedResource.h" #include "platform/graphics/Image.h" #include "platform/heap/Handle.h" #include "wtf/HashSet.h" #include "wtf/OwnPtr.h" #include "wtf/text/CString.h" #include "wtf/text/StringBuilder.h" #include "wtf/text/TextEncoding.h" #include "wtf/text/WTFString.h" namespace blink { static bool shouldIgnoreElement(const Element& element) { if (isHTMLScriptElement(element)) return true; if (isHTMLNoScriptElement(element)) return true; return isHTMLMetaElement(element) && toHTMLMetaElement(element).computeEncoding().isValid(); } class SerializerMarkupAccumulator : public MarkupAccumulator { STACK_ALLOCATED(); public: SerializerMarkupAccumulator(FrameSerializer::Delegate&, const Document&, HeapVector<Member<Node>>&); ~SerializerMarkupAccumulator() override; protected: void appendText(StringBuilder& out, Text&) override; bool shouldIgnoreAttribute(const Attribute&) override; void appendElement(StringBuilder& out, Element&, Namespaces*) override; void appendAttribute(StringBuilder& out, const Element&, const Attribute&, Namespaces*) override; void appendStartTag(Node&, Namespaces* = nullptr) override; void appendEndTag(const Element&) override; private: void appendAttributeValue(StringBuilder& out, const String& attributeValue); void appendRewrittenAttribute( StringBuilder& out, const Element&, const String& attributeName, const String& attributeValue); FrameSerializer::Delegate& m_delegate; Member<const Document> m_document; // FIXME: |FrameSerializer| uses |m_nodes| for collecting nodes in document // included into serialized text then extracts image, object, etc. The size // of this vector isn't small for large document. It is better to use // callback like functionality. HeapVector<Member<Node>>& m_nodes; // Elements with links rewritten via appendAttribute method. HeapHashSet<Member<const Element>> m_elementsWithRewrittenLinks; }; SerializerMarkupAccumulator::SerializerMarkupAccumulator(FrameSerializer::Delegate& delegate, const Document& document, HeapVector<Member<Node>>& nodes) : MarkupAccumulator(ResolveAllURLs) , m_delegate(delegate) , m_document(&document) , m_nodes(nodes) { } SerializerMarkupAccumulator::~SerializerMarkupAccumulator() { } void SerializerMarkupAccumulator::appendText(StringBuilder& result, Text& text) { Element* parent = text.parentElement(); if (parent && !shouldIgnoreElement(*parent)) MarkupAccumulator::appendText(result, text); } bool SerializerMarkupAccumulator::shouldIgnoreAttribute(const Attribute& attribute) { return m_delegate.shouldIgnoreAttribute(attribute); } void SerializerMarkupAccumulator::appendElement(StringBuilder& result, Element& element, Namespaces* namespaces) { if (!shouldIgnoreElement(element)) MarkupAccumulator::appendElement(result, element, namespaces); // TODO(tiger): Refactor MarkupAccumulator so it is easier to append an element like this, without special cases for XHTML if (isHTMLHeadElement(element)) { result.appendLiteral("<meta http-equiv=\"Content-Type\" content=\""); appendAttributeValue(result, m_document->suggestedMIMEType()); result.appendLiteral("; charset="); appendAttributeValue(result, m_document->characterSet()); if (m_document->isXHTMLDocument()) result.appendLiteral("\" />"); else result.appendLiteral("\">"); } // FIXME: For object (plugins) tags and video tag we could replace them by an image of their current contents. } void SerializerMarkupAccumulator::appendAttribute( StringBuilder& out, const Element& element, const Attribute& attribute, Namespaces* namespaces) { // Check if link rewriting can affect the attribute. bool isLinkAttribute = element.hasLegalLinkAttribute(attribute.name()); bool isSrcDocAttribute = isHTMLFrameElementBase(element) && attribute.name() == HTMLNames::srcdocAttr; if (isLinkAttribute || isSrcDocAttribute) { // Check if the delegate wants to do link rewriting for the element. String newLinkForTheElement; if (m_delegate.rewriteLink(element, newLinkForTheElement)) { if (isLinkAttribute) { // Rewrite element links. appendRewrittenAttribute( out, element, attribute.name().toString(), newLinkForTheElement); } else { ASSERT(isSrcDocAttribute); // Emit src instead of srcdoc attribute for frame elements - we want the // serialized subframe to use html contents from the link provided by // Delegate::rewriteLink rather than html contents from srcdoc // attribute. appendRewrittenAttribute( out, element, HTMLNames::srcAttr.localName(), newLinkForTheElement); } return; } } // Fallback to appending the original attribute. MarkupAccumulator::appendAttribute(out, element, attribute, namespaces); } void SerializerMarkupAccumulator::appendStartTag(Node& node, Namespaces* namespaces) { MarkupAccumulator::appendStartTag(node, namespaces); m_nodes.append(&node); } void SerializerMarkupAccumulator::appendEndTag(const Element& element) { if (!shouldIgnoreElement(element)) MarkupAccumulator::appendEndTag(element); } void SerializerMarkupAccumulator::appendAttributeValue( StringBuilder& out, const String& attributeValue) { MarkupFormatter::appendAttributeValue(out, attributeValue, m_document->isHTMLDocument()); } void SerializerMarkupAccumulator::appendRewrittenAttribute( StringBuilder& out, const Element& element, const String& attributeName, const String& attributeValue) { if (m_elementsWithRewrittenLinks.contains(&element)) return; m_elementsWithRewrittenLinks.add(&element); // Append the rewritten attribute. // TODO(tiger): Refactor MarkupAccumulator so it is easier to append an attribute like this. out.append(' '); out.append(attributeName); out.appendLiteral("=\""); appendAttributeValue(out, attributeValue); out.appendLiteral("\""); } // TODO(tiger): Right now there is no support for rewriting URLs inside CSS // documents which leads to bugs like <https://crbug.com/251898>. Not being // able to rewrite URLs inside CSS documents means that resources imported from // url(...) statements in CSS might not work when rewriting links for the // "Webpage, Complete" method of saving a page. It will take some work but it // needs to be done if we want to continue to support non-MHTML saved pages. FrameSerializer::FrameSerializer( Vector<SerializedResource>& resources, Delegate& delegate) : m_resources(&resources) , m_delegate(delegate) { } void FrameSerializer::serializeFrame(const LocalFrame& frame) { ASSERT(frame.document()); Document& document = *frame.document(); KURL url = document.url(); // If frame is an image document, add the image and don't continue if (document.isImageDocument()) { ImageDocument& imageDocument = toImageDocument(document); addImageToResources(imageDocument.cachedImage(), url); return; } HeapVector<Member<Node>> serializedNodes; SerializerMarkupAccumulator accumulator(m_delegate, document, serializedNodes); String text = serializeNodes<EditingStrategy>(accumulator, document, IncludeNode); CString frameHTML = document.encoding().encode(text, WTF::EntitiesForUnencodables); m_resources->append(SerializedResource(url, document.suggestedMIMEType(), SharedBuffer::create(frameHTML.data(), frameHTML.length()))); for (Node* node: serializedNodes) { ASSERT(node); if (!node->isElementNode()) continue; Element& element = toElement(*node); // We have to process in-line style as it might contain some resources (typically background images). if (element.isStyledElement()) { retrieveResourcesForProperties(element.inlineStyle(), document); retrieveResourcesForProperties(element.presentationAttributeStyle(), document); } if (isHTMLImageElement(element)) { HTMLImageElement& imageElement = toHTMLImageElement(element); KURL url = document.completeURL(imageElement.getAttribute(HTMLNames::srcAttr)); ImageResource* cachedImage = imageElement.cachedImage(); addImageToResources(cachedImage, url); } else if (isHTMLInputElement(element)) { HTMLInputElement& inputElement = toHTMLInputElement(element); if (inputElement.type() == InputTypeNames::image && inputElement.imageLoader()) { KURL url = inputElement.src(); ImageResource* cachedImage = inputElement.imageLoader()->image(); addImageToResources(cachedImage, url); } } else if (isHTMLLinkElement(element)) { HTMLLinkElement& linkElement = toHTMLLinkElement(element); if (CSSStyleSheet* sheet = linkElement.sheet()) { KURL url = document.completeURL(linkElement.getAttribute(HTMLNames::hrefAttr)); serializeCSSStyleSheet(*sheet, url); } } else if (isHTMLStyleElement(element)) { HTMLStyleElement& styleElement = toHTMLStyleElement(element); if (CSSStyleSheet* sheet = styleElement.sheet()) serializeCSSStyleSheet(*sheet, KURL()); } } } void FrameSerializer::serializeCSSStyleSheet(CSSStyleSheet& styleSheet, const KURL& url) { StringBuilder cssText; cssText.appendLiteral("@charset \""); cssText.append(styleSheet.contents()->charset().lower()); cssText.appendLiteral("\";\n\n"); for (unsigned i = 0; i < styleSheet.length(); ++i) { CSSRule* rule = styleSheet.item(i); String itemText = rule->cssText(); if (!itemText.isEmpty()) { cssText.append(itemText); if (i < styleSheet.length() - 1) cssText.appendLiteral("\n\n"); } // Some rules have resources associated with them that we need to retrieve. serializeCSSRule(rule); } if (shouldAddURL(url)) { WTF::TextEncoding textEncoding(styleSheet.contents()->charset()); ASSERT(textEncoding.isValid()); String textString = cssText.toString(); CString text = textEncoding.encode(textString, WTF::CSSEncodedEntitiesForUnencodables); m_resources->append(SerializedResource(url, String("text/css"), SharedBuffer::create(text.data(), text.length()))); m_resourceURLs.add(url); } } void FrameSerializer::serializeCSSRule(CSSRule* rule) { ASSERT(rule->parentStyleSheet()->ownerDocument()); Document& document = *rule->parentStyleSheet()->ownerDocument(); switch (rule->type()) { case CSSRule::STYLE_RULE: retrieveResourcesForProperties(&toCSSStyleRule(rule)->styleRule()->properties(), document); break; case CSSRule::IMPORT_RULE: { CSSImportRule* importRule = toCSSImportRule(rule); KURL sheetBaseURL = rule->parentStyleSheet()->baseURL(); ASSERT(sheetBaseURL.isValid()); KURL importURL = KURL(sheetBaseURL, importRule->href()); if (m_resourceURLs.contains(importURL)) break; if (importRule->styleSheet()) serializeCSSStyleSheet(*importRule->styleSheet(), importURL); break; } // Rules inheriting CSSGroupingRule case CSSRule::MEDIA_RULE: case CSSRule::SUPPORTS_RULE: { CSSRuleList* ruleList = rule->cssRules(); for (unsigned i = 0; i < ruleList->length(); ++i) serializeCSSRule(ruleList->item(i)); break; } case CSSRule::FONT_FACE_RULE: retrieveResourcesForProperties(&toCSSFontFaceRule(rule)->styleRule()->properties(), document); break; // Rules in which no external resources can be referenced case CSSRule::CHARSET_RULE: case CSSRule::PAGE_RULE: case CSSRule::KEYFRAMES_RULE: case CSSRule::KEYFRAME_RULE: case CSSRule::VIEWPORT_RULE: break; default: ASSERT_NOT_REACHED(); } } bool FrameSerializer::shouldAddURL(const KURL& url) { return url.isValid() && !m_resourceURLs.contains(url) && !url.protocolIsData() && !m_delegate.shouldSkipResource(url); } void FrameSerializer::addToResources(Resource* resource, PassRefPtr<SharedBuffer> data, const KURL& url) { if (!data) { DLOG(ERROR) << "No data for resource " << url.getString(); return; } String mimeType = resource->response().mimeType(); m_resources->append(SerializedResource(url, mimeType, data)); m_resourceURLs.add(url); } void FrameSerializer::addImageToResources(ImageResource* image, const KURL& url) { if (!image || !image->hasImage() || image->errorOccurred() || !shouldAddURL(url)) return; RefPtr<SharedBuffer> data = image->getImage()->data(); addToResources(image, data, url); } void FrameSerializer::addFontToResources(FontResource* font) { if (!font || !font->isLoaded() || !font->resourceBuffer() || !shouldAddURL(font->url())) return; RefPtr<SharedBuffer> data(font->resourceBuffer()); addToResources(font, data, font->url()); } void FrameSerializer::retrieveResourcesForProperties(const StylePropertySet* styleDeclaration, Document& document) { if (!styleDeclaration) return; // The background-image and list-style-image (for ul or ol) are the CSS properties // that make use of images. We iterate to make sure we include any other // image properties there might be. unsigned propertyCount = styleDeclaration->propertyCount(); for (unsigned i = 0; i < propertyCount; ++i) { CSSValue* cssValue = styleDeclaration->propertyAt(i).value(); retrieveResourcesForCSSValue(cssValue, document); } } void FrameSerializer::retrieveResourcesForCSSValue(CSSValue* cssValue, Document& document) { if (cssValue->isImageValue()) { CSSImageValue* imageValue = toCSSImageValue(cssValue); if (imageValue->isCachePending()) return; StyleImage* styleImage = imageValue->cachedImage(); if (!styleImage || !styleImage->isImageResource()) return; addImageToResources(styleImage->cachedImage(), styleImage->cachedImage()->url()); } else if (cssValue->isFontFaceSrcValue()) { CSSFontFaceSrcValue* fontFaceSrcValue = toCSSFontFaceSrcValue(cssValue); if (fontFaceSrcValue->isLocal()) { return; } addFontToResources(fontFaceSrcValue->fetch(&document)); } else if (cssValue->isValueList()) { CSSValueList* cssValueList = toCSSValueList(cssValue); for (unsigned i = 0; i < cssValueList->length(); i++) retrieveResourcesForCSSValue(cssValueList->item(i), document); } } // Returns MOTW (Mark of the Web) declaration before html tag which is in // HTML comment, e.g. "<!-- saved from url=(%04d)%s -->" // See http://msdn2.microsoft.com/en-us/library/ms537628(VS.85).aspx. String FrameSerializer::markOfTheWebDeclaration(const KURL& url) { StringBuilder builder; bool emitsMinus = false; CString orignalUrl = url.getString().ascii(); for (const char* string = orignalUrl.data(); *string; ++string) { const char ch = *string; if (ch == '-' && emitsMinus) { builder.append("%2D"); emitsMinus = false; continue; } emitsMinus = ch == '-'; builder.append(ch); } CString escapedUrl = builder.toString().ascii(); return String::format("saved from url=(%04d)%s", static_cast<int>(escapedUrl.length()), escapedUrl.data()); } } // namespace blink
38.438272
152
0.69659
[ "object", "vector" ]
643d66a7db044ed9c89acb020e5e537bf09c36e8
3,375
hpp
C++
include/details/storage_with_backref.hpp
obhi-d/cpptables
5716eac6463b1eb028147c2201c116c8e04b7f7b
[ "MIT" ]
null
null
null
include/details/storage_with_backref.hpp
obhi-d/cpptables
5716eac6463b1eb028147c2201c116c8e04b7f7b
[ "MIT" ]
3
2019-09-26T10:57:39.000Z
2019-12-12T12:08:39.000Z
include/details/storage_with_backref.hpp
obhi-d/cpptables
5716eac6463b1eb028147c2201c116c8e04b7f7b
[ "MIT" ]
null
null
null
#pragma once #include "basic_types.hpp" namespace cpptables { namespace details { template <typename Ty, typename Backref, typename SizeType> struct storage_with_backref { using constants = details::constants<SizeType>; storage_with_backref() noexcept { set_null(); } storage_with_backref(const storage_with_backref& iCopy) noexcept { if (!iCopy.is_null()) new (&storage) Ty(iCopy.object()); else set_link_index(iCopy.get_link_index()); } storage_with_backref(storage_with_backref&& iMove) noexcept { if (!iMove.is_null()) new (&storage) Ty(std::move(iMove.object())); else set_link_index(iMove.get_link_index()); } storage_with_backref& operator=(const storage_with_backref& iOther) noexcept { if (!is_null()) { if (!iOther.is_null()) object() = iOther.object(); else { object().~Ty(); set_link_index(iOther.get_link_index()); } } else { if (!iOther.is_null()) new (&storage) Ty(iOther.object()); else set_link_index(iOther.get_link_index()); } return *this; } storage_with_backref& operator=(storage_with_backref&& iOther) noexcept { if (!is_null()) { if (!iOther.is_null()) object() = std::move(iOther.object()); else { object().~Ty(); set_link_index(iOther.get_link_index()); } } else { if (!iOther.is_null()) new (&storage) Ty(std::move(iOther.object())); else set_link_index(iOther.get_link_index()); } return *this; } storage_with_backref(Ty const& iObject) noexcept { new (&storage) Ty(iObject); } storage_with_backref(Ty&& iObject) noexcept { new (&storage) Ty(std::move(iObject)); } template <typename... Args> storage_with_backref(Args&&... args) { new (&storage) Ty(std::forward<Args>(args)...); } ~storage_with_backref() { if (!is_null()) destroy(); } inline Ty& object() noexcept { return reinterpret_cast<Ty&>(storage); } inline Ty const& object() const noexcept { return reinterpret_cast<Ty const&>(storage); } inline SizeType get_link_index() const noexcept { return static_cast<SizeType>( Backref::template get_link<Ty, SizeType>(object())); } inline void set_link_index(SizeType iData) noexcept { return Backref::template set_link<Ty, SizeType>(object(), link<Ty, SizeType>(iData)); } inline bool is_null() const noexcept { return (static_cast<SizeType>( Backref::template get_link<Ty, SizeType>(object())) & constants::k_invalid_bit) != 0; } inline void set_null() noexcept { set_link_index(constants::k_invalid_bit); } void construct(Ty const& iObject) { new (&storage) Ty(iObject); } void construct(Ty&& iObject) { new (&storage) Ty(std::move(iObject)); } template <typename... Args> void construct(Args&&... args) { new (&storage) Ty(std::forward<Args>(args)...); } void destroy_if_not_null() { if (!is_null()) { destroy(); set_null(); } } void destroy() { object().~Ty(); } void set_next_free_index(SizeType iIndex) { assert((iIndex & constants::k_invalid_bit) == 0); set_link_index(iIndex | constants::k_invalid_bit); } SizeType get_next_free_index() const { return get_link_index() & constants::k_link_mask; } Ty const& get() const { return object(); } Ty& get() { return object(); } // Note: Alignmen is handled by allocator std::aligned_storage_t<sizeof(Ty)> storage; }; } // namespace details } // namespace cpptables
28.125
87
0.68
[ "object" ]
6443ddb2426c1b3d6fef9bc98c27e25171bba5dd
133,787
cpp
C++
ripley/src/DefaultAssembler2D.cpp
svn2github/Escript
9c616a3b164446c65d4b8564ecd04fafd7dcf0d2
[ "Apache-2.0" ]
null
null
null
ripley/src/DefaultAssembler2D.cpp
svn2github/Escript
9c616a3b164446c65d4b8564ecd04fafd7dcf0d2
[ "Apache-2.0" ]
1
2019-01-14T03:07:43.000Z
2019-01-14T03:07:43.000Z
ripley/src/DefaultAssembler2D.cpp
svn2github/Escript
9c616a3b164446c65d4b8564ecd04fafd7dcf0d2
[ "Apache-2.0" ]
null
null
null
/***************************************************************************** * * Copyright (c) 2003-2018 by The University of Queensland * http://www.uq.edu.au * * Primary Business: Queensland, Australia * Licensed under the Apache License, version 2.0 * http://www.apache.org/licenses/LICENSE-2.0 * * Development until 2012 by Earth Systems Science Computational Center (ESSCC) * Development 2012-2013 by School of Earth Sciences * Development from 2014 by Centre for Geoscience Computing (GeoComp) * *****************************************************************************/ #include <ripley/DefaultAssembler2D.h> #include <ripley/domainhelpers.h> #include <escript/DataTypes.h> #include <escript/index.h> using namespace std; using escript::AbstractSystemMatrix; using escript::Data; namespace ripley { template<class Scalar> void DefaultAssembler2D<Scalar>::collateFunctionSpaceTypes( vector<int>& fsTypes, const DataMap& coefs) const { if (isNotEmpty("A", coefs)) fsTypes.push_back(coefs.find("A")->second.getFunctionSpace().getTypeCode()); if (isNotEmpty("B", coefs)) fsTypes.push_back(coefs.find("B")->second.getFunctionSpace().getTypeCode()); if (isNotEmpty("C", coefs)) fsTypes.push_back(coefs.find("C")->second.getFunctionSpace().getTypeCode()); if (isNotEmpty("D", coefs)) fsTypes.push_back(coefs.find("D")->second.getFunctionSpace().getTypeCode()); if (isNotEmpty("X", coefs)) fsTypes.push_back(coefs.find("X")->second.getFunctionSpace().getTypeCode()); if (isNotEmpty("Y", coefs)) fsTypes.push_back(coefs.find("Y")->second.getFunctionSpace().getTypeCode()); } /****************************************************************************/ // wrappers /****************************************************************************/ template<class Scalar> void DefaultAssembler2D<Scalar>::assemblePDESingle(AbstractSystemMatrix* mat, Data& rhs, const DataMap& coefs) const { const Data& A = unpackData("A", coefs); const Data& B = unpackData("B", coefs); const Data& C = unpackData("C", coefs); const Data& D = unpackData("D", coefs); const Data& X = unpackData("X", coefs); const Data& Y = unpackData("Y", coefs); assemblePDESingle(mat, rhs, A, B, C, D, X, Y); } template<class Scalar> void DefaultAssembler2D<Scalar>::assemblePDEBoundarySingle( AbstractSystemMatrix* mat, Data& rhs, const DataMap& coefs) const { const Data& d = unpackData("d", coefs); const Data& y = unpackData("y", coefs); assemblePDEBoundarySingle(mat, rhs, d, y); } template<class Scalar> void DefaultAssembler2D<Scalar>::assemblePDESingleReduced( AbstractSystemMatrix* mat, Data& rhs, const DataMap& coefs) const { const Data& A = unpackData("A", coefs); const Data& B = unpackData("B", coefs); const Data& C = unpackData("C", coefs); const Data& D = unpackData("D", coefs); const Data& X = unpackData("X", coefs); const Data& Y = unpackData("Y", coefs); assemblePDESingleReduced(mat, rhs, A, B, C, D, X, Y); } template<class Scalar> void DefaultAssembler2D<Scalar>::assemblePDEBoundarySingleReduced( AbstractSystemMatrix* mat, Data& rhs, const DataMap& coefs) const { const Data& d = unpackData("d", coefs); const Data& y = unpackData("y", coefs); assemblePDEBoundarySingleReduced(mat, rhs, d, y); } template<class Scalar> void DefaultAssembler2D<Scalar>::assemblePDESystem(AbstractSystemMatrix* mat, Data& rhs, const DataMap& coefs) const { const Data& A = unpackData("A", coefs); const Data& B = unpackData("B", coefs); const Data& C = unpackData("C", coefs); const Data& D = unpackData("D", coefs); const Data& X = unpackData("X", coefs); const Data& Y = unpackData("Y", coefs); assemblePDESystem(mat, rhs, A, B, C, D, X, Y); } template<class Scalar> void DefaultAssembler2D<Scalar>::assemblePDEBoundarySystem( AbstractSystemMatrix* mat, Data& rhs, const DataMap& coefs) const { const Data& d = unpackData("d", coefs); const Data& y = unpackData("y", coefs); assemblePDEBoundarySystem(mat, rhs, d, y); } template<class Scalar> void DefaultAssembler2D<Scalar>::assemblePDESystemReduced( AbstractSystemMatrix* mat, Data& rhs, const DataMap& coefs) const { const Data& A = unpackData("A", coefs); const Data& B = unpackData("B", coefs); const Data& C = unpackData("C", coefs); const Data& D = unpackData("D", coefs); const Data& X = unpackData("X", coefs); const Data& Y = unpackData("Y", coefs); assemblePDESystemReduced(mat, rhs, A, B, C, D, X, Y); } template<class Scalar> void DefaultAssembler2D<Scalar>::assemblePDEBoundarySystemReduced( AbstractSystemMatrix* mat, Data& rhs, const DataMap& coefs) const { const Data& d = unpackData("d", coefs); const Data& y = unpackData("y", coefs); assemblePDEBoundarySystemReduced(mat, rhs, d, y); } /****************************************************************************/ // PDE SINGLE /****************************************************************************/ template<class Scalar> void DefaultAssembler2D<Scalar>::assemblePDESingle(AbstractSystemMatrix* mat, Data& rhs, const Data& A, const Data& B, const Data& C, const Data& D, const Data& X, const Data& Y) const { const double SQRT3 = 1.73205080756887719318; const double w1 = 1.0/24.0; const double w5 = -SQRT3/24 + 1.0/12; const double w2 = -SQRT3/24 - 1.0/12; const double w19 = -m_dx[0]/12; const double w11 = w19*(SQRT3 + 3)/12; const double w14 = w19*(-SQRT3 + 3)/12; const double w16 = w19*(5*SQRT3 + 9)/12; const double w17 = w19*(-5*SQRT3 + 9)/12; const double w27 = w19*(-SQRT3 - 3)/2; const double w28 = w19*(SQRT3 - 3)/2; const double w18 = -m_dx[1]/12; const double w12 = w18*(5*SQRT3 + 9)/12; const double w13 = w18*(-5*SQRT3 + 9)/12; const double w10 = w18*(SQRT3 + 3)/12; const double w15 = w18*(-SQRT3 + 3)/12; const double w25 = w18*(-SQRT3 - 3)/2; const double w26 = w18*(SQRT3 - 3)/2; const double w22 = m_dx[0]*m_dx[1]/144; const double w20 = w22*(SQRT3 + 2); const double w21 = w22*(-SQRT3 + 2); const double w23 = w22*(4*SQRT3 + 7); const double w24 = w22*(-4*SQRT3 + 7); const double w3 = m_dx[0]/(24*m_dx[1]); const double w7 = w3*(SQRT3 + 2); const double w8 = w3*(-SQRT3 + 2); const double w6 = -m_dx[1]/(24*m_dx[0]); const double w0 = w6*(SQRT3 + 2); const double w4 = w6*(-SQRT3 + 2); const int NE0 = m_NE[0]; const int NE1 = m_NE[1]; const bool addEM_S = (!A.isEmpty() || !B.isEmpty() || !C.isEmpty() || !D.isEmpty()); const bool addEM_F = (!X.isEmpty() || !Y.isEmpty()); const Scalar zero = static_cast<Scalar>(0); rhs.requireWrite(); #pragma omp parallel { vector<Scalar> EM_S(4*4, zero); vector<Scalar> EM_F(4, zero); for (index_t k1_0 = 0; k1_0 < 2; k1_0++) { // colouring #pragma omp for for (index_t k1 = k1_0; k1 < NE1; k1+=2) { for (index_t k0 = 0; k0 < NE0; ++k0) { const index_t e = k0 + NE0*k1; if (addEM_S) fill(EM_S.begin(), EM_S.end(), zero); if (addEM_F) fill(EM_F.begin(), EM_F.end(), zero); /////////////// // process A // /////////////// if (!A.isEmpty()) { const Scalar* A_p = A.getSampleDataRO(e, zero); if (A.actsExpanded()) { const Scalar A_00_0 = A_p[INDEX3(0,0,0,2,2)]; const Scalar A_01_0 = A_p[INDEX3(0,1,0,2,2)]; const Scalar A_10_0 = A_p[INDEX3(1,0,0,2,2)]; const Scalar A_11_0 = A_p[INDEX3(1,1,0,2,2)]; const Scalar A_00_1 = A_p[INDEX3(0,0,1,2,2)]; const Scalar A_01_1 = A_p[INDEX3(0,1,1,2,2)]; const Scalar A_10_1 = A_p[INDEX3(1,0,1,2,2)]; const Scalar A_11_1 = A_p[INDEX3(1,1,1,2,2)]; const Scalar A_00_2 = A_p[INDEX3(0,0,2,2,2)]; const Scalar A_01_2 = A_p[INDEX3(0,1,2,2,2)]; const Scalar A_10_2 = A_p[INDEX3(1,0,2,2,2)]; const Scalar A_11_2 = A_p[INDEX3(1,1,2,2,2)]; const Scalar A_00_3 = A_p[INDEX3(0,0,3,2,2)]; const Scalar A_01_3 = A_p[INDEX3(0,1,3,2,2)]; const Scalar A_10_3 = A_p[INDEX3(1,0,3,2,2)]; const Scalar A_11_3 = A_p[INDEX3(1,1,3,2,2)]; const Scalar tmp0 = w3*(A_11_0 + A_11_1 + A_11_2 + A_11_3); const Scalar tmp1 = w1*(A_01_0 + A_01_3 - A_10_1 - A_10_2); const Scalar tmp2 = w4*(A_00_2 + A_00_3); const Scalar tmp3 = w0*(A_00_0 + A_00_1); const Scalar tmp4 = w5*(A_01_2 - A_10_3); const Scalar tmp5 = w2*(-A_01_1 + A_10_0); const Scalar tmp6 = w5*(A_01_3 + A_10_0); const Scalar tmp7 = w3*(-A_11_0 - A_11_1 - A_11_2 - A_11_3); const Scalar tmp8 = w6*(A_00_0 + A_00_1 + A_00_2 + A_00_3); const Scalar tmp9 = w1*(A_01_1 + A_01_2 + A_10_1 + A_10_2); const Scalar tmp10 = w2*(-A_01_0 - A_10_3); const Scalar tmp11 = w4*(A_00_0 + A_00_1); const Scalar tmp12 = w0*(A_00_2 + A_00_3); const Scalar tmp13 = w5*(A_01_1 - A_10_0); const Scalar tmp14 = w2*(-A_01_2 + A_10_3); const Scalar tmp15 = w7*(A_11_0 + A_11_2); const Scalar tmp16 = w4*(-A_00_2 - A_00_3); const Scalar tmp17 = w0*(-A_00_0 - A_00_1); const Scalar tmp18 = w5*(A_01_3 + A_10_3); const Scalar tmp19 = w8*(A_11_1 + A_11_3); const Scalar tmp20 = w2*(-A_01_0 - A_10_0); const Scalar tmp21 = w7*(A_11_1 + A_11_3); const Scalar tmp22 = w4*(-A_00_0 - A_00_1); const Scalar tmp23 = w0*(-A_00_2 - A_00_3); const Scalar tmp24 = w5*(A_01_0 + A_10_0); const Scalar tmp25 = w8*(A_11_0 + A_11_2); const Scalar tmp26 = w2*(-A_01_3 - A_10_3); const Scalar tmp27 = w5*(-A_01_1 - A_10_2); const Scalar tmp28 = w1*(-A_01_0 - A_01_3 - A_10_0 - A_10_3); const Scalar tmp29 = w2*(A_01_2 + A_10_1); const Scalar tmp30 = w7*(-A_11_1 - A_11_3); const Scalar tmp31 = w1*(-A_01_1 - A_01_2 + A_10_0 + A_10_3); const Scalar tmp32 = w5*(-A_01_0 + A_10_2); const Scalar tmp33 = w8*(-A_11_0 - A_11_2); const Scalar tmp34 = w6*(-A_00_0 - A_00_1 - A_00_2 - A_00_3); const Scalar tmp35 = w2*(A_01_3 - A_10_1); const Scalar tmp36 = w5*(A_01_0 + A_10_3); const Scalar tmp37 = w2*(-A_01_3 - A_10_0); const Scalar tmp38 = w7*(-A_11_0 - A_11_2); const Scalar tmp39 = w5*(-A_01_3 + A_10_1); const Scalar tmp40 = w8*(-A_11_1 - A_11_3); const Scalar tmp41 = w2*(A_01_0 - A_10_2); const Scalar tmp42 = w5*(A_01_1 - A_10_3); const Scalar tmp43 = w2*(-A_01_2 + A_10_0); const Scalar tmp44 = w5*(A_01_2 - A_10_0); const Scalar tmp45 = w2*(-A_01_1 + A_10_3); const Scalar tmp46 = w5*(-A_01_0 + A_10_1); const Scalar tmp47 = w2*(A_01_3 - A_10_2); const Scalar tmp48 = w5*(-A_01_1 - A_10_1); const Scalar tmp49 = w2*(A_01_2 + A_10_2); const Scalar tmp50 = w5*(-A_01_3 + A_10_2); const Scalar tmp51 = w2*(A_01_0 - A_10_1); const Scalar tmp52 = w5*(-A_01_2 - A_10_1); const Scalar tmp53 = w2*(A_01_1 + A_10_2); const Scalar tmp54 = w5*(-A_01_2 - A_10_2); const Scalar tmp55 = w2*(A_01_1 + A_10_1); EM_S[INDEX2(0,0,4)]+=tmp15 + tmp16 + tmp17 + tmp18 + tmp19 + tmp20 + tmp9; EM_S[INDEX2(0,1,4)]+=tmp0 + tmp1 + tmp2 + tmp3 + tmp4 + tmp5; EM_S[INDEX2(0,2,4)]+=tmp31 + tmp34 + tmp38 + tmp39 + tmp40 + tmp41; EM_S[INDEX2(0,3,4)]+=tmp28 + tmp52 + tmp53 + tmp7 + tmp8; EM_S[INDEX2(1,0,4)]+=tmp0 + tmp2 + tmp3 + tmp31 + tmp50 + tmp51; EM_S[INDEX2(1,1,4)]+=tmp16 + tmp17 + tmp21 + tmp25 + tmp28 + tmp54 + tmp55; EM_S[INDEX2(1,2,4)]+=tmp10 + tmp6 + tmp7 + tmp8 + tmp9; EM_S[INDEX2(1,3,4)]+=tmp1 + tmp30 + tmp33 + tmp34 + tmp44 + tmp45; EM_S[INDEX2(2,0,4)]+=tmp1 + tmp34 + tmp38 + tmp40 + tmp42 + tmp43; EM_S[INDEX2(2,1,4)]+=tmp36 + tmp37 + tmp7 + tmp8 + tmp9; EM_S[INDEX2(2,2,4)]+=tmp15 + tmp19 + tmp22 + tmp23 + tmp28 + tmp48 + tmp49; EM_S[INDEX2(2,3,4)]+=tmp0 + tmp11 + tmp12 + tmp31 + tmp46 + tmp47; EM_S[INDEX2(3,0,4)]+=tmp27 + tmp28 + tmp29 + tmp7 + tmp8; EM_S[INDEX2(3,1,4)]+=tmp30 + tmp31 + tmp32 + tmp33 + tmp34 + tmp35; EM_S[INDEX2(3,2,4)]+=tmp0 + tmp1 + tmp11 + tmp12 + tmp13 + tmp14; EM_S[INDEX2(3,3,4)]+=tmp21 + tmp22 + tmp23 + tmp24 + tmp25 + tmp26 + tmp9; } else { // constant data const Scalar A_00 = A_p[INDEX2(0,0,2)]; const Scalar A_01 = A_p[INDEX2(0,1,2)]; const Scalar A_10 = A_p[INDEX2(1,0,2)]; const Scalar A_11 = A_p[INDEX2(1,1,2)]; const Scalar tmp0 = 6.*w1*(A_01 - A_10); const Scalar tmp1 = 6.*w1*(A_01 + A_10); const Scalar tmp2 = 6.*w1*(-A_01 - A_10); const Scalar tmp3 = 6.*w1*(-A_01 + A_10); EM_S[INDEX2(0,0,4)]+=-8.*A_00*w6 + 8.*A_11*w3 + tmp1; EM_S[INDEX2(0,1,4)]+=8.*A_00*w6 + 4.*A_11*w3 + tmp0; EM_S[INDEX2(0,2,4)]+=-4.*A_00*w6 - 8.*A_11*w3 + tmp3; EM_S[INDEX2(0,3,4)]+=4.*A_00*w6 - 4.*A_11*w3 + tmp2; EM_S[INDEX2(1,0,4)]+=8.*A_00*w6 + 4.*A_11*w3 + tmp3; EM_S[INDEX2(1,1,4)]+=-8.*A_00*w6 + 8.*A_11*w3 + tmp2; EM_S[INDEX2(1,2,4)]+=4.*A_00*w6 - 4.*A_11*w3 + tmp1; EM_S[INDEX2(1,3,4)]+=-4.*A_00*w6 - 8.*A_11*w3 + tmp0; EM_S[INDEX2(2,0,4)]+=-4.*A_00*w6 - 8.*A_11*w3 + tmp0; EM_S[INDEX2(2,1,4)]+=4.*A_00*w6 - 4.*A_11*w3 + tmp1; EM_S[INDEX2(2,2,4)]+=-8.*A_00*w6 + 8.*A_11*w3 + tmp2; EM_S[INDEX2(2,3,4)]+=8.*A_00*w6 + 4.*A_11*w3 + tmp3; EM_S[INDEX2(3,0,4)]+=4.*A_00*w6 - 4.*A_11*w3 + tmp2; EM_S[INDEX2(3,1,4)]+=-4.*A_00*w6 - 8.*A_11*w3 + tmp3; EM_S[INDEX2(3,2,4)]+=8.*A_00*w6 + 4.*A_11*w3 + tmp0; EM_S[INDEX2(3,3,4)]+=-8.*A_00*w6 + 8.*A_11*w3 + tmp1; } } /////////////// // process B // /////////////// if (!B.isEmpty()) { const Scalar* B_p = B.getSampleDataRO(e, zero); if (B.actsExpanded()) { const Scalar B_0_0 = B_p[INDEX2(0,0,2)]; const Scalar B_1_0 = B_p[INDEX2(1,0,2)]; const Scalar B_0_1 = B_p[INDEX2(0,1,2)]; const Scalar B_1_1 = B_p[INDEX2(1,1,2)]; const Scalar B_0_2 = B_p[INDEX2(0,2,2)]; const Scalar B_1_2 = B_p[INDEX2(1,2,2)]; const Scalar B_0_3 = B_p[INDEX2(0,3,2)]; const Scalar B_1_3 = B_p[INDEX2(1,3,2)]; const Scalar tmp0 = w11*(B_1_0 + B_1_1); const Scalar tmp1 = w14*(B_1_2 + B_1_3); const Scalar tmp2 = w15*(-B_0_1 - B_0_3); const Scalar tmp3 = w10*(-B_0_0 - B_0_2); const Scalar tmp4 = w11*(B_1_2 + B_1_3); const Scalar tmp5 = w14*(B_1_0 + B_1_1); const Scalar tmp6 = w11*(-B_1_2 - B_1_3); const Scalar tmp7 = w14*(-B_1_0 - B_1_1); const Scalar tmp8 = w11*(-B_1_0 - B_1_1); const Scalar tmp9 = w14*(-B_1_2 - B_1_3); const Scalar tmp10 = w10*(-B_0_1 - B_0_3); const Scalar tmp11 = w15*(-B_0_0 - B_0_2); const Scalar tmp12 = w15*(B_0_0 + B_0_2); const Scalar tmp13 = w10*(B_0_1 + B_0_3); const Scalar tmp14 = w10*(B_0_0 + B_0_2); const Scalar tmp15 = w15*(B_0_1 + B_0_3); EM_S[INDEX2(0,0,4)]+=B_0_0*w12 + B_0_1*w10 + B_0_2*w15 + B_0_3*w13 + B_1_0*w16 + B_1_1*w14 + B_1_2*w11 + B_1_3*w17; EM_S[INDEX2(0,1,4)]+=B_0_0*w10 + B_0_1*w12 + B_0_2*w13 + B_0_3*w15 + tmp0 + tmp1; EM_S[INDEX2(0,2,4)]+=B_1_0*w11 + B_1_1*w17 + B_1_2*w16 + B_1_3*w14 + tmp14 + tmp15; EM_S[INDEX2(0,3,4)]+=tmp12 + tmp13 + tmp4 + tmp5; EM_S[INDEX2(1,0,4)]+=-B_0_0*w12 - B_0_1*w10 - B_0_2*w15 - B_0_3*w13 + tmp0 + tmp1; EM_S[INDEX2(1,1,4)]+=-B_0_0*w10 - B_0_1*w12 - B_0_2*w13 - B_0_3*w15 + B_1_0*w14 + B_1_1*w16 + B_1_2*w17 + B_1_3*w11; EM_S[INDEX2(1,2,4)]+=tmp2 + tmp3 + tmp4 + tmp5; EM_S[INDEX2(1,3,4)]+=B_1_0*w17 + B_1_1*w11 + B_1_2*w14 + B_1_3*w16 + tmp10 + tmp11; EM_S[INDEX2(2,0,4)]+=-B_1_0*w16 - B_1_1*w14 - B_1_2*w11 - B_1_3*w17 + tmp14 + tmp15; EM_S[INDEX2(2,1,4)]+=tmp12 + tmp13 + tmp8 + tmp9; EM_S[INDEX2(2,2,4)]+=B_0_0*w15 + B_0_1*w13 + B_0_2*w12 + B_0_3*w10 - B_1_0*w11 - B_1_1*w17 - B_1_2*w16 - B_1_3*w14; EM_S[INDEX2(2,3,4)]+=B_0_0*w13 + B_0_1*w15 + B_0_2*w10 + B_0_3*w12 + tmp6 + tmp7; EM_S[INDEX2(3,0,4)]+=tmp2 + tmp3 + tmp8 + tmp9; EM_S[INDEX2(3,1,4)]+=-B_1_0*w14 - B_1_1*w16 - B_1_2*w17 - B_1_3*w11 + tmp10 + tmp11; EM_S[INDEX2(3,2,4)]+=-B_0_0*w15 - B_0_1*w13 - B_0_2*w12 - B_0_3*w10 + tmp6 + tmp7; EM_S[INDEX2(3,3,4)]+=-B_0_0*w13 - B_0_1*w15 - B_0_2*w10 - B_0_3*w12 - B_1_0*w17 - B_1_1*w11 - B_1_2*w14 - B_1_3*w16; } else { // constant data const Scalar B_0 = B_p[0]; const Scalar B_1 = B_p[1]; EM_S[INDEX2(0,0,4)]+= 2.*B_0*w18 + 2.*B_1*w19; EM_S[INDEX2(0,1,4)]+= 2.*B_0*w18 + B_1*w19; EM_S[INDEX2(0,2,4)]+= B_0*w18 + 2.*B_1*w19; EM_S[INDEX2(0,3,4)]+= B_0*w18 + B_1*w19; EM_S[INDEX2(1,0,4)]+=-2.*B_0*w18 + B_1*w19; EM_S[INDEX2(1,1,4)]+=-2.*B_0*w18 + 2.*B_1*w19; EM_S[INDEX2(1,2,4)]+= -B_0*w18 + B_1*w19; EM_S[INDEX2(1,3,4)]+= -B_0*w18 + 2.*B_1*w19; EM_S[INDEX2(2,0,4)]+= B_0*w18 - 2.*B_1*w19; EM_S[INDEX2(2,1,4)]+= B_0*w18 - B_1*w19; EM_S[INDEX2(2,2,4)]+= 2.*B_0*w18 - 2.*B_1*w19; EM_S[INDEX2(2,3,4)]+= 2.*B_0*w18 - B_1*w19; EM_S[INDEX2(3,0,4)]+= -B_0*w18 - B_1*w19; EM_S[INDEX2(3,1,4)]+= -B_0*w18 - 2.*B_1*w19; EM_S[INDEX2(3,2,4)]+=-2.*B_0*w18 - B_1*w19; EM_S[INDEX2(3,3,4)]+=-2.*B_0*w18 - 2.*B_1*w19; } } /////////////// // process C // /////////////// if (!C.isEmpty()) { const Scalar* C_p = C.getSampleDataRO(e, zero); if (C.actsExpanded()) { const Scalar C_0_0 = C_p[INDEX2(0,0,2)]; const Scalar C_1_0 = C_p[INDEX2(1,0,2)]; const Scalar C_0_1 = C_p[INDEX2(0,1,2)]; const Scalar C_1_1 = C_p[INDEX2(1,1,2)]; const Scalar C_0_2 = C_p[INDEX2(0,2,2)]; const Scalar C_1_2 = C_p[INDEX2(1,2,2)]; const Scalar C_0_3 = C_p[INDEX2(0,3,2)]; const Scalar C_1_3 = C_p[INDEX2(1,3,2)]; const Scalar tmp0 = w11*(C_1_0 + C_1_1); const Scalar tmp1 = w14*(C_1_2 + C_1_3); const Scalar tmp2 = w15*(C_0_0 + C_0_2); const Scalar tmp3 = w10*(C_0_1 + C_0_3); const Scalar tmp4 = w11*(-C_1_0 - C_1_1); const Scalar tmp5 = w14*(-C_1_2 - C_1_3); const Scalar tmp6 = w11*(-C_1_2 - C_1_3); const Scalar tmp7 = w14*(-C_1_0 - C_1_1); const Scalar tmp8 = w11*(C_1_2 + C_1_3); const Scalar tmp9 = w14*(C_1_0 + C_1_1); const Scalar tmp10 = w10*(-C_0_1 - C_0_3); const Scalar tmp11 = w15*(-C_0_0 - C_0_2); const Scalar tmp12 = w15*(-C_0_1 - C_0_3); const Scalar tmp13 = w10*(-C_0_0 - C_0_2); const Scalar tmp14 = w10*(C_0_0 + C_0_2); const Scalar tmp15 = w15*(C_0_1 + C_0_3); EM_S[INDEX2(0,0,4)]+=C_0_0*w12 + C_0_1*w10 + C_0_2*w15 + C_0_3*w13 + C_1_0*w16 + C_1_1*w14 + C_1_2*w11 + C_1_3*w17; EM_S[INDEX2(0,1,4)]+=-C_0_0*w12 - C_0_1*w10 - C_0_2*w15 - C_0_3*w13 + tmp0 + tmp1; EM_S[INDEX2(0,2,4)]+=-C_1_0*w16 - C_1_1*w14 - C_1_2*w11 - C_1_3*w17 + tmp14 + tmp15; EM_S[INDEX2(0,3,4)]+=tmp12 + tmp13 + tmp4 + tmp5; EM_S[INDEX2(1,0,4)]+=C_0_0*w10 + C_0_1*w12 + C_0_2*w13 + C_0_3*w15 + tmp0 + tmp1; EM_S[INDEX2(1,1,4)]+=-C_0_0*w10 - C_0_1*w12 - C_0_2*w13 - C_0_3*w15 + C_1_0*w14 + C_1_1*w16 + C_1_2*w17 + C_1_3*w11; EM_S[INDEX2(1,2,4)]+=tmp2 + tmp3 + tmp4 + tmp5; EM_S[INDEX2(1,3,4)]+=-C_1_0*w14 - C_1_1*w16 - C_1_2*w17 - C_1_3*w11 + tmp10 + tmp11; EM_S[INDEX2(2,0,4)]+=C_1_0*w11 + C_1_1*w17 + C_1_2*w16 + C_1_3*w14 + tmp14 + tmp15; EM_S[INDEX2(2,1,4)]+=tmp12 + tmp13 + tmp8 + tmp9; EM_S[INDEX2(2,2,4)]+=C_0_0*w15 + C_0_1*w13 + C_0_2*w12 + C_0_3*w10 - C_1_0*w11 - C_1_1*w17 - C_1_2*w16 - C_1_3*w14; EM_S[INDEX2(2,3,4)]+=-C_0_0*w15 - C_0_1*w13 - C_0_2*w12 - C_0_3*w10 + tmp6 + tmp7; EM_S[INDEX2(3,0,4)]+=tmp2 + tmp3 + tmp8 + tmp9; EM_S[INDEX2(3,1,4)]+=C_1_0*w17 + C_1_1*w11 + C_1_2*w14 + C_1_3*w16 + tmp10 + tmp11; EM_S[INDEX2(3,2,4)]+=C_0_0*w13 + C_0_1*w15 + C_0_2*w10 + C_0_3*w12 + tmp6 + tmp7; EM_S[INDEX2(3,3,4)]+=-C_0_0*w13 - C_0_1*w15 - C_0_2*w10 - C_0_3*w12 - C_1_0*w17 - C_1_1*w11 - C_1_2*w14 - C_1_3*w16; } else { // constant data const Scalar C_0 = C_p[0]; const Scalar C_1 = C_p[1]; EM_S[INDEX2(0,0,4)]+= 2.*C_0*w18 + 2.*C_1*w19; EM_S[INDEX2(0,1,4)]+=-2.*C_0*w18 + C_1*w19; EM_S[INDEX2(0,2,4)]+= C_0*w18 - 2.*C_1*w19; EM_S[INDEX2(0,3,4)]+= -C_0*w18 - C_1*w19; EM_S[INDEX2(1,0,4)]+= 2.*C_0*w18 + C_1*w19; EM_S[INDEX2(1,1,4)]+=-2.*C_0*w18 + 2.*C_1*w19; EM_S[INDEX2(1,2,4)]+= C_0*w18 - C_1*w19; EM_S[INDEX2(1,3,4)]+= -C_0*w18 - 2.*C_1*w19; EM_S[INDEX2(2,0,4)]+= C_0*w18 + 2.*C_1*w19; EM_S[INDEX2(2,1,4)]+= -C_0*w18 + C_1*w19; EM_S[INDEX2(2,2,4)]+= 2.*C_0*w18 - 2.*C_1*w19; EM_S[INDEX2(2,3,4)]+=-2.*C_0*w18 - C_1*w19; EM_S[INDEX2(3,0,4)]+= C_0*w18 + C_1*w19; EM_S[INDEX2(3,1,4)]+= -C_0*w18 + 2.*C_1*w19; EM_S[INDEX2(3,2,4)]+= 2.*C_0*w18 - C_1*w19; EM_S[INDEX2(3,3,4)]+=-2.*C_0*w18 - 2.*C_1*w19; } } /////////////// // process D // /////////////// if (!D.isEmpty()) { const Scalar* D_p = D.getSampleDataRO(e, zero); if (D.actsExpanded()) { const Scalar D_0 = D_p[0]; const Scalar D_1 = D_p[1]; const Scalar D_2 = D_p[2]; const Scalar D_3 = D_p[3]; const Scalar tmp0 = w21*(D_2 + D_3); const Scalar tmp1 = w20*(D_0 + D_1); const Scalar tmp2 = w22*(D_0 + D_1 + D_2 + D_3); const Scalar tmp3 = w21*(D_0 + D_1); const Scalar tmp4 = w20*(D_2 + D_3); const Scalar tmp5 = w22*(D_1 + D_2); const Scalar tmp6 = w21*(D_0 + D_2); const Scalar tmp7 = w20*(D_1 + D_3); const Scalar tmp8 = w21*(D_1 + D_3); const Scalar tmp9 = w20*(D_0 + D_2); const Scalar tmp10 = w22*(D_0 + D_3); EM_S[INDEX2(0,0,4)]+=D_0*w23 + D_3*w24 + tmp5; EM_S[INDEX2(0,1,4)]+=tmp0 + tmp1; EM_S[INDEX2(0,2,4)]+=tmp8 + tmp9; EM_S[INDEX2(0,3,4)]+=tmp2; EM_S[INDEX2(1,0,4)]+=tmp0 + tmp1; EM_S[INDEX2(1,1,4)]+=D_1*w23 + D_2*w24 + tmp10; EM_S[INDEX2(1,2,4)]+=tmp2; EM_S[INDEX2(1,3,4)]+=tmp6 + tmp7; EM_S[INDEX2(2,0,4)]+=tmp8 + tmp9; EM_S[INDEX2(2,1,4)]+=tmp2; EM_S[INDEX2(2,2,4)]+=D_1*w24 + D_2*w23 + tmp10; EM_S[INDEX2(2,3,4)]+=tmp3 + tmp4; EM_S[INDEX2(3,0,4)]+=tmp2; EM_S[INDEX2(3,1,4)]+=tmp6 + tmp7; EM_S[INDEX2(3,2,4)]+=tmp3 + tmp4; EM_S[INDEX2(3,3,4)]+=D_0*w24 + D_3*w23 + tmp5; } else { // constant data const Scalar D_0 = D_p[0]; EM_S[INDEX2(0,0,4)]+=16.*D_0*w22; EM_S[INDEX2(0,1,4)]+= 8.*D_0*w22; EM_S[INDEX2(0,2,4)]+= 8.*D_0*w22; EM_S[INDEX2(0,3,4)]+= 4.*D_0*w22; EM_S[INDEX2(1,0,4)]+= 8.*D_0*w22; EM_S[INDEX2(1,1,4)]+=16.*D_0*w22; EM_S[INDEX2(1,2,4)]+= 4.*D_0*w22; EM_S[INDEX2(1,3,4)]+= 8.*D_0*w22; EM_S[INDEX2(2,0,4)]+= 8.*D_0*w22; EM_S[INDEX2(2,1,4)]+= 4.*D_0*w22; EM_S[INDEX2(2,2,4)]+=16.*D_0*w22; EM_S[INDEX2(2,3,4)]+= 8.*D_0*w22; EM_S[INDEX2(3,0,4)]+= 4.*D_0*w22; EM_S[INDEX2(3,1,4)]+= 8.*D_0*w22; EM_S[INDEX2(3,2,4)]+= 8.*D_0*w22; EM_S[INDEX2(3,3,4)]+=16.*D_0*w22; } } /////////////// // process X // /////////////// if (!X.isEmpty()) { const Scalar* X_p = X.getSampleDataRO(e, zero); if (X.actsExpanded()) { const Scalar X_0_0 = X_p[INDEX2(0,0,2)]; const Scalar X_1_0 = X_p[INDEX2(1,0,2)]; const Scalar X_0_1 = X_p[INDEX2(0,1,2)]; const Scalar X_1_1 = X_p[INDEX2(1,1,2)]; const Scalar X_0_2 = X_p[INDEX2(0,2,2)]; const Scalar X_1_2 = X_p[INDEX2(1,2,2)]; const Scalar X_0_3 = X_p[INDEX2(0,3,2)]; const Scalar X_1_3 = X_p[INDEX2(1,3,2)]; const Scalar tmp0 = 6.*w15*(X_0_2 + X_0_3); const Scalar tmp1 = 6.*w10*(X_0_0 + X_0_1); const Scalar tmp2 = 6.*w11*(X_1_0 + X_1_2); const Scalar tmp3 = 6.*w14*(X_1_1 + X_1_3); const Scalar tmp4 = 6.*w11*(X_1_1 + X_1_3); const Scalar tmp5 = w25*(X_0_0 + X_0_1); const Scalar tmp6 = w26*(X_0_2 + X_0_3); const Scalar tmp7 = 6.*w14*(X_1_0 + X_1_2); const Scalar tmp8 = w27*(X_1_0 + X_1_2); const Scalar tmp9 = w28*(X_1_1 + X_1_3); const Scalar tmp10 = w25*(-X_0_2 - X_0_3); const Scalar tmp11 = w26*(-X_0_0 - X_0_1); const Scalar tmp12 = w27*(X_1_1 + X_1_3); const Scalar tmp13 = w28*(X_1_0 + X_1_2); const Scalar tmp14 = w25*(X_0_2 + X_0_3); const Scalar tmp15 = w26*(X_0_0 + X_0_1); EM_F[0]+=tmp0 + tmp1 + tmp2 + tmp3; EM_F[1]+=tmp4 + tmp5 + tmp6 + tmp7; EM_F[2]+=tmp10 + tmp11 + tmp8 + tmp9; EM_F[3]+=tmp12 + tmp13 + tmp14 + tmp15; } else { // constant data const Scalar X_0 = X_p[0]; const Scalar X_1 = X_p[1]; EM_F[0]+= 6.*X_0*w18 + 6.*X_1*w19; EM_F[1]+=-6.*X_0*w18 + 6.*X_1*w19; EM_F[2]+= 6.*X_0*w18 - 6.*X_1*w19; EM_F[3]+=-6.*X_0*w18 - 6.*X_1*w19; } } /////////////// // process Y // /////////////// if (!Y.isEmpty()) { const Scalar* Y_p = Y.getSampleDataRO(e, zero); if (Y.actsExpanded()) { const Scalar Y_0 = Y_p[0]; const Scalar Y_1 = Y_p[1]; const Scalar Y_2 = Y_p[2]; const Scalar Y_3 = Y_p[3]; const Scalar tmp0 = 6.*w22*(Y_1 + Y_2); const Scalar tmp1 = 6.*w22*(Y_0 + Y_3); EM_F[0]+=6.*Y_0*w20 + 6.*Y_3*w21 + tmp0; EM_F[1]+=6.*Y_1*w20 + 6.*Y_2*w21 + tmp1; EM_F[2]+=6.*Y_1*w21 + 6.*Y_2*w20 + tmp1; EM_F[3]+=6.*Y_0*w21 + 6.*Y_3*w20 + tmp0; } else { // constant data EM_F[0]+=36.*Y_p[0]*w22; EM_F[1]+=36.*Y_p[0]*w22; EM_F[2]+=36.*Y_p[0]*w22; EM_F[3]+=36.*Y_p[0]*w22; } } // add to matrix (if addEM_S) and RHS (if addEM_F) const index_t firstNode = m_NN[0]*k1+k0; domain->addToMatrixAndRHS(mat, rhs, EM_S, EM_F, addEM_S, addEM_F, firstNode); } // end k0 loop } // end k1 loop } // end of colouring } // end of parallel region } /****************************************************************************/ // PDE SINGLE BOUNDARY /****************************************************************************/ template<class Scalar> void DefaultAssembler2D<Scalar>::assemblePDEBoundarySingle( AbstractSystemMatrix* mat, Data& rhs, const Data& d, const Data& y) const { const double SQRT3 = 1.73205080756887719318; const double w5 = m_dx[0]/12; const double w6 = w5*(SQRT3 + 2); const double w7 = w5*(-SQRT3 + 2); const double w8 = w5*(SQRT3 + 3); const double w9 = w5*(-SQRT3 + 3); const double w2 = m_dx[1]/12; const double w0 = w2*(SQRT3 + 2); const double w1 = w2*(-SQRT3 + 2); const double w3 = w2*(SQRT3 + 3); const double w4 = w2*(-SQRT3 + 3); const int NE0 = m_NE[0]; const int NE1 = m_NE[1]; const bool addEM_S = !d.isEmpty(); const bool addEM_F = !y.isEmpty(); const Scalar zero = static_cast<Scalar>(0); rhs.requireWrite(); #pragma omp parallel { vector<Scalar> EM_S(4*4); vector<Scalar> EM_F(4); if (domain->m_faceOffset[0] > -1) { if (addEM_S) fill(EM_S.begin(), EM_S.end(), zero); if (addEM_F) { EM_F[1] = zero; EM_F[3] = zero; } for (index_t k1_0=0; k1_0<2; k1_0++) { // colouring #pragma omp for for (index_t k1=k1_0; k1<NE1; k1+=2) { /////////////// // process d // /////////////// if (addEM_S) { const Scalar* d_p = d.getSampleDataRO(k1, zero); if (d.actsExpanded()) { const Scalar d_0 = d_p[0]; const Scalar d_1 = d_p[1]; const Scalar tmp0 = w2*(d_0 + d_1); EM_S[INDEX2(0,0,4)] = d_0*w0 + d_1*w1; EM_S[INDEX2(2,0,4)] = tmp0; EM_S[INDEX2(0,2,4)] = tmp0; EM_S[INDEX2(2,2,4)] = d_0*w1 + d_1*w0; } else { // constant data EM_S[INDEX2(0,0,4)] = 4.*d_p[0]*w2; EM_S[INDEX2(2,0,4)] = 2.*d_p[0]*w2; EM_S[INDEX2(0,2,4)] = 2.*d_p[0]*w2; EM_S[INDEX2(2,2,4)] = 4.*d_p[0]*w2; } } /////////////// // process y // /////////////// if (addEM_F) { const Scalar* y_p = y.getSampleDataRO(k1, zero); if (y.actsExpanded()) { EM_F[0] = w3*y_p[0] + w4*y_p[1]; EM_F[2] = w3*y_p[1] + w4*y_p[0]; } else { // constant data EM_F[0] = 6.*w2*y_p[0]; EM_F[2] = 6.*w2*y_p[0]; } } const index_t firstNode=m_NN[0]*k1; domain->addToMatrixAndRHS(mat, rhs, EM_S, EM_F, addEM_S, addEM_F, firstNode); } } // end colouring } if (domain->m_faceOffset[1] > -1) { if (addEM_S) fill(EM_S.begin(), EM_S.end(), zero); if (addEM_F) { EM_F[0] = zero; EM_F[2] = zero; } for (index_t k1_0=0; k1_0<2; k1_0++) { // colouring #pragma omp for for (index_t k1=k1_0; k1<NE1; k1+=2) { const index_t e = domain->m_faceOffset[1]+k1; /////////////// // process d // /////////////// if (addEM_S) { const Scalar* d_p = d.getSampleDataRO(e, zero); if (d.actsExpanded()) { const Scalar d_0 = d_p[0]; const Scalar d_1 = d_p[1]; const Scalar tmp0 = w2*(d_0 + d_1); EM_S[INDEX2(1,1,4)] = d_0*w0 + d_1*w1; EM_S[INDEX2(3,1,4)] = tmp0; EM_S[INDEX2(1,3,4)] = tmp0; EM_S[INDEX2(3,3,4)] = d_0*w1 + d_1*w0; } else { // constant data EM_S[INDEX2(1,1,4)] = 4.*d_p[0]*w2; EM_S[INDEX2(3,1,4)] = 2.*d_p[0]*w2; EM_S[INDEX2(1,3,4)] = 2.*d_p[0]*w2; EM_S[INDEX2(3,3,4)] = 4.*d_p[0]*w2; } } /////////////// // process y // /////////////// if (addEM_F) { const Scalar* y_p = y.getSampleDataRO(e, zero); if (y.actsExpanded()) { EM_F[1] = w3*y_p[0] + w4*y_p[1]; EM_F[3] = w3*y_p[1] + w4*y_p[0]; } else { // constant data EM_F[1] = 6.*w2*y_p[0]; EM_F[3] = 6.*w2*y_p[0]; } } const index_t firstNode = m_NN[0]*(k1+1)-2; domain->addToMatrixAndRHS(mat, rhs, EM_S, EM_F, addEM_S, addEM_F, firstNode); } } // end colouring } if (domain->m_faceOffset[2] > -1) { if (addEM_S) fill(EM_S.begin(), EM_S.end(), zero); if (addEM_F) { EM_F[2] = zero; EM_F[3] = zero; } for (index_t k0_0=0; k0_0<2; k0_0++) { // colouring #pragma omp for for (index_t k0 = k0_0; k0 < NE0; k0+=2) { const index_t e = domain->m_faceOffset[2]+k0; /////////////// // process d // /////////////// if (addEM_S) { const Scalar* d_p = d.getSampleDataRO(e, zero); if (d.actsExpanded()) { const Scalar d_0 = d_p[0]; const Scalar d_1 = d_p[1]; const Scalar tmp0 = w5*(d_0 + d_1); EM_S[INDEX2(0,0,4)] = d_0*w6 + d_1*w7; EM_S[INDEX2(1,0,4)] = tmp0; EM_S[INDEX2(0,1,4)] = tmp0; EM_S[INDEX2(1,1,4)] = d_0*w7 + d_1*w6; } else { // constant data EM_S[INDEX2(0,0,4)] = 4.*d_p[0]*w5; EM_S[INDEX2(1,0,4)] = 2.*d_p[0]*w5; EM_S[INDEX2(0,1,4)] = 2.*d_p[0]*w5; EM_S[INDEX2(1,1,4)] = 4.*d_p[0]*w5; } } /////////////// // process y // /////////////// if (addEM_F) { const Scalar* y_p = y.getSampleDataRO(e, zero); if (y.actsExpanded()) { EM_F[0] = w8*y_p[0] + w9*y_p[1]; EM_F[1] = w8*y_p[1] + w9*y_p[0]; } else { // constant data EM_F[0] = 6.*w5*y_p[0]; EM_F[1] = 6.*w5*y_p[0]; } } const index_t firstNode = k0; domain->addToMatrixAndRHS(mat, rhs, EM_S, EM_F, addEM_S, addEM_F, firstNode); } } // end colouring } if (domain->m_faceOffset[3] > -1) { if (addEM_S) fill(EM_S.begin(), EM_S.end(), zero); if (addEM_F) { EM_F[0] = zero; EM_F[1] = zero; } for (index_t k0_0=0; k0_0<2; k0_0++) { // colouring #pragma omp for for (index_t k0 = k0_0; k0 < NE0; k0+=2) { const index_t e = domain->m_faceOffset[3]+k0; /////////////// // process d // /////////////// if (addEM_S) { const Scalar* d_p = d.getSampleDataRO(e, zero); if (d.actsExpanded()) { const Scalar d_0 = d_p[0]; const Scalar d_1 = d_p[1]; const Scalar tmp0 = w5*(d_0 + d_1); EM_S[INDEX2(2,2,4)] = d_0*w6 + d_1*w7; EM_S[INDEX2(3,2,4)] = tmp0; EM_S[INDEX2(2,3,4)] = tmp0; EM_S[INDEX2(3,3,4)] = d_0*w7 + d_1*w6; } else { // constant data EM_S[INDEX2(2,2,4)] = 4.*d_p[0]*w5; EM_S[INDEX2(3,2,4)] = 2.*d_p[0]*w5; EM_S[INDEX2(2,3,4)] = 2.*d_p[0]*w5; EM_S[INDEX2(3,3,4)] = 4.*d_p[0]*w5; } } /////////////// // process y // /////////////// if (addEM_F) { const Scalar* y_p = y.getSampleDataRO(e, zero); if (y.actsExpanded()) { EM_F[2] = w8*y_p[0] + w9*y_p[1]; EM_F[3] = w8*y_p[1] + w9*y_p[0]; } else { // constant data EM_F[2] = 6.*w5*y_p[0]; EM_F[3] = 6.*w5*y_p[0]; } } const index_t firstNode=m_NN[0]*(m_NN[1]-2)+k0; domain->addToMatrixAndRHS(mat, rhs, EM_S, EM_F, addEM_S, addEM_F, firstNode); } } // end colouring } } // end of parallel section } /****************************************************************************/ // PDE SINGLE REDUCED /****************************************************************************/ template<class Scalar> void DefaultAssembler2D<Scalar>::assemblePDESingleReduced( AbstractSystemMatrix* mat, Data& rhs, const Data& A, const Data& B, const Data& C, const Data& D, const Data& X, const Data& Y) const { const double w0 = 1./4; const double w1 = m_dx[0]/8; const double w2 = m_dx[1]/8; const double w3 = m_dx[0]*m_dx[1]/16; const double w4 = m_dx[0]/(4*m_dx[1]); const double w5 = m_dx[1]/(4*m_dx[0]); const int NE0 = m_NE[0]; const int NE1 = m_NE[1]; const bool addEM_S = (!A.isEmpty() || !B.isEmpty() || !C.isEmpty() || !D.isEmpty()); const bool addEM_F = (!X.isEmpty() || !Y.isEmpty()); const Scalar zero = static_cast<Scalar>(0); rhs.requireWrite(); #pragma omp parallel { vector<Scalar> EM_S(4*4, zero); vector<Scalar> EM_F(4, zero); for (index_t k1_0=0; k1_0<2; k1_0++) { // colouring #pragma omp for for (index_t k1=k1_0; k1<NE1; k1+=2) { for (index_t k0=0; k0<NE0; ++k0) { const index_t e = k0 + NE0*k1; if (addEM_S) fill(EM_S.begin(), EM_S.end(), zero); if (addEM_F) fill(EM_F.begin(), EM_F.end(), zero); /////////////// // process A // /////////////// if (!A.isEmpty()) { const Scalar* A_p = A.getSampleDataRO(e, zero); const Scalar A_00 = A_p[INDEX2(0,0,2)]; const Scalar A_10 = A_p[INDEX2(1,0,2)]; const Scalar A_01 = A_p[INDEX2(0,1,2)]; const Scalar A_11 = A_p[INDEX2(1,1,2)]; const Scalar tmp0 = (A_01 + A_10)*w0; const Scalar tmp1 = A_00*w5; const Scalar tmp2 = A_01*w0; const Scalar tmp3 = A_10*w0; const Scalar tmp4 = A_11*w4; EM_S[INDEX2(0,0,4)]+=tmp4 + tmp0 + tmp1; EM_S[INDEX2(1,0,4)]+=tmp4 - tmp1 + tmp3 - tmp2; EM_S[INDEX2(2,0,4)]+=tmp2 - tmp3 - tmp4 + tmp1; EM_S[INDEX2(3,0,4)]+=-tmp1 - tmp4 - tmp0; EM_S[INDEX2(0,1,4)]+=tmp4 - tmp1 + tmp2 - tmp3; EM_S[INDEX2(1,1,4)]+=tmp4 + tmp1 - tmp0; EM_S[INDEX2(2,1,4)]+=-tmp1 + tmp0 - tmp4; EM_S[INDEX2(3,1,4)]+=-tmp4 + tmp1 + tmp3 - tmp2; EM_S[INDEX2(0,2,4)]+=-tmp4 + tmp1 + tmp3 - tmp2; EM_S[INDEX2(1,2,4)]+=-tmp1 + tmp0 - tmp4; EM_S[INDEX2(2,2,4)]+=tmp4 + tmp1 - tmp0; EM_S[INDEX2(3,2,4)]+=tmp4 - tmp1 + tmp2 - tmp3; EM_S[INDEX2(0,3,4)]+=-tmp1 - tmp4 - tmp0; EM_S[INDEX2(1,3,4)]+=tmp2 - tmp3 - tmp4 + tmp1; EM_S[INDEX2(2,3,4)]+=tmp4 - tmp1 + tmp3 - tmp2; EM_S[INDEX2(3,3,4)]+=tmp4 + tmp0 + tmp1; } /////////////// // process B // /////////////// if (!B.isEmpty()) { const Scalar* B_p = B.getSampleDataRO(e, zero); const Scalar tmp0 = B_p[0]*w2; const Scalar tmp1 = B_p[1]*w1; EM_S[INDEX2(0,0,4)]+=-tmp0 - tmp1; EM_S[INDEX2(1,0,4)]+= tmp0 - tmp1; EM_S[INDEX2(2,0,4)]+= tmp1 - tmp0; EM_S[INDEX2(3,0,4)]+= tmp0 + tmp1; EM_S[INDEX2(0,1,4)]+=-tmp0 - tmp1; EM_S[INDEX2(1,1,4)]+= tmp0 - tmp1; EM_S[INDEX2(2,1,4)]+= tmp1 - tmp0; EM_S[INDEX2(3,1,4)]+= tmp0 + tmp1; EM_S[INDEX2(0,2,4)]+=-tmp0 - tmp1; EM_S[INDEX2(1,2,4)]+= tmp0 - tmp1; EM_S[INDEX2(2,2,4)]+= tmp1 - tmp0; EM_S[INDEX2(3,2,4)]+= tmp0 + tmp1; EM_S[INDEX2(0,3,4)]+=-tmp0 - tmp1; EM_S[INDEX2(1,3,4)]+= tmp0 - tmp1; EM_S[INDEX2(2,3,4)]+= tmp1 - tmp0; EM_S[INDEX2(3,3,4)]+= tmp0 + tmp1; } /////////////// // process C // /////////////// if (!C.isEmpty()) { const Scalar* C_p = C.getSampleDataRO(e, zero); const Scalar tmp0 = C_p[0]*w2; const Scalar tmp1 = C_p[1]*w1; EM_S[INDEX2(0,0,4)]+=-tmp1 - tmp0; EM_S[INDEX2(1,0,4)]+=-tmp1 - tmp0; EM_S[INDEX2(2,0,4)]+=-tmp1 - tmp0; EM_S[INDEX2(3,0,4)]+=-tmp1 - tmp0; EM_S[INDEX2(0,1,4)]+= tmp0 - tmp1; EM_S[INDEX2(1,1,4)]+= tmp0 - tmp1; EM_S[INDEX2(2,1,4)]+= tmp0 - tmp1; EM_S[INDEX2(3,1,4)]+= tmp0 - tmp1; EM_S[INDEX2(0,2,4)]+= tmp1 - tmp0; EM_S[INDEX2(1,2,4)]+= tmp1 - tmp0; EM_S[INDEX2(2,2,4)]+= tmp1 - tmp0; EM_S[INDEX2(3,2,4)]+= tmp1 - tmp0; EM_S[INDEX2(0,3,4)]+= tmp0 + tmp1; EM_S[INDEX2(1,3,4)]+= tmp0 + tmp1; EM_S[INDEX2(2,3,4)]+= tmp0 + tmp1; EM_S[INDEX2(3,3,4)]+= tmp0 + tmp1; } /////////////// // process D // /////////////// if (!D.isEmpty()) { const Scalar* D_p = D.getSampleDataRO(e, zero); EM_S[INDEX2(0,0,4)]+=D_p[0]*w3; EM_S[INDEX2(1,0,4)]+=D_p[0]*w3; EM_S[INDEX2(2,0,4)]+=D_p[0]*w3; EM_S[INDEX2(3,0,4)]+=D_p[0]*w3; EM_S[INDEX2(0,1,4)]+=D_p[0]*w3; EM_S[INDEX2(1,1,4)]+=D_p[0]*w3; EM_S[INDEX2(2,1,4)]+=D_p[0]*w3; EM_S[INDEX2(3,1,4)]+=D_p[0]*w3; EM_S[INDEX2(0,2,4)]+=D_p[0]*w3; EM_S[INDEX2(1,2,4)]+=D_p[0]*w3; EM_S[INDEX2(2,2,4)]+=D_p[0]*w3; EM_S[INDEX2(3,2,4)]+=D_p[0]*w3; EM_S[INDEX2(0,3,4)]+=D_p[0]*w3; EM_S[INDEX2(1,3,4)]+=D_p[0]*w3; EM_S[INDEX2(2,3,4)]+=D_p[0]*w3; EM_S[INDEX2(3,3,4)]+=D_p[0]*w3; } /////////////// // process X // /////////////// if (!X.isEmpty()) { const Scalar* X_p = X.getSampleDataRO(e, zero); const Scalar wX0 = 4.*X_p[0]*w2; const Scalar wX1 = 4.*X_p[1]*w1; EM_F[0]+=-wX0 - wX1; EM_F[1]+=-wX1 + wX0; EM_F[2]+=-wX0 + wX1; EM_F[3]+= wX0 + wX1; } /////////////// // process Y // /////////////// if (!Y.isEmpty()) { const Scalar* Y_p = Y.getSampleDataRO(e, zero); EM_F[0]+=4.*Y_p[0]*w3; EM_F[1]+=4.*Y_p[0]*w3; EM_F[2]+=4.*Y_p[0]*w3; EM_F[3]+=4.*Y_p[0]*w3; } // add to matrix (if addEM_S) and RHS (if addEM_F) const index_t firstNode=m_NN[0]*k1+k0; domain->addToMatrixAndRHS(mat, rhs, EM_S, EM_F, addEM_S, addEM_F, firstNode); } // end k0 loop } // end k1 loop } // end of colouring } // end of parallel region } /****************************************************************************/ // PDE SINGLE REDUCED BOUNDARY /****************************************************************************/ template<class Scalar> void DefaultAssembler2D<Scalar>::assemblePDEBoundarySingleReduced( AbstractSystemMatrix* mat, Data& rhs, const Data& d, const Data& y) const { const double w0 = m_dx[0]/4; const double w1 = m_dx[1]/4; const int NE0 = m_NE[0]; const int NE1 = m_NE[1]; const bool addEM_S = !d.isEmpty(); const bool addEM_F = !y.isEmpty(); const Scalar zero = static_cast<Scalar>(0); rhs.requireWrite(); #pragma omp parallel { vector<Scalar> EM_S(4*4, zero); vector<Scalar> EM_F(4, zero); if (domain->m_faceOffset[0] > -1) { if (addEM_S) fill(EM_S.begin(), EM_S.end(), zero); if (addEM_F) { EM_F[1] = zero; EM_F[3] = zero; } for (index_t k1_0=0; k1_0<2; k1_0++) { // colouring #pragma omp for for (index_t k1=k1_0; k1<NE1; k1+=2) { /////////////// // process d // /////////////// if (addEM_S) { const Scalar* d_p = d.getSampleDataRO(k1, zero); EM_S[INDEX2(0,0,4)] = d_p[0]*w1; EM_S[INDEX2(2,0,4)] = d_p[0]*w1; EM_S[INDEX2(0,2,4)] = d_p[0]*w1; EM_S[INDEX2(2,2,4)] = d_p[0]*w1; } /////////////// // process y // /////////////// if (addEM_F) { const Scalar* y_p = y.getSampleDataRO(k1, zero); EM_F[0] = 2.*w1*y_p[0]; EM_F[2] = 2.*w1*y_p[0]; } const index_t firstNode=m_NN[0]*k1; domain->addToMatrixAndRHS(mat, rhs, EM_S, EM_F, addEM_S, addEM_F, firstNode); } } // end colouring } if (domain->m_faceOffset[1] > -1) { if (addEM_S) fill(EM_S.begin(), EM_S.end(), zero); if (addEM_F) { EM_F[0] = zero; EM_F[2] = zero; } for (index_t k1_0=0; k1_0<2; k1_0++) { // colouring #pragma omp for for (index_t k1=k1_0; k1<NE1; k1+=2) { const index_t e = domain->m_faceOffset[1]+k1; /////////////// // process d // /////////////// if (addEM_S) { const Scalar* d_p = d.getSampleDataRO(e, zero); EM_S[INDEX2(1,1,4)] = d_p[0]*w1; EM_S[INDEX2(3,1,4)] = d_p[0]*w1; EM_S[INDEX2(1,3,4)] = d_p[0]*w1; EM_S[INDEX2(3,3,4)] = d_p[0]*w1; } /////////////// // process y // /////////////// if (addEM_F) { const Scalar* y_p = y.getSampleDataRO(e, zero); EM_F[1] = 2.*w1*y_p[0]; EM_F[3] = 2.*w1*y_p[0]; } const index_t firstNode=m_NN[0]*(k1+1)-2; domain->addToMatrixAndRHS(mat, rhs, EM_S, EM_F, addEM_S, addEM_F, firstNode); } } // end colouring } if (domain->m_faceOffset[2] > -1) { if (addEM_S) fill(EM_S.begin(), EM_S.end(), zero); if (addEM_F) { EM_F[2] = zero; EM_F[3] = zero; } for (index_t k0_0=0; k0_0<2; k0_0++) { // colouring #pragma omp for for (index_t k0 = k0_0; k0 < NE0; k0+=2) { const index_t e = domain->m_faceOffset[2]+k0; /////////////// // process d // /////////////// if (addEM_S) { const Scalar* d_p = d.getSampleDataRO(e, zero); EM_S[INDEX2(0,0,4)] = d_p[0]*w0; EM_S[INDEX2(1,0,4)] = d_p[0]*w0; EM_S[INDEX2(0,1,4)] = d_p[0]*w0; EM_S[INDEX2(1,1,4)] = d_p[0]*w0; } /////////////// // process y // /////////////// if (addEM_F) { const Scalar* y_p = y.getSampleDataRO(e, zero); EM_F[0] = 2.*w0*y_p[0]; EM_F[1] = 2.*w0*y_p[0]; } const index_t firstNode = k0; domain->addToMatrixAndRHS(mat, rhs, EM_S, EM_F, addEM_S, addEM_F, firstNode); } } // end colouring } if (domain->m_faceOffset[3] > -1) { if (addEM_S) fill(EM_S.begin(), EM_S.end(), zero); if (addEM_F) { EM_F[0] = zero; EM_F[1] = zero; } for (index_t k0_0=0; k0_0<2; k0_0++) { // colouring #pragma omp for for (index_t k0 = k0_0; k0 < NE0; k0+=2) { const index_t e = domain->m_faceOffset[3]+k0; /////////////// // process d // /////////////// if (addEM_S) { const Scalar* d_p = d.getSampleDataRO(e, zero); EM_S[INDEX2(2,2,4)] = d_p[0]*w0; EM_S[INDEX2(3,2,4)] = d_p[0]*w0; EM_S[INDEX2(2,3,4)] = d_p[0]*w0; EM_S[INDEX2(3,3,4)] = d_p[0]*w0; } /////////////// // process y // /////////////// if (addEM_F) { const Scalar* y_p = y.getSampleDataRO(e, zero); EM_F[2] = 2.*w0*y_p[0]; EM_F[3] = 2.*w0*y_p[0]; } const index_t firstNode=m_NN[0]*(m_NN[1]-2)+k0; domain->addToMatrixAndRHS(mat, rhs, EM_S, EM_F, addEM_S, addEM_F, firstNode); } } // end colouring } } // end of parallel section } /****************************************************************************/ // PDE SYSTEM /****************************************************************************/ template<class Scalar> void DefaultAssembler2D<Scalar>::assemblePDESystem(AbstractSystemMatrix* mat, Data& rhs, const Data& A, const Data& B, const Data& C, const Data& D, const Data& X, const Data& Y) const { dim_t numEq, numComp; if (!mat) numEq=numComp=(rhs.isEmpty() ? 1 : rhs.getDataPointSize()); else { numEq=mat->getRowBlockSize(); numComp=mat->getColumnBlockSize(); } const double SQRT3 = 1.73205080756887719318; const double w1 = 1.0/24; const double w5 = -SQRT3/24 + 1.0/12; const double w2 = -SQRT3/24 - 1.0/12; const double w19 = -m_dx[0]/12; const double w11 = w19*(SQRT3 + 3)/12; const double w14 = w19*(-SQRT3 + 3)/12; const double w16 = w19*(5*SQRT3 + 9)/12; const double w17 = w19*(-5*SQRT3 + 9)/12; const double w27 = w19*(-SQRT3 - 3)/2; const double w28 = w19*(SQRT3 - 3)/2; const double w18 = -m_dx[1]/12; const double w10 = w18*(SQRT3 + 3)/12; const double w15 = w18*(-SQRT3 + 3)/12; const double w12 = w18*(5*SQRT3 + 9)/12; const double w13 = w18*(-5*SQRT3 + 9)/12; const double w25 = w18*(-SQRT3 - 3)/2; const double w26 = w18*(SQRT3 - 3)/2; const double w22 = m_dx[0]*m_dx[1]/144; const double w20 = w22*(SQRT3 + 2); const double w21 = w22*(-SQRT3 + 2); const double w23 = w22*(4*SQRT3 + 7); const double w24 = w22*(-4*SQRT3 + 7); const double w3 = m_dx[0]/(24*m_dx[1]); const double w7 = w3*(SQRT3 + 2); const double w8 = w3*(-SQRT3 + 2); const double w6 = -m_dx[1]/(24*m_dx[0]); const double w0 = w6*(SQRT3 + 2); const double w4 = w6*(-SQRT3 + 2); const int NE0 = m_NE[0]; const int NE1 = m_NE[1]; const bool addEM_S = (!A.isEmpty() || !B.isEmpty() || !C.isEmpty() || !D.isEmpty()); const bool addEM_F = (!X.isEmpty() || !Y.isEmpty()); const Scalar zero = static_cast<Scalar>(0); rhs.requireWrite(); #pragma omp parallel { vector<Scalar> EM_S(4*4*numEq*numComp, zero); vector<Scalar> EM_F(4*numEq, zero); for (index_t k1_0=0; k1_0<2; k1_0++) { // colouring #pragma omp for for (index_t k1=k1_0; k1 < NE1; k1+=2) { for (index_t k0=0; k0 < NE0; ++k0) { const index_t e = k0 + NE0*k1; if (addEM_S) fill(EM_S.begin(), EM_S.end(), zero); if (addEM_F) fill(EM_F.begin(), EM_F.end(), zero); /////////////// // process A // /////////////// if (!A.isEmpty()) { const Scalar* A_p = A.getSampleDataRO(e, zero); if (A.actsExpanded()) { for (index_t k=0; k<numEq; k++) { for (index_t m=0; m<numComp; m++) { const Scalar A_00_0 = A_p[INDEX5(k,0,m,0,0,numEq,2,numComp,2)]; const Scalar A_01_0 = A_p[INDEX5(k,0,m,1,0,numEq,2,numComp,2)]; const Scalar A_10_0 = A_p[INDEX5(k,1,m,0,0,numEq,2,numComp,2)]; const Scalar A_11_0 = A_p[INDEX5(k,1,m,1,0,numEq,2,numComp,2)]; const Scalar A_00_1 = A_p[INDEX5(k,0,m,0,1,numEq,2,numComp,2)]; const Scalar A_01_1 = A_p[INDEX5(k,0,m,1,1,numEq,2,numComp,2)]; const Scalar A_10_1 = A_p[INDEX5(k,1,m,0,1,numEq,2,numComp,2)]; const Scalar A_11_1 = A_p[INDEX5(k,1,m,1,1,numEq,2,numComp,2)]; const Scalar A_00_2 = A_p[INDEX5(k,0,m,0,2,numEq,2,numComp,2)]; const Scalar A_01_2 = A_p[INDEX5(k,0,m,1,2,numEq,2,numComp,2)]; const Scalar A_10_2 = A_p[INDEX5(k,1,m,0,2,numEq,2,numComp,2)]; const Scalar A_11_2 = A_p[INDEX5(k,1,m,1,2,numEq,2,numComp,2)]; const Scalar A_00_3 = A_p[INDEX5(k,0,m,0,3,numEq,2,numComp,2)]; const Scalar A_01_3 = A_p[INDEX5(k,0,m,1,3,numEq,2,numComp,2)]; const Scalar A_10_3 = A_p[INDEX5(k,1,m,0,3,numEq,2,numComp,2)]; const Scalar A_11_3 = A_p[INDEX5(k,1,m,1,3,numEq,2,numComp,2)]; const Scalar tmp0 = w3*(A_11_0 + A_11_1 + A_11_2 + A_11_3); const Scalar tmp1 = w1*(A_01_0 + A_01_3 - A_10_1 - A_10_2); const Scalar tmp2 = w4*(A_00_2 + A_00_3); const Scalar tmp3 = w0*(A_00_0 + A_00_1); const Scalar tmp4 = w5*(A_01_2 - A_10_3); const Scalar tmp5 = w2*(-A_01_1 + A_10_0); const Scalar tmp6 = w5*(A_01_3 + A_10_0); const Scalar tmp7 = w3*(-A_11_0 - A_11_1 - A_11_2 - A_11_3); const Scalar tmp8 = w6*(A_00_0 + A_00_1 + A_00_2 + A_00_3); const Scalar tmp9 = w1*(A_01_1 + A_01_2 + A_10_1 + A_10_2); const Scalar tmp10 = w2*(-A_01_0 - A_10_3); const Scalar tmp11 = w4*(A_00_0 + A_00_1); const Scalar tmp12 = w0*(A_00_2 + A_00_3); const Scalar tmp13 = w5*(A_01_1 - A_10_0); const Scalar tmp14 = w2*(-A_01_2 + A_10_3); const Scalar tmp15 = w7*(A_11_0 + A_11_2); const Scalar tmp16 = w4*(-A_00_2 - A_00_3); const Scalar tmp17 = w0*(-A_00_0 - A_00_1); const Scalar tmp18 = w5*(A_01_3 + A_10_3); const Scalar tmp19 = w8*(A_11_1 + A_11_3); const Scalar tmp20 = w2*(-A_01_0 - A_10_0); const Scalar tmp21 = w7*(A_11_1 + A_11_3); const Scalar tmp22 = w4*(-A_00_0 - A_00_1); const Scalar tmp23 = w0*(-A_00_2 - A_00_3); const Scalar tmp24 = w5*(A_01_0 + A_10_0); const Scalar tmp25 = w8*(A_11_0 + A_11_2); const Scalar tmp26 = w2*(-A_01_3 - A_10_3); const Scalar tmp27 = w5*(-A_01_1 - A_10_2); const Scalar tmp28 = w1*(-A_01_0 - A_01_3 - A_10_0 - A_10_3); const Scalar tmp29 = w2*(A_01_2 + A_10_1); const Scalar tmp30 = w7*(-A_11_1 - A_11_3); const Scalar tmp31 = w1*(-A_01_1 - A_01_2 + A_10_0 + A_10_3); const Scalar tmp32 = w5*(-A_01_0 + A_10_2); const Scalar tmp33 = w8*(-A_11_0 - A_11_2); const Scalar tmp34 = w6*(-A_00_0 - A_00_1 - A_00_2 - A_00_3); const Scalar tmp35 = w2*(A_01_3 - A_10_1); const Scalar tmp36 = w5*(A_01_0 + A_10_3); const Scalar tmp37 = w2*(-A_01_3 - A_10_0); const Scalar tmp38 = w7*(-A_11_0 - A_11_2); const Scalar tmp39 = w5*(-A_01_3 + A_10_1); const Scalar tmp40 = w8*(-A_11_1 - A_11_3); const Scalar tmp41 = w2*(A_01_0 - A_10_2); const Scalar tmp42 = w5*(A_01_1 - A_10_3); const Scalar tmp43 = w2*(-A_01_2 + A_10_0); const Scalar tmp44 = w5*(A_01_2 - A_10_0); const Scalar tmp45 = w2*(-A_01_1 + A_10_3); const Scalar tmp46 = w5*(-A_01_0 + A_10_1); const Scalar tmp47 = w2*(A_01_3 - A_10_2); const Scalar tmp48 = w5*(-A_01_1 - A_10_1); const Scalar tmp49 = w2*(A_01_2 + A_10_2); const Scalar tmp50 = w5*(-A_01_3 + A_10_2); const Scalar tmp51 = w2*(A_01_0 - A_10_1); const Scalar tmp52 = w5*(-A_01_2 - A_10_1); const Scalar tmp53 = w2*(A_01_1 + A_10_2); const Scalar tmp54 = w5*(-A_01_2 - A_10_2); const Scalar tmp55 = w2*(A_01_1 + A_10_1); EM_S[INDEX4(k,m,0,0,numEq,numComp,4)]+=tmp15 + tmp16 + tmp17 + tmp18 + tmp19 + tmp20 + tmp9; EM_S[INDEX4(k,m,0,1,numEq,numComp,4)]+=tmp0 + tmp1 + tmp2 + tmp3 + tmp4 + tmp5; EM_S[INDEX4(k,m,0,2,numEq,numComp,4)]+=tmp31 + tmp34 + tmp38 + tmp39 + tmp40 + tmp41; EM_S[INDEX4(k,m,0,3,numEq,numComp,4)]+=tmp28 + tmp52 + tmp53 + tmp7 + tmp8; EM_S[INDEX4(k,m,1,0,numEq,numComp,4)]+=tmp0 + tmp2 + tmp3 + tmp31 + tmp50 + tmp51; EM_S[INDEX4(k,m,1,1,numEq,numComp,4)]+=tmp16 + tmp17 + tmp21 + tmp25 + tmp28 + tmp54 + tmp55; EM_S[INDEX4(k,m,1,2,numEq,numComp,4)]+=tmp10 + tmp6 + tmp7 + tmp8 + tmp9; EM_S[INDEX4(k,m,1,3,numEq,numComp,4)]+=tmp1 + tmp30 + tmp33 + tmp34 + tmp44 + tmp45; EM_S[INDEX4(k,m,2,0,numEq,numComp,4)]+=tmp1 + tmp34 + tmp38 + tmp40 + tmp42 + tmp43; EM_S[INDEX4(k,m,2,1,numEq,numComp,4)]+=tmp36 + tmp37 + tmp7 + tmp8 + tmp9; EM_S[INDEX4(k,m,2,2,numEq,numComp,4)]+=tmp15 + tmp19 + tmp22 + tmp23 + tmp28 + tmp48 + tmp49; EM_S[INDEX4(k,m,2,3,numEq,numComp,4)]+=tmp0 + tmp11 + tmp12 + tmp31 + tmp46 + tmp47; EM_S[INDEX4(k,m,3,0,numEq,numComp,4)]+=tmp27 + tmp28 + tmp29 + tmp7 + tmp8; EM_S[INDEX4(k,m,3,1,numEq,numComp,4)]+=tmp30 + tmp31 + tmp32 + tmp33 + tmp34 + tmp35; EM_S[INDEX4(k,m,3,2,numEq,numComp,4)]+=tmp0 + tmp1 + tmp11 + tmp12 + tmp13 + tmp14; EM_S[INDEX4(k,m,3,3,numEq,numComp,4)]+=tmp21 + tmp22 + tmp23 + tmp24 + tmp25 + tmp26 + tmp9; } } } else { // constant data for (index_t k=0; k<numEq; k++) { for (index_t m=0; m<numComp; m++) { const Scalar A_00 = A_p[INDEX4(k,0,m,0, numEq,2, numComp)]; const Scalar A_01 = A_p[INDEX4(k,0,m,1, numEq,2, numComp)]; const Scalar A_10 = A_p[INDEX4(k,1,m,0, numEq,2, numComp)]; const Scalar A_11 = A_p[INDEX4(k,1,m,1, numEq,2, numComp)]; const Scalar tmp0 = 6.*w1*(A_01 - A_10); const Scalar tmp1 = 6.*w1*(A_01 + A_10); const Scalar tmp2 = 6.*w1*(-A_01 - A_10); const Scalar tmp3 = 6.*w1*(-A_01 + A_10); EM_S[INDEX4(k,m,0,0,numEq,numComp,4)]+=-8.*A_00*w6 + 8.*A_11*w3 + tmp1; EM_S[INDEX4(k,m,0,1,numEq,numComp,4)]+= 8.*A_00*w6 + 4.*A_11*w3 + tmp0; EM_S[INDEX4(k,m,0,2,numEq,numComp,4)]+=-4.*A_00*w6 - 8.*A_11*w3 + tmp3; EM_S[INDEX4(k,m,0,3,numEq,numComp,4)]+= 4.*A_00*w6 - 4.*A_11*w3 + tmp2; EM_S[INDEX4(k,m,1,0,numEq,numComp,4)]+= 8.*A_00*w6 + 4.*A_11*w3 + tmp3; EM_S[INDEX4(k,m,1,1,numEq,numComp,4)]+=-8.*A_00*w6 + 8.*A_11*w3 + tmp2; EM_S[INDEX4(k,m,1,2,numEq,numComp,4)]+= 4.*A_00*w6 - 4.*A_11*w3 + tmp1; EM_S[INDEX4(k,m,1,3,numEq,numComp,4)]+=-4.*A_00*w6 - 8.*A_11*w3 + tmp0; EM_S[INDEX4(k,m,2,0,numEq,numComp,4)]+=-4.*A_00*w6 - 8.*A_11*w3 + tmp0; EM_S[INDEX4(k,m,2,1,numEq,numComp,4)]+= 4.*A_00*w6 - 4.*A_11*w3 + tmp1; EM_S[INDEX4(k,m,2,2,numEq,numComp,4)]+=-8.*A_00*w6 + 8.*A_11*w3 + tmp2; EM_S[INDEX4(k,m,2,3,numEq,numComp,4)]+= 8.*A_00*w6 + 4.*A_11*w3 + tmp3; EM_S[INDEX4(k,m,3,0,numEq,numComp,4)]+= 4.*A_00*w6 - 4.*A_11*w3 + tmp2; EM_S[INDEX4(k,m,3,1,numEq,numComp,4)]+=-4.*A_00*w6 - 8.*A_11*w3 + tmp3; EM_S[INDEX4(k,m,3,2,numEq,numComp,4)]+= 8.*A_00*w6 + 4.*A_11*w3 + tmp0; EM_S[INDEX4(k,m,3,3,numEq,numComp,4)]+=-8.*A_00*w6 + 8.*A_11*w3 + tmp1; } } } } /////////////// // process B // /////////////// if (!B.isEmpty()) { const Scalar* B_p = B.getSampleDataRO(e, zero); if (B.actsExpanded()) { for (index_t k=0; k<numEq; k++) { for (index_t m=0; m<numComp; m++) { const Scalar B_0_0 = B_p[INDEX4(k,0,m,0, numEq,2,numComp)]; const Scalar B_1_0 = B_p[INDEX4(k,1,m,0, numEq,2,numComp)]; const Scalar B_0_1 = B_p[INDEX4(k,0,m,1, numEq,2,numComp)]; const Scalar B_1_1 = B_p[INDEX4(k,1,m,1, numEq,2,numComp)]; const Scalar B_0_2 = B_p[INDEX4(k,0,m,2, numEq,2,numComp)]; const Scalar B_1_2 = B_p[INDEX4(k,1,m,2, numEq,2,numComp)]; const Scalar B_0_3 = B_p[INDEX4(k,0,m,3, numEq,2,numComp)]; const Scalar B_1_3 = B_p[INDEX4(k,1,m,3, numEq,2,numComp)]; const Scalar tmp0 = w11*(B_1_0 + B_1_1); const Scalar tmp1 = w14*(B_1_2 + B_1_3); const Scalar tmp2 = w15*(-B_0_1 - B_0_3); const Scalar tmp3 = w10*(-B_0_0 - B_0_2); const Scalar tmp4 = w11*(B_1_2 + B_1_3); const Scalar tmp5 = w14*(B_1_0 + B_1_1); const Scalar tmp6 = w11*(-B_1_2 - B_1_3); const Scalar tmp7 = w14*(-B_1_0 - B_1_1); const Scalar tmp8 = w11*(-B_1_0 - B_1_1); const Scalar tmp9 = w14*(-B_1_2 - B_1_3); const Scalar tmp10 = w10*(-B_0_1 - B_0_3); const Scalar tmp11 = w15*(-B_0_0 - B_0_2); const Scalar tmp12 = w15*(B_0_0 + B_0_2); const Scalar tmp13 = w10*(B_0_1 + B_0_3); const Scalar tmp14 = w10*(B_0_0 + B_0_2); const Scalar tmp15 = w15*(B_0_1 + B_0_3); EM_S[INDEX4(k,m,0,0,numEq,numComp,4)]+=B_0_0*w12 + B_0_1*w10 + B_0_2*w15 + B_0_3*w13 + B_1_0*w16 + B_1_1*w14 + B_1_2*w11 + B_1_3*w17; EM_S[INDEX4(k,m,0,1,numEq,numComp,4)]+=B_0_0*w10 + B_0_1*w12 + B_0_2*w13 + B_0_3*w15 + tmp0 + tmp1; EM_S[INDEX4(k,m,0,2,numEq,numComp,4)]+=B_1_0*w11 + B_1_1*w17 + B_1_2*w16 + B_1_3*w14 + tmp14 + tmp15; EM_S[INDEX4(k,m,0,3,numEq,numComp,4)]+=tmp12 + tmp13 + tmp4 + tmp5; EM_S[INDEX4(k,m,1,0,numEq,numComp,4)]+=-B_0_0*w12 - B_0_1*w10 - B_0_2*w15 - B_0_3*w13 + tmp0 + tmp1; EM_S[INDEX4(k,m,1,1,numEq,numComp,4)]+=-B_0_0*w10 - B_0_1*w12 - B_0_2*w13 - B_0_3*w15 + B_1_0*w14 + B_1_1*w16 + B_1_2*w17 + B_1_3*w11; EM_S[INDEX4(k,m,1,2,numEq,numComp,4)]+=tmp2 + tmp3 + tmp4 + tmp5; EM_S[INDEX4(k,m,1,3,numEq,numComp,4)]+=B_1_0*w17 + B_1_1*w11 + B_1_2*w14 + B_1_3*w16 + tmp10 + tmp11; EM_S[INDEX4(k,m,2,0,numEq,numComp,4)]+=-B_1_0*w16 - B_1_1*w14 - B_1_2*w11 - B_1_3*w17 + tmp14 + tmp15; EM_S[INDEX4(k,m,2,1,numEq,numComp,4)]+=tmp12 + tmp13 + tmp8 + tmp9; EM_S[INDEX4(k,m,2,2,numEq,numComp,4)]+=B_0_0*w15 + B_0_1*w13 + B_0_2*w12 + B_0_3*w10 - B_1_0*w11 - B_1_1*w17 - B_1_2*w16 - B_1_3*w14; EM_S[INDEX4(k,m,2,3,numEq,numComp,4)]+=B_0_0*w13 + B_0_1*w15 + B_0_2*w10 + B_0_3*w12 + tmp6 + tmp7; EM_S[INDEX4(k,m,3,0,numEq,numComp,4)]+=tmp2 + tmp3 + tmp8 + tmp9; EM_S[INDEX4(k,m,3,1,numEq,numComp,4)]+=-B_1_0*w14 - B_1_1*w16 - B_1_2*w17 - B_1_3*w11 + tmp10 + tmp11; EM_S[INDEX4(k,m,3,2,numEq,numComp,4)]+=-B_0_0*w15 - B_0_1*w13 - B_0_2*w12 - B_0_3*w10 + tmp6 + tmp7; EM_S[INDEX4(k,m,3,3,numEq,numComp,4)]+=-B_0_0*w13 - B_0_1*w15 - B_0_2*w10 - B_0_3*w12 - B_1_0*w17 - B_1_1*w11 - B_1_2*w14 - B_1_3*w16; } } } else { // constant data for (index_t k=0; k<numEq; k++) { for (index_t m=0; m<numComp; m++) { const Scalar wB0 = B_p[INDEX3(k,0,m,numEq,2)]*w18; const Scalar wB1 = B_p[INDEX3(k,1,m,numEq,2)]*w19; EM_S[INDEX4(k,m,0,0,numEq,numComp,4)]+= 2.*wB0 + 2.*wB1; EM_S[INDEX4(k,m,0,1,numEq,numComp,4)]+= 2.*wB0 + wB1; EM_S[INDEX4(k,m,0,2,numEq,numComp,4)]+= wB0 + 2.*wB1; EM_S[INDEX4(k,m,0,3,numEq,numComp,4)]+= wB0 + wB1; EM_S[INDEX4(k,m,1,0,numEq,numComp,4)]+=-2.*wB0 + wB1; EM_S[INDEX4(k,m,1,1,numEq,numComp,4)]+=-2.*wB0 + 2.*wB1; EM_S[INDEX4(k,m,1,2,numEq,numComp,4)]+= -wB0 + wB1; EM_S[INDEX4(k,m,1,3,numEq,numComp,4)]+= -wB0 + 2.*wB1; EM_S[INDEX4(k,m,2,0,numEq,numComp,4)]+= wB0 - 2.*wB1; EM_S[INDEX4(k,m,2,1,numEq,numComp,4)]+= wB0 - wB1; EM_S[INDEX4(k,m,2,2,numEq,numComp,4)]+= 2.*wB0 - 2.*wB1; EM_S[INDEX4(k,m,2,3,numEq,numComp,4)]+= 2.*wB0 - wB1; EM_S[INDEX4(k,m,3,0,numEq,numComp,4)]+= -wB0 - wB1; EM_S[INDEX4(k,m,3,1,numEq,numComp,4)]+= -wB0 - 2.*wB1; EM_S[INDEX4(k,m,3,2,numEq,numComp,4)]+=-2.*wB0 - wB1; EM_S[INDEX4(k,m,3,3,numEq,numComp,4)]+=-2.*wB0 - 2.*wB1; } } } } /////////////// // process C // /////////////// if (!C.isEmpty()) { const Scalar* C_p = C.getSampleDataRO(e, zero); if (C.actsExpanded()) { for (index_t k=0; k<numEq; k++) { for (index_t m=0; m<numComp; m++) { const Scalar C_0_0 = C_p[INDEX4(k,m,0, 0, numEq,numComp,2)]; const Scalar C_1_0 = C_p[INDEX4(k,m,1, 0, numEq,numComp,2)]; const Scalar C_0_1 = C_p[INDEX4(k,m,0, 1, numEq,numComp,2)]; const Scalar C_1_1 = C_p[INDEX4(k,m,1, 1, numEq,numComp,2)]; const Scalar C_0_2 = C_p[INDEX4(k,m,0, 2, numEq,numComp,2)]; const Scalar C_1_2 = C_p[INDEX4(k,m,1, 2, numEq,numComp,2)]; const Scalar C_0_3 = C_p[INDEX4(k,m,0, 3, numEq,numComp,2)]; const Scalar C_1_3 = C_p[INDEX4(k,m,1, 3, numEq,numComp,2)]; const Scalar tmp0 = w11*(C_1_0 + C_1_1); const Scalar tmp1 = w14*(C_1_2 + C_1_3); const Scalar tmp2 = w15*(C_0_0 + C_0_2); const Scalar tmp3 = w10*(C_0_1 + C_0_3); const Scalar tmp4 = w11*(-C_1_0 - C_1_1); const Scalar tmp5 = w14*(-C_1_2 - C_1_3); const Scalar tmp6 = w11*(-C_1_2 - C_1_3); const Scalar tmp7 = w14*(-C_1_0 - C_1_1); const Scalar tmp8 = w11*(C_1_2 + C_1_3); const Scalar tmp9 = w14*(C_1_0 + C_1_1); const Scalar tmp10 = w10*(-C_0_1 - C_0_3); const Scalar tmp11 = w15*(-C_0_0 - C_0_2); const Scalar tmp12 = w15*(-C_0_1 - C_0_3); const Scalar tmp13 = w10*(-C_0_0 - C_0_2); const Scalar tmp14 = w10*(C_0_0 + C_0_2); const Scalar tmp15 = w15*(C_0_1 + C_0_3); EM_S[INDEX4(k,m,0,0,numEq,numComp,4)]+=C_0_0*w12 + C_0_1*w10 + C_0_2*w15 + C_0_3*w13 + C_1_0*w16 + C_1_1*w14 + C_1_2*w11 + C_1_3*w17; EM_S[INDEX4(k,m,0,1,numEq,numComp,4)]+=-C_0_0*w12 - C_0_1*w10 - C_0_2*w15 - C_0_3*w13 + tmp0 + tmp1; EM_S[INDEX4(k,m,0,2,numEq,numComp,4)]+=-C_1_0*w16 - C_1_1*w14 - C_1_2*w11 - C_1_3*w17 + tmp14 + tmp15; EM_S[INDEX4(k,m,0,3,numEq,numComp,4)]+=tmp12 + tmp13 + tmp4 + tmp5; EM_S[INDEX4(k,m,1,0,numEq,numComp,4)]+=C_0_0*w10 + C_0_1*w12 + C_0_2*w13 + C_0_3*w15 + tmp0 + tmp1; EM_S[INDEX4(k,m,1,1,numEq,numComp,4)]+=-C_0_0*w10 - C_0_1*w12 - C_0_2*w13 - C_0_3*w15 + C_1_0*w14 + C_1_1*w16 + C_1_2*w17 + C_1_3*w11; EM_S[INDEX4(k,m,1,2,numEq,numComp,4)]+=tmp2 + tmp3 + tmp4 + tmp5; EM_S[INDEX4(k,m,1,3,numEq,numComp,4)]+=-C_1_0*w14 - C_1_1*w16 - C_1_2*w17 - C_1_3*w11 + tmp10 + tmp11; EM_S[INDEX4(k,m,2,0,numEq,numComp,4)]+=C_1_0*w11 + C_1_1*w17 + C_1_2*w16 + C_1_3*w14 + tmp14 + tmp15; EM_S[INDEX4(k,m,2,1,numEq,numComp,4)]+=tmp12 + tmp13 + tmp8 + tmp9; EM_S[INDEX4(k,m,2,2,numEq,numComp,4)]+=C_0_0*w15 + C_0_1*w13 + C_0_2*w12 + C_0_3*w10 - C_1_0*w11 - C_1_1*w17 - C_1_2*w16 - C_1_3*w14; EM_S[INDEX4(k,m,2,3,numEq,numComp,4)]+=-C_0_0*w15 - C_0_1*w13 - C_0_2*w12 - C_0_3*w10 + tmp6 + tmp7; EM_S[INDEX4(k,m,3,0,numEq,numComp,4)]+=tmp2 + tmp3 + tmp8 + tmp9; EM_S[INDEX4(k,m,3,1,numEq,numComp,4)]+=C_1_0*w17 + C_1_1*w11 + C_1_2*w14 + C_1_3*w16 + tmp10 + tmp11; EM_S[INDEX4(k,m,3,2,numEq,numComp,4)]+=C_0_0*w13 + C_0_1*w15 + C_0_2*w10 + C_0_3*w12 + tmp6 + tmp7; EM_S[INDEX4(k,m,3,3,numEq,numComp,4)]+=-C_0_0*w13 - C_0_1*w15 - C_0_2*w10 - C_0_3*w12 - C_1_0*w17 - C_1_1*w11 - C_1_2*w14 - C_1_3*w16; } } } else { // constant data for (index_t k=0; k<numEq; k++) { for (index_t m=0; m<numComp; m++) { const Scalar wC0 = C_p[INDEX3(k,m,0,numEq,numComp)]*w18; const Scalar wC1 = C_p[INDEX3(k,m,1,numEq,numComp)]*w19; EM_S[INDEX4(k,m,0,0,numEq,numComp,4)]+= 2.*wC0 + 2.*wC1; EM_S[INDEX4(k,m,0,1,numEq,numComp,4)]+=-2.*wC0 + wC1; EM_S[INDEX4(k,m,0,2,numEq,numComp,4)]+= wC0 - 2.*wC1; EM_S[INDEX4(k,m,0,3,numEq,numComp,4)]+= -wC0 - wC1; EM_S[INDEX4(k,m,1,0,numEq,numComp,4)]+= 2.*wC0 + wC1; EM_S[INDEX4(k,m,1,1,numEq,numComp,4)]+=-2.*wC0 + 2.*wC1; EM_S[INDEX4(k,m,1,2,numEq,numComp,4)]+= wC0 - wC1; EM_S[INDEX4(k,m,1,3,numEq,numComp,4)]+= -wC0 - 2.*wC1; EM_S[INDEX4(k,m,2,0,numEq,numComp,4)]+= wC0 + 2.*wC1; EM_S[INDEX4(k,m,2,1,numEq,numComp,4)]+= -wC0 + wC1; EM_S[INDEX4(k,m,2,2,numEq,numComp,4)]+= 2.*wC0 - 2.*wC1; EM_S[INDEX4(k,m,2,3,numEq,numComp,4)]+=-2.*wC0 - wC1; EM_S[INDEX4(k,m,3,0,numEq,numComp,4)]+= wC0 + wC1; EM_S[INDEX4(k,m,3,1,numEq,numComp,4)]+= -wC0 + 2.*wC1; EM_S[INDEX4(k,m,3,2,numEq,numComp,4)]+= 2.*wC0 - wC1; EM_S[INDEX4(k,m,3,3,numEq,numComp,4)]+=-2.*wC0 - 2.*wC1; } } } } /////////////// // process D // /////////////// if (!D.isEmpty()) { const Scalar* D_p = D.getSampleDataRO(e, zero); if (D.actsExpanded()) { for (index_t k=0; k<numEq; k++) { for (index_t m=0; m<numComp; m++) { const Scalar D_0 = D_p[INDEX3(k,m,0,numEq,numComp)]; const Scalar D_1 = D_p[INDEX3(k,m,1,numEq,numComp)]; const Scalar D_2 = D_p[INDEX3(k,m,2,numEq,numComp)]; const Scalar D_3 = D_p[INDEX3(k,m,3,numEq,numComp)]; const Scalar tmp0 = w21*(D_2 + D_3); const Scalar tmp1 = w20*(D_0 + D_1); const Scalar tmp2 = w22*(D_0 + D_1 + D_2 + D_3); const Scalar tmp3 = w21*(D_0 + D_1); const Scalar tmp4 = w20*(D_2 + D_3); const Scalar tmp5 = w22*(D_1 + D_2); const Scalar tmp6 = w21*(D_0 + D_2); const Scalar tmp7 = w20*(D_1 + D_3); const Scalar tmp8 = w21*(D_1 + D_3); const Scalar tmp9 = w20*(D_0 + D_2); const Scalar tmp10 = w22*(D_0 + D_3); EM_S[INDEX4(k,m,0,0,numEq,numComp,4)]+=D_0*w23 + D_3*w24 + tmp5; EM_S[INDEX4(k,m,0,1,numEq,numComp,4)]+=tmp0 + tmp1; EM_S[INDEX4(k,m,0,2,numEq,numComp,4)]+=tmp8 + tmp9; EM_S[INDEX4(k,m,0,3,numEq,numComp,4)]+=tmp2; EM_S[INDEX4(k,m,1,0,numEq,numComp,4)]+=tmp0 + tmp1; EM_S[INDEX4(k,m,1,1,numEq,numComp,4)]+=D_1*w23 + D_2*w24 + tmp10; EM_S[INDEX4(k,m,1,2,numEq,numComp,4)]+=tmp2; EM_S[INDEX4(k,m,1,3,numEq,numComp,4)]+=tmp6 + tmp7; EM_S[INDEX4(k,m,2,0,numEq,numComp,4)]+=tmp8 + tmp9; EM_S[INDEX4(k,m,2,1,numEq,numComp,4)]+=tmp2; EM_S[INDEX4(k,m,2,2,numEq,numComp,4)]+=D_1*w24 + D_2*w23 + tmp10; EM_S[INDEX4(k,m,2,3,numEq,numComp,4)]+=tmp3 + tmp4; EM_S[INDEX4(k,m,3,0,numEq,numComp,4)]+=tmp2; EM_S[INDEX4(k,m,3,1,numEq,numComp,4)]+=tmp6 + tmp7; EM_S[INDEX4(k,m,3,2,numEq,numComp,4)]+=tmp3 + tmp4; EM_S[INDEX4(k,m,3,3,numEq,numComp,4)]+=D_0*w24 + D_3*w23 + tmp5; } } } else { // constant data for (index_t k=0; k<numEq; k++) { for (index_t m=0; m<numComp; m++) { const Scalar D_0 = D_p[INDEX2(k, m, numEq)]; EM_S[INDEX4(k,m,0,0,numEq,numComp,4)]+=16.*D_0*w22; EM_S[INDEX4(k,m,0,1,numEq,numComp,4)]+= 8.*D_0*w22; EM_S[INDEX4(k,m,0,2,numEq,numComp,4)]+= 8.*D_0*w22; EM_S[INDEX4(k,m,0,3,numEq,numComp,4)]+= 4.*D_0*w22; EM_S[INDEX4(k,m,1,0,numEq,numComp,4)]+= 8.*D_0*w22; EM_S[INDEX4(k,m,1,1,numEq,numComp,4)]+=16.*D_0*w22; EM_S[INDEX4(k,m,1,2,numEq,numComp,4)]+= 4.*D_0*w22; EM_S[INDEX4(k,m,1,3,numEq,numComp,4)]+= 8.*D_0*w22; EM_S[INDEX4(k,m,2,0,numEq,numComp,4)]+= 8.*D_0*w22; EM_S[INDEX4(k,m,2,1,numEq,numComp,4)]+= 4.*D_0*w22; EM_S[INDEX4(k,m,2,2,numEq,numComp,4)]+=16.*D_0*w22; EM_S[INDEX4(k,m,2,3,numEq,numComp,4)]+= 8.*D_0*w22; EM_S[INDEX4(k,m,3,0,numEq,numComp,4)]+= 4.*D_0*w22; EM_S[INDEX4(k,m,3,1,numEq,numComp,4)]+= 8.*D_0*w22; EM_S[INDEX4(k,m,3,2,numEq,numComp,4)]+= 8.*D_0*w22; EM_S[INDEX4(k,m,3,3,numEq,numComp,4)]+=16.*D_0*w22; } } } } /////////////// // process X // /////////////// if (!X.isEmpty()) { const Scalar* X_p = X.getSampleDataRO(e, zero); if (X.actsExpanded()) { for (index_t k=0; k<numEq; k++) { const Scalar X_0_0 = X_p[INDEX3(k,0,0,numEq,2)]; const Scalar X_1_0 = X_p[INDEX3(k,1,0,numEq,2)]; const Scalar X_0_1 = X_p[INDEX3(k,0,1,numEq,2)]; const Scalar X_1_1 = X_p[INDEX3(k,1,1,numEq,2)]; const Scalar X_0_2 = X_p[INDEX3(k,0,2,numEq,2)]; const Scalar X_1_2 = X_p[INDEX3(k,1,2,numEq,2)]; const Scalar X_0_3 = X_p[INDEX3(k,0,3,numEq,2)]; const Scalar X_1_3 = X_p[INDEX3(k,1,3,numEq,2)]; const Scalar tmp0 = 6.*w15*(X_0_2 + X_0_3); const Scalar tmp1 = 6.*w10*(X_0_0 + X_0_1); const Scalar tmp2 = 6.*w11*(X_1_0 + X_1_2); const Scalar tmp3 = 6.*w14*(X_1_1 + X_1_3); const Scalar tmp4 = 6.*w11*(X_1_1 + X_1_3); const Scalar tmp5 = w25*(X_0_0 + X_0_1); const Scalar tmp6 = w26*(X_0_2 + X_0_3); const Scalar tmp7 = 6.*w14*(X_1_0 + X_1_2); const Scalar tmp8 = w27*(X_1_0 + X_1_2); const Scalar tmp9 = w28*(X_1_1 + X_1_3); const Scalar tmp10 = w25*(-X_0_2- X_0_3); const Scalar tmp11 = w26*(-X_0_0- X_0_1); const Scalar tmp12 = w27*(X_1_1 + X_1_3); const Scalar tmp13 = w28*(X_1_0 + X_1_2); const Scalar tmp14 = w25*(X_0_2 + X_0_3); const Scalar tmp15 = w26*(X_0_0 + X_0_1); EM_F[INDEX2(k,0,numEq)]+=tmp0 + tmp1 + tmp2 + tmp3; EM_F[INDEX2(k,1,numEq)]+=tmp4 + tmp5 + tmp6 + tmp7; EM_F[INDEX2(k,2,numEq)]+=tmp10 + tmp11 + tmp8 + tmp9; EM_F[INDEX2(k,3,numEq)]+=tmp12 + tmp13 + tmp14 + tmp15; } } else { // constant data for (index_t k=0; k<numEq; k++) { const Scalar wX0 = X_p[INDEX2(k, 0, numEq)]*w18; const Scalar wX1 = X_p[INDEX2(k, 1, numEq)]*w19; EM_F[INDEX2(k,0,numEq)]+= 6.*wX0 + 6.*wX1; EM_F[INDEX2(k,1,numEq)]+=-6.*wX0 + 6.*wX1; EM_F[INDEX2(k,2,numEq)]+= 6.*wX0 - 6.*wX1; EM_F[INDEX2(k,3,numEq)]+=-6.*wX0 - 6.*wX1; } } } /////////////// // process Y // /////////////// if (!Y.isEmpty()) { const Scalar* Y_p = Y.getSampleDataRO(e, zero); if (Y.actsExpanded()) { for (index_t k=0; k<numEq; k++) { const Scalar Y_0 = Y_p[INDEX2(k, 0, numEq)]; const Scalar Y_1 = Y_p[INDEX2(k, 1, numEq)]; const Scalar Y_2 = Y_p[INDEX2(k, 2, numEq)]; const Scalar Y_3 = Y_p[INDEX2(k, 3, numEq)]; const Scalar tmp0 = 6.*w22*(Y_1 + Y_2); const Scalar tmp1 = 6.*w22*(Y_0 + Y_3); EM_F[INDEX2(k,0,numEq)]+=6.*Y_0*w20 + 6.*Y_3*w21 + tmp0; EM_F[INDEX2(k,1,numEq)]+=6.*Y_1*w20 + 6.*Y_2*w21 + tmp1; EM_F[INDEX2(k,2,numEq)]+=6.*Y_1*w21 + 6.*Y_2*w20 + tmp1; EM_F[INDEX2(k,3,numEq)]+=6.*Y_0*w21 + 6.*Y_3*w20 + tmp0; } } else { // constant data for (index_t k=0; k<numEq; k++) { EM_F[INDEX2(k,0,numEq)]+=36.*Y_p[k]*w22; EM_F[INDEX2(k,1,numEq)]+=36.*Y_p[k]*w22; EM_F[INDEX2(k,2,numEq)]+=36.*Y_p[k]*w22; EM_F[INDEX2(k,3,numEq)]+=36.*Y_p[k]*w22; } } } // add to matrix (if addEM_S) and RHS (if addEM_F) const index_t firstNode=m_NN[0]*k1+k0; domain->addToMatrixAndRHS(mat, rhs, EM_S, EM_F, addEM_S, addEM_F, firstNode, numEq, numComp); } // end k0 loop } // end k1 loop } // end of colouring } // end of parallel region } /****************************************************************************/ // PDE SYSTEM BOUNDARY /****************************************************************************/ template<class Scalar> void DefaultAssembler2D<Scalar>::assemblePDEBoundarySystem( AbstractSystemMatrix* mat, Data& rhs, const Data& d, const Data& y) const { dim_t numEq, numComp; if (!mat) { numEq=numComp=(rhs.isEmpty() ? 1 : rhs.getDataPointSize()); } else { numEq=mat->getRowBlockSize(); numComp=mat->getColumnBlockSize(); } const double SQRT3 = 1.73205080756887719318; const double w5 = m_dx[0]/12; const double w6 = w5*(SQRT3 + 2); const double w7 = w5*(-SQRT3 + 2); const double w8 = w5*(SQRT3 + 3); const double w9 = w5*(-SQRT3 + 3); const double w2 = m_dx[1]/12; const double w0 = w2*(SQRT3 + 2); const double w1 = w2*(-SQRT3 + 2); const double w3 = w2*(SQRT3 + 3); const double w4 = w2*(-SQRT3 + 3); const int NE0 = m_NE[0]; const int NE1 = m_NE[1]; const bool addEM_S = !d.isEmpty(); const bool addEM_F = !y.isEmpty(); const Scalar zero = static_cast<Scalar>(0); rhs.requireWrite(); #pragma omp parallel { vector<Scalar> EM_S(4*4*numEq*numComp, zero); vector<Scalar> EM_F(4*numEq, zero); if (domain->m_faceOffset[0] > -1) { if (addEM_S) fill(EM_S.begin(), EM_S.end(), zero); if (addEM_F) fill(EM_F.begin(), EM_F.end(), zero); for (index_t k1_0=0; k1_0<2; k1_0++) { // colouring #pragma omp for for (index_t k1=k1_0; k1<NE1; k1+=2) { const index_t e = k1; /////////////// // process d // /////////////// if (addEM_S) { const Scalar* d_p = d.getSampleDataRO(e, zero); if (d.actsExpanded()) { for (index_t k=0; k<numEq; k++) { for (index_t m=0; m<numComp; m++) { const Scalar d_0 = d_p[INDEX3(k,m,0,numEq,numComp)]; const Scalar d_1 = d_p[INDEX3(k,m,1,numEq,numComp)]; const Scalar tmp0 = w2*(d_0 + d_1); EM_S[INDEX4(k,m,0,0,numEq,numComp,4)] = d_0*w0 + d_1*w1; EM_S[INDEX4(k,m,2,0,numEq,numComp,4)] = tmp0; EM_S[INDEX4(k,m,0,2,numEq,numComp,4)] = tmp0; EM_S[INDEX4(k,m,2,2,numEq,numComp,4)] = d_0*w1 + d_1*w0; } } } else { // constant data for (index_t k=0; k<numEq; k++) { for (index_t m=0; m<numComp; m++) { const Scalar d_0 = d_p[INDEX2(k, m, numEq)]; EM_S[INDEX4(k,m,0,0,numEq,numComp,4)] = 4.*d_0*w2; EM_S[INDEX4(k,m,2,0,numEq,numComp,4)] = 2.*d_0*w2; EM_S[INDEX4(k,m,0,2,numEq,numComp,4)] = 2.*d_0*w2; EM_S[INDEX4(k,m,2,2,numEq,numComp,4)] = 4.*d_0*w2; } } } } /////////////// // process y // /////////////// if (addEM_F) { const Scalar* y_p = y.getSampleDataRO(e, zero); if (y.actsExpanded()) { for (index_t k=0; k<numEq; k++) { const Scalar y_0 = y_p[INDEX2(k, 0, numEq)]; const Scalar y_1 = y_p[INDEX2(k, 1, numEq)]; EM_F[INDEX2(k,0,numEq)] = w3*y_0 + w4*y_1; EM_F[INDEX2(k,2,numEq)] = w3*y_1 + w4*y_0; } } else { // constant data for (index_t k=0; k<numEq; k++) { EM_F[INDEX2(k,0,numEq)] = 6*w2*y_p[k]; EM_F[INDEX2(k,2,numEq)] = 6*w2*y_p[k]; } } } const index_t firstNode=m_NN[0]*k1; domain->addToMatrixAndRHS(mat, rhs, EM_S, EM_F, addEM_S, addEM_F, firstNode, numEq, numComp); } } // end colouring } if (domain->m_faceOffset[1] > -1) { if (addEM_S) fill(EM_S.begin(), EM_S.end(), zero); if (addEM_F) fill(EM_F.begin(), EM_F.end(), zero); for (index_t k1_0=0; k1_0<2; k1_0++) { // colouring #pragma omp for for (index_t k1=k1_0; k1<NE1; k1+=2) { const index_t e = domain->m_faceOffset[1]+k1; /////////////// // process d // /////////////// if (addEM_S) { const Scalar* d_p = d.getSampleDataRO(e, zero); if (d.actsExpanded()) { for (index_t k=0; k<numEq; k++) { for (index_t m=0; m<numComp; m++) { const Scalar d_0 = d_p[INDEX3(k,m,0,numEq,numComp)]; const Scalar d_1 = d_p[INDEX3(k,m,1,numEq,numComp)]; const Scalar tmp0 = w2*(d_0 + d_1); EM_S[INDEX4(k,m,1,1,numEq,numComp,4)] = d_0*w0 + d_1*w1; EM_S[INDEX4(k,m,3,1,numEq,numComp,4)] = tmp0; EM_S[INDEX4(k,m,1,3,numEq,numComp,4)] = tmp0; EM_S[INDEX4(k,m,3,3,numEq,numComp,4)] = d_0*w1 + d_1*w0; } } } else { // constant data for (index_t k=0; k<numEq; k++) { for (index_t m=0; m<numComp; m++) { const Scalar d_0 = d_p[INDEX2(k, m, numEq)]; EM_S[INDEX4(k,m,1,1,numEq,numComp,4)] = 4.*d_0*w2; EM_S[INDEX4(k,m,3,1,numEq,numComp,4)] = 2.*d_0*w2; EM_S[INDEX4(k,m,1,3,numEq,numComp,4)] = 2.*d_0*w2; EM_S[INDEX4(k,m,3,3,numEq,numComp,4)] = 4.*d_0*w2; } } } } /////////////// // process y // /////////////// if (addEM_F) { const Scalar* y_p = y.getSampleDataRO(e, zero); if (y.actsExpanded()) { for (index_t k=0; k<numEq; k++) { const Scalar y_0 = y_p[INDEX2(k, 0, numEq)]; const Scalar y_1 = y_p[INDEX2(k, 1, numEq)]; EM_F[INDEX2(k,1,numEq)] = w3*y_0 + w4*y_1; EM_F[INDEX2(k,3,numEq)] = w3*y_1 + w4*y_0; } } else { // constant data for (index_t k=0; k<numEq; k++) { EM_F[INDEX2(k,1,numEq)] = 6*w2*y_p[k]; EM_F[INDEX2(k,3,numEq)] = 6*w2*y_p[k]; } } } const index_t firstNode=m_NN[0]*(k1+1)-2; domain->addToMatrixAndRHS(mat, rhs, EM_S, EM_F, addEM_S, addEM_F, firstNode, numEq, numComp); } } // end colouring } if (domain->m_faceOffset[2] > -1) { if (addEM_S) fill(EM_S.begin(), EM_S.end(), zero); if (addEM_F) fill(EM_F.begin(), EM_F.end(), zero); for (index_t k0_0=0; k0_0<2; k0_0++) { // colouring #pragma omp for for (index_t k0 = k0_0; k0 < NE0; k0+=2) { const index_t e = domain->m_faceOffset[2]+k0; /////////////// // process d // /////////////// if (addEM_S) { const Scalar* d_p = d.getSampleDataRO(e, zero); if (d.actsExpanded()) { for (index_t k=0; k<numEq; k++) { for (index_t m=0; m<numComp; m++) { const Scalar d_0 = d_p[INDEX3(k,m,0,numEq,numComp)]; const Scalar d_1 = d_p[INDEX3(k,m,1,numEq,numComp)]; const Scalar tmp0 = w5*(d_0 + d_1); EM_S[INDEX4(k,m,0,0,numEq,numComp,4)] = d_0*w6 + d_1*w7; EM_S[INDEX4(k,m,1,0,numEq,numComp,4)] = tmp0; EM_S[INDEX4(k,m,0,1,numEq,numComp,4)] = tmp0; EM_S[INDEX4(k,m,1,1,numEq,numComp,4)] = d_0*w7 + d_1*w6; } } } else { // constant data for (index_t k=0; k<numEq; k++) { for (index_t m=0; m<numComp; m++) { const Scalar d_0 = d_p[INDEX2(k, m, numEq)]; EM_S[INDEX4(k,m,0,0,numEq,numComp,4)] = 4.*d_0*w5; EM_S[INDEX4(k,m,1,0,numEq,numComp,4)] = 2.*d_0*w5; EM_S[INDEX4(k,m,0,1,numEq,numComp,4)] = 2.*d_0*w5; EM_S[INDEX4(k,m,1,1,numEq,numComp,4)] = 4.*d_0*w5; } } } } /////////////// // process y // /////////////// if (addEM_F) { const Scalar* y_p = y.getSampleDataRO(e, zero); if (y.actsExpanded()) { for (index_t k=0; k<numEq; k++) { const Scalar y_0 = y_p[INDEX2(k, 0, numEq)]; const Scalar y_1 = y_p[INDEX2(k, 1, numEq)]; EM_F[INDEX2(k,0,numEq)] = w8*y_0 + w9*y_1; EM_F[INDEX2(k,1,numEq)] = w8*y_1 + w9*y_0; } } else { // constant data for (index_t k=0; k<numEq; k++) { EM_F[INDEX2(k,0,numEq)] = 6*w5*y_p[k]; EM_F[INDEX2(k,1,numEq)] = 6*w5*y_p[k]; } } } const index_t firstNode=k0; domain->addToMatrixAndRHS(mat, rhs, EM_S, EM_F, addEM_S, addEM_F, firstNode, numEq, numComp); } } // end colouring } if (domain->m_faceOffset[3] > -1) { if (addEM_S) fill(EM_S.begin(), EM_S.end(), zero); if (addEM_F) fill(EM_F.begin(), EM_F.end(), zero); for (index_t k0_0=0; k0_0<2; k0_0++) { // colouring #pragma omp for for (index_t k0 = k0_0; k0 < NE0; k0+=2) { const index_t e = domain->m_faceOffset[3]+k0; /////////////// // process d // /////////////// if (addEM_S) { const Scalar* d_p = d.getSampleDataRO(e, zero); if (d.actsExpanded()) { for (index_t k=0; k<numEq; k++) { for (index_t m=0; m<numComp; m++) { const Scalar d_0 = d_p[INDEX3(k,m,0,numEq,numComp)]; const Scalar d_1 = d_p[INDEX3(k,m,1,numEq,numComp)]; const Scalar tmp0 = w5*(d_0 + d_1); EM_S[INDEX4(k,m,2,2,numEq,numComp,4)] = d_0*w6 + d_1*w7; EM_S[INDEX4(k,m,3,2,numEq,numComp,4)] = tmp0; EM_S[INDEX4(k,m,2,3,numEq,numComp,4)] = tmp0; EM_S[INDEX4(k,m,3,3,numEq,numComp,4)] = d_0*w7 + d_1*w6; } } } else { // constant data for (index_t k=0; k<numEq; k++) { for (index_t m=0; m<numComp; m++) { const Scalar d_0 = d_p[INDEX2(k, m, numEq)]; EM_S[INDEX4(k,m,2,2,numEq,numComp,4)] = 4.*d_0*w5; EM_S[INDEX4(k,m,3,2,numEq,numComp,4)] = 2.*d_0*w5; EM_S[INDEX4(k,m,2,3,numEq,numComp,4)] = 2.*d_0*w5; EM_S[INDEX4(k,m,3,3,numEq,numComp,4)] = 4.*d_0*w5; } } } } /////////////// // process y // /////////////// if (addEM_F) { const Scalar* y_p = y.getSampleDataRO(e, zero); if (y.actsExpanded()) { for (index_t k=0; k<numEq; k++) { const Scalar y_0 = y_p[INDEX2(k, 0, numEq)]; const Scalar y_1 = y_p[INDEX2(k, 1, numEq)]; EM_F[INDEX2(k,2,numEq)] = w8*y_0 + w9*y_1; EM_F[INDEX2(k,3,numEq)] = w8*y_1 + w9*y_0; } } else { // constant data for (index_t k=0; k<numEq; k++) { EM_F[INDEX2(k,2,numEq)] = 6.*w5*y_p[k]; EM_F[INDEX2(k,3,numEq)] = 6.*w5*y_p[k]; } } } const index_t firstNode=m_NN[0]*(m_NN[1]-2)+k0; domain->addToMatrixAndRHS(mat, rhs, EM_S, EM_F, addEM_S, addEM_F, firstNode, numEq, numComp); } } // end colouring } } // end of parallel section } /****************************************************************************/ // PDE SYSTEM REDUCED /****************************************************************************/ template<class Scalar> void DefaultAssembler2D<Scalar>::assemblePDESystemReduced( AbstractSystemMatrix* mat, Data& rhs, const Data& A, const Data& B, const Data& C, const Data& D, const Data& X, const Data& Y) const { dim_t numEq, numComp; if (!mat) numEq=numComp=(rhs.isEmpty() ? 1 : rhs.getDataPointSize()); else { numEq=mat->getRowBlockSize(); numComp=mat->getColumnBlockSize(); } const double w0 = 1./4; const double w1 = m_dx[0]/8; const double w2 = m_dx[1]/8; const double w3 = m_dx[0]*m_dx[1]/16; const double w4 = m_dx[0]/(4*m_dx[1]); const double w5 = m_dx[1]/(4*m_dx[0]); const int NE0 = m_NE[0]; const int NE1 = m_NE[1]; const bool addEM_S = (!A.isEmpty() || !B.isEmpty() || !C.isEmpty() || !D.isEmpty()); const bool addEM_F = (!X.isEmpty() || !Y.isEmpty()); const Scalar zero = static_cast<Scalar>(0); rhs.requireWrite(); #pragma omp parallel { vector<Scalar> EM_S(4*4*numEq*numComp, zero); vector<Scalar> EM_F(4*numEq, zero); for (index_t k1_0=0; k1_0<2; k1_0++) { // colouring #pragma omp for for (index_t k1=k1_0; k1<NE1; k1+=2) { for (index_t k0=0; k0<NE0; ++k0) { if (addEM_S) fill(EM_S.begin(), EM_S.end(), zero); if (addEM_F) fill(EM_F.begin(), EM_F.end(), zero); const index_t e = k0 + NE0*k1; /////////////// // process A // /////////////// if (!A.isEmpty()) { const Scalar* A_p = A.getSampleDataRO(e, zero); for (index_t k=0; k<numEq; k++) { for (index_t m=0; m<numComp; m++) { const Scalar Aw00 = A_p[INDEX4(k,0,m,0, numEq,2, numComp)]*w5; const Scalar Aw01 = A_p[INDEX4(k,0,m,1, numEq,2, numComp)]*w0; const Scalar Aw10 = A_p[INDEX4(k,1,m,0, numEq,2, numComp)]*w0; const Scalar Aw11 = A_p[INDEX4(k,1,m,1, numEq,2, numComp)]*w4; EM_S[INDEX4(k,m,0,0,numEq,numComp,4)]+= Aw00 + Aw01 + Aw10 + Aw11; EM_S[INDEX4(k,m,1,0,numEq,numComp,4)]+=-Aw00 - Aw01 + Aw10 + Aw11; EM_S[INDEX4(k,m,2,0,numEq,numComp,4)]+= Aw00 + Aw01 - Aw10 - Aw11; EM_S[INDEX4(k,m,3,0,numEq,numComp,4)]+=-Aw00 - Aw01 - Aw10 - Aw11; EM_S[INDEX4(k,m,0,1,numEq,numComp,4)]+=-Aw00 + Aw01 - Aw10 + Aw11; EM_S[INDEX4(k,m,1,1,numEq,numComp,4)]+= Aw00 - Aw01 - Aw10 + Aw11; EM_S[INDEX4(k,m,2,1,numEq,numComp,4)]+=-Aw00 + Aw01 + Aw10 - Aw11; EM_S[INDEX4(k,m,3,1,numEq,numComp,4)]+= Aw00 - Aw01 + Aw10 - Aw11; EM_S[INDEX4(k,m,0,2,numEq,numComp,4)]+= Aw00 - Aw01 + Aw10 - Aw11; EM_S[INDEX4(k,m,1,2,numEq,numComp,4)]+=-Aw00 + Aw01 + Aw10 - Aw11; EM_S[INDEX4(k,m,2,2,numEq,numComp,4)]+= Aw00 - Aw01 - Aw10 + Aw11; EM_S[INDEX4(k,m,3,2,numEq,numComp,4)]+=-Aw00 + Aw01 - Aw10 + Aw11; EM_S[INDEX4(k,m,0,3,numEq,numComp,4)]+=-Aw00 - Aw01 - Aw10 - Aw11; EM_S[INDEX4(k,m,1,3,numEq,numComp,4)]+= Aw00 + Aw01 - Aw10 - Aw11; EM_S[INDEX4(k,m,2,3,numEq,numComp,4)]+=-Aw00 - Aw01 + Aw10 + Aw11; EM_S[INDEX4(k,m,3,3,numEq,numComp,4)]+= Aw00 + Aw01 + Aw10 + Aw11; } } } /////////////// // process B // /////////////// if (!B.isEmpty()) { const Scalar* B_p = B.getSampleDataRO(e, zero); for (index_t k=0; k<numEq; k++) { for (index_t m=0; m<numComp; m++) { const Scalar wB0 = B_p[INDEX3(k,0,m, numEq, 2)]*w2; const Scalar wB1 = B_p[INDEX3(k,1,m, numEq, 2)]*w1; EM_S[INDEX4(k,m,0,0,numEq,numComp,4)]+=-wB0 - wB1; EM_S[INDEX4(k,m,0,1,numEq,numComp,4)]+=-wB0 - wB1; EM_S[INDEX4(k,m,0,2,numEq,numComp,4)]+=-wB0 - wB1; EM_S[INDEX4(k,m,0,3,numEq,numComp,4)]+=-wB0 - wB1; EM_S[INDEX4(k,m,1,0,numEq,numComp,4)]+= wB0 - wB1; EM_S[INDEX4(k,m,1,1,numEq,numComp,4)]+= wB0 - wB1; EM_S[INDEX4(k,m,1,2,numEq,numComp,4)]+= wB0 - wB1; EM_S[INDEX4(k,m,1,3,numEq,numComp,4)]+= wB0 - wB1; EM_S[INDEX4(k,m,2,0,numEq,numComp,4)]+=-wB0 + wB1; EM_S[INDEX4(k,m,2,1,numEq,numComp,4)]+=-wB0 + wB1; EM_S[INDEX4(k,m,2,2,numEq,numComp,4)]+=-wB0 + wB1; EM_S[INDEX4(k,m,2,3,numEq,numComp,4)]+=-wB0 + wB1; EM_S[INDEX4(k,m,3,0,numEq,numComp,4)]+= wB0 + wB1; EM_S[INDEX4(k,m,3,1,numEq,numComp,4)]+= wB0 + wB1; EM_S[INDEX4(k,m,3,2,numEq,numComp,4)]+= wB0 + wB1; EM_S[INDEX4(k,m,3,3,numEq,numComp,4)]+= wB0 + wB1; } } } /////////////// // process C // /////////////// if (!C.isEmpty()) { const Scalar* C_p = C.getSampleDataRO(e, zero); for (index_t k=0; k<numEq; k++) { for (index_t m=0; m<numComp; m++) { const Scalar wC0 = C_p[INDEX3(k, m, 0, numEq, numComp)]*w2; const Scalar wC1 = C_p[INDEX3(k, m, 1, numEq, numComp)]*w1; EM_S[INDEX4(k,m,0,0,numEq,numComp,4)]+=-wC0 - wC1; EM_S[INDEX4(k,m,1,0,numEq,numComp,4)]+=-wC0 - wC1; EM_S[INDEX4(k,m,2,0,numEq,numComp,4)]+=-wC0 - wC1; EM_S[INDEX4(k,m,3,0,numEq,numComp,4)]+=-wC0 - wC1; EM_S[INDEX4(k,m,0,1,numEq,numComp,4)]+= wC0 - wC1; EM_S[INDEX4(k,m,1,1,numEq,numComp,4)]+= wC0 - wC1; EM_S[INDEX4(k,m,2,1,numEq,numComp,4)]+= wC0 - wC1; EM_S[INDEX4(k,m,3,1,numEq,numComp,4)]+= wC0 - wC1; EM_S[INDEX4(k,m,0,2,numEq,numComp,4)]+=-wC0 + wC1; EM_S[INDEX4(k,m,1,2,numEq,numComp,4)]+=-wC0 + wC1; EM_S[INDEX4(k,m,2,2,numEq,numComp,4)]+=-wC0 + wC1; EM_S[INDEX4(k,m,3,2,numEq,numComp,4)]+=-wC0 + wC1; EM_S[INDEX4(k,m,0,3,numEq,numComp,4)]+= wC0 + wC1; EM_S[INDEX4(k,m,1,3,numEq,numComp,4)]+= wC0 + wC1; EM_S[INDEX4(k,m,2,3,numEq,numComp,4)]+= wC0 + wC1; EM_S[INDEX4(k,m,3,3,numEq,numComp,4)]+= wC0 + wC1; } } } /////////////// // process D // /////////////// if (!D.isEmpty()) { const Scalar* D_p = D.getSampleDataRO(e, zero); for (index_t k=0; k<numEq; k++) { for (index_t m=0; m<numComp; m++) { const Scalar wD0 = D_p[INDEX2(k, m, numEq)]*w3; EM_S[INDEX4(k,m,0,0,numEq,numComp,4)]+=wD0; EM_S[INDEX4(k,m,1,0,numEq,numComp,4)]+=wD0; EM_S[INDEX4(k,m,2,0,numEq,numComp,4)]+=wD0; EM_S[INDEX4(k,m,3,0,numEq,numComp,4)]+=wD0; EM_S[INDEX4(k,m,0,1,numEq,numComp,4)]+=wD0; EM_S[INDEX4(k,m,1,1,numEq,numComp,4)]+=wD0; EM_S[INDEX4(k,m,2,1,numEq,numComp,4)]+=wD0; EM_S[INDEX4(k,m,3,1,numEq,numComp,4)]+=wD0; EM_S[INDEX4(k,m,0,2,numEq,numComp,4)]+=wD0; EM_S[INDEX4(k,m,1,2,numEq,numComp,4)]+=wD0; EM_S[INDEX4(k,m,2,2,numEq,numComp,4)]+=wD0; EM_S[INDEX4(k,m,3,2,numEq,numComp,4)]+=wD0; EM_S[INDEX4(k,m,0,3,numEq,numComp,4)]+=wD0; EM_S[INDEX4(k,m,1,3,numEq,numComp,4)]+=wD0; EM_S[INDEX4(k,m,2,3,numEq,numComp,4)]+=wD0; EM_S[INDEX4(k,m,3,3,numEq,numComp,4)]+=wD0; } } } /////////////// // process X // /////////////// if (!X.isEmpty()) { const Scalar* X_p = X.getSampleDataRO(e, zero); for (index_t k=0; k<numEq; k++) { const Scalar wX0 = 4.*X_p[INDEX2(k, 0, numEq)]*w2; const Scalar wX1 = 4.*X_p[INDEX2(k, 1, numEq)]*w1; EM_F[INDEX2(k,0,numEq)]+=-wX0 - wX1; EM_F[INDEX2(k,1,numEq)]+= wX0 - wX1; EM_F[INDEX2(k,2,numEq)]+=-wX0 + wX1; EM_F[INDEX2(k,3,numEq)]+= wX0 + wX1; } } /////////////// // process Y // /////////////// if (!Y.isEmpty()) { const Scalar* Y_p = Y.getSampleDataRO(e, zero); for (index_t k=0; k<numEq; k++) { EM_F[INDEX2(k,0,numEq)]+=4.*Y_p[k]*w3; EM_F[INDEX2(k,1,numEq)]+=4.*Y_p[k]*w3; EM_F[INDEX2(k,2,numEq)]+=4.*Y_p[k]*w3; EM_F[INDEX2(k,3,numEq)]+=4.*Y_p[k]*w3; } } // add to matrix (if addEM_S) and RHS (if addEM_F) const index_t firstNode=m_NN[0]*k1+k0; domain->addToMatrixAndRHS(mat, rhs, EM_S, EM_F, addEM_S, addEM_F, firstNode, numEq, numComp); } // end k0 loop } // end k1 loop } // end of colouring } // end of parallel region } /****************************************************************************/ // PDE SYSTEM REDUCED BOUNDARY /****************************************************************************/ template<class Scalar> void DefaultAssembler2D<Scalar>::assemblePDEBoundarySystemReduced( AbstractSystemMatrix* mat, Data& rhs, const Data& d, const Data& y) const { dim_t numEq, numComp; if (!mat) numEq=numComp=(rhs.isEmpty() ? 1 : rhs.getDataPointSize()); else { numEq=mat->getRowBlockSize(); numComp=mat->getColumnBlockSize(); } const double w0 = m_dx[0]/4; const double w1 = m_dx[1]/4; const int NE0 = m_NE[0]; const int NE1 = m_NE[1]; const bool addEM_S = !d.isEmpty(); const bool addEM_F = !y.isEmpty(); const Scalar zero = static_cast<Scalar>(0); rhs.requireWrite(); #pragma omp parallel { vector<Scalar> EM_S(4*4*numEq*numComp, zero); vector<Scalar> EM_F(4*numEq, zero); if (domain->m_faceOffset[0] > -1) { if (addEM_S) fill(EM_S.begin(), EM_S.end(), zero); if (addEM_F) fill(EM_F.begin(), EM_F.end(), zero); for (index_t k1_0=0; k1_0<2; k1_0++) { // colouring #pragma omp for for (index_t k1=k1_0; k1<NE1; k1+=2) { /////////////// // process d // /////////////// if (addEM_S) { const Scalar* d_p = d.getSampleDataRO(k1, zero); for (index_t k=0; k<numEq; k++) { for (index_t m=0; m<numComp; m++) { const Scalar tmp0 = d_p[INDEX2(k, m, numEq)]*w1; EM_S[INDEX4(k,m,0,0,numEq,numComp,4)] = tmp0; EM_S[INDEX4(k,m,2,0,numEq,numComp,4)] = tmp0; EM_S[INDEX4(k,m,0,2,numEq,numComp,4)] = tmp0; EM_S[INDEX4(k,m,2,2,numEq,numComp,4)] = tmp0; } } } /////////////// // process y // /////////////// if (addEM_F) { const Scalar* y_p = y.getSampleDataRO(k1, zero); for (index_t k=0; k<numEq; k++) { EM_F[INDEX2(k,0,numEq)] = 2*w1*y_p[k]; EM_F[INDEX2(k,2,numEq)] = 2*w1*y_p[k]; } } const index_t firstNode=m_NN[0]*k1; domain->addToMatrixAndRHS(mat, rhs, EM_S, EM_F, addEM_S, addEM_F, firstNode, numEq, numComp); } } // end colouring } if (domain->m_faceOffset[1] > -1) { if (addEM_S) fill(EM_S.begin(), EM_S.end(), zero); if (addEM_F) fill(EM_F.begin(), EM_F.end(), zero); for (index_t k1_0=0; k1_0<2; k1_0++) { // colouring #pragma omp for for (index_t k1=k1_0; k1<NE1; k1+=2) { const index_t e = domain->m_faceOffset[1]+k1; /////////////// // process d // /////////////// if (addEM_S) { const Scalar* d_p = d.getSampleDataRO(e, zero); for (index_t k=0; k<numEq; k++) { for (index_t m=0; m<numComp; m++) { const Scalar tmp0 = d_p[INDEX2(k, m, numEq)]*w1; EM_S[INDEX4(k,m,1,1,numEq,numComp,4)] = tmp0; EM_S[INDEX4(k,m,3,1,numEq,numComp,4)] = tmp0; EM_S[INDEX4(k,m,1,3,numEq,numComp,4)] = tmp0; EM_S[INDEX4(k,m,3,3,numEq,numComp,4)] = tmp0; } } } /////////////// // process y // /////////////// if (addEM_F) { const Scalar* y_p = y.getSampleDataRO(e, zero); for (index_t k=0; k<numEq; k++) { EM_F[INDEX2(k,1,numEq)] = 2.*w1*y_p[k]; EM_F[INDEX2(k,3,numEq)] = 2.*w1*y_p[k]; } } const index_t firstNode=m_NN[0]*(k1+1)-2; domain->addToMatrixAndRHS(mat, rhs, EM_S, EM_F, addEM_S, addEM_F, firstNode, numEq, numComp); } } // end colouring } if (domain->m_faceOffset[2] > -1) { if (addEM_S) fill(EM_S.begin(), EM_S.end(), zero); if (addEM_F) fill(EM_F.begin(), EM_F.end(), zero); for (index_t k0_0=0; k0_0<2; k0_0++) { // colouring #pragma omp for for (index_t k0 = k0_0; k0 < NE0; k0+=2) { const index_t e = domain->m_faceOffset[2]+k0; /////////////// // process d // /////////////// if (addEM_S) { const Scalar* d_p = d.getSampleDataRO(e, zero); for (index_t k=0; k<numEq; k++) { for (index_t m=0; m<numComp; m++) { const Scalar tmp0 = d_p[INDEX2(k, m, numEq)]*w0; EM_S[INDEX4(k,m,0,0,numEq,numComp,4)] = tmp0; EM_S[INDEX4(k,m,1,0,numEq,numComp,4)] = tmp0; EM_S[INDEX4(k,m,0,1,numEq,numComp,4)] = tmp0; EM_S[INDEX4(k,m,1,1,numEq,numComp,4)] = tmp0; } } } /////////////// // process y // /////////////// if (addEM_F) { const Scalar* y_p = y.getSampleDataRO(e, zero); for (index_t k=0; k<numEq; k++) { EM_F[INDEX2(k,0,numEq)] = 2.*w0*y_p[k]; EM_F[INDEX2(k,1,numEq)] = 2.*w0*y_p[k]; } } const index_t firstNode=k0; domain->addToMatrixAndRHS(mat, rhs, EM_S, EM_F, addEM_S, addEM_F, firstNode, numEq, numComp); } } // end colouring } if (domain->m_faceOffset[3] > -1) { if (addEM_S) fill(EM_S.begin(), EM_S.end(), zero); if (addEM_F) fill(EM_F.begin(), EM_F.end(), zero); for (index_t k0_0=0; k0_0<2; k0_0++) { // colouring #pragma omp for for (index_t k0 = k0_0; k0 < NE0; k0+=2) { const index_t e = domain->m_faceOffset[3]+k0; /////////////// // process d // /////////////// if (addEM_S) { const Scalar* d_p = d.getSampleDataRO(e, zero); for (index_t k=0; k<numEq; k++) { for (index_t m=0; m<numComp; m++) { const Scalar tmp0 = d_p[INDEX2(k, m, numEq)]*w0; EM_S[INDEX4(k,m,2,2,numEq,numComp,4)] = tmp0; EM_S[INDEX4(k,m,3,2,numEq,numComp,4)] = tmp0; EM_S[INDEX4(k,m,2,3,numEq,numComp,4)] = tmp0; EM_S[INDEX4(k,m,3,3,numEq,numComp,4)] = tmp0; } } } /////////////// // process y // /////////////// if (addEM_F) { const Scalar* y_p = y.getSampleDataRO(e, zero); for (index_t k=0; k<numEq; k++) { EM_F[INDEX2(k,2,numEq)] = 2*w0*y_p[k]; EM_F[INDEX2(k,3,numEq)] = 2*w0*y_p[k]; } } const index_t firstNode=m_NN[0]*(m_NN[1]-2)+k0; domain->addToMatrixAndRHS(mat, rhs, EM_S, EM_F, addEM_S, addEM_F, firstNode, numEq, numComp); } } // end colouring } } // end of parallel section } // instantiate our two supported versions template class DefaultAssembler2D<escript::DataTypes::real_t>; template class DefaultAssembler2D<escript::DataTypes::cplx_t>; } // namespace ripley
56.260303
170
0.386166
[ "vector" ]
64460008b4cbb951aa8a0ce50bd686787b169457
2,592
cpp
C++
Days 181 - 190/Day 184/FindGCD.cpp
LucidSigma/Daily-Coding-Problems
21dc8f7e615edd535d7beb1f5d0e41dd3b4bcc1a
[ "MIT" ]
null
null
null
Days 181 - 190/Day 184/FindGCD.cpp
LucidSigma/Daily-Coding-Problems
21dc8f7e615edd535d7beb1f5d0e41dd3b4bcc1a
[ "MIT" ]
null
null
null
Days 181 - 190/Day 184/FindGCD.cpp
LucidSigma/Daily-Coding-Problems
21dc8f7e615edd535d7beb1f5d0e41dd3b4bcc1a
[ "MIT" ]
null
null
null
#include <algorithm> #include <cmath> #include <iostream> #include <iterator> #include <unordered_map> #include <vector> std::vector<unsigned int> GetPrimeNumbers(const unsigned int max) noexcept { static constexpr unsigned int SmallestPrime = 2u; std::vector<unsigned int> primeNumbers{ SmallestPrime }; for (unsigned int i = SmallestPrime + 1; i < max / 2 + 1; ++i) { bool isPrime = true; for (const auto primeNumber : primeNumbers) { if (i % primeNumber == 0) { isPrime = false; break; } } if (isPrime) { primeNumbers.push_back(i); } } return primeNumbers; } std::unordered_map<unsigned int, unsigned int> GetFactors(unsigned int number, const std::vector<unsigned int>& primeNumbers) noexcept { std::unordered_map<unsigned int, unsigned int> factors; unsigned int primeNumberIndex = 0; while (number > 1) { if (primeNumberIndex >= primeNumbers.size()) { break; } if (number % primeNumbers[primeNumberIndex] == 0) { if (factors.find(primeNumbers[primeNumberIndex]) == std::cend(factors)) { factors[primeNumbers[primeNumberIndex]] = 0; } ++factors[primeNumbers[primeNumberIndex]]; number /= primeNumbers[primeNumberIndex]; } else { ++primeNumberIndex; } } return factors; } unsigned int GetGCD(const std::vector<unsigned int>& numbers) noexcept { const unsigned int minNumber = *std::min_element(std::cbegin(numbers), std::cend(numbers)); const auto primeNumbers = GetPrimeNumbers(minNumber); const auto minFactors = GetFactors(minNumber, primeNumbers); const auto allNumberFactors = [&numbers, &primeNumbers]() { std::unordered_map<unsigned int, std::unordered_map<unsigned int, unsigned int>> allFactors; for (const auto number : numbers) { allFactors[number] = GetFactors(number, primeNumbers); } return allFactors; }(); std::unordered_map<unsigned int, unsigned int> commonFactors; for (const auto [minFactor, _] : minFactors) { commonFactors[minFactor] = 0; std::vector<unsigned int> numberFactors; for (const auto number : numbers) { const auto currentFactors = allNumberFactors.at(number); numberFactors.push_back(currentFactors.at(minFactor)); } commonFactors[minFactor] = *std::min_element(std::cbegin(numberFactors), std::cend(numberFactors)); } unsigned int gcd = 1; for (const auto [factor, commonFactor] : commonFactors) { gcd *= static_cast<unsigned int>(std::pow(factor, commonFactor)); } return gcd; } int main(int argc, char* argv[]) { std::cout << GetGCD({ 42, 56, 14 }) << "\n"; std::cin.get(); return 0; }
21.966102
134
0.696373
[ "vector" ]
644a5d7fdba838d98395bbff8d492c13a557f4ec
33,612
hpp
C++
gsa/wit/COIN/include/ClpSimplex.hpp
kant/CMMPPT
c64b339712db28a619880c4c04839aef7d3b6e2b
[ "Apache-2.0" ]
1
2019-10-25T05:25:23.000Z
2019-10-25T05:25:23.000Z
gsa/wit/COIN/include/ClpSimplex.hpp
kant/CMMPPT
c64b339712db28a619880c4c04839aef7d3b6e2b
[ "Apache-2.0" ]
2
2019-09-04T17:34:59.000Z
2020-09-16T08:10:57.000Z
gsa/wit/COIN/include/ClpSimplex.hpp
kant/CMMPPT
c64b339712db28a619880c4c04839aef7d3b6e2b
[ "Apache-2.0" ]
18
2019-07-22T19:01:25.000Z
2022-03-03T15:36:11.000Z
// Copyright (C) 2002, International Business Machines // Corporation and others. All Rights Reserved. /* Authors John Forrest */ #ifndef ClpSimplex_H #define ClpSimplex_H #include <iostream> #include <cfloat> #include "ClpModel.hpp" #include "ClpMatrixBase.hpp" class ClpDualRowPivot; class ClpPrimalColumnPivot; class ClpFactorization; class CoinIndexedVector; class ClpNonLinearCost; /** This solves LPs using the simplex method It inherits from ClpModel and all its arrays are created at algorithm time. Originally I tried to work with model arrays but for simplicity of coding I changed to single arrays with structural variables then row variables. Some coding is still based on old style and needs cleaning up. For a description of algorithms: for dual see ClpSimplexDual.hpp and at top of ClpSimplexDual.cpp for primal see ClpSimplexPrimal.hpp and at top of ClpSimplexPrimal.cpp There is an algorithm data member. + for primal variations and - for dual variations This file also includes (at end) a very simple class ClpSimplexProgress which is where anti-looping stuff should migrate to */ class ClpSimplex : public ClpModel { friend void ClpSimplexUnitTest(const std::string & mpsDir, const std::string & netlibDir); public: /** enums for status of various sorts. First 4 match CoinWarmStartBasis, isFixed means fixed at lower bound and out of basis */ enum Status { isFree = 0x00, basic = 0x01, atUpperBound = 0x02, atLowerBound = 0x03, superBasic = 0x04, isFixed = 0x05 }; enum FakeBound { noFake = 0x00, bothFake = 0x01, upperFake = 0x02, lowerFake = 0x03 }; /**@name Constructors and destructor and copy */ //@{ /// Default constructor ClpSimplex ( ); /// Copy constructor. ClpSimplex(const ClpSimplex &); /// Copy constructor from model. ClpSimplex(const ClpModel &); /// Assignment operator. This copies the data ClpSimplex & operator=(const ClpSimplex & rhs); /// Destructor ~ClpSimplex ( ); // Ones below are just ClpModel with setti /** Loads a problem (the constraints on the rows are given by lower and upper bounds). If a pointer is 0 then the following values are the default: <ul> <li> <code>colub</code>: all columns have upper bound infinity <li> <code>collb</code>: all columns have lower bound 0 <li> <code>rowub</code>: all rows have upper bound infinity <li> <code>rowlb</code>: all rows have lower bound -infinity <li> <code>obj</code>: all variables have 0 objective coefficient </ul> */ void loadProblem ( const ClpMatrixBase& matrix, const double* collb, const double* colub, const double* obj, const double* rowlb, const double* rowub, const double * rowObjective=NULL); void loadProblem ( const CoinPackedMatrix& matrix, const double* collb, const double* colub, const double* obj, const double* rowlb, const double* rowub, const double * rowObjective=NULL); /** Just like the other loadProblem() method except that the matrix is given in a standard column major ordered format (without gaps). */ void loadProblem ( const int numcols, const int numrows, const CoinBigIndex* start, const int* index, const double* value, const double* collb, const double* colub, const double* obj, const double* rowlb, const double* rowub, const double * rowObjective=NULL); /// This one is for after presolve to save memory void loadProblem ( const int numcols, const int numrows, const CoinBigIndex* start, const int* index, const double* value,const int * length, const double* collb, const double* colub, const double* obj, const double* rowlb, const double* rowub, const double * rowObjective=NULL); /// Read an mps file from the given filename int readMps(const char *filename, bool keepNames=false, bool ignoreErrors = false); /** Borrow model. This is so we dont have to copy large amounts of data around. It assumes a derived class wants to overwrite an empty model with a real one - while it does an algorithm. This is same as ClpModel one, but sets scaling on etc. */ void borrowModel(ClpModel & otherModel); //@} /**@name Functions most useful to user */ //@{ /** Dual algorithm - see ClpSimplexDual.hpp for method */ int dual(int ifValuesPass=0); /** Primal algorithm - see ClpSimplexPrimal.hpp for method */ int primal(int ifValuesPass=0); /** Solves quadratic problem using SLP - may be used as crash for other algorithms when number of iterations small. Also exits if all problematical variables are changing less than deltaTolerance */ int quadraticSLP(int numberPasses,double deltaTolerance); /// Solves quadratic using Wolfe's algorithm - primal int quadraticWolfe(); /// Passes in factorization void setFactorization( ClpFactorization & factorization); /// Sets or unsets scaling, 0 -off, 1 on, 2 dynamic(later) void scaling(int mode=1); /// Gets scalingFlag inline int scalingFlag() const {return scalingFlag_;}; /** Tightens primal bounds to make dual faster. Unless fixed, bounds are slightly looser than they could be. This is to make dual go faster and is probably not needed with a presolve. Returns non-zero if problem infeasible. Fudge for branch and bound - put bounds on columns of factor * largest value (at continuous) - should improve stability in branch and bound on infeasible branches (0.0 is off) */ int tightenPrimalBounds(double factor=0.0); /** Crash - at present just aimed at dual, returns -2 if dual preferred and crash basis created -1 if dual preferred and all slack basis preferred 0 if basis going in was not all slack 1 if primal preferred and all slack basis preferred 2 if primal preferred and crash basis created. if gap between bounds <="gap" variables can be flipped If "pivot" is 0 No pivoting (so will just be choice of algorithm) 1 Simple pivoting e.g. gub 2 Mini iterations */ int crash(double gap,int pivot); /// Sets row pivot choice algorithm in dual void setDualRowPivotAlgorithm(ClpDualRowPivot & choice); /// Sets column pivot choice algorithm in primal void setPrimalColumnPivotAlgorithm(ClpPrimalColumnPivot & choice); /** For strong branching. On input lower and upper are new bounds while on output they are change in objective function values (>1.0e50 infeasible). Return code is 0 if nothing interesting, -1 if infeasible both ways and +1 if infeasible one way (check values to see which one(s)) */ int strongBranching(int numberVariables,const int * variables, double * newLower, double * newUpper, bool stopOnFirstInfeasible=true, bool alwaysFinish=false); //@} /**@name Needed for functionality of OsiSimplexInterface */ //@{ /** Pivot in a variable and out a variable. Returns 0 if okay, 1 if inaccuracy forced re-factorization, -1 if would be singular. Also updates primal/dual infeasibilities. Assumes sequenceIn_ and pivotRow_ set and also directionIn and Out. */ int pivot(); /** Pivot in a variable and choose an outgoing one. Assumes primal feasible - will not go through a bound. Returns step length in theta Returns ray in ray_ (or NULL if no pivot) Return codes as before but -1 means no acceptable pivot */ int primalPivotResult(); /** Pivot out a variable and choose an incoing one. Assumes dual feasible - will not go through a reduced cost. Returns step length in theta Returns ray in ray_ (or NULL if no pivot) Return codes as before but -1 means no acceptable pivot */ int dualPivotResult(); /** Common bits of coding for dual and primal. Return s0 if okay, 1 if bad matrix, 2 if very bad factorization */ int startup(int ifValuesPass); void finish(); /** Factorizes and returns true if optimal. Used by user */ bool statusOfProblem(); //@} /**@name most useful gets and sets */ //@{ /// If problem is primal feasible inline bool primalFeasible() const { return (numberPrimalInfeasibilities_==0);}; /// If problem is dual feasible inline bool dualFeasible() const { return (numberDualInfeasibilities_==0);}; /// factorization inline ClpFactorization * factorization() const { return factorization_;}; /// Sparsity on or off bool sparseFactorization() const; void setSparseFactorization(bool value); /// Dual bound inline double dualBound() const { return dualBound_;}; void setDualBound(double value); /// Infeasibility cost inline double infeasibilityCost() const { return infeasibilityCost_;}; void setInfeasibilityCost(double value); /** Amount of print out: 0 - none 1 - just final 2 - just factorizations 3 - as 2 plus a bit more 4 - verbose above that 8,16,32 etc just for selective debug */ /** Perturbation: -50 to +50 - perturb by this power of ten (-6 sounds good) 100 - auto perturb if takes too long (1.0e-6 largest nonzero) 101 - we are perturbed 102 - don't try perturbing again default is 100 */ inline int perturbation() const { return perturbation_;}; void setPerturbation(int value); /// Current (or last) algorithm inline int algorithm() const {return algorithm_; } ; /// Set algorithm inline void setAlgorithm(int value) {algorithm_=value; } ; /// Sum of dual infeasibilities inline double sumDualInfeasibilities() const { return sumDualInfeasibilities_;} ; /// Number of dual infeasibilities inline int numberDualInfeasibilities() const { return numberDualInfeasibilities_;} ; /// Sum of primal infeasibilities inline double sumPrimalInfeasibilities() const { return sumPrimalInfeasibilities_;} ; /// Number of primal infeasibilities inline int numberPrimalInfeasibilities() const { return numberPrimalInfeasibilities_;} ; /** Save model to file, returns 0 if success. This is designed for use outside algorithms so does not save iterating arrays etc. It does not save any messaging information. Does not save scaling values. It does not know about all types of virtual functions. */ int saveModel(const char * fileName); /** Restore model from file, returns 0 if success, deletes current model */ int restoreModel(const char * fileName); /** Just check solution (for external use) - sets sum of infeasibilities etc */ void checkSolution(); /// Useful row length arrays (0,1,2,3,4,5) inline CoinIndexedVector * rowArray(int index) const { return rowArray_[index];}; /// Useful column length arrays (0,1,2,3,4,5) inline CoinIndexedVector * columnArray(int index) const { return columnArray_[index];}; //@} /******************** End of most useful part **************/ /**@name Functions less likely to be useful to casual user */ //@{ /** Given an existing factorization computes and checks primal and dual solutions. Uses input arrays for variables at bounds. Returns feasibility states */ int getSolution ( const double * rowActivities, const double * columnActivities); /** Given an existing factorization computes and checks primal and dual solutions. Uses current problem arrays for bounds. Returns feasibility states */ int getSolution (); /** Constructs a non linear cost from list of non-linearities (columns only) First lower of each column is taken as real lower Last lower is taken as real upper and cost ignored Returns nonzero if bad data e.g. lowers not monotonic */ int createPiecewiseLinearCosts(const int * starts, const double * lower, const double * gradient); /** Return model - updates any scalars */ void returnModel(ClpSimplex & otherModel); /** Factorizes using current basis. solveType - 1 iterating, 0 initial, -1 external If 10 added then in primal values pass Return codes are as from ClpFactorization unless initial factorization when total number of singularities is returned */ /// Save data ClpDataSave saveData() const; /// Restore data void restoreData(ClpDataSave saved); int internalFactorize(int solveType); /// Factorizes using current basis. For external use int factorize(); /** Computes duals from scratch. If givenDjs then allows for nonzero basic djs */ void computeDuals(double * givenDjs); /// Computes primals from scratch void computePrimals ( const double * rowActivities, const double * columnActivities); /** Unpacks one column of the matrix into indexed array Uses sequenceIn_ Also applies scaling if needed */ void unpack(CoinIndexedVector * rowArray) const ; /** Unpacks one column of the matrix into indexed array Slack if sequence>= numberColumns Also applies scaling if needed */ void unpack(CoinIndexedVector * rowArray,int sequence) const; /** This does basis housekeeping and does values for in/out variables. Can also decide to re-factorize */ int housekeeping(double objectiveChange); /** This sets largest infeasibility and most infeasible and sum and number of infeasibilities (Primal) */ void checkPrimalSolution(const double * rowActivities=NULL, const double * columnActivies=NULL); /** This sets largest infeasibility and most infeasible and sum and number of infeasibilities (Dual) */ void checkDualSolution(); //@} /**@name Matrix times vector methods They can be faster if scalar is +- 1 These are covers so user need not worry about scaling Also for simplex I am not using basic/non-basic split */ //@{ /** Return <code>y + A * x * scalar</code> in <code>y</code>. @pre <code>x</code> must be of size <code>numColumns()</code> @pre <code>y</code> must be of size <code>numRows()</code> */ void times(double scalar, const double * x, double * y) const; /** Return <code>y + x * scalar * A</code> in <code>y</code>. @pre <code>x</code> must be of size <code>numRows()</code> @pre <code>y</code> must be of size <code>numColumns()</code> */ void transposeTimes(double scalar, const double * x, double * y) const ; //@} /**@name most useful gets and sets */ //@{ /// Worst column primal infeasibility inline double columnPrimalInfeasibility() const { return columnPrimalInfeasibility_;} ; /// Sequence of worst (-1 if feasible) inline int columnPrimalSequence() const { return columnPrimalSequence_;} ; /// Worst row primal infeasibility inline double rowPrimalInfeasibility() const { return rowPrimalInfeasibility_;} ; /// Sequence of worst (-1 if feasible) inline int rowPrimalSequence() const { return rowPrimalSequence_;} ; /** Worst column dual infeasibility (note - these may not be as meaningful if the problem is primal infeasible */ inline double columnDualInfeasibility() const { return columnDualInfeasibility_;} ; /// Sequence of worst (-1 if feasible) inline int columnDualSequence() const { return columnDualSequence_;} ; /// Worst row dual infeasibility inline double rowDualInfeasibility() const { return rowDualInfeasibility_;} ; /// Sequence of worst (-1 if feasible) inline int rowDualSequence() const { return rowDualSequence_;} ; /// Primal tolerance needed to make dual feasible (<largeTolerance) inline double primalToleranceToGetOptimal() const { return primalToleranceToGetOptimal_;} ; /// Remaining largest dual infeasibility inline double remainingDualInfeasibility() const { return remainingDualInfeasibility_;} ; /// Large bound value (for complementarity etc) inline double largeValue() const { return largeValue_;} ; void setLargeValue( double value) ; /// Largest error on Ax-b inline double largestPrimalError() const { return largestPrimalError_;} ; /// Largest error on basic duals inline double largestDualError() const { return largestDualError_;} ; /// Largest difference between input primal solution and computed inline double largestSolutionError() const { return largestSolutionError_;} ; /// Basic variables pivoting on which rows inline const int * pivotVariable() const { return pivotVariable_;}; /// Current dual tolerance inline double currentDualTolerance() const { return dualTolerance_;} ; inline void setCurrentDualTolerance(double value) { dualTolerance_ = value;} ; /// Current primal tolerance inline double currentPrimalTolerance() const { return primalTolerance_;} ; inline void setCurrentPrimalTolerance(double value) { primalTolerance_ = value;} ; /// How many iterative refinements to do inline int numberRefinements() const { return numberRefinements_;} ; void setnumberRefinements( int value) ; /// Alpha (pivot element) for use by classes e.g. steepestedge inline double alpha() const { return alpha_;}; /// Reduced cost of last incoming for use by classes e.g. steepestedge inline double dualIn() const { return dualIn_;}; /// Pivot Row for use by classes e.g. steepestedge inline int pivotRow() const{ return pivotRow_;}; /// value of incoming variable (in Dual) double valueIncomingDual() const; //@} protected: /**@name protected methods */ //@{ /** May change basis and then returns number changed. Computation of solutions may be overriden by given pi and solution */ int gutsOfSolution ( const double * rowActivities, const double * columnActivities, double * givenDuals, const double * givenPrimals, bool valuesPass=false); /// Does most of deletion (0 = all, 1 = most, 2 most + factorization) void gutsOfDelete(int type); /// Does most of copying void gutsOfCopy(const ClpSimplex & rhs); /** puts in format I like (rowLower,rowUpper) also see StandardMatrix 1 bit does rows, 2 bit does column bounds, 4 bit does objective(s). 8 bit does solution scaling in 16 bit does rowArray and columnArray indexed vectors and makes row copy if wanted, also sets columnStart_ etc Also creates scaling arrays if needed. It does scaling if needed. 16 also moves solutions etc in to work arrays On 16 returns false if problem "bad" i.e. matrix or bounds bad */ bool createRim(int what,bool makeRowCopy=false); /** releases above arrays and does solution scaling out. May also get rid of factorization data - 0 get rid of nothing, 1 get rid of arrays, 2 also factorization */ void deleteRim(int getRidOfFactorizationData=2); /// Sanity check on input rim data (after scaling) - returns true if okay bool sanityCheck(); /** Get next superbasic (primal) or next free (dual), -1 if none */ int nextSuperBasic(); //@} public: /**@name public methods */ //@{ /** Return row or column sections - not as much needed as it once was. These just map into single arrays */ inline double * solutionRegion(int section) { if (!section) return rowActivityWork_; else return columnActivityWork_;}; inline double * djRegion(int section) { if (!section) return rowReducedCost_; else return reducedCostWork_;}; inline double * lowerRegion(int section) { if (!section) return rowLowerWork_; else return columnLowerWork_;}; inline double * upperRegion(int section) { if (!section) return rowUpperWork_; else return columnUpperWork_;}; inline double * costRegion(int section) { if (!section) return rowObjectiveWork_; else return objectiveWork_;}; /// Return region as single array inline double * solutionRegion() { return solution_;}; inline double * djRegion() { return dj_;}; inline double * lowerRegion() { return lower_;}; inline double * upperRegion() { return upper_;}; inline double * costRegion() { return cost_;}; inline Status getStatus(int sequence) const {return static_cast<Status> (status_[sequence]&7);}; inline void setStatus(int sequence, Status status) { unsigned char & st_byte = status_[sequence]; st_byte &= ~7; st_byte |= status; }; /** Return sequence In or Out */ inline int sequenceIn() const {return sequenceIn_;}; inline int sequenceOut() const {return sequenceOut_;}; /** Set sequenceIn or Out */ inline void setSequenceIn(int sequence) { sequenceIn_=sequence;}; inline void setSequenceOut(int sequence) { sequenceOut_=sequence;}; /** Return direction In or Out */ inline int directionIn() const {return directionIn_;}; inline int directionOut() const {return directionOut_;}; /** Set directionIn or Out */ inline void setDirectionIn(int direction) { directionIn_=direction;}; inline void setDirectionOut(int direction) { directionOut_=direction;}; /// Returns 1 if sequence indicates column inline int isColumn(int sequence) const { return sequence<numberColumns_ ? 1 : 0;}; /// Returns sequence number within section inline int sequenceWithin(int sequence) const { return sequence<numberColumns_ ? sequence : sequence-numberColumns_;}; /// Return row or column values inline double solution(int sequence) { return solution_[sequence];}; /// Return address of row or column values inline double & solutionAddress(int sequence) { return solution_[sequence];}; inline double reducedCost(int sequence) { return dj_[sequence];}; inline double & reducedCostAddress(int sequence) { return dj_[sequence];}; inline double lower(int sequence) { return lower_[sequence];}; /// Return address of row or column lower bound inline double & lowerAddress(int sequence) { return lower_[sequence];}; inline double upper(int sequence) { return upper_[sequence];}; /// Return address of row or column upper bound inline double & upperAddress(int sequence) { return upper_[sequence];}; inline double cost(int sequence) { return cost_[sequence];}; /// Return address of row or column cost inline double & costAddress(int sequence) { return cost_[sequence];}; /// Return original lower bound inline double originalLower(int iSequence) const { if (iSequence<numberColumns_) return columnLower_[iSequence]; else return rowLower_[iSequence-numberColumns_];}; /// Return original lower bound inline double originalUpper(int iSequence) const { if (iSequence<numberColumns_) return columnUpper_[iSequence]; else return rowUpper_[iSequence-numberColumns_];}; /// Theta (pivot change) inline double theta() const { return theta_;}; /// Scaling const double * rowScale() const {return rowScale_;}; const double * columnScale() const {return columnScale_;}; void setRowScale(double * scale) { rowScale_ = scale;}; void setColumnScale(double * scale) { columnScale_ = scale;}; /// Return pointer to details of costs inline ClpNonLinearCost * nonLinearCost() const { return nonLinearCost_;}; //@} /**@name status methods */ //@{ inline void setFakeBound(int sequence, FakeBound fakeBound) { unsigned char & st_byte = status_[sequence]; st_byte &= ~24; st_byte |= fakeBound<<3; }; inline FakeBound getFakeBound(int sequence) const {return static_cast<FakeBound> ((status_[sequence]>>3)&3);}; inline void setRowStatus(int sequence, Status status) { unsigned char & st_byte = status_[sequence+numberColumns_]; st_byte &= ~7; st_byte |= status; }; inline Status getRowStatus(int sequence) const {return static_cast<Status> (status_[sequence+numberColumns_]&7);}; inline void setColumnStatus(int sequence, Status status) { unsigned char & st_byte = status_[sequence]; st_byte &= ~7; st_byte |= status; }; inline Status getColumnStatus(int sequence) const {return static_cast<Status> (status_[sequence]&7);}; inline void setPivoted( int sequence) { status_[sequence] |= 32;}; inline void clearPivoted( int sequence) { status_[sequence] &= ~32; }; inline bool pivoted(int sequence) const {return (((status_[sequence]>>5)&1)!=0);}; inline void setFlagged( int sequence) { status_[sequence] |= 64; }; inline void clearFlagged( int sequence) { status_[sequence] &= ~64; }; inline bool flagged(int sequence) const {return (((status_[sequence]>>6)&1)!=0);}; /** Set up status array (can be used by OsiClp). Also can be used to set up all slack basis */ void createStatus() ; inline void allSlackBasis() { createStatus();}; /// So we know when to be cautious inline int lastBadIteration() const {return lastBadIteration_;}; /// Progress flag - at present 0 bit says artificials out inline int progressFlag() const {return progressFlag_;}; /// Force re-factorization early inline void forceFactorization(int value) { forceFactorization_ = value;}; //@} ////////////////// data ////////////////// protected: /**@name data. Many arrays have a row part and a column part. There is a single array with both - columns then rows and then normally two arrays pointing to rows and columns. The single array is the owner of memory */ //@{ /// Worst column primal infeasibility double columnPrimalInfeasibility_; /// Worst row primal infeasibility double rowPrimalInfeasibility_; /// Sequence of worst (-1 if feasible) int columnPrimalSequence_; /// Sequence of worst (-1 if feasible) int rowPrimalSequence_; /// Worst column dual infeasibility double columnDualInfeasibility_; /// Worst row dual infeasibility double rowDualInfeasibility_; /// Sequence of worst (-1 if feasible) int columnDualSequence_; /// Sequence of worst (-1 if feasible) int rowDualSequence_; /// Primal tolerance needed to make dual feasible (<largeTolerance) double primalToleranceToGetOptimal_; /// Remaining largest dual infeasibility double remainingDualInfeasibility_; /// Large bound value (for complementarity etc) double largeValue_; /// Largest error on Ax-b double largestPrimalError_; /// Largest error on basic duals double largestDualError_; /// Largest difference between input primal solution and computed double largestSolutionError_; /// Dual bound double dualBound_; /// Alpha (pivot element) double alpha_; /// Theta (pivot change) double theta_; /// Lower Bound on In variable double lowerIn_; /// Value of In variable double valueIn_; /// Upper Bound on In variable double upperIn_; /// Reduced cost of In variable double dualIn_; /// Lower Bound on Out variable double lowerOut_; /// Value of Out variable double valueOut_; /// Upper Bound on Out variable double upperOut_; /// Infeasibility (dual) or ? (primal) of Out variable double dualOut_; /// Current dual tolerance for algorithm double dualTolerance_; /// Current primal tolerance for algorithm double primalTolerance_; /// Sum of dual infeasibilities double sumDualInfeasibilities_; /// Sum of primal infeasibilities double sumPrimalInfeasibilities_; /// Weight assigned to being infeasible in primal double infeasibilityCost_; /// Sum of Dual infeasibilities using tolerance based on error in duals double sumOfRelaxedDualInfeasibilities_; /// Sum of Primal infeasibilities using tolerance based on error in primals double sumOfRelaxedPrimalInfeasibilities_; /// Working copy of lower bounds (Owner of arrays below) double * lower_; /// Row lower bounds - working copy double * rowLowerWork_; /// Column lower bounds - working copy double * columnLowerWork_; /// Working copy of upper bounds (Owner of arrays below) double * upper_; /// Row upper bounds - working copy double * rowUpperWork_; /// Column upper bounds - working copy double * columnUpperWork_; /// Working copy of objective (Owner of arrays below) double * cost_; /// Row objective - working copy double * rowObjectiveWork_; /// Column objective - working copy double * objectiveWork_; /// Useful row length arrays CoinIndexedVector * rowArray_[6]; /// Useful column length arrays CoinIndexedVector * columnArray_[6]; /// Sequence of In variable int sequenceIn_; /// Direction of In, 1 going up, -1 going down, 0 not a clude int directionIn_; /// Sequence of Out variable int sequenceOut_; /// Direction of Out, 1 to upper bound, -1 to lower bound, 0 - superbasic int directionOut_; /// Pivot Row int pivotRow_; /// Last good iteration (immediately after a re-factorization) int lastGoodIteration_; /// Working copy of reduced costs (Owner of arrays below) double * dj_; /// Reduced costs of slacks not same as duals (or - duals) double * rowReducedCost_; /// Possible scaled reduced costs double * reducedCostWork_; /// Working copy of primal solution (Owner of arrays below) double * solution_; /// Row activities - working copy double * rowActivityWork_; /// Column activities - working copy double * columnActivityWork_; /// Number of dual infeasibilities int numberDualInfeasibilities_; /// Number of dual infeasibilities (without free) int numberDualInfeasibilitiesWithoutFree_; /// Number of primal infeasibilities int numberPrimalInfeasibilities_; /// How many iterative refinements to do int numberRefinements_; /// dual row pivot choice ClpDualRowPivot * dualRowPivot_; /// primal column pivot choice ClpPrimalColumnPivot * primalColumnPivot_; /// Basic variables pivoting on which rows int * pivotVariable_; /// factorization ClpFactorization * factorization_; /// Row scale factors for matrix // ****** get working simply then make coding more efficient // on full matrix operations double * rowScale_; /// Saved version of solution double * savedSolution_; /// Column scale factors double * columnScale_; /// Scale flag, 0 none, 1 normal, 2 dynamic int scalingFlag_; /// Number of times code has tentatively thought optimal int numberTimesOptimal_; /// If change has been made (first attempt at stopping looping) int changeMade_; /// Algorithm >0 == Primal, <0 == Dual int algorithm_; /** Now for some reliability aids This forces re-factorization early */ int forceFactorization_; /** Perturbation: -50 to +50 - perturb by this power of ten (-6 sounds good) 100 - auto perturb if takes too long (1.0e-6 largest nonzero) 101 - we are perturbed 102 - don't try perturbing again default is 100 */ int perturbation_; /// Saved status regions unsigned char * saveStatus_; /** Very wasteful way of dealing with infeasibilities in primal. However it will allow non-linearities and use of dual analysis. If it doesn't work it can easily be replaced. */ ClpNonLinearCost * nonLinearCost_; /** For advanced options 1 - Don't keep changing infeasibility weight 2 - keep nonLinearCost round solves */ unsigned int specialOptions_; /// So we know when to be cautious int lastBadIteration_; /// Can be used for count of fake bounds (dual) or fake costs (primal) int numberFake_; /// Progress flag - at present 0 bit says artificials out, 1 free in int progressFlag_; /// First free/super-basic variable (-1 if none) int firstFree_; //@} }; //############################################################################# /** A function that tests the methods in the ClpSimplex class. The only reason for it not to be a member method is that this way it doesn't have to be compiled into the library. And that's a gain, because the library should be compiled with optimization on, but this method should be compiled with debugging. It also does some testing of ClpFactorization class */ void ClpSimplexUnitTest(const std::string & mpsDir, const std::string & netlibDir); /// For saving extra information to see if looping. not worth a Class class ClpSimplexProgress { public: /**@name Constructors and destructor and copy */ //@{ /// Default constructor ClpSimplexProgress ( ); /// Constructor from model ClpSimplexProgress ( ClpSimplex * model ); /// Copy constructor. ClpSimplexProgress(const ClpSimplexProgress &); /// Assignment operator. This copies the data ClpSimplexProgress & operator=(const ClpSimplexProgress & rhs); /// Destructor ~ClpSimplexProgress ( ); //@} /**@name Check progress */ //@{ /** Returns -1 if okay, -n+1 (n number of times bad) if bad but action taken, >=0 if give up and use as problem status */ int looping ( ); //@} /**@name Data */ #define CLP_PROGRESS 5 //@{ /// Objective values double objective_[CLP_PROGRESS]; /// Sum of infeasibilities for algorithm double infeasibility_[CLP_PROGRESS]; /// Pointer back to model so we can get information ClpSimplex * model_; /// Number of infeasibilities int numberInfeasibilities_[CLP_PROGRESS]; /// Number of times checked (so won't stop too early) int numberTimes_; /// Number of times it looked like loop int numberBadTimes_; //@} }; #endif
36.855263
79
0.695198
[ "vector", "model" ]
6459861738d1b276e9ddf59b24e17e304cf2c5fe
1,049
cpp
C++
game/prefabs/HoldableBarPrefab.cpp
Khuongnb1997/game-aladdin
74b13ffcd623de0d6f799b0669c7e8917eef3b14
[ "MIT" ]
2
2017-11-08T16:27:25.000Z
2018-08-10T09:08:35.000Z
game/prefabs/HoldableBarPrefab.cpp
Khuongnb1997/game-aladdin
74b13ffcd623de0d6f799b0669c7e8917eef3b14
[ "MIT" ]
null
null
null
game/prefabs/HoldableBarPrefab.cpp
Khuongnb1997/game-aladdin
74b13ffcd623de0d6f799b0669c7e8917eef3b14
[ "MIT" ]
4
2017-11-08T16:25:30.000Z
2021-05-23T06:14:59.000Z
#include "HoldableBarPrefab.h" #include "../Define.h" USING_NAMESPACE_ALA; ALA_CLASS_SOURCE_1(HoldableBarPrefab, ala::PrefabV2) void HoldableBarPrefab::doInstantiate( ala::GameObject* object, std::istringstream& argsStream ) const { // args const auto height = 3.0f; const auto width = nextFloat( argsStream ); // components const auto transform = object->getTransform(); const auto body = new Rigidbody( object, PhysicsMaterial(), ALA_BODY_TYPE_STATIC ); const auto offset = -width / 2; const auto collider = new Collider( object, true, Vec2( offset, 0 ), Size( width, height ), 1, 0 ); collider->setTag( BAR_TAG ); collider->ignoreTag( BAR_TAG ); collider->ignoreTag( ENEMY_TAG ); collider->ignoreTag( APPLE_TAG ); collider->ignoreTag( SWORD_TAG ); // collider renderers // new ColliderRenderer( collider ); // flags collider->setFlags( COLLIDE_ALADDIN_FLAG | STATIC_FLAG ); collider->ignoreIfHasAnyFlags( STATIC_FLAG ); // configurations object->setLayer( "Debug" ); object->setTag( BAR_TAG ); }
28.351351
104
0.71592
[ "object", "transform" ]
645f861f8781d541ab89643299ba49ed50f9500c
120,502
cpp
C++
osx/devkit/plug-ins/gpuCache/CacheReaderAlembic.cpp
leegoonz/Maya-devkit
b81fe799b58e854e4ef16435426d60446e975871
[ "ADSL" ]
10
2018-03-30T16:09:02.000Z
2021-12-07T07:29:19.000Z
osx/devkit/plug-ins/gpuCache/CacheReaderAlembic.cpp
leegoonz/Maya-devkit
b81fe799b58e854e4ef16435426d60446e975871
[ "ADSL" ]
null
null
null
osx/devkit/plug-ins/gpuCache/CacheReaderAlembic.cpp
leegoonz/Maya-devkit
b81fe799b58e854e4ef16435426d60446e975871
[ "ADSL" ]
9
2018-06-02T09:18:49.000Z
2021-12-20T09:24:35.000Z
//- //**************************************************************************/ // Copyright 2015 Autodesk, Inc. All rights reserved. // // Use of this software is subject to the terms of the Autodesk // license agreement provided at the time of installation or download, // or which otherwise accompanies this software in either electronic // or hard copy form. //**************************************************************************/ //+ #include "CacheReaderAlembic.h" #include "CacheAlembicUtil.h" #include "gpuCacheUtil.h" #include "gpuCacheStrings.h" #include <Alembic/AbcCoreFactory/IFactory.h> #include <Alembic/AbcGeom/Visibility.h> #include <Alembic/AbcGeom/ArchiveBounds.h> #include <maya/MStringArray.h> #include <maya/MAnimControl.h> #include <maya/MString.h> #include <maya/MGlobal.h> #include <maya/MFnMesh.h> #include <maya/MFnNurbsCurve.h> #include <maya/MFnNurbsCurveData.h> #include <maya/MTrimBoundaryArray.h> #include <maya/MFloatArray.h> #include <maya/MFloatVector.h> #include <maya/MPointArray.h> #include <maya/MFloatPointArray.h> #include <maya/MFloatVectorArray.h> #include <maya/MUintArray.h> #include <boost/ref.hpp> #include <fstream> #include <cassert> using namespace CacheAlembicUtil; namespace GPUCache { namespace CacheReaderAlembicPrivate { //============================================================================== // CLASS AlembicArray //============================================================================== template <class ArrayProperty> boost::shared_ptr<ReadableArray<typename AlembicArray<ArrayProperty>::T> > AlembicArray<ArrayProperty>::create( const ArraySamplePtr& arraySamplePtr, const Digest& digest ) { const size_t size = (arraySamplePtr->size() * ArrayProperty::traits_type::dataType().getExtent()); #ifndef NDEBUG // Compute the Murmur3 cryptographic hash-key and make sure // that the digest found in the Alembic file is correct. Digest checkDigest; Alembic::Util::MurmurHash3_x64_128( arraySamplePtr->get(), size * sizeof(T), sizeof(T), checkDigest.words); assert(digest == checkDigest); #endif // We first look if a similar array already exists in the // cache. If so, we return the cached array to promote sharing as // much as possible. boost::shared_ptr<ReadableArray<T> > ret; { tbb::mutex::scoped_lock lock(ArrayRegistry<T>::mutex()); // Only accept arrays which contain data we own. This array may happen on a // worker thread, so non-readable arrays can't be converted to readable. ret = ArrayRegistry<T>::lookupReadable(digest, size); if (!ret) { ret = boost::make_shared<AlembicArray<ArrayProperty> >( arraySamplePtr, digest); ArrayRegistry<T>::insert(ret); } } return ret; } template <class ArrayProperty> AlembicArray<ArrayProperty>::~AlembicArray() {} template <class ArrayProperty> const typename AlembicArray<ArrayProperty>::T* AlembicArray<ArrayProperty>::get() const { return reinterpret_cast<const T*>(fArraySamplePtr->get()); } //============================================================================== // CLASS ArrayPropertyCacheWithConverter //============================================================================== template <typename PROPERTY> typename ArrayPropertyCacheWithConverter<PROPERTY>::ConvertionMap ArrayPropertyCacheWithConverter<PROPERTY>::fsConvertionMap; template class ArrayPropertyCacheWithConverter< Alembic::Abc::IInt32ArrayProperty>; //============================================================================== // CLASS ScopedUnlockAlembic //============================================================================== class ScopedUnlockAlembic : boost::noncopyable { public: ScopedUnlockAlembic() { gsAlembicMutex.unlock(); } ~ScopedUnlockAlembic() { gsAlembicMutex.lock(); } }; // This function is the checkpoint of the worker thread's interrupt and pause state. void CheckInterruptAndPause(const char* state) { GlobalReaderCache& readerCache = GlobalReaderCache::theCache(); if (readerCache.isInterrupted()) { // Interrupted. Throw an exception to terminate this reader. throw CacheReaderInterruptException(state); } else if (readerCache.isPaused()) { // Paused. Unlock the Alembic lock and return the control. ScopedUnlockAlembic unlock; readerCache.pauseUntilNotified(); } } //============================================================================== // CLASS DataProvider //============================================================================== template<class INFO> DataProvider::DataProvider( Alembic::AbcGeom::IGeomBaseSchema<INFO>& abcGeom, Alembic::Abc::TimeSamplingPtr timeSampling, size_t numSamples, bool needUVs) : fAnimTimeRange(TimeInterval::kInvalid), fBBoxAndVisValidityInterval(TimeInterval::kInvalid), fValidityInterval(TimeInterval::kInvalid), fNeedUVs(needUVs) { Alembic::Abc::IObject shapeObject = abcGeom.getObject(); // shape visibility Alembic::AbcGeom::IVisibilityProperty visibility = Alembic::AbcGeom::GetVisibilityProperty(shapeObject); if (visibility) { fVisibilityCache.init(visibility); } // bounding box fBoundingBoxCache.init(abcGeom.getSelfBoundsProperty()); // Find parent IObjects std::vector<Alembic::Abc::IObject> parents; Alembic::Abc::IObject current = shapeObject.getParent(); while (current.valid()) { parents.push_back(current); current = current.getParent(); } // parent visibility fParentVisibilityCache.resize(parents.size()); for (size_t i = 0; i < fParentVisibilityCache.size(); i++) { Alembic::AbcGeom::IVisibilityProperty visibilityProp = Alembic::AbcGeom::GetVisibilityProperty(parents[i]); if (visibilityProp) { fParentVisibilityCache[i].init(visibilityProp); } } // exact animation time range fAnimTimeRange = TimeInterval( timeSampling->getSampleTime(0), timeSampling->getSampleTime(numSamples > 0 ? numSamples-1 : 0) ); } DataProvider::~DataProvider() { fValidityInterval = TimeInterval::kInvalid; // free the property readers fVisibilityCache.reset(); fBoundingBoxCache.reset(); fParentVisibilityCache.clear(); } bool DataProvider::valid() const { return fBoundingBoxCache.valid(); } boost::shared_ptr<const ShapeSample> DataProvider::getBBoxPlaceHolderSample(double seconds) { boost::shared_ptr<ShapeSample> sample = ShapeSample::createBoundingBoxPlaceHolderSample( seconds, getBoundingBox(), isVisible() ); return sample; } void DataProvider::fillBBoxAndVisSample(chrono_t time) { fBBoxAndVisValidityInterval = updateBBoxAndVisCache(time); assert(fBBoxAndVisValidityInterval.valid()); } void DataProvider::fillTopoAndAttrSample(chrono_t time) { fValidityInterval = updateCache(time); assert(fValidityInterval.valid()); } TimeInterval DataProvider::updateBBoxAndVisCache(chrono_t time) { // Notes: // // When possible, we try to reuse the samples from the previously // read sample. // update caches if (fVisibilityCache.valid()) { fVisibilityCache.setTime(time); } fBoundingBoxCache.setTime(time); BOOST_FOREACH (ScalarPropertyCache<Alembic::Abc::ICharProperty>& parentVisPropCache, fParentVisibilityCache) { if (parentVisPropCache.valid()) { parentVisPropCache.setTime(time); } } // return the new cache valid interval TimeInterval validityInterval(TimeInterval::kInfinite); if (fVisibilityCache.valid()) { validityInterval &= fVisibilityCache.getValidityInterval(); } validityInterval &= fBoundingBoxCache.getValidityInterval(); BOOST_FOREACH (ScalarPropertyCache<Alembic::Abc::ICharProperty>& parentVisPropCache, fParentVisibilityCache) { if (parentVisPropCache.valid()) { validityInterval &= parentVisPropCache.getValidityInterval(); } } return validityInterval; } TimeInterval DataProvider::updateCache(chrono_t time) { return updateBBoxAndVisCache(time); } bool DataProvider::isVisible() const { // shape invisible if (fVisibilityCache.valid() && fVisibilityCache.getValue() == char(Alembic::AbcGeom::kVisibilityHidden)) { return false; } // parent invisible BOOST_FOREACH (const ScalarPropertyCache<Alembic::Abc::ICharProperty>& parentVisPropCache, fParentVisibilityCache) { if (parentVisPropCache.valid() && parentVisPropCache.getValue() == char(Alembic::AbcGeom::kVisibilityHidden)) { return false; } } // visible return true; } //============================================================================== // CLASS PolyDataProvider //============================================================================== template<class SCHEMA> PolyDataProvider::PolyDataProvider( SCHEMA& abcMesh, const bool needUVs) : DataProvider(abcMesh, abcMesh.getTimeSampling(), abcMesh.getNumSamples(), needUVs) { // polygon counts fFaceCountsCache.init(abcMesh.getFaceCountsProperty()); // positions fPositionsCache.init(abcMesh.getPositionsProperty()); } PolyDataProvider::~PolyDataProvider() { // free the property readers fFaceCountsCache.reset(); fPositionsCache.reset(); } bool PolyDataProvider::valid() const { return DataProvider::valid() && fFaceCountsCache.valid() && fPositionsCache.valid(); } TimeInterval PolyDataProvider::updateCache(chrono_t time) { TimeInterval validityInterval(DataProvider::updateCache(time)); // update caches fFaceCountsCache.setTime(time); fPositionsCache.setTime(time); // return the new cache valid interval validityInterval &= fFaceCountsCache.getValidityInterval(); validityInterval &= fPositionsCache.getValidityInterval(); return validityInterval; } //============================================================================== // CLASS RawDataProvider //============================================================================== RawDataProvider::RawDataProvider( Alembic::AbcGeom::IPolyMeshSchema& abcMesh, const bool needUVs) : PolyDataProvider(abcMesh, needUVs), fFaceIndicesCache(correctPolygonWinding) { // triangle indices fFaceIndicesCache.init(abcMesh.getFaceIndicesProperty()); // custom reader for wireframe indices if (abcMesh.getPropertyHeader(kCustomPropertyWireIndices) != NULL) { fWireIndicesCache.init( Alembic::Abc::IInt32ArrayProperty(abcMesh.getPtr(), kCustomPropertyWireIndices)); } else if (abcMesh.getPropertyHeader(kCustomPropertyWireIndicesOld) != NULL) { fWireIndicesCache.init( Alembic::Abc::IInt32ArrayProperty(abcMesh.getPtr(), kCustomPropertyWireIndicesOld)); } // custom reader for group info if (abcMesh.getPropertyHeader(kCustomPropertyShadingGroupSizes) != NULL) { fGroupSizesCache.init( Alembic::Abc::IInt32ArrayProperty(abcMesh.getPtr(), kCustomPropertyShadingGroupSizes)); } // custom reader for diffuse color if (abcMesh.getPropertyHeader(kCustomPropertyDiffuseColor) != NULL) { fDiffuseColorCache.init( Alembic::Abc::IC4fProperty(abcMesh.getPtr(), kCustomPropertyDiffuseColor)); } // normals, we do not support indexed/facevarying normals Alembic::AbcGeom::IN3fGeomParam normals = abcMesh.getNormalsParam(); if (normals.valid()) { assert(!normals.isIndexed()); assert(normals.getScope() == Alembic::AbcGeom::kVertexScope); fNormalsCache.init(normals.getValueProperty()); } if (fNeedUVs) { // UVs, we do not support indexed/facevarying UVs Alembic::AbcGeom::IV2fGeomParam UVs = abcMesh.getUVsParam(); if (UVs.valid()) { assert(!UVs.isIndexed()); assert(UVs.getScope() == Alembic::AbcGeom::kVertexScope); fUVsCache.init(UVs.getValueProperty()); } } } RawDataProvider::~RawDataProvider() { // free the property readers fFaceIndicesCache.reset(); fWireIndicesCache.reset(); fGroupSizesCache.reset(); fDiffuseColorCache.reset(); fNormalsCache.reset(); fUVsCache.reset(); } bool RawDataProvider::valid() const { return PolyDataProvider::valid() && fFaceIndicesCache.valid() && fWireIndicesCache.valid() && fDiffuseColorCache.valid() && fNormalsCache.valid(); } boost::shared_ptr<const ShapeSample> RawDataProvider::getSample(double seconds) { std::vector<boost::shared_ptr<IndexBuffer> > triangleVertIndices; const boost::shared_ptr<ReadableArray<IndexBuffer::index_t> > indexBuffer = fFaceIndicesCache.getValue(); if (fGroupSizesCache.valid()) { const boost::shared_ptr<ReadableArray<IndexBuffer::index_t> > groupSizes = fGroupSizesCache.getValue(); const IndexBuffer::index_t* groupSizesPtr = groupSizes->get(); for(size_t i=0, offset=0; i<groupSizes->size(); offset+=3*groupSizesPtr[i], ++i) { triangleVertIndices.push_back( IndexBuffer::create( indexBuffer, offset, offset+3*groupSizesPtr[i])); } } else { triangleVertIndices.push_back(IndexBuffer::create(indexBuffer)); } Alembic::Abc::C4f diffuseColor = fDiffuseColorCache.getValue(); boost::shared_ptr<ShapeSample> sample = ShapeSample::create( seconds, // time (in seconds) fWireIndicesCache.getValue()->size() / 2, // number of wireframes fPositionsCache.getValue()->size() / 3, // number of vertices IndexBuffer::create(fWireIndicesCache.getValue()), // wireframe indices triangleVertIndices, // triangle indices VertexBuffer::createPositions(fPositionsCache.getValue()), // position getBoundingBox(), // bounding box MColor(diffuseColor.r, diffuseColor.g, diffuseColor.b, diffuseColor.a), isVisible() ); if (fNormalsCache.valid()) { sample->setNormals( VertexBuffer::createNormals(fNormalsCache.getValue())); } if (fUVsCache.valid()) { sample->setUVs( VertexBuffer::createUVs(fUVsCache.getValue())); } return sample; } boost::shared_ptr<ReadableArray<IndexBuffer::index_t> > RawDataProvider::correctPolygonWinding(const Alembic::Abc::Int32ArraySamplePtr& indices) { size_t count = (*indices).size(); boost::shared_array<IndexBuffer::index_t> faceIndicesCCW( new IndexBuffer::index_t[count]); for (size_t i = 0; i < count; i += 3) { faceIndicesCCW[i + 2] = (*indices)[i + 0]; faceIndicesCCW[i + 1] = (*indices)[i + 1]; faceIndicesCCW[i + 0] = (*indices)[i + 2]; } return SharedArray<IndexBuffer::index_t>::create( faceIndicesCCW, count); } TimeInterval RawDataProvider::updateCache(chrono_t time) { TimeInterval validityInterval(PolyDataProvider::updateCache(time)); // update caches fFaceIndicesCache.setTime(time); fWireIndicesCache.setTime(time); if (fGroupSizesCache.valid()) { fGroupSizesCache.setTime(time); } fNormalsCache.setTime(time); if (fUVsCache.valid()) { fUVsCache.setTime(time); } fDiffuseColorCache.setTime(time); // return the new cache valid interval validityInterval &= fFaceIndicesCache.getValidityInterval(); validityInterval &= fWireIndicesCache.getValidityInterval(); if (fGroupSizesCache.valid()) { validityInterval &= fGroupSizesCache.getValidityInterval(); } validityInterval &= fNormalsCache.getValidityInterval(); if (fUVsCache.valid()) { validityInterval &= fUVsCache.getValidityInterval(); } validityInterval &= fDiffuseColorCache.getValidityInterval(); // check sample consistency size_t numVerts = fPositionsCache.getValue()->size() / 3; size_t numTriangles = fFaceIndicesCache.getValue()->size() / 3; if (fFaceCountsCache.getValue()->size() != numTriangles) { assert(fFaceCountsCache.getValue()->size() == numTriangles); return TimeInterval::kInvalid; } if (fNormalsCache.getValue()->size() / 3 != numVerts) { assert(fNormalsCache.getValue()->size() / 3 == numVerts); return TimeInterval::kInvalid; } if (fUVsCache.valid()) { if (fUVsCache.getValue()->size() / 2 != numVerts) { assert(fUVsCache.getValue()->size() / 2 == numVerts); return TimeInterval::kInvalid; } } return validityInterval; } //============================================================================== // CLASS Triangulator //============================================================================== Triangulator::Triangulator( Alembic::AbcGeom::IPolyMeshSchema& abcMesh, const bool needUVs) : PolyDataProvider(abcMesh, needUVs), fNormalsScope(Alembic::AbcGeom::kUnknownScope), fUVsScope(Alembic::AbcGeom::kUnknownScope) { // polygon indices fFaceIndicesCache.init(abcMesh.getFaceIndicesProperty()); // optional normals Alembic::AbcGeom::IN3fGeomParam normals = abcMesh.getNormalsParam(); if (normals.valid()) { fNormalsScope = normals.getScope(); if (fNormalsScope == Alembic::AbcGeom::kVaryingScope || fNormalsScope == Alembic::AbcGeom::kVertexScope || fNormalsScope == Alembic::AbcGeom::kFacevaryingScope) { fNormalsCache.init(normals.getValueProperty()); if (normals.isIndexed()) { fNormalIndicesCache.init(normals.getIndexProperty()); } } } // optional UVs if (fNeedUVs) { Alembic::AbcGeom::IV2fGeomParam UVs = abcMesh.getUVsParam(); if (UVs.valid()) { fUVsScope = UVs.getScope(); if (fUVsScope == Alembic::AbcGeom::kVaryingScope || fUVsScope == Alembic::AbcGeom::kVertexScope || fUVsScope == Alembic::AbcGeom::kFacevaryingScope) { fUVsCache.init(UVs.getValueProperty()); if (UVs.isIndexed()) { fUVIndicesCache.init(UVs.getIndexProperty()); } } } } } Triangulator::~Triangulator() { // free the property readers fFaceIndicesCache.reset(); fNormalsScope = Alembic::AbcGeom::kUnknownScope; fNormalsCache.reset(); fNormalIndicesCache.reset(); fUVsScope = Alembic::AbcGeom::kUnknownScope; fUVsCache.reset(); fUVIndicesCache.reset(); } bool Triangulator::valid() const { return PolyDataProvider::valid() && fFaceIndicesCache.valid(); } boost::shared_ptr<const ShapeSample> Triangulator::getSample(double seconds) { // empty mesh if (!fWireIndices || !fTriangleIndices) { boost::shared_ptr<ShapeSample> sample = ShapeSample::createEmptySample(seconds); return sample; } // triangle indices // Currently, we only have 1 group std::vector<boost::shared_ptr<IndexBuffer> > triangleVertIndices; triangleVertIndices.push_back(IndexBuffer::create(fTriangleIndices)); boost::shared_ptr<ShapeSample> sample = ShapeSample::create( seconds, // time (in seconds) fWireIndices->size() / 2, // number of wireframes fMappedPositions->size() / 3, // number of vertices IndexBuffer::create(fWireIndices), // wireframe indices triangleVertIndices, // triangle indices (1 group) VertexBuffer::createPositions(fMappedPositions), // position getBoundingBox(), // bounding box Config::kDefaultGrayColor, // diffuse color isVisible() ); if (fMappedNormals) { sample->setNormals( VertexBuffer::createNormals(fMappedNormals)); } if (fMappedUVs) { sample->setUVs( VertexBuffer::createUVs(fMappedUVs)); } return sample; } TimeInterval Triangulator::updateCache(chrono_t time) { // update faceCounts/position cache here so that we can detect topology/position change. // next setTime() in DataProvider::updateCache() simply returns early bool topologyChanged = fFaceCountsCache.setTime(time); bool positionChanged = fPositionsCache.setTime(time); TimeInterval validityInterval(PolyDataProvider::updateCache(time)); // update caches topologyChanged = fFaceIndicesCache.setTime(time) || topologyChanged; if (fNormalsCache.valid()) { fNormalsCache.setTime(time); if (fNormalIndicesCache.valid()) { fNormalIndicesCache.setTime(time); } } if (fUVsCache.valid()) { fUVsCache.setTime(time); if (fUVIndicesCache.valid()) { fUVIndicesCache.setTime(time); } } // return the new cache valid interval validityInterval &= fFaceIndicesCache.getValidityInterval(); if (fNormalsCache.valid()) { validityInterval &= fNormalsCache.getValidityInterval(); if (fNormalIndicesCache.valid()) { validityInterval &= fNormalIndicesCache.getValidityInterval(); } } if (fUVsCache.valid()) { validityInterval &= fUVsCache.getValidityInterval(); if (fUVIndicesCache.valid()) { validityInterval &= fUVIndicesCache.getValidityInterval(); } } // do a minimal check for the consistency check(); // convert the mesh to display-friend format if (positionChanged || topologyChanged || !fComputedNormals) { // recompute normals on position/topology change computeNormals(); } if (topologyChanged || !fVertAttribsIndices) { // convert multi-indexed streams on topology change convertMultiIndexedStreams(); } remapVertAttribs(); if (topologyChanged || !fWireIndices) { // recompute wireframe indices on topology change computeWireIndices(); } if (topologyChanged || !fTriangleIndices) { // recompute triangulation on topology change triangulate(); } return validityInterval; } template<size_t SIZE> boost::shared_ptr<ReadableArray<float> > Triangulator::convertMultiIndexedStream( boost::shared_ptr<ReadableArray<float> > attribArray, boost::shared_ptr<ReadableArray<IndexBuffer::index_t> > indexArray) { // map the indexed array to direct array size_t numVerts = indexArray->size(); const float* srcAttribs = attribArray->get(); const IndexBuffer::index_t* srcIndices = indexArray->get(); boost::shared_array<float> mappedAttribs(new float[numVerts * SIZE]); for (size_t i = 0; i < numVerts; i++) { for (size_t j = 0; j < SIZE; j++) { mappedAttribs[i * SIZE + j] = srcAttribs[srcIndices[i] * SIZE + j]; } } return SharedArray<float>::create(mappedAttribs, numVerts * SIZE); } void Triangulator::check() { size_t numFaceIndices = fFaceIndicesCache.getValue()->size(); size_t numVerts = fPositionsCache.getValue()->size() / 3; // Normals size_t numExpectedNormals = 0; if (fNormalsScope == Alembic::AbcGeom::kVaryingScope || fNormalsScope == Alembic::AbcGeom::kVertexScope) { numExpectedNormals = numVerts; } else if (fNormalsScope == Alembic::AbcGeom::kFacevaryingScope) { numExpectedNormals = numFaceIndices; } size_t numActualNormals = 0; if (fNormalsCache.valid()) { if (fNormalIndicesCache.valid()) { numActualNormals = fNormalIndicesCache.getValue()->size(); } else { numActualNormals = fNormalsCache.getValue()->size() / 3; } } // clear previous result fCheckedNormalsScope = Alembic::AbcGeom::kUnknownScope; fCheckedNormals.reset(); fCheckedNormalIndices.reset(); // forward if (numExpectedNormals == numActualNormals) { if (fNormalsCache.valid()) { fCheckedNormalsScope = fNormalsScope; fCheckedNormals = fNormalsCache.getValue(); if (fNormalIndicesCache.valid()) { fCheckedNormalIndices = fNormalIndicesCache.getValue(); } } } else { DisplayWarning(kBadNormalsMsg); } // UVs size_t numExpectedUVs = 0; if (fUVsScope == Alembic::AbcGeom::kVaryingScope || fUVsScope == Alembic::AbcGeom::kVertexScope) { numExpectedUVs = numVerts; } else if (fUVsScope == Alembic::AbcGeom::kFacevaryingScope) { numExpectedUVs = numFaceIndices; } size_t numActualUVs = 0; if (fUVsCache.valid()) { if (fUVIndicesCache.valid()) { numActualUVs = fUVIndicesCache.getValue()->size(); } else { numActualUVs = fUVsCache.getValue()->size() / 2; } } // clear previous result fCheckedUVsScope = Alembic::AbcGeom::kUnknownScope; fCheckedUVs.reset(); fCheckedUVIndices.reset(); // forward if (numExpectedUVs == numActualUVs) { if (fUVsCache.valid()) { fCheckedUVsScope = fUVsScope; fCheckedUVs = fUVsCache.getValue(); if (fUVIndicesCache.valid()) { fCheckedUVIndices = fUVIndicesCache.getValue(); } } } else { DisplayWarning(kBadUVsMsg); } } void Triangulator::computeNormals() { // compute normals if the normals are missing // later on, we can safely assume that the normals always exist // if (fCheckedNormals && (fCheckedNormalsScope == Alembic::AbcGeom::kVaryingScope || fCheckedNormalsScope == Alembic::AbcGeom::kVertexScope || fCheckedNormalsScope == Alembic::AbcGeom::kFacevaryingScope)) { // the normals exist and we recognize these normals fComputedNormals = fCheckedNormals; fComputedNormalsScope = fCheckedNormalsScope; fComputedNormalIndices.reset(); if (fCheckedNormalIndices) { fComputedNormalIndices = fCheckedNormalIndices; } return; } // input data size_t numFaceCounts = fFaceCountsCache.getValue()->size(); const unsigned int* faceCounts = fFaceCountsCache.getValue()->get(); const IndexBuffer::index_t* faceIndices = fFaceIndicesCache.getValue()->get(); size_t numPositions = fPositionsCache.getValue()->size(); const float* positions = fPositionsCache.getValue()->get(); size_t numVerts = numPositions / 3; if (numVerts == 0) { fComputedNormalsScope = Alembic::AbcGeom::kUnknownScope; fComputedNormals.reset(); fComputedNormalIndices.reset(); return; } // allocate buffers for the new normals boost::shared_array<float> computedFaceNormals(new float[numFaceCounts * 3]); boost::shared_array<float> computedNormals(new float[numVerts * 3]); // compute the face normals for (size_t i = 0, polyVertOffset = 0; i < numFaceCounts; polyVertOffset += faceCounts[i], i++) { size_t numPoints = faceCounts[i]; // Newell's Method MFloatVector faceNormal(0.0f, 0.0f, 0.0f); for (size_t j = 0; j < numPoints; j++) { size_t thisJ = numPoints - j - 1; size_t nextJ = numPoints - ((j + 1) % numPoints) - 1; const float* thisPoint = &positions[faceIndices[polyVertOffset + thisJ] * 3]; const float* nextPoint = &positions[faceIndices[polyVertOffset + nextJ] * 3]; faceNormal.x += (thisPoint[1] - nextPoint[1]) * (thisPoint[2] + nextPoint[2]); faceNormal.y += (thisPoint[2] - nextPoint[2]) * (thisPoint[0] + nextPoint[0]); faceNormal.z += (thisPoint[0] - nextPoint[0]) * (thisPoint[1] + nextPoint[1]); } faceNormal.normalize(); computedFaceNormals[i * 3 + 0] = faceNormal.x; computedFaceNormals[i * 3 + 1] = faceNormal.y; computedFaceNormals[i * 3 + 2] = faceNormal.z; } // compute the normals memset(&computedNormals[0], 0, sizeof(float) * numVerts * 3); for (size_t i = 0, polyVertOffset = 0; i < numFaceCounts; polyVertOffset += faceCounts[i], i++) { size_t numPoints = faceCounts[i]; const float* faceNormal = &computedFaceNormals[i * 3]; // accumulate the face normal for (size_t j = 0; j < numPoints; j++) { float* normal = &computedNormals[faceIndices[polyVertOffset + j] * 3]; normal[0] += faceNormal[0]; normal[1] += faceNormal[1]; normal[2] += faceNormal[2]; } } // normalize normals, MFloatVector functions are inline functions for (size_t i = 0; i < numVerts; i++) { float* normal = &computedNormals[i * 3]; MFloatVector vector(normal[0], normal[1], normal[2]); vector.normalize(); normal[0] = vector.x; normal[1] = vector.y; normal[2] = vector.z; } fComputedNormalsScope = Alembic::AbcGeom::kVertexScope; fComputedNormals = SharedArray<float>::create(computedNormals, numVerts * 3); fComputedNormalIndices.reset(); } void Triangulator::convertMultiIndexedStreams() { // convert multi-indexed streams to single-indexed streams // assume the scope is kVarying/kVertex/kFacevarying // // input polygons data size_t numFaceIndices = fFaceIndicesCache.getValue()->size(); const IndexBuffer::index_t* faceIndices = fFaceIndicesCache.getValue()->get(); // input normals bool normalFaceVarying = false; const IndexBuffer::index_t* normalIndices = NULL; if (fComputedNormals) { normalFaceVarying = (fComputedNormalsScope == Alembic::AbcGeom::kFacevaryingScope); if (fComputedNormalIndices) { normalIndices = fComputedNormalIndices->get(); assert(fComputedNormalIndices->size() == numFaceIndices); } } // input UV indices bool uvFaceVarying = false; const IndexBuffer::index_t* uvIndices = NULL; if (fCheckedUVs) { uvFaceVarying = (fCheckedUVsScope == Alembic::AbcGeom::kFacevaryingScope); if (fCheckedUVIndices) { uvIndices = fCheckedUVIndices->get(); assert(fCheckedUVIndices->size() == numFaceIndices); } } // determine the number of multi-indexed streams MultiIndexedStreamsConverter<IndexBuffer::index_t> converter( numFaceIndices, faceIndices); if (normalFaceVarying) { converter.addMultiIndexedStream(normalIndices); } if (uvFaceVarying) { converter.addMultiIndexedStream(uvIndices); } // only one multi-indexed streams, no need to convert it if (converter.numStreams() == 1) { fVertAttribsIndices.reset(); fMappedFaceIndices = fFaceIndicesCache.getValue(); fNumVertices = fPositionsCache.getValue()->size() / 3; return; } // convert the multi-indexed streams converter.compute(); // the mapped face indices fMappedFaceIndices = SharedArray<IndexBuffer::index_t>::create( converter.mappedFaceIndices(), numFaceIndices); // indices to remap streams fVertAttribsIndices = converter.vertAttribsIndices(); fNumVertices = converter.numVertices(); } void Triangulator::remapVertAttribs() { // remap vertex attribute streams according to the result of convertMultiIndexedStreams() // assume the scope is kVarying/kVertex/kFacevarying // // no multi-index streams, just drop indices if (!fVertAttribsIndices) { // positions is the only stream, just use it fMappedPositions = fPositionsCache.getValue(); // get rid of normal indices if (fComputedNormals) { if (fComputedNormalIndices) { fMappedNormals = convertMultiIndexedStream<3>( fComputedNormals, fComputedNormalIndices); } else { fMappedNormals = fComputedNormals; } } // get rid of UV indices if (fCheckedUVs) { if (fCheckedUVIndices) { fMappedUVs = convertMultiIndexedStream<2>( fCheckedUVs, fCheckedUVIndices); } else { fMappedUVs = fCheckedUVs; } } return; } // input polygons data const float* positions = fPositionsCache.getValue()->get(); const IndexBuffer::index_t* faceIndices = fFaceIndicesCache.getValue()->get(); // input normals const float* normals = NULL; const IndexBuffer::index_t* normalIndices = NULL; if (fComputedNormals) { normals = fComputedNormals->get(); if (fComputedNormalIndices) { normalIndices = fComputedNormalIndices->get(); } } // input UV indices const float* UVs = NULL; const IndexBuffer::index_t* uvIndices = NULL; if (fCheckedUVs) { UVs = fCheckedUVs->get(); if (fCheckedUVIndices) { uvIndices = fCheckedUVIndices->get(); } } // set up multi-indexed streams remapper MultiIndexedStreamsRemapper<IndexBuffer::index_t> remapper( faceIndices, fNumVertices, fVertAttribsIndices.get()); remapper.addMultiIndexedStream(positions, NULL, false, 3); if (normals) { remapper.addMultiIndexedStream(normals, normalIndices, fComputedNormalsScope == Alembic::AbcGeom::kFacevaryingScope, 3); } if (UVs) { remapper.addMultiIndexedStream(UVs, uvIndices, fCheckedUVsScope == Alembic::AbcGeom::kFacevaryingScope, 2); } // remap streams remapper.compute(); fMappedPositions = SharedArray<float>::create( remapper.mappedVertAttribs(0), fNumVertices * 3); unsigned int streamIndex = 1; if (normals) { fMappedNormals = SharedArray<float>::create( remapper.mappedVertAttribs(streamIndex++), fNumVertices * 3); } if (UVs) { fMappedUVs = SharedArray<float>::create( remapper.mappedVertAttribs(streamIndex++), fNumVertices * 2); } } void Triangulator::computeWireIndices() { // compute the wireframe indices // // input data size_t numFaceCounts = fFaceCountsCache.getValue()->size(); const unsigned int* faceCounts = fFaceCountsCache.getValue()->get(); size_t numFaceIndices = fFaceIndicesCache.getValue()->size(); const IndexBuffer::index_t* faceIndices = fFaceIndicesCache.getValue()->get(); const IndexBuffer::index_t* mappedFaceIndices = fMappedFaceIndices->get(); // Compute wireframe indices WireIndicesGenerator<IndexBuffer::index_t> wireIndicesGenerator( numFaceCounts, faceCounts, numFaceIndices, faceIndices, mappedFaceIndices); wireIndicesGenerator.compute(); if (wireIndicesGenerator.numWires() == 0) { fWireIndices.reset(); return; } fWireIndices = SharedArray<IndexBuffer::index_t>::create( wireIndicesGenerator.wireIndices(), wireIndicesGenerator.numWires() * 2); } void Triangulator::triangulate() { // triangulate the polygons // assume that there are no holes // // input data size_t numFaceCounts = fFaceCountsCache.getValue()->size(); const unsigned int* faceCounts = fFaceCountsCache.getValue()->get(); const IndexBuffer::index_t* faceIndices = fMappedFaceIndices->get(); const float* positions = fMappedPositions->get(); const float* normals = fMappedNormals ? fMappedNormals->get() : NULL; if (numFaceCounts == 0) { fTriangleIndices.reset(); return; } // Triangulate polygons PolyTriangulator<IndexBuffer::index_t> polyTriangulator( numFaceCounts, faceCounts, faceIndices, true, positions, normals); polyTriangulator.compute(); fTriangleIndices = SharedArray<IndexBuffer::index_t>::create( polyTriangulator.triangleIndices(), polyTriangulator.numTriangles() * 3); } //============================================================================== // CLASS NurbsTessellator //============================================================================== NurbsTessellator::NurbsTessellator( Alembic::AbcGeom::INuPatchSchema& abcNurbs, const bool needUVs) : DataProvider(abcNurbs, abcNurbs.getTimeSampling(), abcNurbs.getNumSamples(), needUVs), fSurfaceValid(false) { // Control point positions fPositionsCache.init(abcNurbs.getPositionsProperty()); // Number of control points fNumUCache.init(Alembic::Abc::IInt32Property(abcNurbs.getPtr(), "nu")); fNumVCache.init(Alembic::Abc::IInt32Property(abcNurbs.getPtr(), "nv")); // Order (Degree + 1) fUOrderCache.init(Alembic::Abc::IInt32Property(abcNurbs.getPtr(), "uOrder")); fVOrderCache.init(Alembic::Abc::IInt32Property(abcNurbs.getPtr(), "vOrder")); // Knots fUKnotCache.init(abcNurbs.getUKnotsProperty()); fVKnotCache.init(abcNurbs.getVKnotsProperty()); // Control point weights Alembic::AbcGeom::IFloatArrayProperty positionWeights = abcNurbs.getPositionWeightsProperty(); if (positionWeights.valid()) { fPositionWeightsCache.init(positionWeights); } // Trim curves if (abcNurbs.hasTrimCurve()) { // Number of loops fTrimNumLoopsCache.init( Alembic::Abc::IInt32Property(abcNurbs.getPtr(), "trim_nloops")); // Number of curves fTrimNumCurvesCache.init( Alembic::Abc::IInt32ArrayProperty(abcNurbs.getPtr(), "trim_ncurves")); // Number of control points fTrimNumVerticesCache.init( Alembic::Abc::IInt32ArrayProperty(abcNurbs.getPtr(), "trim_n")); // Curve Orders fTrimOrderCache.init( Alembic::Abc::IInt32ArrayProperty(abcNurbs.getPtr(), "trim_order")); // Curve Knots fTrimKnotCache.init( Alembic::Abc::IFloatArrayProperty(abcNurbs.getPtr(), "trim_knot")); // Curve U fTrimUCache.init( Alembic::Abc::IFloatArrayProperty(abcNurbs.getPtr(), "trim_u")); // Curve V fTrimVCache.init( Alembic::Abc::IFloatArrayProperty(abcNurbs.getPtr(), "trim_v")); // Curve W fTrimWCache.init( Alembic::Abc::IFloatArrayProperty(abcNurbs.getPtr(), "trim_w")); } } NurbsTessellator::~NurbsTessellator() { // free the property readers fPositionsCache.reset(); fNumUCache.reset(); fNumVCache.reset(); fUOrderCache.reset(); fVOrderCache.reset(); fUKnotCache.reset(); fVKnotCache.reset(); fPositionWeightsCache.reset(); fTrimNumLoopsCache.reset(); fTrimNumCurvesCache.reset(); fTrimNumVerticesCache.reset(); fTrimOrderCache.reset(); fTrimKnotCache.reset(); fTrimUCache.reset(); fTrimVCache.reset(); fTrimWCache.reset(); } bool NurbsTessellator::valid() const { return DataProvider::valid() && fPositionsCache.valid() && fNumUCache.valid() && fNumVCache.valid() && fUOrderCache.valid() && fVOrderCache.valid() && fUKnotCache.valid() && fVKnotCache.valid(); } boost::shared_ptr<const ShapeSample> NurbsTessellator::getSample(double seconds) { // empty mesh if (!fWireIndices || !fTriangleIndices) { boost::shared_ptr<ShapeSample> sample = ShapeSample::createEmptySample(seconds); return sample; } // triangle indices // Currently, we only have 1 group std::vector<boost::shared_ptr<IndexBuffer> > triangleVertIndices; triangleVertIndices.push_back(IndexBuffer::create(fTriangleIndices)); boost::shared_ptr<ShapeSample> sample = ShapeSample::create( seconds, // time (in seconds) fWireIndices->size() / 2, // number of wireframes fPositions->size() / 3, // number of vertices IndexBuffer::create(fWireIndices), // wireframe indices triangleVertIndices, // triangle indices (1 group) VertexBuffer::createPositions(fPositions), // position getBoundingBox(), // bounding box Config::kDefaultGrayColor, // diffuse color isVisible() ); if (fNormals) { sample->setNormals( VertexBuffer::createNormals(fNormals)); } if (fUVs) { sample->setUVs( VertexBuffer::createUVs(fUVs)); } return sample; } TimeInterval NurbsTessellator::updateCache(chrono_t time) { TimeInterval validityInterval(DataProvider::updateCache(time)); // update caches bool positionsChanged = fPositionsCache.setTime(time); bool topologyChanged = fNumUCache.setTime(time); topologyChanged = fNumVCache.setTime(time) || topologyChanged; topologyChanged = fUOrderCache.setTime(time) || topologyChanged; topologyChanged = fVOrderCache.setTime(time) || topologyChanged; bool knotChanged = fUKnotCache.setTime(time); knotChanged = fVKnotCache.setTime(time) || knotChanged; if (fPositionWeightsCache.valid()) { positionsChanged = fPositionWeightsCache.setTime(time) || positionsChanged; } bool trimCurvesChanged = false; if (fTrimNumLoopsCache.valid()) { trimCurvesChanged = fTrimNumLoopsCache.setTime(time) || trimCurvesChanged; trimCurvesChanged = fTrimNumCurvesCache.setTime(time) || trimCurvesChanged; trimCurvesChanged = fTrimNumVerticesCache.setTime(time) || trimCurvesChanged; trimCurvesChanged = fTrimOrderCache.setTime(time) || trimCurvesChanged; trimCurvesChanged = fTrimKnotCache.setTime(time) || trimCurvesChanged; trimCurvesChanged = fTrimUCache.setTime(time) || trimCurvesChanged; trimCurvesChanged = fTrimVCache.setTime(time) || trimCurvesChanged; trimCurvesChanged = fTrimWCache.setTime(time) || trimCurvesChanged; } // return the new cache valid interval validityInterval &= fPositionsCache.getValidityInterval(); validityInterval &= fNumUCache.getValidityInterval(); validityInterval &= fNumVCache.getValidityInterval(); validityInterval &= fUOrderCache.getValidityInterval(); validityInterval &= fVOrderCache.getValidityInterval(); validityInterval &= fUKnotCache.getValidityInterval(); validityInterval &= fVKnotCache.getValidityInterval(); if (fPositionWeightsCache.valid()) { validityInterval &= fPositionWeightsCache.getValidityInterval(); } if (fTrimNumLoopsCache.valid()) { validityInterval &= fTrimNumLoopsCache.getValidityInterval(); validityInterval &= fTrimNumCurvesCache.getValidityInterval(); validityInterval &= fTrimNumVerticesCache.getValidityInterval(); validityInterval &= fTrimOrderCache.getValidityInterval(); validityInterval &= fTrimKnotCache.getValidityInterval(); validityInterval &= fTrimUCache.getValidityInterval(); validityInterval &= fTrimVCache.getValidityInterval(); validityInterval &= fTrimWCache.getValidityInterval(); } // do a minimal check for the consistency check(); // set Alembic INuPatch to Maya MFnNurbsSurface bool rebuild = topologyChanged || knotChanged || trimCurvesChanged || fNurbsData.object().isNull(); setNurbs(rebuild, positionsChanged); // tessellate Maya NURBS and convert to poly if (rebuild || positionsChanged) { tessellate(); } if (isVisible()) { convertToPoly(); } return validityInterval; } void NurbsTessellator::check() { // reset valid flag MStatus status; fSurfaceValid = true; // numKnots = numCV + degree + 1 int uDegree = fUOrderCache.getValue() - 1; int vDegree = fVOrderCache.getValue() - 1; int numUCV = fNumUCache.getValue(); int numVCV = fNumVCache.getValue(); int numUKnots = (int)fUKnotCache.getValue()->size(); int numVKnots = (int)fVKnotCache.getValue()->size(); if (numUKnots != numUCV + uDegree + 1 || numVKnots != numVCV + vDegree + 1) { fSurfaceValid = false; DisplayWarning(kBadNurbsMsg); return; } // numCV = numU * numV size_t numCVs = numUCV * numVCV; if (numCVs * 3 != fPositionsCache.getValue()->size()) { fSurfaceValid = false; DisplayWarning(kBadNurbsMsg); return; } // numCV = numWeight if (fPositionWeightsCache.valid() && numCVs != fPositionWeightsCache.getValue()->size()) { fSurfaceValid = false; DisplayWarning(kBadNurbsMsg); return; } } void NurbsTessellator::setNurbs(bool rebuild, bool positionsChanged) { if (!fSurfaceValid) { // invalid NURBS fNurbsData.setObject(MObject::kNullObj); fNurbs.setObject(MObject::kNullObj); return; } // Number of control points in U/V direction unsigned int numU = 0; unsigned int numV = 0; MPointArray mayaPositions; if (rebuild || positionsChanged) { numU = fNumUCache.getValue(); numV = fNumVCache.getValue(); // Positions and their weights const float* positions = fPositionsCache.getValue()->get(); const float* positionWeights = NULL; if (fPositionWeightsCache.valid()) { positionWeights = fPositionWeightsCache.getValue()->get(); } // allocate memory for positions mayaPositions.setLength(numU * numV); // Maya is U-major and has inversed V for (unsigned int u = 0; u < numU; u++) { for (unsigned int v = 0; v < numV; v++) { unsigned int alembicIndex = v * numU + u; unsigned int mayaIndex = u * numV + (numV - v - 1); MPoint point(positions[alembicIndex * 3 + 0], positions[alembicIndex * 3 + 1], positions[alembicIndex * 3 + 2], 1.0); if (positionWeights) { point.w = positionWeights[alembicIndex]; } mayaPositions[mayaIndex] = point; } } } if (rebuild) { // Nurbs degree unsigned int uDegree = fUOrderCache.getValue() - 1; unsigned int vDegree = fVOrderCache.getValue() - 1; // Nurbs form // Alemblic file does not record the form of nurb surface, we get the form // by checking the CV data. If the first degree number CV overlap the last // degree number CV, then the form is kPeriodic. If only the first CV overlaps // the last CV, then the form is kClosed. MFnNurbsSurface::Form uForm = MFnNurbsSurface::kPeriodic; MFnNurbsSurface::Form vForm = MFnNurbsSurface::kPeriodic; // Check all curves bool notOpen = true; for (unsigned int v = 0; notOpen && v < numV; v++) { for (unsigned int u = 0; u < uDegree; u++) { unsigned int firstIndex = u * numV + (numV - v - 1); unsigned int lastPeriodicIndex = (numU - uDegree + u) * numV + (numV - v - 1); if (!mayaPositions[firstIndex].isEquivalent(mayaPositions[lastPeriodicIndex])) { uForm = MFnNurbsSurface::kOpen; notOpen = false; break; } } } if (uForm == MFnNurbsSurface::kOpen) { uForm = MFnNurbsSurface::kClosed; for (unsigned int v = 0; v < numV; v++) { unsigned int lastUIndex = (numU - 1) * numV + (numV - v - 1); if (!mayaPositions[numV-v-1].isEquivalent(mayaPositions[lastUIndex])) { uForm = MFnNurbsSurface::kOpen; break; } } } notOpen = true; for (unsigned int u = 0; notOpen && u < numU; u++) { for (unsigned int v = 0; v < vDegree; v++) { unsigned int firstIndex = u * numV + (numV - v - 1); unsigned int lastPeriodicIndex = u * numV + (vDegree - v - 1); //numV - (numV - vDegree + v) - 1; if (!mayaPositions[firstIndex].isEquivalent(mayaPositions[lastPeriodicIndex])) { vForm = MFnNurbsSurface::kOpen; notOpen = false; break; } } } if (vForm == MFnNurbsSurface::kOpen) { vForm = MFnNurbsSurface::kClosed; for (unsigned int u = 0; u < numU; u++) { if (!mayaPositions[u*numV+(numV-1)].isEquivalent(mayaPositions[u*numV])) { vForm = MFnNurbsSurface::kOpen; break; } } } // Knots // Dispose the leading and trailing knots // Alembic duplicate CVs if the form is not kOpen // For more information, refer to MFnNurbsSurface unsigned int numUKnot = (unsigned int)fUKnotCache.getValue()->size(); unsigned int numVKnot = (unsigned int)fVKnotCache.getValue()->size(); const float* uKnot = fUKnotCache.getValue()->get(); const float* vKnot = fVKnotCache.getValue()->get(); MDoubleArray mayaUKnots(uKnot + 1, numUKnot - 2); MDoubleArray mayaVKnots(vKnot + 1, numVKnot - 2); // Create the Nurbs MStatus status; MObject nurbsData = fNurbsData.create(); MObject nurbs = fNurbs.create(mayaPositions, mayaUKnots, mayaVKnots, uDegree, vDegree, uForm, vForm, true, nurbsData, &status); if (status != MS::kSuccess || nurbs.isNull()) { // creation failure fNurbsData.setObject(MObject::kNullObj); fNurbs.setObject(MObject::kNullObj); return; } // Trim Nurbs if (fTrimNumLoopsCache.valid()) { unsigned int trimNumLoops = fTrimNumLoopsCache.getValue(); // mayaV = offsetV - alembicV double startU, endU, startV, endV; fNurbs.getKnotDomain(startU, endU, startV, endV); double offsetV = startV + endV; MTrimBoundaryArray boundaryArray; const unsigned int* trimNumCurves = fTrimNumCurvesCache.getValue()->get(); const unsigned int* trimNumVertices = fTrimNumVerticesCache.getValue()->get(); const unsigned int* trimOrder = fTrimOrderCache.getValue()->get(); const float* trimKnot = fTrimKnotCache.getValue()->get(); const float* trimU = fTrimUCache.getValue()->get(); const float* trimV = fTrimVCache.getValue()->get(); const float* trimW = fTrimWCache.getValue()->get(); for (unsigned int i = 0; i < trimNumLoops; i++) { // Set up curves for each boundary unsigned int numCurves = *trimNumCurves; MObjectArray boundary(numCurves); for (unsigned int j = 0; j < numCurves; j++) { // Set up one curve unsigned int numVertices = *trimNumVertices; unsigned int degree = *trimOrder - 1; unsigned int numKnots = numVertices + degree + 1; MPointArray controlPoints; controlPoints.setLength(numVertices); for (unsigned int k = 0; k < numVertices; k++) { MPoint point(trimU[k], offsetV - trimV[k], 0, trimW[k]); controlPoints[k] = point; } MDoubleArray knots(trimKnot + 1, numKnots - 2); // Create the curve MFnNurbsCurveData curveData; MObject curveDataObject = curveData.create(); MFnNurbsCurve curve; MObject curveObject = curve.create(controlPoints, knots, degree, MFnNurbsCurve::kOpen, true, true, curveDataObject, &status); if (status == MS::kSuccess && !curveObject.isNull()) { boundary[j] = curveDataObject; } // next curve trimNumVertices++; trimOrder++; trimKnot += numKnots; trimU += numVertices; trimV += numVertices; trimW += numVertices; } boundaryArray.append(boundary); // next loop trimNumCurves++; } MTrimBoundaryArray oneRegion; for (unsigned int i = 0; i < boundaryArray.length(); i++) { if (i > 0) { MObject loopData = boundaryArray.getMergedBoundary(i, &status); if (status != MS::kSuccess) continue; MFnNurbsCurve loop(loopData, &status); if (status != MS::kSuccess) continue; // Check whether this loop is an outer boundary. bool isOuterBoundary = false; double length = loop.length(); unsigned int segment = std::max(loop.numCVs(), 10); MPointArray curvePoints; curvePoints.setLength(segment); for (unsigned int j = 0; j < segment; j++) { double param = loop.findParamFromLength(length * j / segment); loop.getPointAtParam(param, curvePoints[j]); } // Find the right most curve point MPoint rightMostPoint = curvePoints[0]; unsigned int rightMostIndex = 0; for (unsigned int j = 0; j < curvePoints.length(); j++) { if (rightMostPoint.x < curvePoints[j].x) { rightMostPoint = curvePoints[j]; rightMostIndex = j; } } // Find the vertex just before and after the right most vertex unsigned int beforeIndex = (rightMostIndex == 0) ? curvePoints.length() - 1 : rightMostIndex - 1; unsigned int afterIndex = (rightMostIndex == curvePoints.length() - 1) ? 0 : rightMostIndex + 1; for (unsigned int j = 0; j < curvePoints.length(); j++) { if (fabs(curvePoints[beforeIndex].x - curvePoints[rightMostIndex].x) < 1e-5) { beforeIndex = (beforeIndex == 0) ? curvePoints.length() - 1 : beforeIndex - 1; } } for (unsigned int j = 0; j < curvePoints.length(); j++) { if (fabs(curvePoints[afterIndex].x - curvePoints[rightMostIndex].x) < 1e-5) { afterIndex = (afterIndex == curvePoints.length() - 1) ? 0 : afterIndex + 1; } } // failed. not a closed curve. if (fabs(curvePoints[afterIndex].x - curvePoints[rightMostIndex].x) < 1e-5 && fabs(curvePoints[beforeIndex].x - curvePoints[rightMostIndex].x) < 1e-5) { continue; } // Compute the cross product MVector vector1 = curvePoints[beforeIndex] - curvePoints[rightMostIndex]; MVector vector2 = curvePoints[afterIndex] - curvePoints[rightMostIndex]; if ((vector1 ^ vector2).z < 0) { isOuterBoundary = true; } // Trim the NURBS surface. An outer boundary starts a new region. if (isOuterBoundary) { status = fNurbs.trimWithBoundaries(oneRegion, false, 1e-3, 1e-5, true); if (status != MS::kSuccess) { fNurbsData.setObject(MObject::kNullObj); fNurbs.setObject(MObject::kNullObj); return; } oneRegion.clear(); } } oneRegion.append(boundaryArray[i]); } status = fNurbs.trimWithBoundaries(oneRegion, false, 1e-3, 1e-5, true); if (status != MS::kSuccess) { fNurbsData.setObject(MObject::kNullObj); fNurbs.setObject(MObject::kNullObj); return; } } } else { assert(!fNurbsData.object().isNull()); if (positionsChanged) { fNurbs.setCVs(mayaPositions); } } } void NurbsTessellator::tessellate() { if (!fSurfaceValid || fNurbsData.object().isNull()) { fPolyMeshData.setObject(MObject::kNullObj); fPolyMesh.setObject(MObject::kNullObj); return; } // Create the mesh data to own the mesh MObject polyMeshData = fPolyMeshData.create(); // Set up parameters MTesselationParams params( MTesselationParams::kStandardFitFormat, MTesselationParams::kTriangles); // Tess the NURBS to triangles MStatus status; MObject polyObject = fNurbs.tesselate(params, polyMeshData, &status); if (status != MS::kSuccess || !polyObject.hasFn(MFn::kMesh)) { // tessellation failed fPolyMeshData.setObject(MObject::kNullObj); fPolyMesh.setObject(MObject::kNullObj); return; } status = fPolyMesh.setObject(polyObject); assert(status == MS::kSuccess); } void NurbsTessellator::convertToPoly() { if (!fSurfaceValid || fPolyMeshData.object().isNull() || fPolyMesh.numVertices() == 0 || fPolyMesh.numFaceVertices() == 0) { fTriangleIndices.reset(); fWireIndices.reset(); fPositions.reset(); fNormals.reset(); fUVs.reset(); return; } MayaMeshExtractor<IndexBuffer::index_t> extractor(fPolyMeshData.object()); extractor.setWantUVs(fNeedUVs); extractor.compute(); fTriangleIndices = extractor.triangleIndices(); fWireIndices = extractor.wireIndices(); fPositions = extractor.positions(); fNormals = extractor.normals(); fUVs.reset(); if (fNeedUVs) { fUVs = extractor.uvs(); } } //============================================================================== // CLASS SubDSmoother //============================================================================== SubDSmoother::SubDSmoother( Alembic::AbcGeom::ISubDSchema& abcSubD, const bool needUVs) : PolyDataProvider(abcSubD, needUVs) { // Face Indices fFaceIndicesCache.init(abcSubD.getFaceIndicesProperty()); // Crease Edges Alembic::Abc::IInt32ArrayProperty creaseIndicesProp = abcSubD.getCreaseIndicesProperty(); Alembic::Abc::IInt32ArrayProperty creaseLengthsProp = abcSubD.getCreaseLengthsProperty(); Alembic::Abc::IFloatArrayProperty creaseSharpnessesProp = abcSubD.getCreaseSharpnessesProperty(); if (creaseIndicesProp.valid() && creaseLengthsProp.valid() && creaseSharpnessesProp.valid()) { fCreaseIndicesCache.init(creaseIndicesProp); fCreaseLengthsCache.init(creaseLengthsProp); fCreaseSharpnessesCache.init(creaseSharpnessesProp); } // Crease Vertices Alembic::Abc::IInt32ArrayProperty cornerIndicesProp = abcSubD.getCornerIndicesProperty(); Alembic::Abc::IFloatArrayProperty cornerSharpnessesProp = abcSubD.getCornerSharpnessesProperty(); if (cornerIndicesProp.valid() && cornerSharpnessesProp.valid()) { fCornerIndicesCache.init(cornerIndicesProp); fCornerSharpnessesCache.init(cornerSharpnessesProp); } // Invisible Faces Alembic::Abc::IInt32ArrayProperty holesProp = abcSubD.getHolesProperty(); if (holesProp.valid()) { fHolesCache.init(holesProp); } // UVs if (fNeedUVs) { Alembic::AbcGeom::IV2fGeomParam UVs = abcSubD.getUVsParam(); if (UVs.valid()) { fUVsScope = UVs.getScope(); if (fUVsScope == Alembic::AbcGeom::kVaryingScope || fUVsScope == Alembic::AbcGeom::kVertexScope || fUVsScope == Alembic::AbcGeom::kFacevaryingScope) { fUVsCache.init(UVs.getValueProperty()); if (UVs.isIndexed()) { fUVIndicesCache.init(UVs.getIndexProperty()); } } } } } SubDSmoother::~SubDSmoother() { // free the property readers fFaceIndicesCache.reset(); fCreaseIndicesCache.reset(); fCreaseLengthsCache.reset(); fCreaseSharpnessesCache.reset(); fCornerIndicesCache.reset(); fCornerSharpnessesCache.reset(); fHolesCache.reset(); fUVsScope = Alembic::AbcGeom::kUnknownScope; fUVsCache.reset(); fUVIndicesCache.reset(); } bool SubDSmoother::valid() const { return PolyDataProvider::valid() && fFaceIndicesCache.valid(); } boost::shared_ptr<const ShapeSample> SubDSmoother::getSample(double seconds) { // empty mesh if (!fWireIndices || !fTriangleIndices) { boost::shared_ptr<ShapeSample> sample = ShapeSample::createEmptySample(seconds); return sample; } // triangle indices // Currently, we only have 1 group std::vector<boost::shared_ptr<IndexBuffer> > triangleVertIndices; triangleVertIndices.push_back(IndexBuffer::create(fTriangleIndices)); boost::shared_ptr<ShapeSample> sample = ShapeSample::create( seconds, // time (in seconds) fWireIndices->size() / 2, // number of wireframes fPositions->size() / 3, // number of vertices IndexBuffer::create(fWireIndices), // wireframe indices triangleVertIndices, // triangle indices (1 group) VertexBuffer::createPositions(fPositions), // position getBoundingBox(), // bounding box Config::kDefaultGrayColor, // diffuse color isVisible() ); if (fNormals) { sample->setNormals( VertexBuffer::createNormals(fNormals)); } if (fUVs) { sample->setUVs( VertexBuffer::createUVs(fUVs)); } return sample; } TimeInterval SubDSmoother::updateCache(chrono_t time) { // update faceCounts/position cache here so that we can detect topology/position change. // next setTime() in DataProvider::updateCache() simply returns early bool topologyChanged = fFaceCountsCache.setTime(time); bool positionChanged = fPositionsCache.setTime(time); TimeInterval validityInterval(PolyDataProvider::updateCache(time)); // update caches topologyChanged = fFaceIndicesCache.setTime(time) || topologyChanged; bool creaseEdgeChanged = false; if (fCreaseSharpnessesCache.valid()) { creaseEdgeChanged = fCreaseIndicesCache.setTime(time) || creaseEdgeChanged; creaseEdgeChanged = fCreaseLengthsCache.setTime(time) || creaseEdgeChanged; creaseEdgeChanged = fCreaseSharpnessesCache.setTime(time) || creaseEdgeChanged; } bool creaseVertexChanged = false; if (fCornerSharpnessesCache.valid()) { creaseVertexChanged = fCornerIndicesCache.setTime(time) || creaseVertexChanged; creaseVertexChanged = fCornerSharpnessesCache.setTime(time) || creaseVertexChanged; } bool invisibleFaceChanged = false; if (fHolesCache.valid()) { invisibleFaceChanged = fHolesCache.setTime(time); } bool uvChanged = false; if (fUVsCache.valid()) { uvChanged = fUVsCache.setTime(time); if (fUVIndicesCache.valid()) { uvChanged = fUVIndicesCache.setTime(time) || uvChanged; } } // return the new cache valid interval validityInterval &= fFaceIndicesCache.getValidityInterval(); if (fCreaseSharpnessesCache.valid()) { validityInterval &= fCreaseIndicesCache.getValidityInterval(); validityInterval &= fCreaseLengthsCache.getValidityInterval(); validityInterval &= fCreaseSharpnessesCache.getValidityInterval(); } if (fCornerSharpnessesCache.valid()) { validityInterval &= fCornerIndicesCache.getValidityInterval(); validityInterval &= fCornerSharpnessesCache.getValidityInterval(); } if (fHolesCache.valid()) { validityInterval &= fHolesCache.getValidityInterval(); } if (fUVsCache.valid()) { validityInterval &= fUVsCache.getValidityInterval(); if (fUVIndicesCache.valid()) { validityInterval &= fUVIndicesCache.getValidityInterval(); } } // do a minimal check for the consistency check(); if (topologyChanged || creaseEdgeChanged || creaseVertexChanged || invisibleFaceChanged || fSubDData.object().isNull()) { rebuildSubD(); setCreaseEdges(); setCreaseVertices(); setInvisibleFaces(); setUVs(); } else { if (positionChanged) { setPositions(); } if (uvChanged) { setUVs(); } } if (isVisible()) { convertToPoly(); } return validityInterval; } void SubDSmoother::check() { size_t numFaceIndices = fFaceIndicesCache.getValue()->size(); size_t numVerts = fPositionsCache.getValue()->size() / 3; // UVs size_t numExpectedUVs = 0; if (fUVsScope == Alembic::AbcGeom::kVaryingScope || fUVsScope == Alembic::AbcGeom::kVertexScope) { numExpectedUVs = numVerts; } else if (fUVsScope == Alembic::AbcGeom::kFacevaryingScope) { numExpectedUVs = numFaceIndices; } size_t numActualUVs = 0; if (fUVsCache.valid()) { if (fUVIndicesCache.valid()) { numActualUVs = fUVIndicesCache.getValue()->size(); } else { numActualUVs = fUVsCache.getValue()->size() / 2; } } // clear previous result fCheckedUVsScope = Alembic::AbcGeom::kUnknownScope; fCheckedUVs.reset(); fCheckedUVIndices.reset(); // forward if (numExpectedUVs == numActualUVs) { if (fUVsCache.valid()) { fCheckedUVsScope = fUVsScope; fCheckedUVs = fUVsCache.getValue(); if (fUVIndicesCache.valid()) { fCheckedUVIndices = fUVIndicesCache.getValue(); } } } else { DisplayWarning(kBadUVsMsg); } } void SubDSmoother::rebuildSubD() { // input data size_t numFaceCounts = fFaceCountsCache.getValue()->size(); const unsigned int* faceCounts = fFaceCountsCache.getValue()->get(); size_t numFaceIndices = fFaceIndicesCache.getValue()->size(); const IndexBuffer::index_t* faceIndices = fFaceIndicesCache.getValue()->get(); size_t numPositions = fPositionsCache.getValue()->size(); const float* positions = fPositionsCache.getValue()->get(); size_t numVertices = numPositions / 3; // Build Maya data structure MIntArray mayaCounts, mayaConnects; mayaCounts.setLength((unsigned int)numFaceCounts); mayaConnects.setLength((unsigned int)numFaceIndices); for (unsigned int i = 0, polyVertOffset = 0; i < numFaceCounts; i++) { unsigned int faceCount = mayaCounts[i] = faceCounts[i]; for (unsigned int j = 0; j < faceCount; j++) { // Alembic's polygon winding is CW mayaConnects[polyVertOffset + j] = faceIndices[polyVertOffset + faceCount - j - 1]; } polyVertOffset += faceCount; } MFloatPointArray mayaPositions; mayaPositions.setLength((unsigned int)numVertices); for (unsigned int i = 0; i < numVertices; i++) { mayaPositions[i] = MFloatPoint(positions[i * 3 + 0], positions[i * 3 + 1], positions[i * 3 + 2]); } // Create Maya mesh MStatus status; MObject subdData = fSubDData.create(&status); assert(status == MS::kSuccess); fSubD.setCheckSamePointTwice(false); MObject subd = fSubD.create((int)numVertices, (int)numFaceCounts, mayaPositions, mayaCounts, mayaConnects, subdData, &status); if (status != MS::kSuccess || subd.isNull()) { fSubDData.setObject(MObject::kNullObj); fSubD.setObject(MObject::kNullObj); } } void SubDSmoother::setPositions() { if (fSubDData.object().isNull()) { return; } // input data size_t numPositions = fPositionsCache.getValue()->size(); const float* positions = fPositionsCache.getValue()->get(); size_t numVertices = numPositions / 3; // Set vertex positions only MFloatPointArray mayaPositions; mayaPositions.setLength((unsigned int)numVertices); for (unsigned int i = 0; i < numVertices; i++) { mayaPositions[i] = MFloatPoint(positions[i * 3 + 0], positions[i * 3 + 1], positions[i * 3 + 2]); } fSubD.setPoints(mayaPositions); } void SubDSmoother::setCreaseEdges() { if (fSubDData.object().isNull() || !fCreaseIndicesCache.valid() || !fCreaseLengthsCache.valid() || !fCreaseSharpnessesCache.valid()) { return; } // input data size_t numCreaseIndices = fCreaseIndicesCache.getValue()->size(); const unsigned int* creaseIndices = fCreaseIndicesCache.getValue()->get(); size_t numCreaseLengths = fCreaseLengthsCache.getValue()->size(); const unsigned int* creaseLengths = fCreaseLengthsCache.getValue()->get(); size_t numCreaseSharpnesses = fCreaseSharpnessesCache.getValue()->size(); const float* creaseSharpnesses = fCreaseSharpnessesCache.getValue()->get(); if (numCreaseSharpnesses == 0) { return; } // Prepare (startVertex, endVertex) => (edgeId) lookup map typedef boost::unordered_map<std::pair<int,int>,int> EdgeMap; EdgeMap edgeMap(size_t(fSubD.numEdges() / 0.75f)); int numEdges = fSubD.numEdges(); for (int i = 0; i < numEdges; i++) { int2 vertexList; fSubD.getEdgeVertices(i, vertexList); if (vertexList[0] > vertexList[1]) { std::swap(vertexList[0], vertexList[1]); } edgeMap.insert(std::make_pair(std::make_pair(vertexList[0], vertexList[1]), i)); } // Fill Maya crease edges MUintArray mayaEdgeIds; MDoubleArray mayaCreaseData; for (size_t i = 0, index = 0; i < numCreaseLengths && i < numCreaseSharpnesses; i++) { // length should always be 2 unsigned int length = creaseLengths[i]; float sharpness = creaseSharpnesses[i]; if (length == 2 && index + length <= numCreaseIndices) { // find the edge ID from vertex ID std::pair<int,int> edge = std::make_pair(creaseIndices[index],creaseIndices[index+1]); if (edge.first > edge.second) { std::swap(edge.first, edge.second); } EdgeMap::iterator iter = edgeMap.find(edge); if (iter != edgeMap.end() && iter->second < numEdges) { // edge found, store it crease data mayaEdgeIds.append(iter->second); mayaCreaseData.append(sharpness); } } index += length; } // Set Maya crease edges MStatus status; status = fSubD.setCreaseEdges(mayaEdgeIds, mayaCreaseData); assert(status == MS::kSuccess); } void SubDSmoother::setCreaseVertices() { if (fSubDData.object().isNull() || !fCornerIndicesCache.valid() || !fCornerSharpnessesCache.valid()) { return; } // input data size_t numCornerIndices = fCornerIndicesCache.getValue()->size(); const unsigned int* cornerIndices = fCornerIndicesCache.getValue()->get(); size_t numCornerSharpnesses = fCornerSharpnessesCache.getValue()->size(); const float* cornerSharpnesses = fCornerSharpnessesCache.getValue()->get(); if (cornerSharpnesses == 0) { return; } // Fill Maya crease vertices MUintArray mayaVertexIds; MDoubleArray mayaCreaseData; size_t numCreaseVertices = std::min(numCornerIndices, numCornerSharpnesses); mayaVertexIds.setLength((unsigned int)numCreaseVertices); mayaCreaseData.setLength((unsigned int)numCreaseVertices); for (unsigned int i = 0; i < numCreaseVertices; i++) { mayaVertexIds[i] = cornerIndices[i]; mayaCreaseData[i] = cornerSharpnesses[i]; } // Set Maya crease vertices MStatus status; status = fSubD.setCreaseVertices(mayaVertexIds, mayaCreaseData); assert(status == MS::kSuccess); } void SubDSmoother::setInvisibleFaces() { if (fSubDData.object().isNull() || !fHolesCache.valid()) { return; } // input data size_t numHoles = fHolesCache.getValue()->size(); const unsigned int* holes = fHolesCache.getValue()->get(); if (numHoles == 0) { return; } // Fill Maya invisible faces MUintArray mayaFaceIds(holes, (unsigned int)numHoles); // Set Maya invisible faces MStatus status; status = fSubD.setInvisibleFaces(mayaFaceIds); assert(status == MS::kSuccess); } void SubDSmoother::setUVs() { if (fSubDData.object().isNull()) { return; } // unsupported scope if (fCheckedUVsScope != Alembic::AbcGeom::kVaryingScope && fCheckedUVsScope != Alembic::AbcGeom::kVertexScope && fCheckedUVsScope != Alembic::AbcGeom::kFacevaryingScope) { return; } // no UVs if (!fCheckedUVs) { return; } // input data size_t numFaceCounts = fFaceCountsCache.getValue()->size(); const unsigned int* faceCounts = fFaceCountsCache.getValue()->get(); size_t numFaceIndices = fFaceIndicesCache.getValue()->size(); const IndexBuffer::index_t* faceIndices = fFaceIndicesCache.getValue()->get(); size_t numUVs = fCheckedUVs->size(); const float* UVs = fCheckedUVs->get(); const IndexBuffer::index_t* uvIndices = NULL; if (fCheckedUVIndices) { uvIndices = fCheckedUVIndices->get(); } // Clear Maya UVs if the number of UVs does not equal // MFnMesh::setUVs() only allow uv arrays equal or larger than current UV set size if (int(numUVs) != fSubD.numUVs()) { fSubD.clearUVs(); } // no UVs, we are done if (numUVs == 0) { return; } // Fill Maya UVs MFloatArray mayaUArray((unsigned int)numUVs); MFloatArray mayaVArray((unsigned int)numUVs); for (unsigned int i = 0; i < numUVs; i++) { mayaUArray[i] = UVs[i * 2 + 0]; mayaVArray[i] = UVs[i * 2 + 1]; } // Fill Maya UV indices MIntArray mayaUVCounts((unsigned int)numFaceCounts); MIntArray mayaUVIds((unsigned int)numFaceIndices); for (unsigned int i = 0, polyVertOffset = 0; i < numFaceCounts; i++) { unsigned int faceCount = mayaUVCounts[i] = faceCounts[i]; for (unsigned int j = 0; j < faceCount; j++) { unsigned int uvIndex = 0; // Alembic's polygon winding is CW unsigned int polyVertIndex = polyVertOffset + faceCount - j - 1; if (fCheckedUVsScope == Alembic::AbcGeom::kVaryingScope || fCheckedUVsScope == Alembic::AbcGeom::kVertexScope) { // per-vertex UV unsigned int vertIndex = faceIndices[polyVertIndex]; uvIndex = uvIndices ? uvIndices[vertIndex] : vertIndex; } else if (fCheckedUVsScope == Alembic::AbcGeom::kFacevaryingScope) { // per-face per-vertex UV uvIndex = uvIndices ? uvIndices[polyVertIndex] : polyVertIndex; } else { assert(0); } mayaUVIds[polyVertOffset + j] = uvIndex; } polyVertOffset += faceCount; } // Set Maya UVs and UV indices MStatus status; status = fSubD.setUVs(mayaUArray, mayaVArray); assert(status == MS::kSuccess); status = fSubD.assignUVs(mayaUVCounts, mayaUVIds); assert(status == MS::kSuccess); } void SubDSmoother::convertToPoly() { if (fSubDData.object().isNull() || fSubD.numVertices() == 0 || fSubD.numFaceVertices() == 0) { fTriangleIndices.reset(); fWireIndices.reset(); fPositions.reset(); fNormals.reset(); fUVs.reset(); return; } // Smooth the subdivision mesh MFnMeshData smoothMeshData; MObject smoothMeshDataObj = smoothMeshData.create(); MMeshSmoothOptions smoothOptions; smoothOptions.setDivisions(2); MObject smoothMeshObj = fSubD.generateSmoothMesh(smoothMeshDataObj, &smoothOptions); MayaMeshExtractor<IndexBuffer::index_t> extractor(smoothMeshDataObj); extractor.setWantUVs(fNeedUVs); extractor.compute(); fTriangleIndices = extractor.triangleIndices(); fWireIndices = extractor.wireIndices(); fPositions = extractor.positions(); fNormals = extractor.normals(); fUVs.reset(); if (fNeedUVs) { fUVs = extractor.uvs(); } } //============================================================================== // CLASS AlembicCacheObjectReader //============================================================================== AlembicCacheObjectReader::Ptr AlembicCacheObjectReader::create(Alembic::Abc::IObject& abcObj, bool needUVs) { CheckInterruptAndPause("reader initialization"); // The object type can be mesh or nurbs. if (Alembic::AbcGeom::IPolyMesh::matches(abcObj.getHeader()) || Alembic::AbcGeom::INuPatch::matches(abcObj.getHeader()) || Alembic::AbcGeom::ISubD::matches(abcObj.getHeader())) { Ptr reader = boost::make_shared<AlembicCacheMeshReader>(abcObj, needUVs); return reader->valid() ? reader : Ptr(); } // or an xform... if (Alembic::AbcGeom::IXform::matches(abcObj.getHeader())) { Ptr reader = boost::make_shared<AlembicCacheXformReader>(abcObj, needUVs); return reader->valid() ? reader : Ptr(); } return Ptr(); } AlembicCacheObjectReader::~AlembicCacheObjectReader() {} //============================================================================== // CLASS AlembicCacheTopReader //============================================================================== AlembicCacheTopReader::AlembicCacheTopReader( Alembic::Abc::IObject abcObj, const bool needUVs ) : fBoundingBoxValidityInterval(TimeInterval::kInvalid) { fXformData = XformData::create(); size_t numChildren = abcObj.getNumChildren(); for (size_t ii=0; ii<numChildren; ++ii) { Alembic::Abc::IObject child(abcObj, abcObj.getChildHeader(ii).getName()); Ptr childReader = create(child, needUVs); if (childReader) fChildren.push_back(childReader); } // Compute the exact animation time range TimeInterval animTimeRange(TimeInterval::kInvalid); BOOST_FOREACH(const AlembicCacheObjectReader::Ptr& childReader, fChildren) { animTimeRange |= childReader->getAnimTimeRange(); } fXformData->setAnimTimeRange(animTimeRange); } AlembicCacheTopReader::~AlembicCacheTopReader() {} bool AlembicCacheTopReader::valid() const { return true; } TimeInterval AlembicCacheTopReader::sampleHierarchy(double seconds, const MMatrix& rootMatrix, TimeInterval rootMatrixInterval) { TimeInterval validityInterval(TimeInterval::kInfinite); MBoundingBox bbox; TimeInterval bboxValIntrvl(TimeInterval::kInfinite); BOOST_FOREACH(const AlembicCacheObjectReader::Ptr& childReader, fChildren) { validityInterval &= childReader->sampleHierarchy(seconds, rootMatrix, rootMatrixInterval); bbox.expand(childReader->getBoundingBox()); bboxValIntrvl &= childReader->getBoundingBoxValidityInterval(); } // The computed validity interval must contain the current time. assert(validityInterval.contains(seconds)); // The current and previous bounding box intervals are either // disjoint or equal. assert(!(fBoundingBoxValidityInterval & bboxValIntrvl).valid() || fBoundingBoxValidityInterval == bboxValIntrvl); if (seconds == bboxValIntrvl.startTime()) { fBoundingBox = bbox; fBoundingBoxValidityInterval = bboxValIntrvl; boost::shared_ptr<GPUCache::XformSample> sample = GPUCache::XformSample::create( seconds, MMatrix::identity, fBoundingBox, true ); fXformData->addSample(sample); } return validityInterval; } TimeInterval AlembicCacheTopReader::sampleShape(double seconds) { // Top reader has no shape data! assert(0); return TimeInterval(TimeInterval::kInvalid); } SubNode::MPtr AlembicCacheTopReader::get() const { SubNode::MPtr node = SubNode::create(MString("|"), fXformData); BOOST_FOREACH(const AlembicCacheObjectReader::Ptr& childReader, fChildren) { SubNode::MPtr child = childReader->get(); if (child) SubNode::connect(node, child); } if (node->getChildren().empty()) { return SubNode::MPtr(); } return node; } MBoundingBox AlembicCacheTopReader::getBoundingBox() const { return fBoundingBox; } TimeInterval AlembicCacheTopReader::getBoundingBoxValidityInterval() const { return fBoundingBoxValidityInterval; } TimeInterval AlembicCacheTopReader::getAnimTimeRange() const { return fXformData->animTimeRange(); } void AlembicCacheTopReader::saveAndReset(AlembicCacheReader& cacheReader) { // We don't save xform readers. Just call children's saveAndReset(). BOOST_FOREACH (const AlembicCacheObjectReader::Ptr& childReader, fChildren) { childReader->saveAndReset(cacheReader); } } //============================================================================== // CLASS AlembicCacheXformReader //============================================================================== AlembicCacheXformReader::AlembicCacheXformReader( Alembic::Abc::IObject abcObj, const bool needUVs ) : fName(abcObj.getName()), fValidityInterval(TimeInterval::kInvalid), fBoundingBoxValidityInterval(TimeInterval::kInvalid) { Alembic::AbcGeom::IXform xform(abcObj, Alembic::Abc::kWrapExisting); // Xform schema Alembic::AbcGeom::IXformSchema schema = xform.getSchema(); // transform fXformCache.init(schema); // transform visibility Alembic::AbcGeom::IVisibilityProperty visibility = Alembic::AbcGeom::GetVisibilityProperty(abcObj); if (visibility) { fVisibilityCache.init(visibility); } fXformData = XformData::create(); const size_t numChildren = abcObj.getNumChildren(); for (size_t ii=0; ii<numChildren; ++ii) { Alembic::Abc::IObject child(abcObj, abcObj.getChildHeader(ii).getName()); Ptr childReader = create(child, needUVs); if (childReader) fChildren.push_back(childReader); } // Compute the exact animation time range Alembic::Abc::TimeSamplingPtr timeSampling = schema.getTimeSampling(); size_t numSamples = schema.getNumSamples(); TimeInterval animTimeRange( timeSampling->getSampleTime(0), timeSampling->getSampleTime(numSamples > 0 ? numSamples-1 : 0) ); BOOST_FOREACH(const AlembicCacheObjectReader::Ptr& childReader, fChildren) { animTimeRange |= childReader->getAnimTimeRange(); } fXformData->setAnimTimeRange(animTimeRange); } AlembicCacheXformReader::~AlembicCacheXformReader() {} bool AlembicCacheXformReader::valid() const { return fXformCache.valid(); } TimeInterval AlembicCacheXformReader::sampleHierarchy(double seconds, const MMatrix& rootMatrix, TimeInterval rootMatrixInterval) { // Fill the sample if this sample has not been read if (!fValidityInterval.contains(seconds)) { fillTopoAndAttrSample(seconds); } // Inherit transformation MMatrix newRootMatrix = fXformCache.getValue() * rootMatrix; TimeInterval newRootMatrixInterval = fXformCache.getValidityInterval() & rootMatrixInterval; TimeInterval validityInterval = fValidityInterval; MBoundingBox bbox; TimeInterval bboxValIntrvl(TimeInterval::kInfinite); BOOST_FOREACH(const AlembicCacheObjectReader::Ptr& childReader, fChildren) { validityInterval &= childReader->sampleHierarchy(seconds, newRootMatrix, newRootMatrixInterval); bbox.expand(childReader->getBoundingBox()); bboxValIntrvl &= childReader->getBoundingBoxValidityInterval(); } // The computed validity interval must contain the current time. assert(validityInterval.contains(seconds)); // The current and previous bounding box intervals are either // disjoint or equal. assert(!(fBoundingBoxValidityInterval & bboxValIntrvl).valid() || fBoundingBoxValidityInterval == bboxValIntrvl); if (seconds == (fValidityInterval & bboxValIntrvl).startTime()) { fBoundingBox = bbox; fBoundingBoxValidityInterval = bboxValIntrvl; boost::shared_ptr<GPUCache::XformSample> sample = GPUCache::XformSample::create( seconds, fXformCache.getValue(), fBoundingBox, isVisible() ); fXformData->addSample(sample); } return validityInterval; } TimeInterval AlembicCacheXformReader::sampleShape(double seconds) { // Transform reader has no shape data! assert(0); return TimeInterval(TimeInterval::kInvalid); } SubNode::MPtr AlembicCacheXformReader::get() const { SubNode::MPtr node = SubNode::create(MString(fName.c_str()), fXformData); BOOST_FOREACH(const AlembicCacheObjectReader::Ptr& childReader, fChildren) { SubNode::MPtr child = childReader->get(); if (child) SubNode::connect(node, child); } if (node->getChildren().empty()) { return SubNode::MPtr(); } return node; } void AlembicCacheXformReader::fillTopoAndAttrSample(chrono_t time) { // Notes: // // When possible, we try to reuse the samples from the previously // read sample. // update caches fXformCache.setTime(time); if (fVisibilityCache.valid()) { fVisibilityCache.setTime(time); } // return the new cache valid interval TimeInterval validityInterval(TimeInterval::kInfinite); validityInterval &= fXformCache.getValidityInterval(); if (fVisibilityCache.valid()) { validityInterval &= fVisibilityCache.getValidityInterval(); } assert(validityInterval.valid()); fValidityInterval = validityInterval; } bool AlembicCacheXformReader::isVisible() const { // xform invisible if (fVisibilityCache.valid() && fVisibilityCache.getValue() == char(Alembic::AbcGeom::kVisibilityHidden)) { return false; } // visible return true; } MBoundingBox AlembicCacheXformReader::getBoundingBox() const { return fBoundingBox; } TimeInterval AlembicCacheXformReader::getBoundingBoxValidityInterval() const { return fBoundingBoxValidityInterval; } TimeInterval AlembicCacheXformReader::getAnimTimeRange() const { return fXformData->animTimeRange(); } void AlembicCacheXformReader::saveAndReset(AlembicCacheReader& cacheReader) { // We don't save xform readers. Just call children's saveAndReset(). BOOST_FOREACH (const AlembicCacheObjectReader::Ptr& childReader, fChildren) { childReader->saveAndReset(cacheReader); } } //============================================================================== // CLASS AlembicCacheMeshReader //============================================================================== AlembicCacheMeshReader::AlembicCacheMeshReader( Alembic::Abc::IObject object, const bool needUVs ) : fName(object.getName()), fFullName(object.getFullName()), fBoundingBoxValidityInterval(TimeInterval::kInvalid), fNumTransparentSample(0) { // Shape schema if (Alembic::AbcGeom::IPolyMesh::matches(object.getHeader())) { Alembic::AbcGeom::IPolyMesh meshObj(object, Alembic::Abc::kWrapExisting); Alembic::AbcGeom::IPolyMeshSchema schema = meshObj.getSchema(); // check the existence of wireframe index property // if the mesh is written by gpuCache command, the wireframe index property must exist if (schema.getPropertyHeader(kCustomPropertyWireIndices) != NULL || schema.getPropertyHeader(kCustomPropertyWireIndicesOld) != NULL) { fDataProvider.reset(new RawDataProvider(schema, needUVs)); } else { fDataProvider.reset(new Triangulator(schema, needUVs)); } } else if (Alembic::AbcGeom::INuPatch::matches(object.getHeader())) { Alembic::AbcGeom::INuPatch nurbsObj(object, Alembic::Abc::kWrapExisting); Alembic::AbcGeom::INuPatchSchema schema = nurbsObj.getSchema(); fDataProvider.reset(new NurbsTessellator(schema, needUVs)); } else if (Alembic::AbcGeom::ISubD::matches(object.getHeader())) { Alembic::AbcGeom::ISubD subdObj(object, Alembic::Abc::kWrapExisting); Alembic::AbcGeom::ISubDSchema schema = subdObj.getSchema(); fDataProvider.reset(new SubDSmoother(schema, needUVs)); } else { DisplayWarning(kUnsupportedGeomMsg); } fShapeData = ShapeData::create(); fShapeData->setAnimTimeRange(fDataProvider->getAnimTimeRange()); // Whole object material assignment MString material; std::string materialAssignmentPath; if (Alembic::AbcMaterial::getMaterialAssignmentPath( object, materialAssignmentPath)) { // We assume all materials are stored in "/materials" std::string prefix = "/"; prefix += kMaterialsObject; prefix += "/"; if (std::equal(prefix.begin(), prefix.end(), materialAssignmentPath.begin())) { std::string objectName = materialAssignmentPath.substr(prefix.size()).c_str(); // No material inheritance here. if (objectName.find("/") == std::string::npos) { material = objectName.c_str(); } } } if (material.length() > 0) { fShapeData->setMaterial(material); } } AlembicCacheMeshReader::~AlembicCacheMeshReader() { fDataProvider.reset(); } bool AlembicCacheMeshReader::valid() const { return fDataProvider && fDataProvider->valid(); } TimeInterval AlembicCacheMeshReader::sampleHierarchy(double seconds, const MMatrix& rootMatrix, TimeInterval rootMatrixInterval) { CheckInterruptAndPause("sampling hierarchy"); // Fill the sample if this sample has not been read if (!fDataProvider->getBBoxAndVisValidityInterval().contains(seconds)) { // Read minimal data to construct the hierarchy fDataProvider->fillBBoxAndVisSample(seconds); } TimeInterval validityInterval = fDataProvider->getBBoxAndVisValidityInterval(); // Compute bounding box in root sub-node axis fBoundingBox = fDataProvider->getBoundingBox(); fBoundingBox.transformUsing(rootMatrix); fBoundingBoxValidityInterval = rootMatrixInterval & fDataProvider->getBoundingBoxValidityInterval(); // We only add the sample if it is the first sample of the // interval. if (seconds == validityInterval.startTime()) { boost::shared_ptr<const ShapeSample> sample = fDataProvider->getBBoxPlaceHolderSample(seconds); fShapeData->addSample(sample); } return validityInterval; } TimeInterval AlembicCacheMeshReader::sampleShape(double seconds) { CheckInterruptAndPause("sampling shape"); // Fill the sample if this sample has not been read if (!fDataProvider->getValidityInterval().contains(seconds)) { fDataProvider->fillTopoAndAttrSample(seconds); } TimeInterval validityInterval = fDataProvider->getValidityInterval(); // We only add the sample if it is the first sample of the // interval. if (seconds == validityInterval.startTime()) { if (fDataProvider->isVisible()) { boost::shared_ptr<const ShapeSample> sample = fDataProvider->getSample(seconds); fShapeData->addSample(sample); float alpha = sample->diffuseColor()[3]; if (alpha > 0.0f && alpha < 1.0f) { fNumTransparentSample++; } } else { // hidden geometry, simply append an empty sample boost::shared_ptr<ShapeSample> sample = ShapeSample::createEmptySample(seconds); fShapeData->addSample(sample); } } return validityInterval; } SubNode::MPtr AlembicCacheMeshReader::get() const { if (fShapeData->getSamples().size() == 1 && !fShapeData->getSamples().begin()->second->visibility()) { // Prune the node entirely if it is hidden. return SubNode::MPtr(); } SubNode::MPtr subNode = SubNode::create(MString(fName.c_str()), fShapeData); if (fNumTransparentSample == 0) { subNode->setTransparentType(SubNode::kOpaque); } else if (fNumTransparentSample == fShapeData->getSamples().size()) { subNode->setTransparentType(SubNode::kTransparent); } else { subNode->setTransparentType(SubNode::kOpaqueAndTransparent); } return subNode; } MBoundingBox AlembicCacheMeshReader::getBoundingBox() const { return fBoundingBox; } TimeInterval AlembicCacheMeshReader::getBoundingBoxValidityInterval() const { return fBoundingBoxValidityInterval; } TimeInterval AlembicCacheMeshReader::getAnimTimeRange() const { return fShapeData->animTimeRange(); } void AlembicCacheMeshReader::saveAndReset(AlembicCacheReader& cacheReader) { // Clear the content of this reader for reuse. fBoundingBox.clear(); fBoundingBoxValidityInterval = TimeInterval(TimeInterval::kInvalid); fNumTransparentSample = 0; // Create a new shape data. ShapeData::MPtr newShapeData = ShapeData::create(); // Animation time range and material assignment won't change so just copy them. newShapeData->setAnimTimeRange(fShapeData->animTimeRange()); newShapeData->setMaterials(fShapeData->getMaterials()); // Release the reference to the old shape data to avoid instability. fShapeData = newShapeData; Ptr thisPtr = shared_from_this(); cacheReader.saveReader(fFullName, thisPtr); } //============================================================================== // CLASS AlembicCacheMaterialReader //============================================================================== AlembicCacheMaterialReader::AlembicCacheMaterialReader(Alembic::Abc::IObject abcObj) : fName(abcObj.getName()), fValidityInterval(TimeInterval::kInvalid) { // Wrap with IMaterial Alembic::AbcMaterial::IMaterial material(abcObj, Alembic::Abc::kWrapExisting); // Material schema Alembic::AbcMaterial::IMaterialSchema schema = material.getSchema(); // Create the material graph fMaterialGraph = boost::make_shared<MaterialGraph>(MString(fName.c_str())); // The number of nodes in the material size_t numNetworkNodes = schema.getNumNetworkNodes(); // Map: name -> (IMaterialSchema::NetworkNode,MaterialNode) typedef std::pair<Alembic::AbcMaterial::IMaterialSchema::NetworkNode,MaterialNode::MPtr> NodePair; typedef boost::unordered_map<std::string,NodePair> NodeMap; NodeMap nodeMap; // Read nodes for (size_t i = 0; i < numNetworkNodes; i++) { Alembic::AbcMaterial::IMaterialSchema::NetworkNode abcNode = schema.getNetworkNode(i); std::string target; if (!abcNode.valid() || !abcNode.getTarget(target) || target != kMaterialsGpuCacheTarget) { continue; // Invalid node } std::string type; if (!abcNode.getNodeType(type) || type.empty()) { continue; // Invalid type } // Node name std::string name = abcNode.getName(); assert(!name.empty()); // Create material node MaterialNode::MPtr node = MaterialNode::create(name.c_str(), type.c_str()); assert(node); fMaterialGraph->addNode(node); nodeMap.insert(std::make_pair(name, std::make_pair(abcNode, node))); } // Initialize property caches. BOOST_FOREACH (NodeMap::value_type& val, nodeMap) { Alembic::AbcMaterial::IMaterialSchema::NetworkNode& abcNode = val.second.first; MaterialNode::MPtr& node = val.second.second; // Loop over all child properties Alembic::Abc::ICompoundProperty compoundProp = abcNode.getParameters(); size_t numProps = compoundProp.getNumProperties(); for (size_t i = 0; i < numProps; i++) { const Alembic::Abc::PropertyHeader& header = compoundProp.getPropertyHeader(i); const std::string propName = header.getName(); if (Alembic::Abc::IBoolProperty::matches(header)) { fBoolCaches.push_back( ScalarMaterialProp<Alembic::Abc::IBoolProperty>(compoundProp, propName, node)); } else if (Alembic::Abc::IInt32Property::matches(header)) { fInt32Caches.push_back( ScalarMaterialProp<Alembic::Abc::IInt32Property>(compoundProp, propName, node)); } else if (Alembic::Abc::IFloatProperty::matches(header)) { fFloatCaches.push_back( ScalarMaterialProp<Alembic::Abc::IFloatProperty>(compoundProp, propName, node)); } else if (Alembic::Abc::IV2fProperty::matches(header)) { fFloat2Caches.push_back( ScalarMaterialProp<Alembic::Abc::IV2fProperty>(compoundProp, propName, node)); } else if (Alembic::Abc::IV3fProperty::matches(header)) { fFloat3Caches.push_back( ScalarMaterialProp<Alembic::Abc::IV3fProperty>(compoundProp, propName, node)); } else if (Alembic::Abc::IC3fProperty::matches(header)) { fRGBCaches.push_back( ScalarMaterialProp<Alembic::Abc::IC3fProperty>(compoundProp, propName, node)); } else if (Alembic::Abc::IWstringProperty::matches(header)) { fStringCaches.push_back( ScalarMaterialProp<Alembic::Abc::IWstringProperty>(compoundProp, propName, node)); } } } // Read connections BOOST_FOREACH (NodeMap::value_type& val, nodeMap) { Alembic::AbcMaterial::IMaterialSchema::NetworkNode& abcNode = val.second.first; MaterialNode::MPtr& node = val.second.second; // Loop over the connections and connect properties size_t numConnections = abcNode.getNumConnections(); for (size_t i = 0; i < numConnections; i++) { std::string inputName, connectedNodeName, connectedOutputName; abcNode.getConnection(i, inputName, connectedNodeName, connectedOutputName); // Find destination property MaterialProperty::MPtr prop = node->findProperty(inputName.c_str()); // Find source node MaterialNode::MPtr srcNode; NodeMap::iterator it = nodeMap.find(connectedNodeName); if (it != nodeMap.end()) { srcNode = (*it).second.second; } // Find source property MaterialProperty::MPtr srcProp; if (srcNode) { srcProp = srcNode->findProperty(connectedOutputName.c_str()); } // Make the connection if (prop && srcNode && srcProp) { prop->connect(srcNode, srcProp); } } } // Read Terminal node (ignore output) std::string rootNodeName, rootOutput; if (schema.getNetworkTerminal(kMaterialsGpuCacheTarget, kMaterialsGpuCacheType, rootNodeName, rootOutput)) { NodeMap::iterator it = nodeMap.find(rootNodeName); if (it != nodeMap.end()) { fMaterialGraph->setRootNode((*it).second.second); } } } AlembicCacheMaterialReader::~AlembicCacheMaterialReader() {} TimeInterval AlembicCacheMaterialReader::sampleMaterial(double seconds) { TimeInterval validityInterval(TimeInterval::kInfinite); BOOST_FOREACH (ScalarMaterialProp<Alembic::Abc::IBoolProperty>& cache, fBoolCaches) { validityInterval &= cache.sample(seconds); } BOOST_FOREACH (ScalarMaterialProp<Alembic::Abc::IInt32Property>& cache, fInt32Caches) { validityInterval &= cache.sample(seconds); } BOOST_FOREACH (ScalarMaterialProp<Alembic::Abc::IFloatProperty>& cache, fFloatCaches) { validityInterval &= cache.sample(seconds); } BOOST_FOREACH (ScalarMaterialProp<Alembic::Abc::IV2fProperty>& cache, fFloat2Caches) { validityInterval &= cache.sample(seconds); } BOOST_FOREACH (ScalarMaterialProp<Alembic::Abc::IV3fProperty>& cache, fFloat3Caches) { validityInterval &= cache.sample(seconds); } BOOST_FOREACH (ScalarMaterialProp<Alembic::Abc::IC3fProperty>& cache, fRGBCaches) { validityInterval &= cache.sample(seconds); } BOOST_FOREACH (ScalarMaterialProp<Alembic::Abc::IWstringProperty>& cache, fStringCaches) { validityInterval &= cache.sample(seconds); } return validityInterval; } MaterialGraph::MPtr AlembicCacheMaterialReader::get() const { // Check invalid graph. if (!fMaterialGraph || !fMaterialGraph->rootNode() || fMaterialGraph->getNodes().empty()) { return MaterialGraph::MPtr(); } return fMaterialGraph; } } // namespace CacheReaderAlembicPrivate //============================================================================== // CLASS AlembicCacheReader //============================================================================== boost::shared_ptr<CacheReader> AlembicCacheReader::create(const MFileObject& file) { return boost::make_shared<AlembicCacheReader>(file); } AlembicCacheReader::AlembicCacheReader(const MFileObject& file) : fFile(file) { // Open the archive for reading. MString resolvedFullName = file.resolvedFullName(); try { tbb::mutex::scoped_lock alembicLock(gsAlembicMutex); if (resolvedFullName.length() != 0 && std::ifstream(resolvedFullName.asChar()).good()) { Alembic::AbcCoreFactory::IFactory factory; // Disable Alembic caching as we have implemented our own // caching... factory.setSampleCache( Alembic::AbcCoreAbstract::ReadArraySampleCachePtr()); factory.setPolicy(Alembic::Abc::ErrorHandler::kThrowPolicy); fAbcArchive = factory.getArchive(resolvedFullName.asChar()); // File exists but Alembic fails to open. if (!fAbcArchive.valid()) { DisplayError(kFileFormatWrongMsg, file.rawFullName()); } } else { // File doesn't exist. DisplayError(kFileDoesntExistMsg, file.rawFullName()); } } catch (CacheReaderInterruptException& ex) { // pass upward throw ex; } catch (std::exception& ex) { //The resolved full name will be empty if the resolution fails. //Print the raw full name in case of this situation. DisplayError(kCacheOpenFileErrorMsg, file.rawFullName(), ex.what()); } } AlembicCacheReader::~AlembicCacheReader() { try { tbb::mutex::scoped_lock alembicLock(gsAlembicMutex); fAbcArchive.reset(); } catch (CacheReaderInterruptException& ex) { // pass upward throw ex; } catch (std::exception& ex) { DisplayError(kCloseFileErrorMsg, fFile.resolvedFullName(), ex.what()); } } bool AlembicCacheReader::valid() const { tbb::mutex::scoped_lock alembicLock(gsAlembicMutex); return fAbcArchive.valid(); } bool AlembicCacheReader::validateGeomPath( const MString& geomPath, MString& validatedGeomPath) const { if (!valid()) { validatedGeomPath = MString("|"); return false; } try { tbb::mutex::scoped_lock alembicLock(gsAlembicMutex); // path: |xform1|xform2|meshShape MStringArray pathArray; geomPath.split('|', pathArray); bool valid = true; // find the mesh in Alembic archive validatedGeomPath = MString(); Alembic::Abc::IObject current = fAbcArchive.getTop(); for (unsigned int i = 0; i < pathArray.length(); i++) { MString step = pathArray[i]; current = current.getChild(step.asChar()); if (!current.valid()) { valid = false; break; } validatedGeomPath += MString("|"); validatedGeomPath += step; } if (validatedGeomPath.length() == 0) { validatedGeomPath = MString("|"); } return valid; } catch (CacheReaderInterruptException& ex) { // pass upward throw ex; } catch (std::exception& ex) { DisplayError(kReadMeshErrorMsg, fFile.resolvedFullName(), geomPath, ex.what()); validatedGeomPath = MString("|"); return false; } } SubNode::Ptr AlembicCacheReader::readScene( const MString& geomPath, bool needUVs) { // Read sub-node hierarchy SubNode::Ptr top = readHierarchy(geomPath, needUVs); if (!top) return SubNode::Ptr(); // Extract shape paths ShapePathVisitor::ShapePathAndSubNodeList shapeGeomPaths; ShapePathVisitor shapePathVisitor(shapeGeomPaths); top->accept(shapePathVisitor); // The absolute shape path in the archive is prefix+shapePath MString prefix; int lastStep = geomPath.rindexW('|'); if (lastStep > 0) { prefix = geomPath.substringW(0, lastStep - 1); } // Read shapes BOOST_FOREACH (const ShapePathVisitor::ShapePathAndSubNode& pair, shapeGeomPaths) { SubNode::Ptr shape = readShape(prefix + pair.first, needUVs); if (shape && pair.first.length() > 0) { ReplaceSubNodeData(top, shape, pair.first); } } // Update transparent type SubNodeTransparentTypeVisitor transparentTypeVisitor; top->accept(transparentTypeVisitor); return top; } SubNode::Ptr AlembicCacheReader::readHierarchy( const MString& geomPath, bool needUVs) { using namespace CacheReaderAlembicPrivate; if (!valid()) return SubNode::Ptr(); try { tbb::mutex::scoped_lock alembicLock(gsAlembicMutex); // path: |xform1|xform2|meshShape MStringArray pathArray; geomPath.split('|', pathArray); Alembic::Abc::IObject current = fAbcArchive.getTop(); AlembicCacheObjectReader::Ptr reader; if (pathArray.length() == 0) { // Determine the number of children under the top level object. // We skip objects that we don't recognize. (Cameras, Materials, ..) size_t numChildren = 0; size_t lastChild = 0; for (size_t i = 0; i < current.getNumChildren(); i++) { if (Alembic::AbcGeom::IPolyMesh::matches(current.getChildHeader(i)) || Alembic::AbcGeom::INuPatch::matches(current.getChildHeader(i)) || Alembic::AbcGeom::ISubD::matches(current.getChildHeader(i)) || Alembic::AbcGeom::IXform::matches(current.getChildHeader(i))) { numChildren++; lastChild = i; } } if (numChildren == 1) { current = Alembic::Abc::IObject( current, current.getChildHeader(lastChild).getName()); if (current.valid()) reader = AlembicCacheObjectReader::create( current, needUVs); } else if (numChildren > 1) { // The top level object is not a proper xform object. We // therefore have to create a dummy top-level transform in // that case. reader = boost::make_shared<AlembicCacheTopReader>( current, needUVs); } } else { // find the top level node in the Alembic archive bool geometryFound = true; for (unsigned int i = 0; i < pathArray.length(); i++) { MString step = pathArray[i]; current = current.getChild(step.asChar()); if (!current.valid()) { geometryFound = false; break; } } if (geometryFound) reader = AlembicCacheObjectReader::create(current, needUVs); } if (!reader || !reader->valid()) return SubNode::Ptr(); // Each time samplings only records the start time, i.e. there // is no way to ask for the end time of a TimeSampling! // Therefore, to determine the end of the animation, we simply // loop until time no longer advances... { TimeInterval interval = reader->sampleHierarchy( -std::numeric_limits<double>::max(), MMatrix::identity, TimeInterval::kInfinite); while (interval.endTime() != std::numeric_limits<double>::max()) { interval = reader->sampleHierarchy( interval.endTime(), MMatrix::identity, TimeInterval::kInfinite); } } // The sub-node hierarchy with bounding box place holders. SubNode::Ptr top = reader->get(); // Save the object readers for reuse. reader->saveAndReset(*this); return top; } catch (CacheReaderInterruptException& ex) { // pass upward throw ex; } catch (std::exception& ex) { DisplayError(kReadMeshErrorMsg, fFile.resolvedFullName(), geomPath, ex.what()); return SubNode::Ptr(); } } SubNode::Ptr AlembicCacheReader::readShape( const MString& geomPath, bool needUVs) { using namespace CacheReaderAlembicPrivate; if (!valid()) return SubNode::Ptr(); try { tbb::mutex::scoped_lock alembicLock(gsAlembicMutex); AlembicCacheObjectReader::Ptr reader; // Search saved readers ObjectReaderMap::iterator iter = fSavedReaders.find(geomPath.asChar()); if (iter != fSavedReaders.end()) { reader = (*iter).second; } else { // path: |xform1|xform2|meshShape MStringArray pathArray; geomPath.split('|', pathArray); Alembic::Abc::IObject current = fAbcArchive.getTop(); if (pathArray.length() > 0) { // Find the shape in the Alembic archive bool geometryFound = true; for (unsigned int i = 0; i < pathArray.length(); i++) { MString step = pathArray[i]; current = current.getChild(step.asChar()); if (!current.valid()) { geometryFound = false; break; } } if (geometryFound) { reader = AlembicCacheObjectReader::create(current, needUVs); } } } if (!reader || !reader->valid()) return SubNode::Ptr(); // Each time samplings only records the start time, i.e. there // is no way to ask for the end time of a TimeSampling! // Therefore, to determine the end of the animation, we simply // loop until time no longer advances... { TimeInterval interval = reader->sampleShape( -std::numeric_limits<double>::max()); while (interval.endTime() != std::numeric_limits<double>::max()) { interval = reader->sampleShape( interval.endTime()); } } // The sub-node with mesh shape data. SubNode::Ptr top = reader->get(); // Save the object readers for reuse. reader->saveAndReset(*this); return top; } catch (CacheReaderInterruptException& ex) { // pass upward throw ex; } catch (std::exception& ex) { DisplayError(kReadMeshErrorMsg, fFile.resolvedFullName(), geomPath, ex.what()); return SubNode::Ptr(); } } MaterialGraphMap::Ptr AlembicCacheReader::readMaterials() { using namespace CacheReaderAlembicPrivate; if (!valid()) return MaterialGraphMap::Ptr(); try { tbb::mutex::scoped_lock alembicLock(gsAlembicMutex); // Find "/materials" Alembic::Abc::IObject topObject = fAbcArchive.getTop(); Alembic::Abc::IObject materialsObject = topObject.getChild(kMaterialsObject); // "/materials" doesn't exist! if (!materialsObject.valid()) { return MaterialGraphMap::Ptr(); } MaterialGraphMap::MPtr materials = boost::make_shared<MaterialGraphMap>(); // Read materials one by one. Hierarchical materials are not supported. for (size_t i = 0; i < materialsObject.getNumChildren(); i++) { Alembic::Abc::IObject object = materialsObject.getChild(i); if (Alembic::AbcMaterial::IMaterial::matches(object.getHeader())) { AlembicCacheMaterialReader reader(object); // Read the material TimeInterval interval = reader.sampleMaterial( -std::numeric_limits<double>::max()); while (interval.endTime() != std::numeric_limits<double>::max()) { interval = reader.sampleMaterial(interval.endTime()); } MaterialGraph::MPtr graph = reader.get(); if (graph) { materials->addMaterialGraph(graph); } } } // No materials.. if (materials->getGraphs().empty()) { return MaterialGraphMap::Ptr(); } return materials; } catch (CacheReaderInterruptException& ex) { // pass upward throw ex; } catch (std::exception& ex) { DisplayError(kReadFileErrorMsg, fFile.resolvedFullName(), ex.what()); return MaterialGraphMap::Ptr(); } } bool AlembicCacheReader::readAnimTimeRange(GPUCache::TimeInterval& range) { if (!valid()) return false; try { tbb::mutex::scoped_lock alembicLock(gsAlembicMutex); // Try *.samples property. double samplesMin = std::numeric_limits<double>::infinity(); double samplesMax = -std::numeric_limits<double>::infinity(); unsigned int numTimeSamplings = fAbcArchive.getNumTimeSamplings(); for (unsigned int i = 0; i < numTimeSamplings; i++) { // *.samples property std::stringstream propName; propName << i << ".samples"; Alembic::Abc::IUInt32Property samplesProp( fAbcArchive.getTop().getProperties(), propName.str(), Alembic::Abc::ErrorHandler::kQuietNoopPolicy ); // The time sampling. Alembic::Abc::TimeSamplingPtr timeSampling = fAbcArchive.getTimeSampling(i); if (samplesProp && timeSampling) { unsigned int numSamples = 0; samplesProp.get(numSamples); if (numSamples > 0) { samplesMin = std::min(samplesMin, timeSampling->getSampleTime(0)); samplesMax = std::max(samplesMax, timeSampling->getSampleTime(numSamples - 1)); } } } // Successfully read *.samples property. if (samplesMin <= samplesMax) { range = TimeInterval(samplesMin, samplesMax); return true; } // Try archive bounds property. Alembic::Abc::IBox3dProperty boxProp = Alembic::AbcGeom::GetIArchiveBounds( fAbcArchive, Alembic::Abc::ErrorHandler::kQuietNoopPolicy); if (boxProp) { // The time range of the archive bounds property. size_t numSamples = boxProp.getNumSamples(); Alembic::Abc::TimeSamplingPtr timeSampling = boxProp.getTimeSampling(); if (numSamples > 0 && timeSampling) { range = TimeInterval( timeSampling->getSampleTime(0), timeSampling->getSampleTime(numSamples - 1) ); return true; } } // No enough animation range info on the archive. return false; } catch (CacheReaderInterruptException& ex) { // pass upward throw ex; } catch (std::exception& ex) { DisplayError(kReadFileErrorMsg, fFile.resolvedFullName(), ex.what()); return false; } } void AlembicCacheReader::saveReader( const std::string& fullName, CacheReaderAlembicPrivate::AlembicCacheObjectReader::Ptr& reader ) { // We save the object reader in this AlembicCacheReader so that // the object reader won't be destroyed after readHierarchy() or readShape(). // The life time of the object reader would be the same as this AlembicCacheReader. // The object reader can be reused as long as the Alembic archive is not closed. // There are 2 situations that will cause an Alembic archive to be closed: // 1) There are no references to CacheReaderProxy. (Read complete) // 2) Maya is running out of file handles. (Temporarily close some inactive archives) if (reader && reader->valid()) { std::string geometryPath = fullName; std::replace(geometryPath.begin(), geometryPath.end(), '/', '|'); fSavedReaders.insert(std::make_pair(geometryPath, reader)); } } } // namespace GPUCache
33.982516
117
0.608753
[ "mesh", "geometry", "object", "shape", "vector", "transform" ]
64600dcd977f0e00623ec058223c7c17926fa61f
2,520
cpp
C++
Algorithms/Work 5/taskA.cpp
alexstrive/Ifmo-Works
1f4fb67dfde9c4e14130b6614be9ec4b0642d3c0
[ "Unlicense" ]
4
2017-10-06T08:26:23.000Z
2017-10-17T12:40:52.000Z
Algorithms/Work 5/taskA.cpp
novopashin/Ifmo-Works
1f4fb67dfde9c4e14130b6614be9ec4b0642d3c0
[ "Unlicense" ]
5
2017-11-16T18:01:51.000Z
2018-01-15T18:05:58.000Z
Algorithms/Work 5/taskA.cpp
allordiron/LabWorks
1f4fb67dfde9c4e14130b6614be9ec4b0642d3c0
[ "Unlicense" ]
1
2017-12-08T06:48:42.000Z
2017-12-08T06:48:42.000Z
#include <fstream> #include <vector> using namespace std; class LinkedList { private: class Node { public: int value; Node *next; explicit Node(int data, Node *next = nullptr) : value(data), next(next) {}; }; Node *head = nullptr; public: void insert(const int value) { Node *wrappedNode = new Node(value, head); head = wrappedNode; } void remove(const int targetValue) { if (head && head->value == targetValue) { head = nullptr; return; } auto currentNode = head; while (currentNode && currentNode->next != nullptr) { if (currentNode->next->value == targetValue) { currentNode->next = currentNode->next->next; delete currentNode->next; return; } currentNode = currentNode->next; } } bool doesExist(int targetValue) { Node *currentNode = this->head; if (currentNode && currentNode->value == targetValue) { return true; } while (currentNode && currentNode->next != nullptr) { if (currentNode->next->value == targetValue) { return true; } currentNode = currentNode->next; } return false; } }; class HashTable { private: vector<LinkedList> list; const int MAX_SIZE = 100000; // TODO: another hash function? int hashify(int value) { return value % MAX_SIZE; } public: HashTable() { list.resize(MAX_SIZE); } void insert(const int value) { if (!doesExist(value)) { int hash = hashify(value); list[hash].insert(value); } } void remove(const int value) { int hash = hashify(value); list[hash].remove(value); } bool doesExist(const int value) { int hash = hashify(value); return list[hash].doesExist(value); } }; int main() { string command; ifstream input("set.in"); ofstream output("set.out"); HashTable hashTable; while (input >> command) { int value; input >> value; if (command == "insert") { hashTable.insert(value); } if (command == "delete") { hashTable.remove(value); } if (command == "exists") { output << (hashTable.doesExist(value) ? "true" : "false") << endl; } } return 0; }
20
83
0.522619
[ "vector" ]
6468125e9c2a5a70e3e384a23cdd549f74b2aca0
206
cpp
C++
engine/SfmlEngine/draw.cpp
Quinn-R/HackingGameG
e22c6f326b3efbcfa6b9610638bc8633b88741b5
[ "Unlicense" ]
null
null
null
engine/SfmlEngine/draw.cpp
Quinn-R/HackingGameG
e22c6f326b3efbcfa6b9610638bc8633b88741b5
[ "Unlicense" ]
null
null
null
engine/SfmlEngine/draw.cpp
Quinn-R/HackingGameG
e22c6f326b3efbcfa6b9610638bc8633b88741b5
[ "Unlicense" ]
null
null
null
#include "../SfmlEngine.hpp" void SfmlEngine::draw() { clear(); display(); } void SfmlEngine::draw(sf::Color col, std::vector<sf::RectangleShape> &rects) { clear(col); drawEntity(rects); display(); }
17.166667
78
0.669903
[ "vector" ]
646889df9f2209812cf2924fe0b93e61bcd4ab7c
41,740
cpp
C++
LotteryScan/Helper/common.cpp
agelessZeal/LotteryScan-iOS
d1115a0f7a9cf7323e931eba85a74614939e803a
[ "MIT" ]
null
null
null
LotteryScan/Helper/common.cpp
agelessZeal/LotteryScan-iOS
d1115a0f7a9cf7323e931eba85a74614939e803a
[ "MIT" ]
null
null
null
LotteryScan/Helper/common.cpp
agelessZeal/LotteryScan-iOS
d1115a0f7a9cf7323e931eba85a74614939e803a
[ "MIT" ]
null
null
null
#include "common.h" #include "Coupon.h" bool insertCouponTomapvector(vector <map<int, cv::Rect>>& coupon_rects) { int prev_coupon_number=0; vector <map<int, Rect>>::iterator preiter=coupon_rects.begin(); for (vector <map<int, Rect>>::iterator it=coupon_rects.begin(); it!=coupon_rects.end(); it++) { if (prev_coupon_number!=0&&prev_coupon_number!=it->size()) { if (prev_coupon_number>it->size()) { cout<<"the minus rect is added."<<endl; Rect nowonwrt=Rect(it->begin()->second); it->clear(); for (map<int,Rect>::iterator mapit=preiter->begin(); mapit!=preiter->end(); mapit++) { Rect rt=Rect(mapit->second); it->insert(make_pair(rt.x, Rect(rt.x,nowonwrt.y,rt.width,rt.height))); } } } if (it->size()<5) { return false; } preiter=it; prev_coupon_number=(int)it->size(); } return true; } bool isValidCouponRect(vector <map<int, Rect>>& coupon_rects) { int prev_coupon_number=0; for (vector <map<int, Rect>>::iterator it=coupon_rects.begin(); it!=coupon_rects.end(); it++) { if (prev_coupon_number!=0&&prev_coupon_number!=it->size()) { cout<<"from the isvalid now row "<<it->size()<<" pre "<<prev_coupon_number<<endl; return false; } if (it->size()<5) { return false; } prev_coupon_number=(int)it->size(); } return true; } void merge_conflict_rects(vector<Rect> &rects) { bool is_finished = false; while (is_finished == false) { is_finished = true; int min_x, min_y, max_x, max_y; if (rects.size() == 0) break; for (auto it = rects.begin(); it != rects.end() - 1; it++) { for (auto it1 = it + 1; it1 != rects.end(); it1++) { if (it->contains(it1->tl()) || it->contains(it1->br()) || it->contains(Point(it1->tl().x, it1->br().y-1)) || it->contains(Point(it1->br().x, it1->tl().y+1)) || it1->contains(it->tl()) || it1->contains(it->br()) || it1->contains(Point(it->tl().x, it->br().y-1)) || it1->contains(Point(it->br().x, it->tl().y+1))) { min_x = it->tl().x < it1->tl().x ? it->tl().x : it1->tl().x; max_x = it->br().x > it1->br().x ? it->br().x : it1->br().x; min_y = it->tl().y < it1->tl().y ? it->tl().y : it1->tl().y; max_y = it->br().y > it1->br().y ? it->br().y : it1->br().y; it->x = min_x; it->y = min_y; it->width = max_x - min_x; it->height = max_y - min_y; rects.erase(it1); is_finished = false; break; } } if (is_finished == false) break; } } } void remove_include_rects(vector<Rect> &rects) { bool is_finished = false; while (is_finished == false) { is_finished = true; int min_x, min_y, max_x, max_y; if (rects.size() == 0) break; for (auto it = rects.begin(); it != rects.end() - 1; it++) { for (auto it1 = it + 1; it1 != rects.end(); it1++) { if ((it->contains(it1->tl()) &&it->contains(Point(it1->br().x-2,it1->br().y-2))) || (it1->contains(it->tl()) && it1->contains(Point(it->br().x - 1, it->br().y - 1)))) { min_x = it->tl().x < it1->tl().x ? it->tl().x : it1->tl().x; max_x = it->br().x > it1->br().x ? it->br().x : it1->br().x; min_y = it->tl().y < it1->tl().y ? it->tl().y : it1->tl().y; max_y = it->br().y > it1->br().y ? it->br().y : it1->br().y; it->x = min_x; it->y = min_y; it->width = max_x - min_x; it->height = max_y - min_y; rects.erase(it1); is_finished = false; break; } ///////// float maxheight = it->height > it1->height ? it->height : it1->height; int intervlaWidth = ceil(maxheight*0.1); if ((abs(it->br().x - it1->tl().x) <= intervlaWidth &&it->br().x<it1->br().x && it->tl().y >= it1->tl().y&&it->br().y <= it1->br().y+2) || (it->contains(Point(it1->br().x+3,it1->tl().y+3)))|| (it1->contains(Point(it->br().x+3,it->tl().y+3)))|| (abs(it->br().x - it1->tl().x) <= intervlaWidth &&it->br().x<it1->br().x && it1->tl().y >= it->tl().y&&it1->br().y <= it->br().y+2)|| (abs(it1->br().x - it->tl().x) <= intervlaWidth &&it1->br().x < it->br().x && it1->tl().y >= it->tl().y&&it1->br().y <= it->br().y+2) || (abs(it1->br().x - it->tl().x) <= intervlaWidth &&it1->br().x < it->br().x && it->tl().y >= it1->tl().y&&it->br().y <= it1->br().y+2)) { min_x = it->tl().x < it1->tl().x ? it->tl().x : it1->tl().x; max_x = it->br().x > it1->br().x ? it->br().x : it1->br().x; min_y = it->tl().y < it1->tl().y ? it->tl().y : it1->tl().y; max_y = it->br().y > it1->br().y ? it->br().y : it1->br().y; it->x = min_x; it->y = min_y; it->width = max_x - min_x; it->height = max_y - min_y; rects.erase(it1); is_finished = false; break; } ///////////// } if (is_finished == false) break; } } } void merge_height_rects(vector<cv::Rect> &rects) { bool is_finished = false; while (is_finished == false) { is_finished = true; int min_x, min_y, max_x, max_y; if (rects.size() == 0) break; for (auto it = rects.begin(); it != rects.end() - 1; it++) { for (auto it1 = it + 1; it1 != rects.end(); it1++) { //float maxheight = it->height > it1->height ? it->height : it1->height; //int interWidth = ceil(maxheight*0.4); int interWidth = 10; int interHeight = 6; if (it->contains(it1->tl()) || it->contains(it1->br()) || it->contains(Point(it1->tl().x, it1->tl().y-interHeight)) || it->contains(Point(it1->tl().x+interWidth, it1->tl().y-interHeight)) || it1->contains(it->tl()) || it1->contains(it->br()) || it1->contains(Point(it->tl().x, it->tl().y-interHeight)) || it1->contains(Point(it->tl().x+interWidth, it->tl().y-interHeight)) ) { min_x = it->tl().x < it1->tl().x ? it->tl().x : it1->tl().x; max_x = it->br().x > it1->br().x ? it->br().x : it1->br().x; min_y = it->tl().y < it1->tl().y ? it->tl().y : it1->tl().y; max_y = it->br().y > it1->br().y ? it->br().y : it1->br().y; it->x = min_x; it->y = min_y; it->width = max_x - min_x; it->height = max_y - min_y; rects.erase(it1); is_finished = false; break; } } if (is_finished == false) break; } } } void merge_width_rects(vector<Rect> &rects) { bool is_finished = false; while (is_finished == false) { is_finished = true; int min_x, min_y, max_x, max_y; if (rects.size() == 0) break; for (auto it = rects.begin(); it != rects.end() - 1; it++) { for (auto it1 = it + 1; it1 != rects.end(); it1++) { //float maxheight = it->height > it1->height ? it->height : it1->height; //int interWidth = ceil(maxheight*0.4); int interWidth = 4; int interHeight = 5; if (( ((abs(it->tl().y - it1->tl().y) <=interHeight)&&(abs(it->br().y - it1->br().y) <= interHeight))|| (it->br().y>it1->tl().y&&it->br().y<it1->br().y&&it->tl().y<it1->br().y&&it->tl().y+interHeight>it1->tl().y)|| (it1->br().y>it->tl().y&&it1->br().y<it->br().y&&it1->tl().y<it->br().y&&it1->tl().y+interHeight>it->tl().y) )&& ( (abs(it1->tl().x - it->br().x) <= interWidth &&it->br().x < it1->br().x)|| (abs(it->br().x - it1->tl().x) <= interWidth &&it->br().x < it1->br().x )|| (abs(it1->br().x - it->tl().x) <= interWidth &&it1->br().x < it->br().x)|| (abs(it1->br().x - it->tl().x) <= interWidth &&it1->br().x < it->br().x )|| (abs(it1->tl().x - it->tl().x) <= interWidth&&abs(it1->br().x - it->br().x) <= interWidth) )) { min_x = it->tl().x < it1->tl().x ? it->tl().x : it1->tl().x; max_x = it->br().x > it1->br().x ? it->br().x : it1->br().x; min_y = it->tl().y < it1->tl().y ? it->tl().y : it1->tl().y; max_y = it->br().y > it1->br().y ? it->br().y : it1->br().y; it->x = min_x; it->y = min_y; it->width = max_x - min_x; it->height = max_y - min_y; rects.erase(it1); is_finished = false; break; } } if (is_finished == false) break; } } } void merge_width_rects_other(vector<cv::Rect> &rects) { bool is_finished = false; while (is_finished == false) { is_finished = true; int min_x, min_y, max_x, max_y; if (rects.size() == 0) break; for (auto it = rects.begin(); it != rects.end() - 1; it++) { for (auto it1 = it + 1; it1 != rects.end(); it1++) { //float maxheight = it->height > it1->height ? it->height : it1->height; //int interWidth = ceil(maxheight*0.4); int interWidth = 30; int interHeight = 10; if ((abs(it1->tl().x - it->br().x) <= interWidth &&it->br().x < it1->br().x && abs(it->tl().y - it1->tl().y) <=interHeight&&abs(it->br().y - it1->br().y) <= interHeight) || (abs(it->br().x - it1->tl().x) <= interWidth &&it->br().x < it1->br().x && abs(it1->tl().y - it->tl().y) <=interHeight&&abs(it1->br().y -it->br().y) <=interHeight) || (abs(it1->br().x - it->tl().x) <= interWidth &&it1->br().x < it->br().x && abs(it1->tl().y - it->tl().y) <=interHeight&&abs(it1->br().y - it->br().y) <=interHeight) || (abs(it1->br().x - it->tl().x) <= interWidth &&it1->br().x < it->br().x && abs(it->tl().y - it1->tl().y) <=interHeight&&abs(it->br().y - it1->br().y) <=interHeight)|| (abs(it1->tl().x - it->br().x) <= interWidth &&it1->tl().x > it->br().x && (it->tl().y < it1->tl().y) &&((it->br().y > it1->br().y)||abs(it1->br().y -it->br().y) <=interHeight ))|| // (it1->tl().x <= interWidth+it->br().x&& (it->tl().y+10 >= it1->tl().y ) &&((it->br().y <= it1->br().y+10) ))|| // (it->tl().x <= interWidth+it1->br().x&& (it1->tl().y+10 >= it->tl().y ) &&((it1->br().y <= it->br().y+10) ))|| (abs(it->tl().x - it1->br().x) <= interWidth &&it->tl().x > it1->br().x && (it1->tl().y < it->tl().y) &&(it1->br().y > it->br().y) )) { min_x = it->tl().x < it1->tl().x ? it->tl().x : it1->tl().x; max_x = it->br().x > it1->br().x ? it->br().x : it1->br().x; min_y = it->tl().y < it1->tl().y ? it->tl().y : it1->tl().y; max_y = it->br().y > it1->br().y ? it->br().y : it1->br().y; it->x = min_x; it->y = min_y; it->width = max_x - min_x; it->height = max_y - min_y; rects.erase(it1); is_finished = false; break; } if (it->contains(it1->tl()) || it->contains(it1->br()) || it->contains(Point(it1->tl().x, it1->br().y+10)) || it->contains(Point(abs(it1->tl().x-10), it1->tl().y)) || it->contains(Point(it1->br().x, it1->tl().y+10)) || it->contains(Point(it1->br().x+5, it1->br().y+5)) || it->contains(Point(it1->br().x+10, it1->br().y+5)) || it->contains(Point(it1->br().x+5, it1->tl().y+5)) || (it->contains(Point(it1->tl().x, it1->tl().y-4)) && it->contains(Point(it1->br().x, it1->tl().y-4)))|| it1->contains(it->tl()) || it1->contains(it->br()) || it1->contains(Point(it->tl().x, it->br().y+10)) || it1->contains(Point(abs(it->tl().x-10), it->tl().y)) || it1->contains(Point(it->br().x+5, it->br().y+5)) || it1->contains(Point(it->br().x+10, it->br().y+5)) || it1->contains(Point(it->br().x+5, it->tl().y+5)) || (it1->contains(Point(it->tl().x, it->tl().y-4)) && it1->contains(Point(it->br().x, it->tl().y-4)))|| it1->contains(Point(it->br().x, it->tl().y+10))) { min_x = it->tl().x < it1->tl().x ? it->tl().x : it1->tl().x; max_x = it->br().x > it1->br().x ? it->br().x : it1->br().x; min_y = it->tl().y < it1->tl().y ? it->tl().y : it1->tl().y; max_y = it->br().y > it1->br().y ? it->br().y : it1->br().y; it->x = min_x; it->y = min_y; it->width = max_x - min_x; it->height = max_y - min_y; rects.erase(it1); is_finished = false; break; } } if (is_finished == false) break; } } } std::vector<cv::Rect> get_coupon_rects(vector<cv::Rect> &possible_rect, vector<cv::Rect> &dash_rects,Mat&src) { cout<<"from the get coupon rects:possible_rect:"<<possible_rect.size()<<endl; cout<<"from the get cooupon rects ::dash rect " <<dash_rects.size()<<endl; std::vector<cv::Rect> coupon_number_rects; //dash_rects.clear(); if (dash_rects.size()!=2) { dash_rects.clear(); bool is_finished = false; float ratiovalue = 0; while (is_finished == false) { is_finished = true; if (possible_rect.size() < 2) break; for (auto it = possible_rect.begin(); it != possible_rect.end(); it++) { if (dash_rects.size() >= 2) { is_finished = true; break; } else { ratiovalue = float(it->width) / float(it->height); if (ratiovalue > 16) { if (dash_rects.size()) { if (dash_rects.front().y > it->y) { dash_rects.insert(dash_rects.begin(), Rect(*it)); } else { dash_rects.push_back(Rect(*it)); } } else { dash_rects.push_back(Rect(*it)); } possible_rect.erase(it); is_finished = false; break; } } } if (is_finished == true) break; } } if (dash_rects.size()==2) { Rect top= dash_rects.front().y > dash_rects.back().y ? dash_rects.back() : dash_rects.front(); Rect bottom= dash_rects.front().y > dash_rects.back().y ? dash_rects.front(): dash_rects.back(); //int top_x = top.br().x >= 0 ? top.br().x : 0; int top_y = top.br().y>= 0 ? top.br().y : 0; for (auto it = possible_rect.begin(); it != possible_rect.end(); it++) { if (it->br().y > top_y&&it->br().y < bottom.br().y&&top.tl().y<it->tl().y&&bottom.tl().y+5>it->br().y) // if (it->y > dash_rects.front().br().y&&it->br().y < dash_rects.back().tl().y) { if (it->width<src.cols/7&&it->height<src.rows/4) { float ratio=float(it->height)/float(it->width); if (ratio>4.2) { coupon_number_rects.push_back(Rect(it->x-2,it->y,it->width+ratio*0.4,it->height)); } else { coupon_number_rects.push_back(Rect(*it)); } //rectangle(src, Rect(it->x-1,it->y-1,it->width+2,it->height+2), Scalar(205,4,232)); // rects.erase(it); } } } if (coupon_number_rects.size()>8) { cout<<"from the get coupon rects:coupon_number_rects:"<<coupon_number_rects.size()<<endl; return coupon_number_rects; } } return coupon_number_rects; } vector <map<int, Rect>> get_coupon_rects_new(vector<Rect>& rects, Mat&src, vector<Rect> &dash_rects) { vector <map<int, Rect>> return_rects; cout<<"get_coupon_rects_new"<<endl; if (dash_rects.size()!=2) { dash_rects.clear(); bool is_finished = false; float ratiovalue = 0; while (is_finished == false) { is_finished = true; if (rects.size() < 2) break; for (auto it = rects.begin(); it != rects.end(); it++) { // if (dash_rects.size() >= 2) // { // is_finished = true; // break; // } // else { ratiovalue = float(it->width) / float(it->height); if (ratiovalue > 16) { cout <<"@@@@@@this is dash rect"<<endl; cout << "\tx\t:" << it->x << endl; cout << "\ty\t:" << it->y << endl; cout << "\twidth\t:" << it->width << endl; cout << "\theight\t:" << it->height << endl; cout << "\tratio\t:" << ratiovalue << endl; //rectangle(src, *it, Scalar(4,4,245)); if (dash_rects.size()) { if (dash_rects.front().y > it->y) { dash_rects.insert(dash_rects.begin(), Rect(*it)); } else { dash_rects.push_back(Rect(*it)); } } else { dash_rects.push_back(Rect(*it)); } rects.erase(it); is_finished = false; break; } } } if (is_finished == true) break; } } if(dash_rects.size()>=2) { if(dash_rects.size()==2) { Rect rt1 =Rect(dash_rects.front()); Rect rt2 = Rect(dash_rects.back()); if(abs(rt1.y-rt2.y)<6) { int min_x = rt1.tl().x < rt2.tl().x ? rt1.tl().x : rt2.tl().x; int max_x = rt1.br().x > rt2.br().x ? rt1.br().x : rt2.br().x; int min_y = rt1.tl().y < rt2.tl().y ? rt1.tl().y : rt2.tl().y; int max_y = rt1.br().y > rt2.br().y ? rt1.br().y : rt2.br().y; rt1.x = min_x; rt1.y = min_y; rt1.width = max_x - min_x; rt1.height = max_y - min_y; dash_rects.clear(); dash_rects.push_back(rt1); } } merge_conflict_rects(dash_rects); cout <<"after merge dash rect :"<<dash_rects.size()<<endl; //rectangle(src, dash_rects.front(), Scalar(4,4,255),3); } ////////////////////////// if (dash_rects.size() == 2) { cout <<"the dash rect is recognized. "<<dash_rects.size()<<"other rect size "<< rects.size()<<endl; vector<Rect> coupon_number_rects; coupon_number_rects.clear(); bool is_finished = false; Rect top= dash_rects.front().y > dash_rects.back().y ? dash_rects.back() : dash_rects.front(); Rect bottom= dash_rects.front().y > dash_rects.back().y ? dash_rects.front(): dash_rects.back(); //int top_x = top.br().x >= 0 ? top.br().x : 0; int top_y = top.br().y>= 0 ? top.br().y : 0; //int min_x=top.tl().x >=bottom.tl().x? top.tl().x : bottom.tl().x; // int max_x=top.br().x >=bottom.br().x? top.br().x : bottom.br().x; // int width = abs(max_x-min_x); // int height =abs( bottom.tl().y - top.br().y); while (is_finished == false) { is_finished = true; for (auto it = rects.begin(); it != rects.end(); it++) { if (it->br().y > top_y&&it->br().y < bottom.br().y&&top.tl().y<it->tl().y&&bottom.tl().y+5>it->br().y) // if (it->y > dash_rects.front().br().y&&it->br().y < dash_rects.back().tl().y) { if (it->width<src.cols/7&&it->height<src.rows/4) { coupon_number_rects.push_back(Rect(*it)); rects.erase(it); is_finished = false; break; } } if (it == rects.end()-1) { is_finished = true; break; } } if (is_finished == true) break; } cout<<"the all detected coupon rects is "<<coupon_number_rects.size()<<endl; ///sorted the coupon number rect if (coupon_number_rects.size()>=7) { map<int, Rect> one_row_coupons; map<int, Rect> sorted_rect; for (auto it = coupon_number_rects.begin(); it != coupon_number_rects.end(); it++) { int x = it->x >= 0 ? it->x : 0; int y = it->y >= 0 ? it->y : 0; int width = it->x + it->width >= src.size().width ? src.size().width - it->x - 1 : it->width; int height = it->y + it->height >= src.size().height ? src.size().height - it->y - 1 : it->height; int key = x + y*src.size().width;//* src.size().width //rectangle(src,*it, Scalar(15,134,224) ); //rectangle(src, Rect(it->x-2,it->y-2,it->width+4,it->height+4), Scalar(20,24,244)); sorted_rect.insert(make_pair(key, Rect(x, y, width, height))); } bool isdiffer= get_map_vector_rect(sorted_rect, return_rects); /////////////////// if (isdiffer) { map<int, Rect>::iterator get_sorted_rect_iterator=return_rects.front().begin()++; Rect normalrt=Rect(return_rects.front().begin()->second); Rect cnrt=Rect(get_sorted_rect_iterator->second); // get_sorted_rect_iterator++; // Rect cnrt1=Rect(get_sorted_rect_iterator->second); // int between=cnrt.y-cnrt1.br().y>0 ? cnrt.y-cnrt1.br().y:cnrt1.y-cnrt.br().y; for (auto it = return_rects.begin(); it != return_rects.end(); it++) { Rows onerows; int compare_index=0; for (auto mapit = it->begin(); mapit != it->end(); mapit++) { compare_index++; cout<<"index"<<compare_index<<":w"<<mapit->second.width<<":h"<<mapit->second.height<<endl; Rect temprt=Rect(mapit->second); if (temprt.width>8&&temprt.width<32&&temprt.height>19&&temprt.height<42) { cnrt=Rect(temprt); } } } cout<<"nor w:"<<cnrt.width<<endl; cout<<"nor h:"<<cnrt.height<<endl; bool is_finished = false; float ratiovalue = 0; while (is_finished == false) { is_finished = true; for (auto it = sorted_rect.begin(); it != sorted_rect.end(); it++) { /////// if (it->second.width<cnrt.width*3&&(float)it->second.width/(float)cnrt.width>1.8&&abs(cnrt.height-it->second.height)<5) { //rectangle(src, it->second, Scalar(255,255,1)); cout<<"double width rect is removed"<<endl; cout<<"nor w:"<<cnrt.width<<endl; cout<<"nor h:"<<cnrt.height<<endl; cout<<"ori x:"<<it->second.x<<endl; cout<<"ori y:"<<it->second.y<<endl; cout<<"ori w:"<<it->second.width<<endl; cout<<"ori h:"<<it->second.height<<endl; cout<<"ori br x:"<<it->second.br().x<<endl; cout<<"ori br y:"<<it->second.br().y<<endl; ///it->second.height=normalrt.height; int m_key1=it->first+1; Rect newitem1=Rect(it->second.x,it->second.y,cnrt.width,it->second.height); sorted_rect.insert(make_pair(m_key1,newitem1)); int m_key=it->second.br().x-cnrt.width+(it->second.y)*src.size().width; Rect newitem=Rect(it->second.br().x-cnrt.width,it->second.y,cnrt.width,it->second.height); sorted_rect.insert(make_pair(m_key,newitem)); sorted_rect.erase(it); is_finished=false; break; } //////// if (it->second.height<normalrt.height*3&&(float)it->second.height/(float)normalrt.height>1.8&&abs(normalrt.width-it->second.width)<5) { cout<<"double height rect is removed"<<endl; ///it->second.height=normalrt.height; int m_key1=it->first+1; Rect newitem1=Rect(it->second.x,it->second.y,it->second.width,it->second.height/2-3); sorted_rect.insert(make_pair(m_key1,newitem1)); int m_key=it->second.x+(it->second.height/2+it->second.y+1)*src.size().width; Rect newitem=Rect(it->second.x,it->second.y+it->second.height/2+2,it->second.width,it->second.height/2); sorted_rect.insert(make_pair(m_key,newitem)); sorted_rect.erase(it); is_finished=false; break; } if (it->second.height<normalrt.height*4&&(float)it->second.height/(float)normalrt.height>2.8&&abs(normalrt.width-it->second.width)<5) { int m_high=it->second.height; int m_key=it->second.x+(m_high/3+it->second.y+2)*src.size().width; Rect newitem=Rect(it->second.x,it->second.y+m_high/3+1,it->second.width,m_high/3); sorted_rect.insert(make_pair(m_key,newitem)); int m_key1=it->second.x+(m_high*2/3+it->second.y+1)*src.size().width; Rect newitem1=Rect(it->second.x,it->second.y+m_high*2/3+1,it->second.width,m_high/3); sorted_rect.insert(make_pair(m_key1,newitem1)); it->second.height=normalrt.height; } if (it==sorted_rect.end()--) { is_finished=true; break; } } if(is_finished) break; } isdiffer= get_map_vector_rect(sorted_rect, return_rects); if (isdiffer) { return_rects.clear(); } } /////// } } return return_rects; } vector <map<int, cv::Rect>> get_map_vector_rect_without_same(map<int, cv::Rect> &sorted_rect) { vector <map<int, cv::Rect>> map_vector; if (sorted_rect.size()) { map<int, Rect> one_row_coupons; map_vector.clear(); int one_row_coupon_number_prev = 0; Rect firstRect = sorted_rect.begin()->second; one_row_coupons.clear(); // cout << "#####get_map_vector_rect_without_same" << endl; for (auto it = sorted_rect.begin(); it != sorted_rect.end(); it++) { // cout << "\tx\t:" << it->second.x << endl; // cout << "\ty\t:" << it->second.y << endl; // cout << "\twidth\t:" << it->second.width << endl; // cout << "\theight\t:" << it->second.height << endl; // cout << "\tbtx\t:" << it->second.br().x << endl; // cout << "\tbtyy\t:" << it->second.br().y << endl; if (it->second.y < firstRect.br().y-10 ) { one_row_coupons.insert(make_pair(it->second.x, Rect(it->second))); } else { ///new map body create map<int, Rect> other_row_coupons; other_row_coupons.clear(); for (auto mapit = one_row_coupons.begin(); mapit != one_row_coupons.end(); mapit++) { other_row_coupons.insert(make_pair(mapit->first, mapit->second)); } // if (one_row_coupon_number_prev != 0 && one_row_coupon_number_prev != other_row_coupons.size()) // { // number_differ=true; // cout<<"the row is differnt coupon number. pre is "<< one_row_coupon_number_prev<<"\tnow is "<<other_row_coupons.size()<<endl; // return map_vector; // // } map_vector.push_back(other_row_coupons); one_row_coupon_number_prev =(int) other_row_coupons.size(); one_row_coupons.clear(); one_row_coupons.insert(make_pair(it->second.x, Rect(it->second))); firstRect = it->second; continue; } } ////////////////////////////////////////////////////////////////////////// map<int, Rect> other_row_coupons; other_row_coupons.clear(); for (auto mapit = one_row_coupons.begin(); mapit != one_row_coupons.end(); mapit++) { other_row_coupons.insert(make_pair(mapit->first, mapit->second)); } // if (one_row_coupon_number_prev != 0 && one_row_coupon_number_prev != other_row_coupons.size()) // { // // cout<<"the last row is differnt number of coupons.pre is "<< one_row_coupon_number_prev<<"\tnow is "<<other_row_coupons.size()<<endl; // number_differ=true; // return map_vector; // } map_vector.push_back(other_row_coupons); one_row_coupons.clear(); return map_vector; } return map_vector; } bool get_map_vector_rect(map<int, cv::Rect> &sorted_rect,vector <map<int, cv::Rect>>&map_vector) { cout<<"get_map_vector_rect"<<endl; if (sorted_rect.size()) { map<int, Rect> one_row_coupons; map_vector.clear(); bool number_differ=false; int one_row_coupon_number_prev = 0; Rect firstRect = sorted_rect.begin()->second; // for (auto it = sorted_rect.begin(); it != sorted_rect.end(); it++) // { // if (firstRect.y>it->second.y) { // firstRect=Rect(it->second); // } // } one_row_coupons.clear(); for (auto it = sorted_rect.begin(); it != sorted_rect.end(); it++) { // cout << "\tx\t:" << it->second.x << endl; // cout << "\ty\t:" << it->second.y << endl; // cout << "\twidth\t:" << it->second.width << endl; // cout << "\theight\t:" << it->second.height << endl; if (it->second.y < firstRect.br().y) { one_row_coupons.insert(make_pair(it->second.x, Rect(it->second))); } else { ///new map body create map<int, Rect> other_row_coupons; other_row_coupons.clear(); for (auto mapit = one_row_coupons.begin(); mapit != one_row_coupons.end(); mapit++) { other_row_coupons.insert(make_pair(mapit->first, mapit->second)); } if (one_row_coupon_number_prev != 0 && one_row_coupon_number_prev != other_row_coupons.size()) { number_differ=true; cout<<"the row is differnt coupon number. pre is "<< one_row_coupon_number_prev<<"\tnow is "<<other_row_coupons.size()<<endl; return true; } map_vector.push_back(other_row_coupons); if(other_row_coupons.size()<6||other_row_coupons.size()>12) { cout<<"from get_map_vector_rect row size invalid "<<other_row_coupons.size()<<endl; return true; } one_row_coupon_number_prev =(int) other_row_coupons.size(); one_row_coupons.clear(); one_row_coupons.insert(make_pair(it->second.x, Rect(it->second))); firstRect = it->second; continue; } } ////////////////////////////////////////////////////////////////////////// map<int, Rect> other_row_coupons; other_row_coupons.clear(); for (auto mapit = one_row_coupons.begin(); mapit != one_row_coupons.end(); mapit++) { other_row_coupons.insert(make_pair(mapit->first, mapit->second)); } if (one_row_coupon_number_prev != 0 && one_row_coupon_number_prev != other_row_coupons.size()) { cout<<"the last row is differnt number of coupons.pre is "<< one_row_coupon_number_prev<<"\tnow is "<<other_row_coupons.size()<<endl; number_differ=true; return true; } map_vector.push_back(other_row_coupons); if(other_row_coupons.size()<6||other_row_coupons.size()>12) { cout<<"from get_map_vector_rect row size invalid "<<other_row_coupons.size()<<endl; return true; } if(map_vector.size()==1) { if(map_vector.front().size()<11&&map_vector.front().size()>9) { return true; } } one_row_coupons.clear(); return number_differ; } return true; } void remove_include_rects_in_number(vector<Rect2f> &rects) { bool is_finished = false; while (is_finished == false) { is_finished = true; int min_x, min_y, max_x, max_y; if (rects.size() == 0) break; for (auto it = rects.begin(); it != rects.end() - 1; it++) { for (auto it1 = it + 1; it1 != rects.end(); it1++) { if ( (it->contains(Point(it1->tl().x+1,it1->tl().y+1)) && ((it->br().x>=it1->br().x)&&(it1->y>=it->y))) || (it1->contains(Point(it->tl().x + 1, it->tl().y + 1)) && ((it1->br().x >= it->br().x) && (it->y >= it1->y)))|| ( ((it->br().x >= it1->tl().x&&it->br().x < it1->br().x) || (it1->br().x >= it->tl().x&&it1->br().x < it->br().x)))//it->y == it1->y&&it->height == it1->height && ) { min_x = it->tl().x < it1->tl().x ? it->tl().x : it1->tl().x; max_x = it->br().x > it1->br().x ? it->br().x : it1->br().x; min_y = it->tl().y < it1->tl().y ? it->tl().y : it1->tl().y; max_y = it->br().y > it1->br().y ? it->br().y : it1->br().y; it->x = min_x; it->y = min_y; it->width = max_x - min_x; it->height = max_y - min_y; rects.erase(it1); is_finished = false; break; } } if (is_finished == false) break; } } //// //////////the two rect height is different if (rects.size()==2) { int min_x, min_y, max_x, max_y; Rect first = rects.front(); Rect second = rects.back(); if ((first.y - second.y)>2 ) { min_y = second.y; max_y = first.br().y < second.br().y ? first.br().y : second.br().y; rects.front().y = min_y; rects.front().height = max_y - min_y; } if (second.y - first.y > 2) { min_y = first.y; max_y = first.br().y < second.br().y ? first.br().y : second.br().y; rects.back().y = min_y; rects.back().height = max_y - min_y; } } ///////// } vector <map<int, Rect>> get_coupon_sort_rects(std::vector<cv::Rect> &rects, Mat& src) { cout<<"get_coupon_sort_rects"<<endl; vector <map<int, Rect>> return_rects; if (rects.size()) { map<int, Rect> one_row_coupons; map<int, Rect> sorted_rect; for (auto it = rects.begin(); it != rects.end(); it++) { int x = it->x >= 0 ? it->x : 0; int y = it->y >= 0 ? it->y : 0; int width = it->x + it->width >= src.size().width ? src.size().width - it->x - 1 : it->width; int height = it->y + it->height >= src.size().height ? src.size().height - it->y - 1 : it->height; int key = x + y*src.size().width;//* src.size().width sorted_rect.insert(make_pair(key, Rect(x, y, width, height))); } if (sorted_rect.size()) { int one_row_coupon_number_prev = 0; Rect firstRect = sorted_rect.begin()->second; one_row_coupons.clear(); for (auto it = sorted_rect.begin(); it != sorted_rect.end(); it++) { if (it->second.y < firstRect.br().y) { one_row_coupons.insert(make_pair(it->second.x, Rect(it->second))); } else { ///new map body create map<int, Rect> other_row_coupons; other_row_coupons.clear(); for (auto mapit = one_row_coupons.begin(); mapit != one_row_coupons.end(); mapit++) { other_row_coupons.insert(make_pair(mapit->first, mapit->second)); } //one_row_coupon_number_prev=0; if (one_row_coupon_number_prev != 0 && one_row_coupon_number_prev != other_row_coupons.size()) { cout<<"the row is differnt coupon number. pre is "<< one_row_coupon_number_prev<<"\tnow is "<<other_row_coupons.size()<<endl; return_rects.clear(); return return_rects; } return_rects.push_back(other_row_coupons); one_row_coupon_number_prev =(int) other_row_coupons.size(); one_row_coupons.clear(); one_row_coupons.insert(make_pair(it->second.x, Rect(it->second))); firstRect = it->second; continue; } } ////////////////////////////////////////////////////////////////////////// ////the last row of coupon map<int, Rect> other_row_coupons; other_row_coupons.clear(); for (auto mapit = one_row_coupons.begin(); mapit != one_row_coupons.end(); mapit++) { other_row_coupons.insert(make_pair(mapit->first, mapit->second)); } if (one_row_coupon_number_prev != 0 && one_row_coupon_number_prev != other_row_coupons.size()) { cout<<"the last row is differnt number of coupons.pre is "<< one_row_coupon_number_prev<<"\tnow is "<<other_row_coupons.size()<<endl; return_rects.clear(); return return_rects; } return_rects.push_back(other_row_coupons); one_row_coupons.clear(); /////////////////// } } return return_rects; } //// vector <map<int, cv::Rect>> get_coupon_rects_without_dash(std::vector<cv::Rect> &rects, Mat& src,int bottom_y) { cout<<"get_coupon_rects_without_dash"<<endl; vector <map<int, Rect>> return_rects; if (rects.size()) { map<int, Rect> one_row_coupons; map<int, Rect> sorted_rect; for (auto it = rects.begin(); it != rects.end(); it++) { int x = it->x >= 0 ? it->x : 0; int y = it->y >= 0 ? it->y : 0; int width = it->x + it->width >= src.size().width ? src.size().width - it->x - 1 : it->width; int height = it->y + it->height >= src.size().height ? src.size().height - it->y - 1 : it->height; if (height>=24&&width<src.size().width/7&&y>src.size().height/10)//width>=13&& { //(width>=18&&height>=38&&width<src.size().width/5) if(bottom_y) { if (y<bottom_y) { int key = x + y*src.size().width;//* src.size().width sorted_rect.insert(make_pair(key, Rect(x, y, width, height))); //rectangle(src,Rect(x, y, width, height), Scalar(2,234,231)); } } else { int key = x + y*src.size().width;//* src.size().width sorted_rect.insert(make_pair(key, Rect(x, y, width, height))); //rectangle(src,Rect(x, y, width, height), Scalar(2,234,231)); } } } cout << " get_coupon_rects_without_dash possible sorted_rect " <<sorted_rect.size()<< endl; if (sorted_rect.size()) { int one_row_coupon_number_prev = 0; Rect firstRect = sorted_rect.begin()->second; one_row_coupons.clear(); for (auto it = sorted_rect.begin(); it != sorted_rect.end(); it++) { if (it->second.y < firstRect.br().y) { one_row_coupons.insert(make_pair(it->second.x, Rect(it->second))); } else { ///new map body create map<int, Rect> other_row_coupons; other_row_coupons.clear(); for (auto mapit = one_row_coupons.begin(); mapit != one_row_coupons.end(); mapit++) { other_row_coupons.insert(make_pair(mapit->first, mapit->second)); } if (other_row_coupons.size()>=7&&other_row_coupons.size()<13) { return_rects.push_back(other_row_coupons); } one_row_coupon_number_prev =(int) other_row_coupons.size(); one_row_coupons.clear(); one_row_coupons.insert(make_pair(it->second.x, Rect(it->second))); firstRect = it->second; continue; } } ////////////////////////////////////////////////////////////////////////// ////the last row of coupon map<int, Rect> other_row_coupons; other_row_coupons.clear(); one_row_coupon_number_prev=0; for (auto mapit = one_row_coupons.begin(); mapit != one_row_coupons.end(); mapit++) { other_row_coupons.insert(make_pair(mapit->first, mapit->second)); } if (other_row_coupons.size()>=7&&other_row_coupons.size()<13) { return_rects.push_back(other_row_coupons); } one_row_coupons.clear(); /////////////////// } } return return_rects; } vector <map<int, cv::Rect>> mergewidthfrommat(vector <map<int, cv::Rect>> &sorted_rect,cv::Mat &src) { cout<<"the total rows "<<sorted_rect.size()<<endl; for (auto it = sorted_rect.begin(); it != sorted_rect.end()--; it++) { cout<<"the indi rows coupon "<<it->size()<<endl; for (auto mapit = it->begin(); mapit != it->end(); mapit++) { Rect rt=mapit->second; //rectangle(src,Rect(rt.x-1,rt.y-1,rt.width+2,rt.height+2), Scalar(233,23,3)); } } cout<<"from the mergewidthfrommat"<<endl; Rect first_rect,second_rect; int terrain_width=7; for (auto it = sorted_rect.begin(); it != sorted_rect.end()--; it++) { bool is_break=false; bool is_finished = false; while (is_finished == false) { is_finished = true; for (auto mapit = it->begin(); mapit != it->end(); mapit++) { first_rect=Rect(mapit->second); for (auto secmapit = mapit++; secmapit != it->end(); secmapit++) { second_rect=Rect(secmapit->second); if (first_rect.br().x<second_rect.tl().x&&second_rect.tl().x-first_rect.br().x<terrain_width) { mapit->second.width=second_rect.br().x-first_rect.x; it->erase(secmapit); is_break=true; break; } if (first_rect.tl().x>second_rect.br().x&&first_rect.tl().x-second_rect.br().x<terrain_width) { mapit->second.width=first_rect.br().x-second_rect.x; mapit->second.x=second_rect.x; it->erase(secmapit); is_break=true; break; } } if (is_break) { break; } if (mapit==it->end()--) { is_finished=true; break; } } if(is_finished) break; } } cout<<"the total rows "<<sorted_rect.size()<<endl; for (auto it = sorted_rect.begin(); it != sorted_rect.end()--; it++) { cout<<"the indi rows coupon "<<it->size()<<endl; for (auto mapit = it->begin(); mapit != it->end(); mapit++) { Rect rt=mapit->second; //rectangle(src,Rect(rt.x-3,rt.y,rt.width+6,rt.height), Scalar(3,3,193)); } } return sorted_rect; } ////
33.87987
192
0.511572
[ "vector" ]
6488dadc417dfe31f3428105215595ca69d0be17
798
cpp
C++
Days 151 - 160/Day 156/SumOfSquaredNumbers.cpp
LucidSigma/Daily-Coding-Problems
21dc8f7e615edd535d7beb1f5d0e41dd3b4bcc1a
[ "MIT" ]
null
null
null
Days 151 - 160/Day 156/SumOfSquaredNumbers.cpp
LucidSigma/Daily-Coding-Problems
21dc8f7e615edd535d7beb1f5d0e41dd3b4bcc1a
[ "MIT" ]
null
null
null
Days 151 - 160/Day 156/SumOfSquaredNumbers.cpp
LucidSigma/Daily-Coding-Problems
21dc8f7e615edd535d7beb1f5d0e41dd3b4bcc1a
[ "MIT" ]
null
null
null
#include <iostream> #include <iterator> #include <vector> unsigned int GetTotalSquareSum(unsigned int number) noexcept { std::vector<unsigned int> validSquares; unsigned int squareCounter = 1; while (squareCounter * squareCounter < number) { validSquares.push_back(squareCounter * squareCounter); ++squareCounter; } unsigned int currentSquareIndex = validSquares.size() - 1; unsigned int squareSumCount = 0; while (number > 0) { if (validSquares[currentSquareIndex] > number) { --currentSquareIndex; } else { number -= validSquares[currentSquareIndex]; ++squareSumCount; } } return squareSumCount; } int main(int argc, char* argv[]) { std::cout << GetTotalSquareSum(13) << "\n"; std::cout << GetTotalSquareSum(27) << "\n"; std::cin.get(); return 0; }
18.55814
60
0.696742
[ "vector" ]
52be2081f4bc6f699a0b977f03bed02bed4c481b
2,828
cpp
C++
leetcode/top_interview_questions/easy/linked_list/4.cpp
bvbasavaraju/competitive_programming
a82ffc1b639588a84f4273b44285d57cdc2f4b11
[ "Apache-2.0" ]
1
2020-05-05T13:06:51.000Z
2020-05-05T13:06:51.000Z
leetcode/top_interview_questions/easy/linked_list/4.cpp
bvbasavaraju/competitive_programming
a82ffc1b639588a84f4273b44285d57cdc2f4b11
[ "Apache-2.0" ]
null
null
null
leetcode/top_interview_questions/easy/linked_list/4.cpp
bvbasavaraju/competitive_programming
a82ffc1b639588a84f4273b44285d57cdc2f4b11
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <vector> using namespace std; /* Q: Merge Two Sorted Lists Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists. Example 1: Input: l1 = [1,2,4], l2 = [1,3,4] Output: [1,1,2,3,4,4] Example 2: Input: l1 = [], l2 = [] Output: [] Example 3: Input: l1 = [], l2 = [0] Output: [0] Constraints: The number of nodes in both lists is in the range [0, 50]. -100 <= Node.val <= 100 Both l1 and l2 are sorted in non-decreasing order. */ struct ListNode { int val; ListNode *next; ListNode() : val(0), next(nullptr) {} ListNode(int x) : val(x), next(nullptr) {} ListNode(int x, ListNode *next) : val(x), next(next) {} }; class Solution { public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { ListNode* ans = NULL; ListNode* node = ans; while((l1 != NULL) && (l2 != NULL)) { if(l1->val <= l2->val) { if(node == NULL) { node = l1; ans = node; } else { node->next = l1; node = node->next; } l1 = l1->next; } else { if(node == NULL) { node = l2; ans = node; } else { node->next = l2; node = node->next; } l2 = l2->next; } } while(l1 != NULL) { if(node != NULL) { node->next = l1; node = node->next; } else { node = l1; ans = node; } l1 = l1->next; } while(l2 != NULL) { if(node != NULL) { node->next = l2; node = node->next; } else { node = l2; ans = node; } l2 = l2->next; } return ans; //O(3n) // vector<int> v; // while(l1 != NULL) // { // v.push_back(l1->val); // l1 = l1->next; // } // while(l2 != NULL) // { // v.push_back(l2->val); // l2 = l2->next; // } // sort(v.begin(), v.end()); // int l = v.size(); // ListNode* retVal = NULL; // ListNode* p = retVal; // for(int i = 0; i < l; i++) // { // ListNode* n = new ListNode(v[i]); // if(p == NULL) // { // p = n; // retVal = p; // } // else // { // p->next = n; // p = p->next; // } // } // return retVal; } };
18.979866
142
0.381895
[ "vector" ]
52c198df51655e2a64e751d49d4f7408ddb20799
5,415
hh
C++
dune/gdt/test/interpolations/default.hh
pymor/dune-gdt
fabc279a79e7362181701866ce26133ec40a05e0
[ "BSD-2-Clause" ]
4
2018-10-12T21:46:08.000Z
2020-08-01T18:54:02.000Z
dune/gdt/test/interpolations/default.hh
dune-community/dune-gdt
fabc279a79e7362181701866ce26133ec40a05e0
[ "BSD-2-Clause" ]
154
2016-02-16T13:50:54.000Z
2021-12-13T11:04:29.000Z
dune/gdt/test/interpolations/default.hh
dune-community/dune-gdt
fabc279a79e7362181701866ce26133ec40a05e0
[ "BSD-2-Clause" ]
5
2016-03-02T10:11:20.000Z
2020-02-08T03:56:24.000Z
// This file is part of the dune-gdt project: // https://github.com/dune-community/dune-gdt // Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved. // License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // or GPL-2.0+ (http://opensource.org/licenses/gpl-license) // with "runtime exception" (http://www.dune-project.org/license.html) // Authors: // Felix Schindler (2019) #ifndef DUNE_GDT_TEST_INTERPOLATIONS_DEFAULT_HH #define DUNE_GDT_TEST_INTERPOLATIONS_DEFAULT_HH #include <dune/xt/common/fvector.hh> #include <dune/xt/common/fmatrix.hh> #include <dune/xt/common/string.hh> #include <dune/xt/test/gtest/gtest.h> #include <dune/xt/test/common.hh> #include <dune/xt/grid/boundaryinfo/normalbased.hh> #include <dune/xt/grid/gridprovider/cube.hh> #include <dune/xt/grid/structuredgridfactory.hh> #include <dune/xt/grid/type_traits.hh> #include <dune/xt/functions/constant.hh> #include <dune/xt/functions/generic/function.hh> #include <dune/xt/functions/grid-function.hh> #include <dune/gdt/discretefunction/default.hh> #include <dune/gdt/interpolations/boundary.hh> #include <dune/gdt/local/bilinear-forms/integrals.hh> #include <dune/gdt/local/integrands/product.hh> #include <dune/gdt/norms.hh> #include <dune/gdt/spaces/h1/continuous-lagrange.hh> namespace Dune { namespace GDT { namespace Test { template <class G> struct DefaultInterpolationOnLeafViewTest : public ::testing::Test { static_assert(XT::Grid::is_grid<G>::value, ""); using GV = typename G::LeafGridView; using D = typename GV::ctype; static constexpr size_t d = GV::dimension; using E = XT::Grid::extract_entity_t<GV>; using I = XT::Grid::extract_intersection_t<GV>; using M = XT::LA::IstlRowMajorSparseMatrix<double>; using V = XT::LA::IstlDenseVector<double>; std::shared_ptr<XT::Grid::GridProvider<G>> grid_provider; std::shared_ptr<XT::Functions::GenericFunction<d>> source; std::shared_ptr<ContinuousLagrangeSpace<GV>> space; std::shared_ptr<DiscreteFunction<V, GV>> range; virtual std::shared_ptr<XT::Grid::GridProvider<G>> make_grid() { return std::make_shared<XT::Grid::GridProvider<G>>( XT::Grid::make_cube_grid<G>(XT::Common::from_string<FieldVector<double, d>>("[-1 0 0 0]"), XT::Common::from_string<FieldVector<double, d>>("[1 1 1 1]"), XT::Common::from_string<std::array<unsigned int, d>>("[5 5 5 2]"))); } void SetUp() override { grid_provider = make_grid(); space = std::make_shared<ContinuousLagrangeSpace<GV>>(make_continuous_lagrange_space(grid_provider->leaf_view(), 2)); source = std::make_shared<XT::Functions::GenericFunction<d>>( [](const auto&) { return 2; }, [](const auto& x, const auto&) { const auto x_dependent = 2 * std::pow(x[0], 2) - x[0] + 3; [[maybe_unused]] D xy_dependent; if constexpr (d >= 2) xy_dependent = x_dependent + x[0] * x[1] + 0.5 * x[1] - std::pow(x[1], 2); if constexpr (d == 1) return x_dependent; else if constexpr (d == 2) return xy_dependent; else return xy_dependent + 0.5 * std::pow(x[2], 2) + x[2] * x[0] - 3 * x[2] * x[1]; }, "second order polynomial", XT::Common::ParameterType{}, [](const auto& x, const auto&) { const std::vector<double> x_dependent_jacobian{4 * x[0] - 1, 0, 0, 0}; [[maybe_unused]] std::vector<double> y_dependent_jacobian; [[maybe_unused]] std::vector<double> z_dependent_jacobian; if constexpr (d >= 2) y_dependent_jacobian = {x[1], x[0] + 0.5 - 2 * x[1], 0, 0}; if constexpr (d >= 3) z_dependent_jacobian = {x[2], -3 * x[2], x[2] + x[0] - 3 * x[1], 0}; XT::Common::FieldMatrix<double, 1, d> jacobian; for (size_t ii = 0; ii < d; ++ii) { jacobian[0][ii] = x_dependent_jacobian[ii]; if constexpr (d >= 2) jacobian[0][ii] += y_dependent_jacobian[ii]; if constexpr (d >= 3) jacobian[0][ii] += z_dependent_jacobian[ii]; } return jacobian; }); range = std::make_shared<DiscreteFunction<V, GV>>(*space); } // ... SetUp(...) void interpolates_correctly(const double expected_l2_error = 1e-14) { default_interpolation(*source, *range, space->grid_view()); const auto l2_error = l2_norm(space->grid_view(), XT::Functions::make_grid_function<E>(*source) - *range); EXPECT_LT(l2_error, expected_l2_error) << "XT::Common::Test::get_unique_test_name() = '" << XT::Common::Test::get_unique_test_name() << "'"; const auto local_range = range->local_discrete_function(); for (auto&& element : Dune::elements(space->grid_view())) { local_range->bind(element); const auto center = element.geometry().center(); const auto range_jacobian = local_range->jacobian(element.geometry().local(center)); const auto expected_jacobian = source->jacobian(center); EXPECT_LT((range_jacobian - expected_jacobian)[0].two_norm(), expected_l2_error); } } // ... interpolates_correctly(...) }; // struct DefaultInterpolationOnLeafViewTest } // namespace Test } // namespace GDT } // namespace Dune #endif // DUNE_GDT_TEST_INTERPOLATIONS_DEFAULT_HH
41.976744
117
0.64783
[ "geometry", "vector" ]
52c36316f31ba6f34cb0775d38b4f4ea009a030e
3,436
cpp
C++
src/pbnjson_c/selectors/test/TestSyntaxParser.cpp
webosce/libpbnjson
6cd4815a81830bbf6b22647ae8bb4fc818148ee7
[ "Apache-2.0" ]
4
2018-03-20T15:15:50.000Z
2020-05-02T02:30:15.000Z
src/pbnjson_c/selectors/test/TestSyntaxParser.cpp
webosce/libpbnjson
6cd4815a81830bbf6b22647ae8bb4fc818148ee7
[ "Apache-2.0" ]
null
null
null
src/pbnjson_c/selectors/test/TestSyntaxParser.cpp
webosce/libpbnjson
6cd4815a81830bbf6b22647ae8bb4fc818148ee7
[ "Apache-2.0" ]
4
2018-03-19T12:43:43.000Z
2020-05-02T02:30:19.000Z
// Copyright (c) 2015-2018 LG Electronics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // SPDX-License-Identifier: Apache-2.0 #include <gtest/gtest.h> #include <memory> #include <vector> #include <string> #include <iostream> #include "Utils.hpp" namespace { using namespace std; static const vector<string> queries = { ".languagesSpoken .lang", ".drinkPreference :first-child", ".seatingPreference :nth-child(15)", ".\"weight\"", ".lang", ".favoriteColor", "string.favoriteColor", "string:last-child", "string:nth-child(2)", "string:nth-last-child(1)", ":root", "number", ":has(:root > .preferred)", ".preferred ~ .lang", ":has(.lang:val(\"Spanish\")) > .level", ".lang:val(\"Bulgarian\") ~ .level", ".weight:expr(x<160) ~ .name .first" }; TEST(Selectors, SelectorExamples) { for (const string &query_str: queries) { jerror *err = NULL; jquery_ptr query = jquery_create(query_str.c_str(), &err); if (!query) { fprintf(stderr, "Parser error. Query: '%s'. Error: '%s'\n", query_str.c_str(), getErrorString(err).c_str()); } ASSERT_TRUE(query); jquery_free(query); } } TEST(Selectors, TestBaseSelection) { jerror *err = NULL; jvalue_ref json = jdom_create(j_cstr_to_buffer(R"({"test": 3, "test2": true, "test3": "str"})"), jschema_all(), &err); ASSERT_TRUE(jis_valid(json)); jquery_ptr query = jquery_create("*", &err); ASSERT_TRUE(query); ASSERT_TRUE(jquery_init(query, json, &err)); ASSERT_TRUE(jvalue_equal(json, jquery_next(query))); j_release(&json); jquery_free(query); } TEST(Selectors, TestInvalidSymbols) { jerror *err = NULL; jquery_ptr query = jquery_create("#", &err); ASSERT_FALSE(query); ASSERT_STREQ("Syntax error. Unexpected symbol '#' in the query string", getErrorString(err).c_str()); jerror_free(err); err = NULL; jquery_free(query); query = jquery_create(" ", &err); ASSERT_FALSE(query); ASSERT_STREQ("Syntax error. Unexpected symbol '\\t' in the query string", getErrorString(err).c_str()); jerror_free(err); jquery_free(query); } TEST(Selectors, TestInvalidTokens) { jerror *err = NULL; jquery_ptr query = jquery_create("fuzz.bazz", &err); ASSERT_FALSE(query); ASSERT_STREQ("Syntax error. Unexpected token 'fuzz' in the query string", getErrorString(err).c_str()); jerror_free(err); err = NULL; jquery_free(query); query = jquery_create(".key ", &err); ASSERT_FALSE(query); ASSERT_STREQ("Syntax error. Unexpected end of the query string", getErrorString(err).c_str()); jerror_free(err); jquery_free(query); } TEST(Selectors, TestSelectorNullErr) { jquery_ptr query = jquery_create("fuzz.bazz", NULL); ASSERT_FALSE(query); query = jquery_create("*", NULL); ASSERT_TRUE(query); ASSERT_FALSE(jquery_init(query, NULL, NULL)); ASSERT_TRUE(jquery_init(query, jnull(), NULL)); jquery_free(query); } } // namespace
23.534247
104
0.684808
[ "vector" ]
52c49ad1ca8bbdd45e01226f27f86f36b361c65e
10,427
cpp
C++
oldsrc/findpertsurface2_fft.cpp
ron2015schmitt/coildes
2583bc1beb6b5809ed75367970e4f32ba242894a
[ "MIT" ]
null
null
null
oldsrc/findpertsurface2_fft.cpp
ron2015schmitt/coildes
2583bc1beb6b5809ed75367970e4f32ba242894a
[ "MIT" ]
null
null
null
oldsrc/findpertsurface2_fft.cpp
ron2015schmitt/coildes
2583bc1beb6b5809ed75367970e4f32ba242894a
[ "MIT" ]
null
null
null
/************************************************************************* * * File Name : findpertsurface2_fft.cpp * Platform : gnu C++ compiler * Author : Ron Schmitt * Date : * * * SYNOPSIS * * This takes the differnece between the necessary fourier flux coef's * and the acutal flux coef's and finds the location of the perturbed magnetic * surface. * * * VERSION NOTES: * Uses magnetic coordinates to calculate Omega * * created from findpertsurface_fft.cpp on 05.12.2007 **************************************************************************/ // Standard C libraries #include <cstdio> #include <cstring> #include <cstdlib> #include <cmath> // Standard C++ libraries #include <iostream> #include <complex> using namespace std; // coil libraries #include "coils.hpp" #include "coilio.hpp" #include "coils_cmdline.hpp" #include "surface.hpp" #include "omegamatrix_fft.hpp" #include "omegasubspace.hpp" #include "coilfft.hpp" // This is the file that defines the B field configuration // Main Function for code int main (int argc, char *argv[]) { disable_all_options(); enable_option(opt_pf); enable_option(opt_ff); enable_option(opt_Nphi); enable_option(opt_Ntheta); enable_option(opt_Nnn); enable_option(opt_Nmm); enable_option(opt_Nharm); enable_option(opt_Mharm); enable_option(opt_lambdaf); enable_option(opt_iota); enable_option(opt_fluxshear); // parse command line input if (!parse_cmd(argc, argv)) return 1; printcr("----------------------------------------------------"); for(int i=0; i<argc; i++){ print(argv[i]); print(" "); } cr(); printcr("----------------------------------------------------"); // // ios_base::fmtflags flags = ios_base::right | ios_base::scientific; string fext = "txt"; string ftemp; p3vectorformat::textformat(text_nobraces); Vector <double> datavec("datavec"); datavec.perline(1); datavec.textformat(text_nobraces); Matrix <double> data("data"); Matrix <double> data2("data2"); data2.perline(1); data2.textformat(text_nobraces); string fname; // variables for measuring times struct tms tbuff; clock_t ckstart; // display Matricks mode cout << endl; display_execution_mode(); cout << endl; ostringstream strmtemp; string methstr(".pert2"); string plasma_name; { unsigned int j = plasma_filename.rfind("_"); plasma_name = plasma_filename.substr(0,j); plasma_name = "."+plasma_name; } strmtemp <<Ntheta; string Ntheta_str(strmtemp.str()); strmtemp.str(""); Ntheta_str = ".Ntheta="+Ntheta_str; strmtemp <<Nphi; string Nphi_str(strmtemp.str()); strmtemp.str(""); Nphi_str = ".Nphi="+Nphi_str; strmtemp <<Nnn; string Nnn_str(strmtemp.str()); strmtemp.str(""); Nnn_str = ".Nn="+Nnn_str; strmtemp <<Nmm; string Nmm_str(strmtemp.str()); strmtemp.str(""); Nmm_str = ".Nm="+Nmm_str; strmtemp <<iota_given; cout.precision(6); string iotaval_str(strmtemp.str()); strmtemp.str(""); cout.precision(15); iotaval_str = ".iota="+iotaval_str; dispcr(plasma_name); dispcr(methstr); dispcr(Nphi_str+Ntheta_str); dispcr(Nnn_str+Nmm_str); dispcr(iotaval_str); dispcr(fluxshear_given); // Create angle grid const unsigned int Npts = Ntheta*Nphi; Vector<double> thetas(Npts,"thetas"); Vector<double> phis(Npts,"phis"); anglevectors(thetas, phis, Ntheta, Nphi); // Create Fourier Mode vectors Vector<double> nn("nn"); Vector<double> mm("mm"); unsigned int NF; bool mode00 = true; if ( (Nharm >1) ||(Mharm>1) ) modevectors(NF,nn,mm,Nnn,Nmm,Nharm,Mharm,mode00); else modevectors(NF,nn,mm,Nnn,Nmm,mode00); // these exclude the n=0,m=0 case Vector<double> nnR("nnR"); Vector<double> mmR("mmR"); unsigned int NFR; mode00 = false; if ( (Nharm >1) ||(Mharm>1) ) modevectors(NFR,nnR,mmR,Nnn,Nmm,Nharm,Mharm,mode00); else modevectors(NFR,nnR,mmR,Nnn,Nmm,mode00); nn.perline(1); nn.textformat(text_nobraces); save(nn,"nn.out"); mm.perline(1); mm.textformat(text_nobraces); save(mm,"mm.out"); nnR.perline(1); nnR.textformat(text_nobraces); save(nnR,"nnR.out"); mmR.perline(1); mmR.textformat(text_nobraces); save(mmR,"mmR.out"); // load the plasma surface fourier coef's cout << "$ Loading PLASMA SURFACE fourier coefficients from " << plasma_filename << endl; FourierSurface plasmafourier; if (load_fourier_surface(plasma_filename,plasmafourier)) return 1; plasmafourier.RF().name("p.RF"); plasmafourier.ZF().name("p.ZF"); // print coef's // printfouriercoefs(plasmafourier.nn(),plasmafourier.mm(),plasmafourier.RF(),plasmafourier.ZF(),10,18); // load the plasma flux fourier coef's // WE CAN IGNORE THE (m=0,n=0) mode because the omega matrix is identically zero // for (m=0,n=0) (both in row and column index) Vector<complex<double> > delFluxF(NFR,"FluxF"); cout <<endl<< "$ Loading perturbed Plasma Flux sin/cos fourier coefficients from " << flux_filename << endl; if (load_coefs(flux_filename,CoefFileFormat_sincos,nnR,mmR,delFluxF)) return 3; // lay plasma surface onto grid Vector<p3vector<double> > X(Npts, "X"); Vector<p3vector<double> > dA_dtdp(Npts, "dA_dtdp"); Vector<p3vector<double> > dx_dr(Npts, "dx_dr"); Vector<p3vector<double> > dx_dtheta(Npts,"dx_dtheta"); Vector<p3vector<double> > dx_dphi(Npts,"dx_dphi"); Vector<p3vector<double> > grad_r(Npts,"grad_r"); Vector<p3vector<double> > grad_theta(Npts,"grad_theta"); Vector<p3vector<double> > grad_phi(Npts,"grad_phi"); cout << endl; cout <<"$ Mapping plasma surface fourier coefficients to "<<Ntheta<<" x "<<Nphi<<" (theta by phi) grid"<<endl; STARTTIME(tbuff,ckstart); expandsurfaceandbases(X,dA_dtdp,dx_dr,dx_dtheta,dx_dphi,grad_r,grad_theta,grad_phi,plasmafourier,thetas,phis); Vector<double> J(Npts, "J"); for (unsigned int j =0; j<Npts; j++) { J[j] = dot(dx_dr[j],cross(dx_dtheta[j], dx_dphi[j])); } STOPTIME(tbuff,ckstart); double iota = iota_given; Vector<double> W0(NFR,"W0"); const double coef1 = fluxshear_given/ (2.0*PI); for (unsigned int j =0; j<NFR; j++) { W0[j] = (coef1)*(nnR[j] + iota*mmR[j]); // dispcr(W0[j]); } // P converts from magnetic to geometric fourier // so rows are in (nnR,mmR) order and // columns are in (nnR_maf,mmR_mag) order Matrix<complex<double> > P(NFR,NFR,"P"); if ( omega_filename.empty() ) { Vector<complex<double> > lambdaF(NFR,"lambdaF"); cout <<endl<< "$ Loading lambda sin/cos fourier coefficients from " << lambda_filename << endl; if (load_coefs(lambda_filename,CoefFileFormat_sincos,nnR,mmR,lambdaF,false)){ printcr("Above ERROR occurred in "+myname+"."); return 4; } cout << endl; cout<<"$ Calculate OmegaN matrix ("<<NFR<<"x"<<NFR<<")"<<endl; STARTTIME(tbuff,ckstart); Vector<double> lambda(Npts, "lambda"); // expandfunction(lambda,lambdaF,fsR); mode00=false; ifft2d(lambda,lambdaF,Nphi,Ntheta,Nnn,Nmm,Nharm,Mharm,1e-10,1/(2*PI),mode00); OmegaN_PF_from_lambda_fft(P,lambda,nnR,mmR,thetas,phis,Nphi, Ntheta, Nnn, Nmm, Nharm, Mharm); STOPTIME(tbuff,ckstart);STARTTIME(tbuff,ckstart); } else { cout << endl; cout<<"$ Load Omega eigenvector matrix("<<NFR<<"x"<<NFR<<")"<<endl; STARTTIME(tbuff,ckstart); data.resize(NFR,NFR); data.perline(1); data.textformat(text_nobraces); fname = "PF."+omega_filename +".R.out"; dispcr(fname); Matricks::load(data,fname); data2.resize(NFR,NFR); data2.perline(1); data2.textformat(text_nobraces); fname = "PF."+omega_filename +".I.out"; dispcr(fname); Matricks::load(data2,fname); P = mcomplex(data,data2); data.clear(); data2.clear(); STOPTIME(tbuff,ckstart); } // Invert Omega Eigenvector Matrix cout << endl; cout<<"$ Invert Omega Eigenvector Matrix ("<<NFR<<"x"<<NFR<<")"<<endl; STARTTIME(tbuff,ckstart); Matrix<complex<double> > Pinv(NFR,NFR,"Pinv"); matricks_lapack::inv(P,Pinv); STOPTIME(tbuff,ckstart); // Calculate Omega Inv matrix cout << endl; cout<<"$ Calculate Omega Inv matrix ("<<NFR<<"x"<<NFR<<")"<<endl; STARTTIME(tbuff,ckstart); for(unsigned int r=0; r<NFR;r++) { double temp1 = 1.0/W0[r]; complex<double> temp2 = std::complex<double>(0,-temp1); for(unsigned int c=0; c<NFR;c++) { Pinv(r,c) = temp2*Pinv(r,c); } } Matrix<complex<double> > OmegaInv(NFR,NFR,"OmegaInv"); OmegaInv = (P|Pinv); P.clear(); Pinv.clear(); STOPTIME(tbuff,ckstart); // calculate perturbations cout << endl; cout<<"$ Calculate perturbations to plasma surface"<<endl; STARTTIME(tbuff,ckstart); Vector<complex<double> > deltaF(NFR,"deltaF"); deltaF = (OmegaInv|(delFluxF)); Vector<double> delta(Npts,"delta"); mode00=false; ifft2d(delta,deltaF,Nphi,Ntheta,Nnn,Nmm,Nharm,Mharm,1e-10,1/(2*PI),mode00); STOPTIME(tbuff,ckstart); // calculate new surface coords cout << endl; cout<<"$ Calculate new plasma surface"<<endl; STARTTIME(tbuff,ckstart); Vector<p3vector<double> > ksi(Npts,"ksi"); Vector<p3vector<double> > Xnew(Npts,"Xnew"); for(unsigned int i=0; i<Npts;i++) { ksi[i] = delta[i] * dx_dr[i]; Xnew[i] = X[i] + ksi[i]; } // ALL DONE, NOW SAVE TO FILES OmegaInv.clear(); massage(deltaF,1e-8); fname = "deltaF"+plasma_name+methstr+".out"; dispcr(fname); save_coefs(fname,CoefFileFormat_sincos,nnR,mmR,deltaF); cout << endl; cout<<"$ Generate orthonormal series matrix ("<<Npts<<" x "<<NF<<")"<<endl; STARTTIME(tbuff,ckstart); Matrix<complex<double> > fs(Npts,NF,"fs"); fseries(nn,mm,thetas,phis,fs); STOPTIME(tbuff,ckstart); FourierSurface newfourier; transformsurface(Xnew,newfourier,fs,nn,mm); massage(newfourier,1e-8); fname = "perturbedsurface"+plasma_name+methstr+".out"; dispcr(fname); save_fourier_surface(fname,newfourier); return 0; } // main()
23.915138
113
0.622614
[ "vector" ]
52c6c2f83091ac35624bc7881a2864d9c2dff4ed
1,315
cpp
C++
app/hexperiment/sqlutil.cpp
vsui/hypergraph-k-cut
1134ca254fb709bce62a4506c931362d84a06894
[ "MIT" ]
2
2021-01-17T07:31:36.000Z
2021-07-14T08:36:50.000Z
app/hexperiment/sqlutil.cpp
vsui/hypergraph-k-cut
1134ca254fb709bce62a4506c931362d84a06894
[ "MIT" ]
null
null
null
app/hexperiment/sqlutil.cpp
vsui/hypergraph-k-cut
1134ca254fb709bce62a4506c931362d84a06894
[ "MIT" ]
null
null
null
// // Created by Victor on 4/16/20. // #include "sqlutil.hpp" #include <algorithm> sqlutil::InsertStatementBuilder::InsertStatementBuilder(std::string table_name) : table_name_(std::move(table_name)) {} void sqlutil::InsertStatementBuilder::add(const std::string &col_name, const std::string &val) { col_vals_.emplace_back(col_name, _impl::sql_val_str(val)); } void sqlutil::InsertStatementBuilder::add(const std::string &col_name, const int val) { col_vals_.emplace_back(col_name, _impl::sql_val_str(val)); } std::string sqlutil::InsertStatementBuilder::string() { std::vector<std::string> names; std::vector<std::string> vals; std::transform(col_vals_.cbegin(), col_vals_.cend(), std::back_inserter(names), [](const auto &a) { return std::get<0>(a); }); std::transform(col_vals_.cbegin(), col_vals_.cend(), std::back_inserter(vals), [](const auto &a) { return std::get<1>(a); }); std::string names_str = _impl::comma_delimit(std::begin(names), std::end(names)); std::string vals_str = _impl::comma_delimit(std::begin(vals), std::end(vals)); std::ostringstream oss; oss << "INSERT INTO " << table_name_ << " (" << names_str << ") VALUES (" << vals_str << ")"; return oss.str(); }
32.875
119
0.643346
[ "vector", "transform" ]
52cb5ac13f8cea1d033e02e6285f8c7c994d8775
23,920
hpp
C++
Aha/Aha/OBJModel.hpp
templateguy/aha
8965f3dfa318a8ee02e38fa082bbc5c8c6afa100
[ "MIT" ]
null
null
null
Aha/Aha/OBJModel.hpp
templateguy/aha
8965f3dfa318a8ee02e38fa082bbc5c8c6afa100
[ "MIT" ]
null
null
null
Aha/Aha/OBJModel.hpp
templateguy/aha
8965f3dfa318a8ee02e38fa082bbc5c8c6afa100
[ "MIT" ]
1
2018-04-27T05:48:41.000Z
2018-04-27T05:48:41.000Z
// // OBJModel.hpp // AhaOBJ // // Created by Sinha, Saurabh on 5/8/18. // Copyright © 2018 Sinha, Saurabh. All rights reserved. // #pragma once #include "Texture.hpp" #include "Shader.hpp" namespace aha { class OBJModel { public: void loadModel(const std::string& fileName) { shader_.load("pbr/shaders/obj_model.vs", "pbr/shaders/obj_model.fs"); shader_.use(); base_ = getBaseDir_(fileName) + "/"; parseFile_(fileName); appendDefaultMaterial_(); printOBJModelInfo_(); loadDiffuseTextures_(); populateBuffer_(); printMaxMin_(); } const Shader& getShader() const { return shader_; } void render(bool wireframe = false) const { if(!wireframe) { glEnable(GL_DEPTH_TEST); for(const auto& mesh : meshes_) { if(mesh.vbo < 1) { continue; } shader_.use(); // view/projection transformations //glm::mat4 projection = glm::perspective(glm::radians(45.0f), (float) 768.0f / (float) 768.0f, 0.1f, 100.0f); //glm::mat4 view = glm::lookAt(glm::vec3(0.0f, 0.0f, 3.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f)); //shader_.setMat4("projection", projection); //shader_.setMat4("view", view); // render the loaded model glm::mat4 model; //build_rotmatrix_(model, currQuat); model = glm::rotate(model, (-90.0f * 3.1415f) / 180.0f, glm::vec3(1.0f, 0.0f, 0.0f)); model = glm::rotate(model, (-90.0f * 3.1415f) / 180.0f, glm::vec3(0.0f, 0.0f, 1.0f)); // Fit to -1, 1 float maxExtent(getMaxExtent()); model = glm::scale(model, glm::vec3(1.0f / maxExtent, 1.0f / maxExtent, 1.0f / maxExtent)); // Centerize object model = glm::translate(model, glm::vec3(-0.5 * (max_[0] + min_[0]), -0.5 * (max_[1] + min_[1]), -0.5 * (max_[2] + min_[2]))); shader_.setMat4("model", model); glBindVertexArray(mesh.vao); if((mesh.materialId < materials_.size())) { const std::string diffuse_texname = materials_[mesh.materialId].diffuse_texname; std::string tex(base_ + diffuse_texname); if(textures_.find(tex) != textures_.end()) { glActiveTexture(GL_TEXTURE0); auto l(glGetUniformLocation(shader_.ID, "texture_diffuse1")); glUniform1i(l, 0); glBindTexture(GL_TEXTURE_2D, textures_.at(tex)->handle()); } } glDrawArrays(GL_TRIANGLES, 0, 3 * static_cast <int> (mesh.numTriangles)); checkErrors("drawarrays"); glBindTexture(GL_TEXTURE_2D, 0); } } } const float* const getMax() const { return max_; } const float* const getMin() const { return min_; } float getMaxExtent() const { float maxExtent(0.5f * (max_[0] - min_[0])); if(maxExtent < 0.5f * (max_[1] - min_[1])) { maxExtent = 0.5f * (max_[1] - min_[1]); } if(maxExtent < 0.5f * (max_[2] - min_[2])) { maxExtent = 0.5f * (max_[2] - min_[2]); } return maxExtent; } protected: void parseFile_(const std::string& fileName) { std::string err; tinyobj::LoadObj(&attrib_, &shapes_, &materials_, &err, fileName.c_str(), base_.c_str()); if(!err.empty()) { std::cerr << err << std::endl; } } void appendDefaultMaterial_() { materials_.push_back(tinyobj::material_t()); } void printOBJModelInfo_() { printf("# of vertices = %d\n", static_cast <int> (attrib_.vertices.size() / 3)); printf("# of normals = %d\n", static_cast <int> (attrib_.normals.size() / 3)); printf("# of texcoords = %d\n", static_cast <int> (attrib_.texcoords.size() / 2)); printf("# of materials = %d\n", static_cast <int> (materials_.size())); printf("# of shapes = %d\n", static_cast <int> (shapes_.size())); for(size_t i = 0; i < materials_.size(); i++) { printf("material[%d].diffuse_texname = %s\n", int(i), materials_[i].diffuse_texname.c_str()); } } void loadDiffuseTextures_() { for(auto& material : materials_) { if(material.diffuse_texname.length() > 0) { std::string tex(base_ + material.diffuse_texname); // Only load the texture if it is not already loaded if(textures_.find(tex) == textures_.end()) { auto texture(Texture::New(tex)); textures_.insert(std::make_pair(tex, texture)); } } } } void populateBuffer_() { size_t s{}; for(auto& shape : shapes_) { Mesh_ mesh; std::vector <float> buffer; // Check for smoothing group and compute smoothing normals std::map <int, vec3_> smoothVertexNormals; if(hasSmoothingGroup_(shape) > 0) { std::cout << "Compute smoothingNormal for shape [" << s << "]" << std::endl; computeSmoothingNormals(attrib_, shape, smoothVertexNormals); } for(size_t f(0); f < shape.mesh.indices.size() / 3; ++f) { tinyobj::index_t idx0 = shape.mesh.indices[3 * f + 0]; tinyobj::index_t idx1 = shape.mesh.indices[3 * f + 1]; tinyobj::index_t idx2 = shape.mesh.indices[3 * f + 2]; int currentMaterialId = shape.mesh.material_ids[f]; if((currentMaterialId < 0) || (currentMaterialId >= static_cast <int> (materials_.size()))) { // Invaid material ID. Use default material. currentMaterialId = static_cast <int> (materials_.size() - 1); // Default material is added to the last item in `materials`. } float diffuse[3]; for(size_t i = 0; i < 3; i++) { diffuse[i] = materials_[currentMaterialId].diffuse[i]; } float tc[3][2]; if((attrib_.texcoords.size() <= 0) || (idx0.texcoord_index < 0) || (idx1.texcoord_index < 0) || (idx2.texcoord_index < 0)) { // face does not contain valid uv index. tc[0][0] = 0.0f; tc[0][1] = 0.0f; tc[1][0] = 0.0f; tc[1][1] = 0.0f; tc[2][0] = 0.0f; tc[2][1] = 0.0f; } else { assert(attrib_.texcoords.size() > size_t(2 * idx0.texcoord_index + 1)); assert(attrib_.texcoords.size() > size_t(2 * idx1.texcoord_index + 1)); assert(attrib_.texcoords.size() > size_t(2 * idx2.texcoord_index + 1)); // Flip Y coord. tc[0][0] = attrib_.texcoords[2 * idx0.texcoord_index]; tc[0][1] = 1.0f - attrib_.texcoords[2 * idx0.texcoord_index + 1]; tc[1][0] = attrib_.texcoords[2 * idx1.texcoord_index]; tc[1][1] = 1.0f - attrib_.texcoords[2 * idx1.texcoord_index + 1]; tc[2][0] = attrib_.texcoords[2 * idx2.texcoord_index]; tc[2][1] = 1.0f - attrib_.texcoords[2 * idx2.texcoord_index + 1]; } // Vertices float v[3][3]; for (int k = 0; k < 3; k++) { int f0 = idx0.vertex_index; int f1 = idx1.vertex_index; int f2 = idx2.vertex_index; assert(f0 >= 0); assert(f1 >= 0); assert(f2 >= 0); v[0][k] = attrib_.vertices[3 * f0 + k]; v[1][k] = attrib_.vertices[3 * f1 + k]; v[2][k] = attrib_.vertices[3 * f2 + k]; min_[k] = std::min(v[0][k], min_[k]); min_[k] = std::min(v[1][k], min_[k]); min_[k] = std::min(v[2][k], min_[k]); max_[k] = std::max(v[0][k], max_[k]); max_[k] = std::max(v[1][k], max_[k]); max_[k] = std::max(v[2][k], max_[k]); } // Normals float n[3][3]; bool invalidNormalIndex(false); if(attrib_.normals.size() > 0) { int nf0 = idx0.normal_index; int nf1 = idx1.normal_index; int nf2 = idx2.normal_index; if((nf0 < 0) || (nf1 < 0) || (nf2 < 0)) { // normal index is missing from this face. invalidNormalIndex = true; } else { for(int k = 0; k < 3; k++) { assert(size_t(3 * nf0 + k) < attrib_.normals.size()); assert(size_t(3 * nf1 + k) < attrib_.normals.size()); assert(size_t(3 * nf2 + k) < attrib_.normals.size()); n[0][k] = attrib_.normals[3 * nf0 + k]; n[1][k] = attrib_.normals[3 * nf1 + k]; n[2][k] = attrib_.normals[3 * nf2 + k]; } } } else { invalidNormalIndex = true; } if(invalidNormalIndex && !smoothVertexNormals.empty()) { // Use smoothing normals int f0 = idx0.vertex_index; int f1 = idx1.vertex_index; int f2 = idx2.vertex_index; if(f0 >= 0 && f1 >= 0 && f2 >= 0) { n[0][0] = smoothVertexNormals[f0].v[0]; n[0][1] = smoothVertexNormals[f0].v[1]; n[0][2] = smoothVertexNormals[f0].v[2]; n[1][0] = smoothVertexNormals[f1].v[0]; n[1][1] = smoothVertexNormals[f1].v[1]; n[1][2] = smoothVertexNormals[f1].v[2]; n[2][0] = smoothVertexNormals[f2].v[0]; n[2][1] = smoothVertexNormals[f2].v[1]; n[2][2] = smoothVertexNormals[f2].v[2]; invalidNormalIndex = false; } } if(invalidNormalIndex) { // compute geometric normal calculateNormal_(n[0], v[0], v[1], v[2]); n[1][0] = n[0][0]; n[1][1] = n[0][1]; n[1][2] = n[0][2]; n[2][0] = n[0][0]; n[2][1] = n[0][1]; n[2][2] = n[0][2]; } // Push values into buffer for(int k = 0; k < 3; k++) { buffer.push_back(v[k][0]); buffer.push_back(v[k][1]); buffer.push_back(v[k][2]); buffer.push_back(n[k][0]); buffer.push_back(n[k][1]); buffer.push_back(n[k][2]); // Combine normal and diffuse to get color. float normal_factor = 0.2; float diffuse_factor = 1 - normal_factor; float c[3] = {n[k][0] * normal_factor + diffuse[0] * diffuse_factor, n[k][1] * normal_factor + diffuse[1] * diffuse_factor, n[k][2] * normal_factor + diffuse[2] * diffuse_factor}; float len2 = c[0] * c[0] + c[1] * c[1] + c[2] * c[2]; if(len2 > 0.0f) { float len = sqrtf(len2); c[0] /= len; c[1] /= len; c[2] /= len; } buffer.push_back(c[0] * 0.5 + 0.5); buffer.push_back(c[1] * 0.5 + 0.5); buffer.push_back(c[2] * 0.5 + 0.5); buffer.push_back(tc[k][0]); buffer.push_back(tc[k][1]); } } // Generate vbo mesh.vbo = 0; mesh.numTriangles = 0; // OpenGL viewer does not support texturing with per-face material. if(shape.mesh.material_ids.size() > 0 && shape.mesh.material_ids.size() > s) { mesh.materialId = shape.mesh.material_ids[0]; // use the material ID of the first face. } else { mesh.materialId = materials_.size() - 1; // = ID for default material. } printf("shape[%d] material_id %d\n", int(s), int(mesh.materialId)); if(buffer.size() > 0) { glGenVertexArrays(1, &mesh.vao); glGenBuffers(1, &mesh.vbo); glBindVertexArray(mesh.vao); glBindBuffer(GL_ARRAY_BUFFER, mesh.vbo); glBufferData(GL_ARRAY_BUFFER, buffer.size() * sizeof(float), &buffer.at(0), GL_STATIC_DRAW); GLsizei stride = (3 + 3 + 3 + 2) * sizeof(float); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, stride, (void*) 0); // vertex normals glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, stride, (void*) (3 * sizeof(float))); // vertex color glEnableVertexAttribArray(2); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, stride, (void*) (6 * sizeof(float))); // vertex texture coords glEnableVertexAttribArray(3); glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE, stride, (void*) (9 * sizeof(float))); mesh.numTriangles = static_cast <int> (buffer.size()) / (3 + 3 + 3 + 2) / 3; // 3:vtx, 3:normal, 3:col, 2:texcoord printf("shape[%d] # of triangles = %d\n", static_cast <int> (s), static_cast <int> (mesh.numTriangles)); } meshes_.push_back(mesh); ++s; } } void printMaxMin_() { printf("bmin = %f, %f, %f\n", min_[0], min_[1], min_[2]); printf("bmax = %f, %f, %f\n", max_[0], max_[1], max_[2]); } static void calculateNormal_(float N[3], float v0[3], float v1[3], float v2[3]) { const float v10[] = {v1[0] - v0[0], v1[1] - v0[1], v1[2] - v0[2]}; const float v20[] = {v2[0] - v0[0], v2[1] - v0[1], v2[2] - v0[2]}; N[0] = v20[1] * v10[2] - v20[2] * v10[1]; N[1] = v20[2] * v10[0] - v20[0] * v10[2]; N[2] = v20[0] * v10[1] - v20[1] * v10[0]; const float len2(N[0] * N[0] + N[1] * N[1] + N[2] * N[2]); if(len2 > 0.0f) { float len = sqrtf(len2); N[0] /= len; N[1] /= len; N[2] /= len; } } struct vec3_ { float v[3] = {0.0f, 0.0f, 0.0f}; }; void normalizeVector_(vec3_& v) { float len2 = v.v[0] * v.v[0] + v.v[1] * v.v[1] + v.v[2] * v.v[2]; if(len2 > 0.0f) { float len = sqrtf(len2); v.v[0] /= len; v.v[1] /= len; v.v[2] /= len; } } // Check if`mesh_t` contains smoothing group id. bool hasSmoothingGroup_(const tinyobj::shape_t& shape) { for (size_t i = 0; i < shape.mesh.smoothing_group_ids.size(); i++) { if(shape.mesh.smoothing_group_ids[i] > 0) { return true; } } return false; } void computeSmoothingNormals(const tinyobj::attrib_t& attrib, const tinyobj::shape_t& shape, std::map<int, vec3_>& smoothVertexNormals) { smoothVertexNormals.clear(); std::map <int, vec3_>::iterator iter; for(size_t f = 0; f < shape.mesh.indices.size() / 3; f++) { // Get the three indexes of the face (all faces are triangular) tinyobj::index_t idx0 = shape.mesh.indices[3 * f + 0]; tinyobj::index_t idx1 = shape.mesh.indices[3 * f + 1]; tinyobj::index_t idx2 = shape.mesh.indices[3 * f + 2]; // Get the three vertex indexes and coordinates int vi[3]; // indexes float v[3][3]; // coordinates for (int k = 0; k < 3; k++) { vi[0] = idx0.vertex_index; vi[1] = idx1.vertex_index; vi[2] = idx2.vertex_index; assert(vi[0] >= 0); assert(vi[1] >= 0); assert(vi[2] >= 0); v[0][k] = attrib.vertices[3 * vi[0] + k]; v[1][k] = attrib.vertices[3 * vi[1] + k]; v[2][k] = attrib.vertices[3 * vi[2] + k]; } // Compute the normal of the face float normal[3]; calculateNormal_(normal, v[0], v[1], v[2]); // Add the normal to the three vertexes for(size_t i = 0; i < 3; ++i) { iter = smoothVertexNormals.find(vi[i]); if(iter != smoothVertexNormals.end()) { // add iter->second.v[0] += normal[0]; iter->second.v[1] += normal[1]; iter->second.v[2] += normal[2]; } else { smoothVertexNormals[vi[i]].v[0] = normal[0]; smoothVertexNormals[vi[i]].v[1] = normal[1]; smoothVertexNormals[vi[i]].v[2] = normal[2]; } } } // Normalize the normals, that is, make them unit vectors for(iter = smoothVertexNormals.begin(); iter != smoothVertexNormals.end(); iter++) { normalizeVector_(iter->second); } } void build_rotmatrix_(glm::mat4& m, const float q[4]) const { m[0][0] = 1.0 - 2.0 * (q[1] * q[1] + q[2] * q[2]); m[0][1] = 2.0 * (q[0] * q[1] - q[2] * q[3]); m[0][2] = 2.0 * (q[2] * q[0] + q[1] * q[3]); m[0][3] = 0.0; m[1][0] = 2.0 * (q[0] * q[1] + q[2] * q[3]); m[1][1] = 1.0 - 2.0 * (q[2] * q[2] + q[0] * q[0]); m[1][2] = 2.0 * (q[1] * q[2] - q[0] * q[3]); m[1][3] = 0.0; m[2][0] = 2.0 * (q[2] * q[0] - q[1] * q[3]); m[2][1] = 2.0 * (q[1] * q[2] + q[0] * q[3]); m[2][2] = 1.0 - 2.0 * (q[1] * q[1] + q[0] * q[0]); m[2][3] = 0.0; m[3][0] = 0.0; m[3][1] = 0.0; m[3][2] = 0.0; m[3][3] = 1.0; } static std::string getBaseDir_(const std::string& filepath) { if(filepath.find_last_of("/\\") != std::string::npos) { return filepath.substr(0, filepath.find_last_of("/\\")); } return ""; } static void checkErrors(std::string desc) { GLenum e = glGetError(); if(e != GL_NO_ERROR) { fprintf(stderr, "OpenGL error in \"%s\": %d (%d)\n", desc.c_str(), e, e); exit(20); } } struct Mesh_ { unsigned int vao{}; unsigned int vbo{}; size_t numTriangles{}; size_t materialId{}; }; std::string base_{}; std::vector <Mesh_> meshes_; std::map <std::string, std::shared_ptr <Texture>> textures_; // tinyobj objects tinyobj::attrib_t attrib_; std::vector <tinyobj::shape_t> shapes_; std::vector <tinyobj::material_t> materials_; float min_[3] = {std::numeric_limits <float>::max(), std::numeric_limits <float>::max(), std::numeric_limits <float>::max()}; float max_[3] = {-std::numeric_limits <float>::max(), -std::numeric_limits <float>::max(), -std::numeric_limits <float>::max()}; float currQuat[4] = {0.0f, 0.0f, 0.0f, 0.0f}; // Shader aha::Shader shader_; }; }
41.170396
203
0.386998
[ "mesh", "render", "object", "shape", "vector", "model" ]
52cfe63c6046512b763fd625a0f30b963d71c82d
2,727
cpp
C++
SPlisHSPlasH/PCISPH/SimulationDataPCISPH.cpp
esCharacter/SPlisHSPlasH
139e5fd0e4f0ace801f039ab065a2e5ee72f8f9f
[ "MIT" ]
2
2022-03-04T02:16:35.000Z
2022-03-30T02:05:48.000Z
SPlisHSPlasH/PCISPH/SimulationDataPCISPH.cpp
HuangChunying/SPlisHSPlasH
139e5fd0e4f0ace801f039ab065a2e5ee72f8f9f
[ "MIT" ]
null
null
null
SPlisHSPlasH/PCISPH/SimulationDataPCISPH.cpp
HuangChunying/SPlisHSPlasH
139e5fd0e4f0ace801f039ab065a2e5ee72f8f9f
[ "MIT" ]
1
2017-06-27T09:48:20.000Z
2017-06-27T09:48:20.000Z
#include "SimulationDataPCISPH.h" #include "SPlisHSPlasH/SPHKernels.h" #include <iostream> #include "SPlisHSPlasH/TimeManager.h" using namespace SPH; SimulationDataPCISPH::SimulationDataPCISPH() { m_model = NULL; } SimulationDataPCISPH::~SimulationDataPCISPH(void) { cleanup(); } void SimulationDataPCISPH::init(FluidModel *model) { m_model = model; m_lastX.resize(model->numParticles(), SPH::Vector3r::Zero()); m_lastV.resize(model->numParticles(), SPH::Vector3r::Zero()); m_pressureAccel.resize(model->numParticles(), SPH::Vector3r::Zero()); m_densityAdv.resize(model->numParticles(), 0.0); m_pressure.resize(model->numParticles(), 0.0); m_pressureAccel.resize(model->numParticles(), SPH::Vector3r::Zero()); std::cout << "Initialize PCISPH scaling factor\n"; m_pcisph_factor = 0.0; model->getNeighborhoodSearch()->find_neighbors(); // Find prototype particle // => particle with max. fluid neighbors const Real h = TimeManager::getCurrent()->getTimeStepSize(); const Real h2 = h*h; const Real density0 = m_model->getDensity0(); unsigned int index = 0; unsigned int maxNeighbors = 0; for (int i = 0; i < (int)model->numParticles(); i++) { if (m_model->numberOfNeighbors(0, i) > maxNeighbors) { maxNeighbors = m_model->numberOfNeighbors(0, i); index = i; } } Vector3r sumGradW = Vector3r::Zero(); Real sumGradW2 = 0.0; const Vector3r &xi = model->getPosition(0, index); ////////////////////////////////////////////////////////////////////////// // Fluid ////////////////////////////////////////////////////////////////////////// for (unsigned int j = 0; j < m_model->numberOfNeighbors(0, index); j++) { const unsigned int neighborIndex = m_model->getNeighbor(0, index, j); const Vector3r &xj = m_model->getPosition(0, neighborIndex); const Vector3r gradW = m_model->gradW(xi - xj); sumGradW += gradW; sumGradW2 += gradW.squaredNorm(); } const Real beta = 2.0 * model->getMass(index)*model->getMass(index) / (density0*density0); // h^2 is multiplied in each iteration // to make the factor independent of h m_pcisph_factor = 1.0 / (beta * (sumGradW.squaredNorm() + sumGradW2)); } void SimulationDataPCISPH::cleanup() { m_lastX.clear(); m_lastV.clear(); m_densityAdv.clear(); m_pressure.clear(); m_pressureAccel.clear(); } void SimulationDataPCISPH::reset() { } void SimulationDataPCISPH::performNeighborhoodSearchSort() { const unsigned int numPart = m_model->numParticles(); if (numPart == 0) return; auto const& d = m_model->getNeighborhoodSearch()->point_set(0); d.sort_field(&m_lastX[0]); d.sort_field(&m_lastV[0]); d.sort_field(&m_densityAdv[0]); d.sort_field(&m_pressure[0]); d.sort_field(&m_pressureAccel[0]); }
28.113402
130
0.6685
[ "model" ]
52d262af76e5f2e9c5c40f8774eb67aa9ab5169a
3,293
cpp
C++
aligndiff/algorithms/ses_dp.cpp
mogemimi/daily-snippets
d9da3db8c62538e4a37f0f6b69c5d46d55c4225f
[ "MIT" ]
14
2017-06-16T22:52:38.000Z
2022-02-14T04:11:06.000Z
aligndiff/algorithms/ses_dp.cpp
mogemimi/daily-snippets
d9da3db8c62538e4a37f0f6b69c5d46d55c4225f
[ "MIT" ]
2
2016-03-13T14:50:04.000Z
2019-04-01T09:53:17.000Z
aligndiff/algorithms/ses_dp.cpp
mogemimi/daily-snippets
d9da3db8c62538e4a37f0f6b69c5d46d55c4225f
[ "MIT" ]
2
2016-03-13T14:05:17.000Z
2018-09-18T01:28:42.000Z
// Copyright (c) 2017 mogemimi. Distributed under the MIT license. #include "aligndiff.h" #include "optional.h" #include <cassert> namespace aligndiff { std::vector<DiffEdit> computeShortestEditScript_DynamicProgramming( const std::string& text1, const std::string& text2) { if (text1.empty() && text2.empty()) { return {}; } const auto rows = static_cast<int>(text1.size()) + 1; const auto columns = static_cast<int>(text2.size()) + 1; std::vector<int> matrix(rows * columns, 0); const auto mat = [&matrix, rows, columns](int row, int column) -> auto& { const auto index = row + rows * column; assert(index < static_cast<int>(matrix.size())); return matrix[index]; }; for (int row = 1; row < rows; row++) { mat(row, 0) = row; } for (int column = 1; column < columns; column++) { mat(0, column) = column; } // levenshtein distance for (int row = 1; row < rows; row++) { for (int column = 1; column < columns; column++) { auto minCost = std::min(mat(row - 1, column), mat(row, column - 1)) + 1; if (text1[row - 1] == text2[column - 1]) { minCost = std::min(mat(row - 1, column - 1), minCost); } mat(row, column) = minCost; } } #if 0 std::printf("\n"); for (int row = 0; row < rows; row++) { for (int column = 0; column < columns; column++) { std::printf("%3d", mat(row, column)); } std::printf("\n"); } std::printf("\n"); #endif std::vector<DiffEdit> edits; int row = rows - 1; int column = columns - 1; aligndiff::optional<int> longestCommonSubsequence; while ((row > 0) && (column > 0)) { // edit costs const auto deletion = mat(row - 1, column); const auto insertion = mat(row, column - 1); const auto equality = mat(row - 1, column - 1); if (longestCommonSubsequence && (*longestCommonSubsequence == mat(row, column)) && (text1[row - 1] == text2[column - 1])) { edits.push_back(makeDiffEdit(text1[row - 1], DiffOperation::Equality)); --row; --column; continue; } longestCommonSubsequence = aligndiff::nullopt; if ((text1[row - 1] == text2[column - 1]) && (equality < deletion) && (equality < insertion)) { edits.push_back(makeDiffEdit(text1[row - 1], DiffOperation::Equality)); --row; --column; longestCommonSubsequence = mat(row, column); } else if (deletion < insertion) { edits.push_back(makeDiffEdit(text1[row - 1], DiffOperation::Deletion)); --row; } else { edits.push_back(makeDiffEdit(text2[column - 1], DiffOperation::Insertion)); --column; } } while (column > 0) { edits.push_back(makeDiffEdit(text2[column - 1], DiffOperation::Insertion)); --column; } while (row > 0) { edits.push_back(makeDiffEdit(text1[row - 1], DiffOperation::Deletion)); --row; } std::reverse(std::begin(edits), std::end(edits)); return edits; } } // namespace aligndiff
29.401786
87
0.541755
[ "vector", "3d" ]
52e60bc7296b8fa4cf04ed325cf95a248b764b90
2,864
cpp
C++
examples/vector_prof.cpp
JCGoran/LATfield2
6d6d61d9c9730252c2ad08ef0150beddb8eb946e
[ "MIT" ]
13
2016-04-21T06:25:35.000Z
2021-08-11T07:19:51.000Z
examples/vector_prof.cpp
JCGoran/LATfield2
6d6d61d9c9730252c2ad08ef0150beddb8eb946e
[ "MIT" ]
13
2017-02-16T14:58:44.000Z
2021-05-29T21:42:31.000Z
examples/vector_prof.cpp
Lagrang3/LATfield2
5f21b631385f6e32f97f693d8259e34fa196e37a
[ "MIT" ]
13
2017-07-10T13:51:23.000Z
2021-11-08T02:32:32.000Z
/*! file gettingStarted.cpp Created by David Daverio. A simple example of LATfield2 usage. */ #include "LATfield2.hpp" using namespace LATfield2; #include <scorep/SCOREP_User.h> #include "timer.hpp" #define NTIMER 16 #define T_FADD_COMP 0 #define T_FDER3 1 #define T_FADD_COMP_OLD 2 #define T_FDER3_OLD 3 int main(int argc, char **argv) { //-------- Initilization of the parallel object --------- int n,m; int latSize = 64; int iteration = 1; for (int i=1 ; i < argc ; i++ ){ if ( argv[i][0] != '-' ) continue; switch(argv[i][1]) { case 'n': n = atoi(argv[++i]); break; case 'm': m = atoi(argv[++i]); break; case 's': latSize = atoi(argv[++i]); break; case 'i': iteration = atoi(argv[++i]); break; } } parallel.initialize(n,m); SCOREP_USER_REGION_DEFINE(fadd_comp) SCOREP_USER_REGION_DEFINE(fder3) int dim = 3; //int latSize = 256; int halo = 2; int vectorSize = 64;//latSize / 2; Lattice lat(dim,latSize,halo); Lattice lat_part(dim,latSize,0); Site x(lat); long npts3d = latSize*latSize*latSize; Field<Real> rho(lat,3); Field<Real> phi(lat); Field<Real> beta(lat,3); MPI_timer timer(NTIMER); for(x.first();x.test();x.next()) { for(int i=0;i<3;i++)rho(x,i) = x.coord(i); } rho.updateHalo(); for(int i = 0;i<iteration;i++) { timer.start(T_FADD_COMP); SCOREP_USER_REGION_BEGIN( fadd_comp, "fadd_comp", SCOREP_USER_REGION_TYPE_COMMON ) for(x.first();x.test();x.next()) { phi(x)=rho(x,0)+rho(x,1)+rho(x,2); } SCOREP_USER_REGION_END( fadd_comp ) timer.stop(T_FADD_COMP); timer.start(T_FDER3); SCOREP_USER_REGION_BEGIN( fder3, "fadd_comp", SCOREP_USER_REGION_TYPE_COMMON ) for(x.first();x.test();x.next()) { for(int i = 0;i<3;i++)beta(x,i)=phi(x+i)-phi(x-i); } SCOREP_USER_REGION_END( fder3 ) timer.stop(T_FDER3); } for(int i = 0;i<iteration;i++) { timer.start(T_FADD_COMP_OLD); for(x.first();x.test();x.next()) { phi(x)=rho(x,0)+rho(x,1)+rho(x,2); } timer.stop(T_FADD_COMP_OLD); timer.start(T_FDER3_OLD); for(x.first();x.test();x.next()) { for(int i = 0;i<3;i++)beta(x,i)=phi(x+i)-phi(x-i); } timer.stop(T_FDER3_OLD); } COUT<<"field comp sum time: "<<timer.timer(T_FADD_COMP)<<endl; COUT<<"field deriv_3p time: "<<timer.timer(T_FDER3)<<endl; COUT<<"field comp sum old time: "<<timer.timer(T_FADD_COMP_OLD)<<endl; COUT<<"field deriv_3p old time: "<<timer.timer(T_FDER3_OLD)<<endl; cout<<"done"<<endl; //-------------------------------------------------------- }
21.862595
90
0.54993
[ "object" ]
52f623909654750c43d9f0b3f66bd6274f06c04b
9,069
cpp
C++
apps/solver/list_controller.cpp
VersiraSec/epsilon-cfw
d12b44c6c6668ecc14b60d8dd098ba5c230b1291
[ "FSFAP" ]
1,442
2017-08-28T19:39:45.000Z
2022-03-30T00:56:14.000Z
apps/solver/list_controller.cpp
VersiraSec/epsilon-cfw
d12b44c6c6668ecc14b60d8dd098ba5c230b1291
[ "FSFAP" ]
1,321
2017-08-28T23:03:10.000Z
2022-03-31T19:32:17.000Z
apps/solver/list_controller.cpp
VersiraSec/epsilon-cfw
d12b44c6c6668ecc14b60d8dd098ba5c230b1291
[ "FSFAP" ]
421
2017-08-28T22:02:39.000Z
2022-03-28T20:52:21.000Z
#include "list_controller.h" #include "app.h" #include <poincare/circuit_breaker_checkpoint.h> #include <poincare/code_point_layout.h> #include <poincare/variable_context.h> #include <assert.h> using namespace Shared; using namespace Escher; namespace Solver { ListController::ListController(Responder * parentResponder, EquationStore * equationStore, ButtonRowController * footer) : ExpressionModelListController(parentResponder, I18n::Message::AddEquation), ButtonRowDelegate(nullptr, footer), m_equationListView(this), m_expressionCells{}, m_resolveButton(this, equationStore->numberOfDefinedModels() > 1 ? I18n::Message::ResolveSystem : I18n::Message::ResolveEquation, Invocation([](void * context, void * sender) { ListController * list = (ListController *)context; list->resolveEquations(); return true; }, this), KDFont::LargeFont, Palette::PurpleBright), m_modelsParameterController(this, equationStore, this), m_modelsStackController(nullptr, &m_modelsParameterController) { m_addNewModel.setAlignment(0.3f, 0.5f); // (EquationListView::k_braceTotalWidth+k_expressionMargin) / (Ion::Display::Width-m_addNewModel.text().size()) = (30+5)/(320-200) for (int i = 0; i < k_maxNumberOfRows; i++) { m_expressionCells[i].setLeftMargin(EquationListView::k_braceTotalWidth+k_expressionMargin); m_expressionCells[i].setEven(true); } } int ListController::numberOfButtons(ButtonRowController::Position position) const { if (position == ButtonRowController::Position::Bottom) { return 1; } return 0; } Button * ListController::buttonAtIndex(int index, ButtonRowController::Position position) const { if (position == ButtonRowController::Position::Top) { return nullptr; } return const_cast<Button *>(&m_resolveButton); } HighlightCell * ListController::reusableCell(int index, int type) { assert(index >= 0); assert(index < k_maxNumberOfRows); switch (type) { case 0: return &m_expressionCells[index]; case 1: return &m_addNewModel; default: assert(false); return nullptr; } } int ListController::reusableCellCount(int type) { if (type == 1) { return 1; } return k_maxNumberOfRows; } void ListController::willDisplayCellForIndex(HighlightCell * cell, int index) { if (!isAddEmptyRow(index)) { willDisplayExpressionCellAtIndex(cell, index); } cell->setHighlighted(index == selectedRow()); } bool ListController::handleEvent(Ion::Events::Event event) { if (event == Ion::Events::Up && selectedRow() == -1) { footer()->setSelectedButton(-1); selectableTableView()->selectCellAtLocation(0, numberOfRows()-1); Container::activeApp()->setFirstResponder(selectableTableView()); return true; } if (event == Ion::Events::Down) { if (selectedRow() == -1) { return false; } selectableTableView()->deselectTable(); footer()->setSelectedButton(0); return true; } return handleEventOnExpression(event); } void ListController::didBecomeFirstResponder() { if (selectedRow() == -1) { selectCellAtLocation(0, 0); } else { selectCellAtLocation(selectedColumn(), selectedRow()); } if (selectedRow() >= numberOfRows()) { selectCellAtLocation(selectedColumn(), numberOfRows()-1); } footer()->setSelectedButton(-1); Container::activeApp()->setFirstResponder(selectableTableView()); } void ListController::didEnterResponderChain(Responder * previousFirstResponder) { selectableTableView()->reloadData(); // Reload brace if the model store has evolved reloadBrace(); } bool textRepresentsAnEquality(const char * text) { char equal = '='; return UTF8Helper::CodePointIs(UTF8Helper::CodePointSearch(text, equal), equal); } bool layoutRepresentsAnEquality(Poincare::Layout l) { Poincare::Layout match = l.recursivelyMatches( [](Poincare::Layout layout) { return layout.type() == Poincare::LayoutNode::Type::CodePointLayout && static_cast<Poincare::CodePointLayout &>(layout).codePoint() == '='; }); return !match.isUninitialized(); } bool ListController::textFieldDidReceiveEvent(TextField * textField, Ion::Events::Event event) { if (textField->isEditing() && textField->shouldFinishEditing(event)) { const char * text = textField->text(); if (!textRepresentsAnEquality(text)) { textField->setCursorLocation(text + strlen(text)); textField->handleEventWithText("=0"); if (!textRepresentsAnEquality(text)) { Container::activeApp()->displayWarning(I18n::Message::RequireEquation); return true; } } } if (Shared::TextFieldDelegate::textFieldDidReceiveEvent(textField, event)) { return true; } return false; } bool ListController::layoutFieldDidReceiveEvent(LayoutField * layoutField, Ion::Events::Event event) { if (layoutField->isEditing() && layoutField->shouldFinishEditing(event)) { if (!layoutRepresentsAnEquality(layoutField->layout())) { layoutField->putCursorRightOfLayout(); layoutField->handleEventWithText("=0"); if (!layoutRepresentsAnEquality(layoutField->layout())) { Container::activeApp()->displayWarning(I18n::Message::RequireEquation); return true; } } } if (Shared::LayoutFieldDelegate::layoutFieldDidReceiveEvent(layoutField, event)) { return true; } return false; } bool ListController::textFieldDidFinishEditing(TextField * textField, const char * text, Ion::Events::Event event) { reloadButtonMessage(); return true; } bool ListController::layoutFieldDidFinishEditing(LayoutField * layoutField, Poincare::Layout layout, Ion::Events::Event event) { reloadButtonMessage(); return true; } void ListController::resolveEquations() { if (modelStore()->numberOfDefinedModels() == 0) { Container::activeApp()->displayWarning(I18n::Message::EnterEquation); return; } // Tidy model before checkpoint, during which older TreeNodes can't be altered modelStore()->tidy(); Poincare::UserCircuitBreakerCheckpoint checkpoint; if (CircuitBreakerRun(checkpoint)) { bool resultWithoutUserDefinedSymbols = false; EquationStore::Error e = modelStore()->exactSolve(textFieldDelegateApp()->localContext(), &resultWithoutUserDefinedSymbols); switch (e) { case EquationStore::Error::EquationUndefined: Container::activeApp()->displayWarning(I18n::Message::UndefinedEquation); return; case EquationStore::Error::EquationUnreal: Container::activeApp()->displayWarning(I18n::Message::UnrealEquation); return; case EquationStore::Error::TooManyVariables: Container::activeApp()->displayWarning(I18n::Message::TooManyVariables); return; case EquationStore::Error::NonLinearSystem: Container::activeApp()->displayWarning(I18n::Message::NonLinearSystem); return; case EquationStore::Error::RequireApproximateSolution: { reinterpret_cast<IntervalController *>(App::app()->intervalController())->setShouldReplaceFuncionsButNotSymbols(resultWithoutUserDefinedSymbols); stackController()->push(App::app()->intervalController(), KDColorWhite, Palette::PurpleBright, Palette::PurpleBright); return; } default: { assert(e == EquationStore::Error::NoError); StackViewController * stack = stackController(); reinterpret_cast<IntervalController *>(App::app()->intervalController())->setShouldReplaceFuncionsButNotSymbols(resultWithoutUserDefinedSymbols); stack->push(App::app()->solutionsControllerStack(), KDColorWhite, Palette::PurpleBright, Palette::PurpleBright); } } } else { modelStore()->tidy(); } } void ListController::reloadButtonMessage() { footer()->setMessageOfButtonAtIndex(modelStore()->numberOfDefinedModels() > 1 ? I18n::Message::ResolveSystem : I18n::Message::ResolveEquation, 0); } void ListController::addModel() { Container::activeApp()->displayModalViewController(&m_modelsStackController, 0.f, 0.f, Metric::PopUpTopMargin, Metric::PopUpRightMargin, 0, Metric::PopUpLeftMargin); } bool ListController::removeModelRow(Ion::Storage::Record record) { ExpressionModelListController::removeModelRow(record); reloadButtonMessage(); reloadBrace(); return true; } void ListController::reloadBrace() { EquationListView::BraceStyle braceStyle = modelStore()->numberOfModels() <= 1 ? EquationListView::BraceStyle::None : (modelStore()->numberOfModels() == modelStore()->maxNumberOfModels() ? EquationListView::BraceStyle::Full : EquationListView::BraceStyle::OneRowShort); m_equationListView.setBraceStyle(braceStyle); } EquationStore * ListController::modelStore() { return App::app()->equationStore(); } SelectableTableView * ListController::selectableTableView() { return m_equationListView.selectableTableView(); } StackViewController * ListController::stackController() const { return static_cast<StackViewController *>(parentResponder()->parentResponder()); } InputViewController * ListController::inputController() { return App::app()->inputViewController(); } }
36.421687
270
0.72632
[ "model" ]
52f62a8a68079134fe2c1423cfcba963c0e41ac7
58,180
cc
C++
third_party/blink/renderer/core/layout/ng/inline/ng_inline_cursor.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/blink/renderer/core/layout/ng/inline/ng_inline_cursor.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/blink/renderer/core/layout/ng/inline/ng_inline_cursor.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2021-01-05T23:43:46.000Z
2021-01-07T23:36:34.000Z
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_cursor.h" #include "third_party/blink/renderer/core/editing/position_with_affinity.h" #include "third_party/blink/renderer/core/layout/geometry/writing_mode_converter.h" #include "third_party/blink/renderer/core/layout/layout_block_flow.h" #include "third_party/blink/renderer/core/layout/layout_text.h" #include "third_party/blink/renderer/core/layout/ng/inline/ng_fragment_items.h" #include "third_party/blink/renderer/core/layout/ng/inline/ng_physical_line_box_fragment.h" #include "third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.h" #include "third_party/blink/renderer/core/paint/ng/ng_paint_fragment.h" #include "third_party/blink/renderer/core/paint/ng/ng_paint_fragment_traversal.h" namespace blink { inline void NGInlineCursor::MoveToItem(const ItemsSpan::iterator& iter) { DCHECK(IsItemCursor()); DCHECK(iter >= items_.begin() && iter <= items_.end()); if (iter != items_.end()) { current_.Set(iter); return; } MakeNull(); } void NGInlineCursor::SetRoot(const NGFragmentItems& fragment_items, ItemsSpan items) { DCHECK(items.data() || !items.size()); fragment_items_ = &fragment_items; items_ = items; DCHECK(fragment_items_->IsSubSpan(items_)); MoveToItem(items_.begin()); } void NGInlineCursor::SetRoot(const NGFragmentItems& items) { SetRoot(items, items.Items()); } void NGInlineCursor::SetRoot(const NGPaintFragment& root_paint_fragment) { DCHECK(&root_paint_fragment); DCHECK(!HasRoot()); root_paint_fragment_ = &root_paint_fragment; current_.paint_fragment_ = root_paint_fragment.FirstChild(); } bool NGInlineCursor::TrySetRootFragmentItems() { DCHECK(root_block_flow_); DCHECK(!fragment_items_ || fragment_items_->Equals(items_)); for (; fragment_index_ <= max_fragment_index_; ++fragment_index_) { const NGPhysicalBoxFragment* fragment = root_block_flow_->GetPhysicalFragment(fragment_index_); DCHECK(fragment); if (const NGFragmentItems* items = fragment->Items()) { SetRoot(*items); return true; } } return false; } void NGInlineCursor::SetRoot(const LayoutBlockFlow& block_flow) { DCHECK(&block_flow); DCHECK(!HasRoot()); if (const wtf_size_t fragment_count = block_flow.PhysicalFragmentCount()) { root_block_flow_ = &block_flow; max_fragment_index_ = fragment_count - 1; fragment_index_ = 0; if (TrySetRootFragmentItems()) return; } if (const NGPaintFragment* paint_fragment = block_flow.PaintFragment()) { SetRoot(*paint_fragment); return; } // We reach here in case of |ScrollANchor::NotifyBeforeLayout()| via // |LayoutText::PhysicalLinesBoundingBox()| // See external/wpt/css/css-scroll-anchoring/wrapped-text.html } NGInlineCursor::NGInlineCursor(const LayoutBlockFlow& block_flow) { SetRoot(block_flow); } NGInlineCursor::NGInlineCursor(const NGFragmentItems& fragment_items, ItemsSpan items) { SetRoot(fragment_items, items); } NGInlineCursor::NGInlineCursor(const NGFragmentItems& items) { SetRoot(items); } NGInlineCursor::NGInlineCursor(const NGPaintFragment& root_paint_fragment) { SetRoot(root_paint_fragment); } NGInlineCursor::NGInlineCursor(const NGInlineBackwardCursor& backward_cursor) : NGInlineCursor(backward_cursor.cursor_) { MoveTo(backward_cursor.Current()); } bool NGInlineCursor::operator==(const NGInlineCursor& other) const { if (root_paint_fragment_) { return root_paint_fragment_ == other.root_paint_fragment_ && current_.paint_fragment_ == other.current_.paint_fragment_; } if (current_.item_ != other.current_.item_) return false; DCHECK_EQ(items_.data(), other.items_.data()); DCHECK_EQ(items_.size(), other.items_.size()); DCHECK_EQ(fragment_items_, other.fragment_items_); DCHECK(current_.item_iter_ == other.current_.item_iter_); return true; } const LayoutBlockFlow* NGInlineCursor::GetLayoutBlockFlow() const { if (IsPaintFragmentCursor()) { // |root_paint_fragment_| is either |LayoutBlockFlow| or |LayoutInline|. const NGPhysicalFragment& physical_fragment = root_paint_fragment_->PhysicalFragment(); const LayoutObject* layout_object = physical_fragment.IsLineBox() ? To<NGPhysicalLineBoxFragment>(physical_fragment) .ContainerLayoutObject() : physical_fragment.GetLayoutObject(); if (const LayoutBlockFlow* block_flow = DynamicTo<LayoutBlockFlow>(layout_object)) return block_flow; DCHECK(layout_object->IsLayoutInline()); return layout_object->RootInlineFormattingContext(); } if (IsItemCursor()) { const NGFragmentItem& item = fragment_items_->front(); const LayoutObject* layout_object = item.GetLayoutObject(); if (item.Type() == NGFragmentItem::kLine) return To<LayoutBlockFlow>(layout_object); return layout_object->RootInlineFormattingContext(); } NOTREACHED(); return nullptr; } bool NGInlineCursorPosition::HasChildren() const { if (paint_fragment_) return paint_fragment_->FirstChild(); if (item_) return item_->HasChildren(); NOTREACHED(); return false; } NGInlineCursor NGInlineCursor::CursorForDescendants() const { if (current_.paint_fragment_) return NGInlineCursor(*current_.paint_fragment_); if (current_.item_) { unsigned descendants_count = current_.item_->DescendantsCount(); if (descendants_count > 1) { DCHECK(fragment_items_); return NGInlineCursor( *fragment_items_, ItemsSpan(&*(current_.item_iter_ + 1), descendants_count - 1)); } return NGInlineCursor(); } NOTREACHED(); return NGInlineCursor(); } void NGInlineCursor::ExpandRootToContainingBlock() { if (root_paint_fragment_) { root_paint_fragment_ = root_paint_fragment_->Root(); return; } if (fragment_items_) { const unsigned index_diff = items_.data() - fragment_items_->Items().data(); DCHECK_LT(index_diff, fragment_items_->Items().size()); const unsigned item_index = current_.item_iter_ - items_.begin(); items_ = fragment_items_->Items(); // Update the iterator to the one for the new span. MoveToItem(items_.begin() + item_index + index_diff); return; } NOTREACHED(); } bool NGInlineCursorPosition::HasSoftWrapToNextLine() const { DCHECK(IsLineBox()); const NGInlineBreakToken* break_token = InlineBreakToken(); DCHECK(break_token); return !break_token->IsFinished() && !break_token->IsForcedBreak(); } bool NGInlineCursorPosition::IsInlineBox() const { if (paint_fragment_) return paint_fragment_->PhysicalFragment().IsInlineBox(); if (item_) return item_->IsInlineBox(); NOTREACHED(); return false; } bool NGInlineCursorPosition::IsAtomicInline() const { if (paint_fragment_) return paint_fragment_->PhysicalFragment().IsAtomicInline(); if (item_) return item_->IsAtomicInline(); NOTREACHED(); return false; } bool NGInlineCursorPosition::IsEllipsis() const { if (paint_fragment_) return paint_fragment_->IsEllipsis(); if (item_) return item_->IsEllipsis(); NOTREACHED(); return false; } bool NGInlineCursorPosition::IsGeneratedText() const { if (paint_fragment_) { if (auto* text_fragment = DynamicTo<NGPhysicalTextFragment>( paint_fragment_->PhysicalFragment())) return text_fragment->IsGeneratedText(); return false; } if (item_) return item_->IsGeneratedText(); NOTREACHED(); return false; } bool NGInlineCursorPosition::IsLayoutGeneratedText() const { if (paint_fragment_) { if (auto* text_fragment = DynamicTo<NGPhysicalTextFragment>( paint_fragment_->PhysicalFragment())) { return text_fragment->TextType() == NGTextType::kLayoutGenerated; } return false; } if (item_) return item_->Type() == NGFragmentItem::kGeneratedText; NOTREACHED(); return false; } bool NGInlineCursorPosition::IsHiddenForPaint() const { if (paint_fragment_) return paint_fragment_->PhysicalFragment().IsHiddenForPaint(); if (item_) return item_->IsHiddenForPaint(); NOTREACHED(); return false; } bool NGInlineCursorPosition::IsInlineLeaf() const { if (IsHiddenForPaint()) return false; if (IsText()) return !IsLayoutGeneratedText(); if (!IsAtomicInline()) return false; return !IsListMarker(); } bool NGInlineCursor::IsLastLineInInlineBlock() const { DCHECK(Current().IsLineBox()); if (!GetLayoutBlockFlow()->IsAtomicInlineLevel()) return false; NGInlineCursor next_sibling(*this); for (;;) { next_sibling.MoveToNextSkippingChildren(); if (!next_sibling) return true; if (next_sibling.Current().IsLineBox()) return false; // There maybe other top-level objects such as floats, OOF, or list-markers. } } bool NGInlineCursorPosition::IsLineBreak() const { if (paint_fragment_) { if (auto* text_fragment = DynamicTo<NGPhysicalTextFragment>( paint_fragment_->PhysicalFragment())) return text_fragment->IsLineBreak(); return false; } if (item_) return IsText() && item_->IsLineBreak(); NOTREACHED(); return false; } bool NGInlineCursorPosition::IsListMarker() const { if (paint_fragment_) return paint_fragment_->PhysicalFragment().IsListMarker(); if (item_) return item_->IsListMarker(); NOTREACHED(); return false; } bool NGInlineCursorPosition::IsText() const { if (paint_fragment_) return paint_fragment_->PhysicalFragment().IsText(); if (item_) return item_->IsText(); NOTREACHED(); return false; } bool NGInlineCursor::IsBeforeSoftLineBreak() const { if (Current().IsLineBreak()) return false; // Inline block is not be container line box. // See paint/selection/text-selection-inline-block.html. NGInlineCursor line(*this); line.MoveToContainingLine(); if (line.IsLastLineInInlineBlock()) { // We don't paint a line break the end of inline-block // because if an inline-block is at the middle of line, we should not paint // a line break. // Old layout paints line break if the inline-block is at the end of line, // but since its complex to determine if the inline-block is at the end of // line on NG, we just cancels block-end line break painting for any // inline-block. return false; } NGInlineCursor last_leaf(line); last_leaf.MoveToLastLogicalLeaf(); if (last_leaf != *this) return false; // Even If |fragment| is before linebreak, if its direction differs to line // direction, we don't paint line break. See // paint/selection/text-selection-newline-mixed-ltr-rtl.html. return line.Current().BaseDirection() == Current().ResolvedDirection(); } bool NGInlineCursorPosition::CanHaveChildren() const { if (paint_fragment_) return paint_fragment_->PhysicalFragment().IsContainer(); if (item_) { return item_->Type() == NGFragmentItem::kLine || (item_->Type() == NGFragmentItem::kBox && !item_->IsAtomicInline()); } NOTREACHED(); return false; } bool NGInlineCursorPosition::IsEmptyLineBox() const { DCHECK(IsLineBox()); if (paint_fragment_) { return To<NGPhysicalLineBoxFragment>(paint_fragment_->PhysicalFragment()) .IsEmptyLineBox(); } if (item_) return item_->IsEmptyLineBox(); NOTREACHED(); return false; } bool NGInlineCursorPosition::IsLineBox() const { if (paint_fragment_) return paint_fragment_->PhysicalFragment().IsLineBox(); if (item_) return item_->Type() == NGFragmentItem::kLine; NOTREACHED(); return false; } TextDirection NGInlineCursorPosition::BaseDirection() const { DCHECK(IsLineBox()); if (paint_fragment_) { return To<NGPhysicalLineBoxFragment>(paint_fragment_->PhysicalFragment()) .BaseDirection(); } if (item_) return item_->BaseDirection(); NOTREACHED(); return TextDirection::kLtr; } UBiDiLevel NGInlineCursorPosition::BidiLevel() const { if (IsText()) { if (IsLayoutGeneratedText()) { // TODO(yosin): Until we have clients, we don't support bidi-level for // ellipsis and soft hyphens. NOTREACHED() << this; return 0; } const LayoutText& layout_text = *ToLayoutText(GetLayoutObject()); DCHECK(!layout_text.NeedsLayout()) << this; const auto* const items = layout_text.GetNGInlineItems(); if (!items || items->size() == 0) { // In case of <br>, <wbr>, text-combine-upright, etc. return 0; } const NGTextOffset offset = TextOffset(); const auto& item = std::find_if( items->begin(), items->end(), [offset](const NGInlineItem& item) { return item.StartOffset() <= offset.start && item.EndOffset() >= offset.end; }); DCHECK(item != items->end()) << this; return item->BidiLevel(); } if (IsAtomicInline()) { const NGPhysicalBoxFragment* fragmentainer = GetLayoutObject()->ContainingBlockFlowFragment(); DCHECK(fragmentainer); const LayoutBlockFlow& block_flow = *To<LayoutBlockFlow>(fragmentainer->GetLayoutObject()); const Vector<NGInlineItem> items = block_flow.GetNGInlineNodeData()->ItemsData(UsesFirstLineStyle()).items; const LayoutObject* const layout_object = GetLayoutObject(); const auto* const item = std::find_if( items.begin(), items.end(), [layout_object](const NGInlineItem& item) { return item.GetLayoutObject() == layout_object; }); DCHECK(item != items.end()) << this; return item->BidiLevel(); } NOTREACHED(); return 0; } const NGPhysicalBoxFragment* NGInlineCursorPosition::BoxFragment() const { if (paint_fragment_) { return DynamicTo<NGPhysicalBoxFragment>( &paint_fragment_->PhysicalFragment()); } if (item_) return item_->BoxFragment(); NOTREACHED(); return nullptr; } const DisplayItemClient* NGInlineCursorPosition::GetDisplayItemClient() const { if (paint_fragment_) return paint_fragment_; if (item_) return item_->GetDisplayItemClient(); NOTREACHED(); return nullptr; } const DisplayItemClient* NGInlineCursorPosition::GetSelectionDisplayItemClient() const { if (const auto* client = GetLayoutObject()->GetSelectionDisplayItemClient()) return client; return GetDisplayItemClient(); } wtf_size_t NGInlineCursorPosition::FragmentId() const { if (paint_fragment_) return 0; DCHECK(item_); return item_->FragmentId(); } const NGInlineBreakToken* NGInlineCursorPosition::InlineBreakToken() const { DCHECK(IsLineBox()); if (paint_fragment_) { return To<NGInlineBreakToken>( To<NGPhysicalLineBoxFragment>(paint_fragment_->PhysicalFragment()) .BreakToken()); } DCHECK(item_); return item_->InlineBreakToken(); } const LayoutObject* NGInlineCursorPosition::GetLayoutObject() const { if (paint_fragment_) return paint_fragment_->GetLayoutObject(); if (item_) return item_->GetLayoutObject(); NOTREACHED(); return nullptr; } LayoutObject* NGInlineCursorPosition::GetMutableLayoutObject() const { if (paint_fragment_) return paint_fragment_->GetMutableLayoutObject(); if (item_) return item_->GetMutableLayoutObject(); NOTREACHED(); return nullptr; } const Node* NGInlineCursorPosition::GetNode() const { if (const LayoutObject* layout_object = GetLayoutObject()) return layout_object->GetNode(); return nullptr; } const PhysicalRect NGInlineCursorPosition::InkOverflow() const { if (paint_fragment_) return paint_fragment_->InkOverflow(); if (item_) return item_->InkOverflow(); NOTREACHED(); return PhysicalRect(); } const PhysicalOffset NGInlineCursorPosition::OffsetInContainerBlock() const { if (paint_fragment_) return paint_fragment_->OffsetInContainerBlock(); if (item_) return item_->OffsetInContainerBlock(); NOTREACHED(); return PhysicalOffset(); } const PhysicalSize NGInlineCursorPosition::Size() const { if (paint_fragment_) return paint_fragment_->Size(); if (item_) return item_->Size(); NOTREACHED(); return PhysicalSize(); } const PhysicalRect NGInlineCursorPosition::RectInContainerBlock() const { if (paint_fragment_) { return {paint_fragment_->OffsetInContainerBlock(), paint_fragment_->Size()}; } if (item_) return item_->RectInContainerBlock(); NOTREACHED(); return PhysicalRect(); } const PhysicalRect NGInlineCursorPosition::SelfInkOverflow() const { if (paint_fragment_) return paint_fragment_->SelfInkOverflow(); if (item_) return item_->SelfInkOverflow(); NOTREACHED(); return PhysicalRect(); } TextDirection NGInlineCursorPosition::ResolvedDirection() const { if (paint_fragment_) return paint_fragment_->PhysicalFragment().ResolvedDirection(); if (item_) return item_->ResolvedDirection(); NOTREACHED(); return TextDirection::kLtr; } const ComputedStyle& NGInlineCursorPosition::Style() const { if (paint_fragment_) return paint_fragment_->Style(); return item_->Style(); } NGStyleVariant NGInlineCursorPosition::StyleVariant() const { if (paint_fragment_) return paint_fragment_->PhysicalFragment().StyleVariant(); return item_->StyleVariant(); } bool NGInlineCursorPosition::UsesFirstLineStyle() const { return StyleVariant() == NGStyleVariant::kFirstLine; } NGTextOffset NGInlineCursorPosition::TextOffset() const { if (paint_fragment_) { const auto& text_fragment = To<NGPhysicalTextFragment>(paint_fragment_->PhysicalFragment()); return text_fragment.TextOffset(); } if (item_) return item_->TextOffset(); NOTREACHED(); return {}; } StringView NGInlineCursorPosition::Text(const NGInlineCursor& cursor) const { DCHECK(IsText()); cursor.CheckValid(*this); if (paint_fragment_) { return To<NGPhysicalTextFragment>(paint_fragment_->PhysicalFragment()) .Text(); } if (item_) return item_->Text(cursor.Items()); NOTREACHED(); return ""; } const ShapeResultView* NGInlineCursorPosition::TextShapeResult() const { DCHECK(IsText()); if (paint_fragment_) { return To<NGPhysicalTextFragment>(paint_fragment_->PhysicalFragment()) .TextShapeResult(); } if (item_) return item_->TextShapeResult(); NOTREACHED(); return nullptr; } PhysicalRect NGInlineCursor::CurrentLocalRect(unsigned start_offset, unsigned end_offset) const { DCHECK(Current().IsText()); if (current_.paint_fragment_) { return To<NGPhysicalTextFragment>( current_.paint_fragment_->PhysicalFragment()) .LocalRect(start_offset, end_offset); } if (current_.item_) { return current_.item_->LocalRect(current_.item_->Text(*fragment_items_), start_offset, end_offset); } NOTREACHED(); return PhysicalRect(); } LayoutUnit NGInlineCursor::InlinePositionForOffset(unsigned offset) const { DCHECK(Current().IsText()); if (current_.paint_fragment_) { return To<NGPhysicalTextFragment>( current_.paint_fragment_->PhysicalFragment()) .InlinePositionForOffset(offset); } if (current_.item_) { return current_.item_->InlinePositionForOffset( current_.item_->Text(*fragment_items_), offset); } NOTREACHED(); return LayoutUnit(); } PhysicalOffset NGInlineCursorPosition::LineStartPoint() const { DCHECK(IsLineBox()) << this; const LogicalOffset logical_start; // (0, 0) const PhysicalSize pixel_size(LayoutUnit(1), LayoutUnit(1)); return logical_start.ConvertToPhysical(Style().GetWritingMode(), BaseDirection(), Size(), pixel_size); } PhysicalOffset NGInlineCursorPosition::LineEndPoint() const { DCHECK(IsLineBox()) << this; const WritingMode writing_mode = Style().GetWritingMode(); const LayoutUnit inline_size = IsHorizontalWritingMode(writing_mode) ? Size().width : Size().height; const LogicalOffset logical_end(inline_size, LayoutUnit()); const PhysicalSize pixel_size(LayoutUnit(1), LayoutUnit(1)); return logical_end.ConvertToPhysical(writing_mode, BaseDirection(), Size(), pixel_size); } LogicalRect NGInlineCursorPosition::ConvertChildToLogical( const PhysicalRect& physical_rect) const { return WritingModeConverter( {Style().GetWritingMode(), ResolvedOrBaseDirection()}, Size()) .ToLogical(physical_rect); } PhysicalRect NGInlineCursorPosition::ConvertChildToPhysical( const LogicalRect& logical_rect) const { return WritingModeConverter( {Style().GetWritingMode(), ResolvedOrBaseDirection()}, Size()) .ToPhysical(logical_rect); } PositionWithAffinity NGInlineCursor::PositionForPointInInlineFormattingContext( const PhysicalOffset& point, const NGPhysicalBoxFragment& container) { DCHECK(IsItemCursor()); const ComputedStyle& container_style = container.Style(); const WritingMode writing_mode = container_style.GetWritingMode(); const TextDirection direction = container_style.Direction(); const PhysicalSize& container_size = container.Size(); const LayoutUnit point_block_offset = point .ConvertToLogical(writing_mode, direction, container_size, // |point| is actually a pixel with size 1x1. PhysicalSize(LayoutUnit(1), LayoutUnit(1))) .block_offset; // Stores the closest line box child after |point| in the block direction. // Used if we can't find any child |point| falls in to resolve the position. NGInlineCursorPosition closest_line_after; LayoutUnit closest_line_after_block_offset = LayoutUnit::Min(); // Stores the closest line box child before |point| in the block direction. // Used if we can't find any child |point| falls in to resolve the position. NGInlineCursorPosition closest_line_before; LayoutUnit closest_line_before_block_offset = LayoutUnit::Max(); while (*this) { const NGFragmentItem* child_item = CurrentItem(); DCHECK(child_item); if (child_item->Type() == NGFragmentItem::kLine) { if (!CursorForDescendants().TryToMoveToFirstInlineLeafChild()) { // editing/selection/last-empty-inline.html requires this to skip // empty <span> with padding. MoveToNextItemSkippingChildren(); continue; } // Try to resolve if |point| falls in a line box in block direction. const LayoutUnit child_block_offset = child_item->OffsetInContainerBlock() .ConvertToLogical(writing_mode, direction, container_size, child_item->Size()) .block_offset; if (point_block_offset < child_block_offset) { if (child_block_offset < closest_line_before_block_offset) { closest_line_before_block_offset = child_block_offset; closest_line_before = Current(); } MoveToNextItemSkippingChildren(); continue; } // Hitting on line bottom doesn't count, to match legacy behavior. const LayoutUnit child_block_end_offset = child_block_offset + child_item->Size().ConvertToLogical(writing_mode).block_size; if (point_block_offset >= child_block_end_offset) { if (child_block_end_offset > closest_line_after_block_offset) { closest_line_after_block_offset = child_block_end_offset; closest_line_after = Current(); } MoveToNextItemSkippingChildren(); continue; } if (const PositionWithAffinity child_position = PositionForPointInInlineBox(point)) return child_position; MoveToNextItemSkippingChildren(); continue; } DCHECK_NE(child_item->Type(), NGFragmentItem::kText); MoveToNextItem(); } // At here, |point| is not inside any line in |this|: // |closest_line_before| // |point| // |closest_line_after| if (closest_line_before) { MoveTo(closest_line_before); // Note: |move_caret_to_boundary| is true for Mac and Unix. const bool move_caret_to_boundary = To<LayoutBlockFlow>(Current().GetLayoutObject()) ->ShouldMoveCaretToHorizontalBoundaryWhenPastTopOrBottom(); if (move_caret_to_boundary) { // Tests[1-3] reach here. // [1] editing/selection/click-in-margins-inside-editable-div.html // [2] fast/writing-mode/flipped-blocks-hit-test-line-edges.html // [3] All/LayoutViewHitTestTest.HitTestHorizontal/4 if (auto first_position = PositionForStartOfLine()) return PositionWithAffinity(first_position.GetPosition()); } else if (const PositionWithAffinity child_position = PositionForPointInInlineBox(point)) return child_position; } if (closest_line_after) { MoveTo(closest_line_after); // Note: |move_caret_to_boundary| is true for Mac and Unix. const bool move_caret_to_boundary = To<LayoutBlockFlow>(Current().GetLayoutObject()) ->ShouldMoveCaretToHorizontalBoundaryWhenPastTopOrBottom(); if (move_caret_to_boundary) { // Tests[1-3] reach here. // [1] editing/selection/click-in-margins-inside-editable-div.html // [2] fast/writing-mode/flipped-blocks-hit-test-line-edges.html // [3] All/LayoutViewHitTestTest.HitTestHorizontal/4 if (auto last_position = PositionForEndOfLine()) return PositionWithAffinity(last_position.GetPosition()); } else if (const PositionWithAffinity child_position = PositionForPointInInlineBox(point)) { // Test[1] reaches here. // [1] editing/selection/last-empty-inline.html return child_position; } } return PositionWithAffinity(); } PositionWithAffinity NGInlineCursor::PositionForPointInInlineBox( const PhysicalOffset& point) const { if (const NGPaintFragment* paint_fragment = CurrentPaintFragment()) { DCHECK(paint_fragment->PhysicalFragment().IsLineBox()); return paint_fragment->PositionForPoint(point); } const NGFragmentItem* container = CurrentItem(); DCHECK(container); DCHECK(container->Type() == NGFragmentItem::kLine || container->Type() == NGFragmentItem::kBox); const ComputedStyle& container_style = container->Style(); const WritingMode writing_mode = container_style.GetWritingMode(); const TextDirection direction = container_style.Direction(); const PhysicalSize& container_size = container->Size(); const LayoutUnit point_inline_offset = point .ConvertToLogical(writing_mode, direction, container_size, // |point| is actually a pixel with size 1x1. PhysicalSize(LayoutUnit(1), LayoutUnit(1))) .inline_offset; // Stores the closest child before |point| in the inline direction. Used if we // can't find any child |point| falls in to resolve the position. NGInlineCursorPosition closest_child_before; LayoutUnit closest_child_before_inline_offset = LayoutUnit::Min(); // Stores the closest child after |point| in the inline direction. Used if we // can't find any child |point| falls in to resolve the position. NGInlineCursorPosition closest_child_after; LayoutUnit closest_child_after_inline_offset = LayoutUnit::Max(); NGInlineCursor descendants = CursorForDescendants(); for (; descendants; descendants.MoveToNext()) { const NGFragmentItem* child_item = descendants.CurrentItem(); DCHECK(child_item); if (child_item->Type() == NGFragmentItem::kBox && !child_item->BoxFragment()) { // Skip virtually "culled" inline box, e.g. <span>foo</span> // "editing/selection/shift-click.html" reaches here. DCHECK(child_item->GetLayoutObject()->IsLayoutInline()) << child_item; continue; } const LayoutUnit child_inline_offset = child_item->OffsetInContainerBlock() .ConvertToLogical(writing_mode, direction, container_size, child_item->Size()) .inline_offset; if (point_inline_offset < child_inline_offset) { if (child_inline_offset < closest_child_after_inline_offset) { closest_child_after_inline_offset = child_inline_offset; closest_child_after = descendants.Current(); } continue; } const LayoutUnit child_inline_end_offset = child_inline_offset + child_item->Size().ConvertToLogical(writing_mode).inline_size; if (point_inline_offset > child_inline_end_offset) { if (child_inline_end_offset > closest_child_before_inline_offset) { closest_child_before_inline_offset = child_inline_end_offset; closest_child_before = descendants.Current(); } continue; } if (const PositionWithAffinity child_position = descendants.PositionForPointInChild(point)) return child_position; } if (closest_child_after) { descendants.MoveTo(closest_child_after); if (const PositionWithAffinity child_position = descendants.PositionForPointInChild(point)) return child_position; if (closest_child_after->BoxFragment()) { // Hit test at left of "12"[1] and after "cd"[2] reache here. // "<span dir="rtl">12<b>&#x05E7;&#x05D0;43</b></span>ab" // [1] "editing/selection/caret-at-bidi-boundary.html" // [2] HitTestingTest.PseudoElementAfter if (const PositionWithAffinity child_position = descendants.PositionForPointInInlineBox(point)) return child_position; } } if (closest_child_before) { descendants.MoveTo(closest_child_before); if (const PositionWithAffinity child_position = descendants.PositionForPointInChild(point)) return child_position; if (closest_child_before->BoxFragment()) { // LayoutViewHitTest.HitTestHorizontal "Top-right corner (outside) of div" // reach here. if (const PositionWithAffinity child_position = descendants.PositionForPointInInlineBox(point)) return child_position; } } return PositionWithAffinity(); } PositionWithAffinity NGInlineCursor::PositionForPointInChild( const PhysicalOffset& point_in_container) const { if (auto* paint_fragment = CurrentPaintFragment()) { const PhysicalOffset point_in_child = point_in_container - paint_fragment->OffsetInContainerBlock(); return paint_fragment->PositionForPoint(point_in_child); } DCHECK(CurrentItem()); const NGFragmentItem& child_item = *CurrentItem(); switch (child_item.Type()) { case NGFragmentItem::kText: return child_item.PositionForPointInText( point_in_container - child_item.OffsetInContainerBlock(), *this); case NGFragmentItem::kGeneratedText: break; case NGFragmentItem::kBox: if (const NGPhysicalBoxFragment* box_fragment = child_item.BoxFragment()) { if (!box_fragment->IsInlineBox()) { // In case of inline block with with block formatting context that // has block children[1]. // Example: <b style="display:inline-block"><div>b</div></b> // [1] NGInlineCursorTest.PositionForPointInChildBlockChildren return child_item.GetLayoutObject()->PositionForPoint( point_in_container - child_item.OffsetInContainerBlock()); } } else { // |LayoutInline| used to be culled. } DCHECK(child_item.GetLayoutObject()->IsLayoutInline()) << child_item; break; case NGFragmentItem::kLine: NOTREACHED(); break; } return PositionWithAffinity(); } PositionWithAffinity NGInlineCursor::PositionForStartOfLine() const { DCHECK(Current().IsLineBox()); const PhysicalOffset point_in_line = Current().LineStartPoint(); if (IsItemCursor()) { return PositionForPointInInlineBox(point_in_line + Current().OffsetInContainerBlock()); } return CurrentPaintFragment()->PositionForPoint(point_in_line); } PositionWithAffinity NGInlineCursor::PositionForEndOfLine() const { DCHECK(Current().IsLineBox()); const PhysicalOffset point_in_line = Current().LineEndPoint(); if (IsItemCursor()) { return PositionForPointInInlineBox(point_in_line + Current().OffsetInContainerBlock()); } return CurrentPaintFragment()->PositionForPoint(point_in_line); } void NGInlineCursor::MoveTo(const NGInlineCursorPosition& position) { CheckValid(position); current_ = position; } inline wtf_size_t NGInlineCursor::SpanBeginItemIndex() const { DCHECK(IsItemCursor()); DCHECK(!items_.empty()); DCHECK(fragment_items_->IsSubSpan(items_)); const wtf_size_t delta = items_.data() - fragment_items_->Items().data(); DCHECK_LT(delta, fragment_items_->Items().size()); return delta; } inline wtf_size_t NGInlineCursor::SpanIndexFromItemIndex(unsigned index) const { DCHECK(IsItemCursor()); DCHECK(!items_.empty()); DCHECK(fragment_items_->IsSubSpan(items_)); if (items_.data() == fragment_items_->Items().data()) return index; const wtf_size_t span_index = fragment_items_->Items().data() - items_.data() + index; DCHECK_LT(span_index, items_.size()); return span_index; } void NGInlineCursor::MoveTo(const NGFragmentItem& fragment_item) { DCHECK(!root_paint_fragment_ && !current_.paint_fragment_); MoveTo(*fragment_item.GetLayoutObject()); while (IsNotNull()) { if (CurrentItem() == &fragment_item) return; MoveToNext(); } NOTREACHED(); } void NGInlineCursor::MoveTo(const NGInlineCursor& cursor) { if (const NGPaintFragment* paint_fragment = cursor.CurrentPaintFragment()) { MoveTo(*paint_fragment); return; } if (cursor.current_.item_) { if (!fragment_items_) SetRoot(*cursor.fragment_items_); // Note: We use address instead of iterato because we can't compare // iterators in different span. See |base::CheckedContiguousIterator<T>|. const ptrdiff_t index = &*cursor.current_.item_iter_ - &*items_.begin(); DCHECK_GE(index, 0); DCHECK_LT(static_cast<size_t>(index), items_.size()); MoveToItem(items_.begin() + index); return; } *this = cursor; } void NGInlineCursor::MoveTo(const NGPaintFragment& paint_fragment) { DCHECK(!fragment_items_); if (!root_paint_fragment_) root_paint_fragment_ = paint_fragment.Root(); DCHECK(root_paint_fragment_); DCHECK(paint_fragment.IsDescendantOfNotSelf(*root_paint_fragment_)) << paint_fragment << " " << root_paint_fragment_; current_.paint_fragment_ = &paint_fragment; } void NGInlineCursor::MoveTo(const NGPaintFragment* paint_fragment) { if (paint_fragment) { MoveTo(*paint_fragment); return; } MakeNull(); } void NGInlineCursor::MoveToContainingLine() { DCHECK(!Current().IsLineBox()); if (current_.paint_fragment_) { current_.paint_fragment_ = current_.paint_fragment_->ContainerLineBox(); return; } if (current_.item_) { while (current_.item_ && !Current().IsLineBox()) MoveToPreviousItem(); return; } NOTREACHED(); } bool NGInlineCursor::IsAtFirst() const { if (const NGPaintFragment* paint_fragment = Current().PaintFragment()) return paint_fragment == root_paint_fragment_->FirstChild(); if (const NGFragmentItem* item = Current().Item()) return item == &items_.front(); return false; } void NGInlineCursor::MoveToFirst() { if (root_paint_fragment_) { current_.paint_fragment_ = root_paint_fragment_->FirstChild(); return; } if (IsItemCursor()) { MoveToItem(items_.begin()); return; } NOTREACHED(); } void NGInlineCursor::MoveToFirstChild() { DCHECK(Current().CanHaveChildren()); if (!TryToMoveToFirstChild()) MakeNull(); } void NGInlineCursor::MoveToFirstLine() { if (root_paint_fragment_) { MoveTo(root_paint_fragment_->FirstLineBox()); return; } if (IsItemCursor()) { auto iter = std::find_if( items_.begin(), items_.end(), [](const auto& item) { return item.Type() == NGFragmentItem::kLine; }); if (iter != items_.end()) { MoveToItem(iter); return; } MakeNull(); return; } NOTREACHED(); } void NGInlineCursor::MoveToFirstLogicalLeaf() { DCHECK(Current().IsLineBox()); // TODO(yosin): This isn't correct for mixed Bidi. Fix it. Besides, we // should compute and store it during layout. // TODO(yosin): We should check direction of each container instead of line // box. if (IsLtr(Current().Style().Direction())) { while (TryToMoveToFirstChild()) continue; return; } while (TryToMoveToLastChild()) continue; } void NGInlineCursor::MoveToLastChild() { DCHECK(Current().CanHaveChildren()); if (!TryToMoveToLastChild()) MakeNull(); } void NGInlineCursor::MoveToLastLine() { DCHECK(IsItemCursor()); auto iter = std::find_if( items_.rbegin(), items_.rend(), [](const auto& item) { return item.Type() == NGFragmentItem::kLine; }); if (iter != items_.rend()) MoveToItem(std::next(iter).base()); else MakeNull(); } void NGInlineCursor::MoveToLastLogicalLeaf() { DCHECK(Current().IsLineBox()); // TODO(yosin): This isn't correct for mixed Bidi. Fix it. Besides, we // should compute and store it during layout. // TODO(yosin): We should check direction of each container instead of line // box. if (IsLtr(Current().Style().Direction())) { while (TryToMoveToLastChild()) continue; return; } while (TryToMoveToFirstChild()) continue; } void NGInlineCursor::MoveToNext() { if (root_paint_fragment_) return MoveToNextPaintFragment(); MoveToNextItem(); } void NGInlineCursor::MoveToNextInlineLeaf() { if (Current() && Current().IsInlineLeaf()) MoveToNext(); while (Current() && !Current().IsInlineLeaf()) MoveToNext(); } void NGInlineCursor::MoveToNextInlineLeafIgnoringLineBreak() { do { MoveToNextInlineLeaf(); } while (Current() && Current().IsLineBreak()); } void NGInlineCursor::MoveToNextInlineLeafOnLine() { MoveToLastForSameLayoutObject(); if (IsNull()) return; NGInlineCursor last_item = *this; MoveToContainingLine(); NGInlineCursor cursor = CursorForDescendants(); cursor.MoveTo(last_item); // Note: AX requires this for AccessibilityLayoutTest.NextOnLine. if (!cursor.Current().IsInlineLeaf()) cursor.MoveToNextInlineLeaf(); cursor.MoveToNextInlineLeaf(); MoveTo(cursor); } void NGInlineCursor::MoveToNextLine() { DCHECK(Current().IsLineBox()); if (current_.paint_fragment_) { if (auto* paint_fragment = current_.paint_fragment_->NextSibling()) return MoveTo(*paint_fragment); return MakeNull(); } if (current_.item_) { do { MoveToNextItem(); } while (Current() && !Current().IsLineBox()); return; } NOTREACHED(); } void NGInlineCursor::MoveToNextSkippingChildren() { if (root_paint_fragment_) return MoveToNextPaintFragmentSkippingChildren(); MoveToNextItemSkippingChildren(); } void NGInlineCursor::MoveToPrevious() { if (root_paint_fragment_) return MoveToPreviousPaintFragment(); MoveToPreviousItem(); } void NGInlineCursor::MoveToPreviousInlineLeaf() { if (Current() && Current().IsInlineLeaf()) MoveToPrevious(); while (Current() && !Current().IsInlineLeaf()) MoveToPrevious(); } void NGInlineCursor::MoveToPreviousInlineLeafIgnoringLineBreak() { do { MoveToPreviousInlineLeaf(); } while (Current() && Current().IsLineBreak()); } void NGInlineCursor::MoveToPreviousInlineLeafOnLine() { if (IsNull()) return; NGInlineCursor first_item = *this; MoveToContainingLine(); NGInlineCursor cursor = CursorForDescendants(); cursor.MoveTo(first_item); // Note: AX requires this for AccessibilityLayoutTest.NextOnLine. if (!cursor.Current().IsInlineLeaf()) cursor.MoveToPreviousInlineLeaf(); cursor.MoveToPreviousInlineLeaf(); MoveTo(cursor); } void NGInlineCursor::MoveToPreviousLine() { // Note: List marker is sibling of line box. DCHECK(Current().IsLineBox()); if (current_.paint_fragment_) { do { MoveToPreviousSiblingPaintFragment(); } while (Current() && !Current().IsLineBox()); return; } if (current_.item_) { do { MoveToPreviousItem(); } while (Current() && !Current().IsLineBox()); return; } NOTREACHED(); } bool NGInlineCursor::TryToMoveToFirstChild() { if (!Current().HasChildren()) return false; if (root_paint_fragment_) { MoveTo(*current_.paint_fragment_->FirstChild()); return true; } MoveToItem(current_.item_iter_ + 1); return true; } bool NGInlineCursor::TryToMoveToFirstInlineLeafChild() { while (IsNotNull()) { if (Current().IsInlineLeaf()) return true; MoveToNext(); } return false; } bool NGInlineCursor::TryToMoveToLastChild() { if (!Current().HasChildren()) return false; if (root_paint_fragment_) { MoveTo(current_.paint_fragment_->Children().back()); return true; } const auto end = current_.item_iter_ + CurrentItem()->DescendantsCount(); MoveToNextItem(); // Move to the first child. DCHECK(!IsNull()); while (true) { ItemsSpan::iterator previous = Current().item_iter_; DCHECK(previous < end); MoveToNextSkippingChildren(); if (!Current() || Current().item_iter_ == end) { MoveToItem(previous); break; } } return true; } void NGInlineCursor::MoveToNextItem() { DCHECK(IsItemCursor()); if (UNLIKELY(!current_.item_)) return; DCHECK(current_.item_iter_ != items_.end()); if (++current_.item_iter_ != items_.end()) { current_.item_ = &*current_.item_iter_; return; } MakeNull(); } void NGInlineCursor::MoveToNextItemSkippingChildren() { DCHECK(IsItemCursor()); if (UNLIKELY(!current_.item_)) return; // If the current item has |DescendantsCount|, add it to move to the next // sibling, skipping all children and their descendants. if (wtf_size_t descendants_count = current_.item_->DescendantsCount()) return MoveToItem(current_.item_iter_ + descendants_count); return MoveToNextItem(); } void NGInlineCursor::MoveToPreviousItem() { DCHECK(IsItemCursor()); if (UNLIKELY(!current_.item_)) return; if (current_.item_iter_ == items_.begin()) return MakeNull(); --current_.item_iter_; current_.item_ = &*current_.item_iter_; } void NGInlineCursor::MoveToParentPaintFragment() { DCHECK(IsPaintFragmentCursor() && current_.paint_fragment_); const NGPaintFragment* parent = current_.paint_fragment_->Parent(); if (parent && parent != root_paint_fragment_) { current_.paint_fragment_ = parent; return; } current_.paint_fragment_ = nullptr; } void NGInlineCursor::MoveToNextPaintFragment() { DCHECK(IsPaintFragmentCursor() && current_.paint_fragment_); if (const NGPaintFragment* child = current_.paint_fragment_->FirstChild()) { current_.paint_fragment_ = child; return; } MoveToNextPaintFragmentSkippingChildren(); } void NGInlineCursor::MoveToNextSiblingPaintFragment() { DCHECK(IsPaintFragmentCursor() && current_.paint_fragment_); if (const NGPaintFragment* next = current_.paint_fragment_->NextSibling()) { current_.paint_fragment_ = next; return; } current_.paint_fragment_ = nullptr; } void NGInlineCursor::MoveToNextPaintFragmentSkippingChildren() { DCHECK(IsPaintFragmentCursor() && current_.paint_fragment_); while (current_.paint_fragment_) { if (const NGPaintFragment* next = current_.paint_fragment_->NextSibling()) { current_.paint_fragment_ = next; return; } MoveToParentPaintFragment(); } } void NGInlineCursor::MoveToPreviousPaintFragment() { DCHECK(IsPaintFragmentCursor() && current_.paint_fragment_); const NGPaintFragment* const parent = current_.paint_fragment_->Parent(); MoveToPreviousSiblingPaintFragment(); if (current_.paint_fragment_) { while (TryToMoveToLastChild()) continue; return; } current_.paint_fragment_ = parent == root_paint_fragment_ ? nullptr : parent; } void NGInlineCursor::MoveToPreviousSiblingPaintFragment() { DCHECK(IsPaintFragmentCursor() && current_.paint_fragment_); const NGPaintFragment* const current = current_.paint_fragment_; current_.paint_fragment_ = nullptr; for (auto* sibling : current->Parent()->Children()) { if (sibling == current) return; current_.paint_fragment_ = sibling; } NOTREACHED(); } void NGInlineCursor::MoveToFirstIncludingFragmentainer() { if (!fragment_index_ || IsPaintFragmentCursor()) { MoveToFirst(); return; } fragment_index_ = 0; if (!TrySetRootFragmentItems()) MakeNull(); } void NGInlineCursor::MoveToNextFragmentainer() { DCHECK(CanMoveAcrossFragmentainer()); if (fragment_index_ < max_fragment_index_) { ++fragment_index_; if (TrySetRootFragmentItems()) return; } MakeNull(); } void NGInlineCursor::MoveToNextIncludingFragmentainer() { MoveToNext(); if (!Current() && max_fragment_index_ && CanMoveAcrossFragmentainer()) MoveToNextFragmentainer(); } inline bool NGInlineCursor::CanUseLayoutObjectIndex() const { if (!RuntimeEnabledFeatures::LayoutNGBlockFragmentationEnabled()) return true; return CanMoveAcrossFragmentainer() && max_fragment_index_ == 0; } void NGInlineCursor::SlowMoveToForIfNeeded(const LayoutObject& layout_object) { while (Current() && Current().GetLayoutObject() != &layout_object) MoveToNextIncludingFragmentainer(); } void NGInlineCursor::SlowMoveToFirstFor(const LayoutObject& layout_object) { MoveToFirstIncludingFragmentainer(); SlowMoveToForIfNeeded(layout_object); } void NGInlineCursor::SlowMoveToNextForSameLayoutObject( const LayoutObject& layout_object) { MoveToNextIncludingFragmentainer(); SlowMoveToForIfNeeded(layout_object); } void NGInlineCursor::MoveTo(const LayoutObject& layout_object) { DCHECK(layout_object.IsInLayoutNGInlineFormattingContext()); if (UNLIKELY(layout_object.IsOutOfFlowPositioned())) { NOTREACHED(); MakeNull(); return; } if (!RuntimeEnabledFeatures::LayoutNGFragmentItemEnabled()) { // If this cursor is rootless, find the root of the inline formatting // context. if (!HasRoot()) { const LayoutBlockFlow& root = *layout_object.RootInlineFormattingContext(); DCHECK(&root); SetRoot(root); if (!HasRoot()) { const auto fragments = NGPaintFragment::InlineFragmentsFor(&layout_object); if (!fragments.IsInLayoutNGInlineFormattingContext() || fragments.IsEmpty()) return MakeNull(); // external/wpt/css/css-scroll-anchoring/text-anchor-in-vertical-rl.html // reaches here. root_paint_fragment_ = fragments.front().Root(); } DCHECK(HasRoot()); } const auto fragments = NGPaintFragment::InlineFragmentsFor(&layout_object); if (!fragments.IsEmpty()) { // If |this| is IFC root, just move to the first fragment. if (!root_paint_fragment_->Parent()) { DCHECK(fragments.front().IsDescendantOfNotSelf(*root_paint_fragment_)); MoveTo(fragments.front()); return; } // If |this| is limited, find the first fragment in the range. for (const auto* fragment : fragments) { if (fragment->IsDescendantOfNotSelf(*root_paint_fragment_)) { MoveTo(*fragment); return; } } } return MakeNull(); } // If this cursor is rootless, find the root of the inline formatting context. bool is_descendants_cursor = false; if (!HasRoot()) { const LayoutBlockFlow* root = layout_object.FragmentItemsContainer(); DCHECK(root); SetRoot(*root); if (UNLIKELY(!HasRoot())) { MakeNull(); return; } DCHECK(!IsDescendantsCursor()); } else { is_descendants_cursor = IsDescendantsCursor(); } // TODO(crbug.com/829028): |FirstInlineFragmentItemIndex| is not setup when // block fragmented. Use the slow codepath. if (UNLIKELY(!CanUseLayoutObjectIndex())) { layout_object_to_slow_move_to_ = &layout_object; SlowMoveToFirstFor(layout_object); return; } wtf_size_t item_index = layout_object.FirstInlineFragmentItemIndex(); if (UNLIKELY(!item_index)) { #if DCHECK_IS_ON() const LayoutBlockFlow* root = layout_object.FragmentItemsContainer(); NGInlineCursor check_cursor(*root); check_cursor.SlowMoveToFirstFor(layout_object); DCHECK(!check_cursor); #endif MakeNull(); return; } // |FirstInlineFragmentItemIndex| is 1-based. Convert to 0-based index. --item_index; DCHECK_EQ(is_descendants_cursor, IsDescendantsCursor()); if (root_block_flow_) { DCHECK(!is_descendants_cursor); #if DCHECK_IS_ON() NGInlineCursor check_cursor(*root_block_flow_); check_cursor.SlowMoveToFirstFor(layout_object); DCHECK_EQ(check_cursor.Current().Item(), &fragment_items_->Items()[item_index]); #endif } else { #if DCHECK_IS_ON() const LayoutBlockFlow* root = layout_object.FragmentItemsContainer(); NGInlineCursor check_cursor(*root); check_cursor.SlowMoveToFirstFor(layout_object); while (check_cursor && fragment_items_ != check_cursor.fragment_items_) check_cursor.SlowMoveToNextForSameLayoutObject(layout_object); DCHECK_EQ(check_cursor.Current().Item(), &fragment_items_->Items()[item_index]); #endif // Skip items before |items_|, in case |this| is part of IFC. if (UNLIKELY(is_descendants_cursor)) { const wtf_size_t span_begin_item_index = SpanBeginItemIndex(); while (UNLIKELY(item_index < span_begin_item_index)) { const NGFragmentItem& item = fragment_items_->Items()[item_index]; const wtf_size_t next_delta = item.DeltaToNextForSameLayoutObject(); if (!next_delta) { MakeNull(); return; } item_index += next_delta; } if (UNLIKELY(item_index >= span_begin_item_index + items_.size())) { MakeNull(); return; } item_index -= span_begin_item_index; } } DCHECK_LT(item_index, items_.size()); current_.Set(items_.begin() + item_index); } void NGInlineCursor::MoveToNextForSameLayoutObjectExceptCulledInline() { if (current_.paint_fragment_) { if (auto* paint_fragment = current_.paint_fragment_->NextForSameLayoutObject()) { if (!root_paint_fragment_->Parent()) { // |paint_fragment| can be in another fragment tree rooted by // |root_paint_fragment_|, e.g. "multicol-span-all-restyle-002.html" root_paint_fragment_ = paint_fragment->Root(); MoveTo(*paint_fragment); return; } // If |this| is limited, make sure the result is in the range. if (paint_fragment->IsDescendantOfNotSelf(*root_paint_fragment_)) { MoveTo(*paint_fragment); return; } } return MakeNull(); } if (current_.item_) { if (UNLIKELY(layout_object_to_slow_move_to_)) { SlowMoveToNextForSameLayoutObject(*layout_object_to_slow_move_to_); return; } const wtf_size_t delta = current_.item_->DeltaToNextForSameLayoutObject(); if (delta) { // Check the next item is in |items_| because |delta| can be beyond // |end()| if |this| is limited. const wtf_size_t delta_to_end = items_.end() - current_.item_iter_; if (delta < delta_to_end) { MoveToItem(current_.item_iter_ + delta); return; } DCHECK(IsDescendantsCursor()); } MakeNull(); } } void NGInlineCursor::MoveToLastForSameLayoutObject() { if (!Current()) return; NGInlineCursorPosition last; do { last = Current(); MoveToNextForSameLayoutObject(); } while (Current()); MoveTo(last); } // // Functions to enumerate fragments that contribute to a culled inline. // // Traverse the |LayoutObject| tree in pre-order DFS and find a |LayoutObject| // that contributes to the culled inline. const LayoutObject* NGInlineCursor::CulledInlineTraversal::Find( const LayoutObject* child) const { while (child) { if (child->IsText()) return child; if (child->IsBox()) { if (!child->IsFloatingOrOutOfFlowPositioned()) return child; child = child->NextInPreOrderAfterChildren(layout_inline_); continue; } if (const LayoutInline* child_layout_inline = ToLayoutInlineOrNull(child)) { if (child_layout_inline->ShouldCreateBoxFragment()) return child; // A culled inline can be computed from its direct children, but when the // child is also culled, traverse its grand children. if (const LayoutObject* grand_child = child_layout_inline->FirstChild()) { child = grand_child; continue; } } child = child->NextInPreOrderAfterChildren(layout_inline_); } return nullptr; } const LayoutObject* NGInlineCursor::CulledInlineTraversal::MoveToFirstFor( const LayoutInline& layout_inline) { layout_inline_ = &layout_inline; current_object_ = Find(layout_inline.FirstChild()); return current_object_; } const LayoutObject* NGInlineCursor::CulledInlineTraversal::MoveToNext() { current_object_ = Find(current_object_->NextInPreOrderAfterChildren(layout_inline_)); return current_object_; } void NGInlineCursor::MoveToFirstForCulledInline( const LayoutInline& layout_inline) { if (const LayoutObject* layout_object = culled_inline_.MoveToFirstFor(layout_inline)) { MoveTo(*layout_object); // This |MoveTo| may fail if |this| is a descendant cursor. Try the next // |LayoutObject|. MoveToNextCulledInlineDescendantIfNeeded(); } } void NGInlineCursor::MoveToNextForCulledInline() { DCHECK(culled_inline_); MoveToNextForSameLayoutObjectExceptCulledInline(); // If we're at the end of fragments for the current |LayoutObject| that // contributes to the current culled inline, find the next |LayoutObject|. MoveToNextCulledInlineDescendantIfNeeded(); } void NGInlineCursor::MoveToNextCulledInlineDescendantIfNeeded() { DCHECK(culled_inline_); if (Current()) return; while (const LayoutObject* layout_object = culled_inline_.MoveToNext()) { MoveTo(*layout_object); if (Current()) return; } } void NGInlineCursor::MoveToIncludingCulledInline( const LayoutObject& layout_object) { DCHECK(layout_object.IsInLayoutNGInlineFormattingContext()) << layout_object; culled_inline_.Reset(); MoveTo(layout_object); if (Current() || !HasRoot()) return; // If this is a culled inline, find fragments for descendant |LayoutObject|s // that contribute to the culled inline. if (const LayoutInline* layout_inline = ToLayoutInlineOrNull(&layout_object)) { if (!layout_inline->ShouldCreateBoxFragment()) MoveToFirstForCulledInline(*layout_inline); } } void NGInlineCursor::MoveToNextForSameLayoutObject() { if (UNLIKELY(culled_inline_)) { MoveToNextForCulledInline(); return; } MoveToNextForSameLayoutObjectExceptCulledInline(); } // // |NGInlineBackwardCursor| functions. // NGInlineBackwardCursor::NGInlineBackwardCursor(const NGInlineCursor& cursor) : cursor_(cursor) { if (cursor.root_paint_fragment_) { DCHECK(!cursor.CurrentPaintFragment() || cursor.CurrentPaintFragment()->Parent()->FirstChild() == cursor.CurrentPaintFragment()); for (NGInlineCursor sibling(cursor); sibling; sibling.MoveToNextSiblingPaintFragment()) sibling_paint_fragments_.push_back(sibling.CurrentPaintFragment()); current_index_ = sibling_paint_fragments_.size(); if (current_index_) current_.paint_fragment_ = sibling_paint_fragments_[--current_index_]; return; } if (cursor.IsItemCursor()) { DCHECK(!cursor || cursor.items_.begin() == cursor.Current().item_iter_); for (NGInlineCursor sibling(cursor); sibling; sibling.MoveToNextSkippingChildren()) sibling_item_iterators_.push_back(sibling.Current().item_iter_); current_index_ = sibling_item_iterators_.size(); if (current_index_) current_.Set(sibling_item_iterators_[--current_index_]); return; } DCHECK(!cursor); } NGInlineCursor NGInlineBackwardCursor::CursorForDescendants() const { if (const NGPaintFragment* current_paint_fragment = Current().PaintFragment()) return NGInlineCursor(*current_paint_fragment); if (current_.item_) { NGInlineCursor cursor(cursor_); cursor.MoveToItem(sibling_item_iterators_[current_index_]); return cursor.CursorForDescendants(); } NOTREACHED(); return NGInlineCursor(); } void NGInlineBackwardCursor::MoveToPreviousSibling() { if (current_index_) { if (current_.paint_fragment_) { current_.paint_fragment_ = sibling_paint_fragments_[--current_index_]; return; } if (current_.item_) { current_.Set(sibling_item_iterators_[--current_index_]); return; } NOTREACHED(); } current_.paint_fragment_ = nullptr; current_.item_ = nullptr; } std::ostream& operator<<(std::ostream& ostream, const NGInlineCursor& cursor) { if (cursor.IsNull()) return ostream << "NGInlineCursor()"; if (cursor.IsPaintFragmentCursor()) { return ostream << "NGInlineCursor(" << *cursor.CurrentPaintFragment() << ")"; } DCHECK(cursor.IsItemCursor()); return ostream << "NGInlineCursor(" << *cursor.CurrentItem() << ")"; } std::ostream& operator<<(std::ostream& ostream, const NGInlineCursor* cursor) { if (!cursor) return ostream << "<null>"; return ostream << *cursor; } #if DCHECK_IS_ON() void NGInlineCursor::CheckValid(const NGInlineCursorPosition& position) const { if (position.PaintFragment()) { DCHECK(root_paint_fragment_); DCHECK( position.PaintFragment()->IsDescendantOfNotSelf(*root_paint_fragment_)); } else if (position.Item()) { DCHECK(IsItemCursor()); const unsigned index = position.item_iter_ - items_.begin(); DCHECK_LT(index, items_.size()); } } #endif } // namespace blink
32.214839
91
0.705053
[ "geometry", "vector" ]
5e0165153de56f6f969230107c3466765508e0a2
1,182
cpp
C++
code/Combination Sum.cpp
htfy96/leetcode-solutions
4736e87958d7e5aea3cbd999f88c7a86de13205a
[ "Apache-2.0" ]
1
2021-02-21T15:43:13.000Z
2021-02-21T15:43:13.000Z
code/Combination Sum.cpp
htfy96/leetcode-solutions
4736e87958d7e5aea3cbd999f88c7a86de13205a
[ "Apache-2.0" ]
null
null
null
code/Combination Sum.cpp
htfy96/leetcode-solutions
4736e87958d7e5aea3cbd999f88c7a86de13205a
[ "Apache-2.0" ]
1
2018-12-13T07:14:09.000Z
2018-12-13T07:14:09.000Z
class Solution { public: vector<vector<int>> combinationSum(vector<int>& candidates, int target) { vector<vector<vector<int>>> a((target+1) * 2); if (!target) return {{}}; #define idx(i, j) ((i) % 2 * (target + 1) + (j)) for (int i=0; i<candidates.size(); ++i) for (int j=0; j<=target; ++j) { a[idx(i, j)].clear(); if (j >= candidates[i]) { auto& last = a[idx(i, j- candidates[i])]; for (auto&& res: last) { a[idx(i, j)].push_back(res); a[idx(i, j)].rbegin()->push_back(candidates[i]); } } if (i) { auto& last = a[idx(i-1, j)]; move(last.cbegin(), last.cend(), back_inserter(a[idx(i, j)])); } else if (!j) a[idx(i, j)].push_back({}); //cout << "i=" << i << " j=" << j << "\t size=" << a[idx(i, j)].size() << endl; } return a[idx(candidates.size() - 1, target)]; } };
38.129032
95
0.367174
[ "vector" ]
5e028cb777ed62050510e15c3ccbfa7b432f61d9
5,439
cpp
C++
test/unit/math/opencl/rev/uniform_lcdf_test.cpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
null
null
null
test/unit/math/opencl/rev/uniform_lcdf_test.cpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
null
null
null
test/unit/math/opencl/rev/uniform_lcdf_test.cpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
null
null
null
#ifdef STAN_OPENCL #include <stan/math/opencl/rev.hpp> #include <stan/math.hpp> #include <gtest/gtest.h> #include <test/unit/math/opencl/util.hpp> #include <vector> TEST(ProbDistributionsUniformLcdf, error_checking) { int N = 3; Eigen::VectorXd y(N); y << 0.3, 0.8, 1.0; Eigen::VectorXd y_size(N - 1); y_size << 0.3, 0.8; Eigen::VectorXd y_value(N); y_value << 0.3, NAN, 0.5; Eigen::VectorXd alpha(N); alpha << 0.1, 0.8, -1.0; Eigen::VectorXd alpha_size(N - 1); alpha_size << 0.3, 0.8; Eigen::VectorXd alpha_value(N); alpha_value << 0.1, -INFINITY, 0.5; Eigen::VectorXd beta(N); beta << 0.3, 1.8, 1.0; Eigen::VectorXd beta_size(N - 1); beta_size << 0.3, 0.8; Eigen::VectorXd beta_value(N); beta_value << 0.3, 0.8, INFINITY; stan::math::matrix_cl<double> y_cl(y); stan::math::matrix_cl<double> y_size_cl(y_size); stan::math::matrix_cl<double> y_value_cl(y_value); stan::math::matrix_cl<double> alpha_cl(alpha); stan::math::matrix_cl<double> alpha_size_cl(alpha_size); stan::math::matrix_cl<double> alpha_value_cl(alpha_value); stan::math::matrix_cl<double> beta_cl(beta); stan::math::matrix_cl<double> beta_size_cl(beta_size); stan::math::matrix_cl<double> beta_value_cl(beta_value); EXPECT_NO_THROW(stan::math::uniform_lcdf(y_cl, alpha_cl, beta_cl)); EXPECT_THROW(stan::math::uniform_lcdf(y_size_cl, alpha_cl, beta_cl), std::invalid_argument); EXPECT_THROW(stan::math::uniform_lcdf(y_cl, alpha_size_cl, beta_cl), std::invalid_argument); EXPECT_THROW(stan::math::uniform_lcdf(y_cl, alpha_cl, beta_size_cl), std::invalid_argument); EXPECT_THROW(stan::math::uniform_lcdf(y_value_cl, alpha_cl, beta_cl), std::domain_error); EXPECT_THROW(stan::math::uniform_lcdf(y_cl, alpha_value_cl, beta_cl), std::domain_error); EXPECT_THROW(stan::math::uniform_lcdf(y_cl, alpha_cl, beta_value_cl), std::domain_error); } auto uniform_lcdf_functor = [](const auto& y, const auto& alpha, const auto& beta) { return stan::math::uniform_lcdf(y, alpha, beta); }; TEST(ProbDistributionsUniformLcdf, opencl_matches_cpu_small) { int N = 3; int M = 2; Eigen::VectorXd y(N); y << 0.3, 0.8, 1.0; Eigen::VectorXd alpha(N); alpha << 0.1, 0.5, -1.0; Eigen::VectorXd beta(N); beta << 0.3, 0.8, 1.0; stan::math::test::compare_cpu_opencl_prim_rev(uniform_lcdf_functor, y, alpha, beta); stan::math::test::compare_cpu_opencl_prim_rev( uniform_lcdf_functor, y.transpose().eval(), alpha.transpose().eval(), beta.transpose().eval()); } TEST(ProbDistributionsUniformLcdf, opencl_matches_cpu_small_y_neg_inf) { int N = 3; int M = 2; Eigen::VectorXd y(N); y << 0.3, -INFINITY, 1.0; Eigen::VectorXd alpha(N); alpha << 0.1, 0.5, -1.0; Eigen::VectorXd beta(N); beta << 0.3, 0.8, 1.0; stan::math::test::compare_cpu_opencl_prim_rev(uniform_lcdf_functor, y, alpha, beta); stan::math::test::compare_cpu_opencl_prim_rev( uniform_lcdf_functor, y.transpose().eval(), alpha.transpose().eval(), beta.transpose().eval()); } TEST(ProbDistributionsUniformLcdf, opencl_broadcast_y) { int N = 3; double y_scal = 12.3; Eigen::VectorXd alpha(N); alpha << 0.1, 0.5, -1.0; Eigen::VectorXd beta(N); beta << 0.3, 0.8, 1.0; stan::math::test::test_opencl_broadcasting_prim_rev<0>(uniform_lcdf_functor, y_scal, alpha, beta); stan::math::test::test_opencl_broadcasting_prim_rev<0>( uniform_lcdf_functor, y_scal, alpha.transpose().eval(), beta); } TEST(ProbDistributionsUniformLcdf, opencl_broadcast_alpha) { int N = 3; Eigen::VectorXd y(N); y << 0.3, 0.8, 1.0; double alpha_scal = -0.1; Eigen::VectorXd beta(N); beta << 0.3, 0.8, 1.0; stan::math::test::test_opencl_broadcasting_prim_rev<1>(uniform_lcdf_functor, y, alpha_scal, beta); stan::math::test::test_opencl_broadcasting_prim_rev<1>( uniform_lcdf_functor, y.transpose().eval(), alpha_scal, beta); } TEST(ProbDistributionsUniformLcdf, opencl_broadcast_beta) { int N = 3; Eigen::VectorXd y(N); y << 0.3, 0.8, 1.0; Eigen::VectorXd alpha(N); alpha << 0.1, 0.5, -1.0; double beta_scal = 12.3; stan::math::test::test_opencl_broadcasting_prim_rev<2>(uniform_lcdf_functor, y, alpha, beta_scal); stan::math::test::test_opencl_broadcasting_prim_rev<2>( uniform_lcdf_functor, y.transpose().eval(), alpha, beta_scal); } TEST(ProbDistributionsUniformLcdf, opencl_matches_cpu_big) { int N = 153; Eigen::Matrix<double, Eigen::Dynamic, 1> y = Eigen::Array<double, Eigen::Dynamic, 1>::Random(N, 1).abs(); Eigen::Matrix<double, Eigen::Dynamic, 1> alpha = Eigen::Array<double, Eigen::Dynamic, 1>::Random(N, 1); Eigen::Matrix<double, Eigen::Dynamic, 1> beta = Eigen::Array<double, Eigen::Dynamic, 1>::Random(N, 1).abs() + alpha.array(); stan::math::test::compare_cpu_opencl_prim_rev(uniform_lcdf_functor, y, alpha, beta); stan::math::test::compare_cpu_opencl_prim_rev( uniform_lcdf_functor, y.transpose().eval(), alpha.transpose().eval(), beta.transpose().eval()); } #endif
33.368098
79
0.640375
[ "vector" ]
5e0350e2cecb160e979bae38dff9705ad1d2eb54
7,014
hpp
C++
include/seqan3/alignment/pairwise/alignment_selector.hpp
giesselmann/seqan3
3a26b42b7066ac424b6e604115fe516607c308c0
[ "BSD-3-Clause" ]
null
null
null
include/seqan3/alignment/pairwise/alignment_selector.hpp
giesselmann/seqan3
3a26b42b7066ac424b6e604115fe516607c308c0
[ "BSD-3-Clause" ]
null
null
null
include/seqan3/alignment/pairwise/alignment_selector.hpp
giesselmann/seqan3
3a26b42b7066ac424b6e604115fe516607c308c0
[ "BSD-3-Clause" ]
null
null
null
// ============================================================================ // SeqAn - The Library for Sequence Analysis // ============================================================================ // // Copyright (c) 2006-2018, Knut Reinert & Freie Universitaet Berlin // Copyright (c) 2016-2018, Knut Reinert & MPI Molekulare Genetik // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Knut Reinert or the FU Berlin nor the names of // its contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. // // ============================================================================ /*!\file * \brief Provides seqan3::detail::alignment_selector. * \author Rene Rahn <rene.rahn AT fu-berlin.de> */ #pragma once #include <functional> #include <tuple> #include <utility> #include <vector> #include <seqan3/alignment/configuration/all.hpp> #include <seqan3/alignment/matrix/alignment_trace_matrix.hpp> #include <seqan3/alignment/pairwise/align_result.hpp> #include <seqan3/alignment/pairwise/edit_distance_unbanded.hpp> #include <seqan3/alphabet/gap/gapped.hpp> #include <seqan3/core/concept/tuple.hpp> #include <seqan3/core/metafunction/range.hpp> #include <seqan3/core/type_list.hpp> #include <seqan3/range/view/persist.hpp> namespace seqan3::detail { /*!\brief Helper metafunction to determine the alignment result type based on the configuration. * \ingroup pairwise * \tparam seq1_t The type of the first sequence. * \tparam seq2_t The type of the second sequence. * \tparam configuration_t The configuration type. Must be of type seqan3::detail::configuration */ template <typename seq1_t, typename seq2_t, typename configuration_t> struct determine_result_type { //!\brief Helper function to determine the actual result type. static constexpr auto _determine() { using seq1_value_type = value_type_t<std::remove_reference_t<seq1_t>>; using seq2_value_type = value_type_t<std::remove_reference_t<seq2_t>>; using score_type = int32_t; if constexpr (has_align_cfg_v<align_cfg::id::output, configuration_t>) { if constexpr (get<align_cfg::id::output>(configuration_t{}) == align_result_key::end) return align_result<type_list<uint32_t, score_type, alignment_coordinate>>{}; else if constexpr (get<align_cfg::id::output>(configuration_t{}) == align_result_key::begin) return align_result<type_list<uint32_t, score_type, alignment_coordinate, alignment_coordinate>>{}; else if constexpr (get<align_cfg::id::output>(configuration_t{}) == align_result_key::trace) return align_result<type_list<uint32_t, score_type, alignment_coordinate, alignment_coordinate, std::tuple<std::vector<gapped<seq1_value_type>>, std::vector<gapped<seq2_value_type>>>>>{}; else return align_result<type_list<uint32_t, score_type>>{}; } else { return align_result<type_list<uint32_t, score_type>>{}; } } //!\brief The determined result type. using type = decltype(_determine()); }; /*!\brief Selects the correct alignment algorithm based on the algorithm configuration. * \ingroup pairwise * \tparam seq_tuple_t A tuple like object containing the two source sequences. * Must model seqan3::tuple_like_concept. * \tparam configuration_t The specified configuration type. */ template <tuple_like_concept seq_tuple_t, typename configuration_t> struct alignment_selector { //!\brief The configuration stored globally for all alignment instances. configuration_t config; //!\brief The result type of invoking the algorithm. using result_type = typename determine_result_type<std::tuple_element_t<0, std::remove_reference_t<seq_tuple_t>>, std::tuple_element_t<1, std::remove_reference_t<seq_tuple_t>>, configuration_t>::type; /*!\brief Selects the corresponding alignment algorithm based on compile time and runtime decisions. * \param[in] seq The sequences as a tuple. * \returns A std::function object to be called within the alignment execution. * * \details * * \todo Write detail description and explain rationale about the function object. */ template <tuple_like_concept _seq_tuple_t> auto select(_seq_tuple_t && seq) { //TODO Currently we only support edit_distance. We need would actually need real checks for this. std::function<result_type(result_type &)> func = pairwise_alignment_edit_distance_unbanded{std::get<0>(std::forward<_seq_tuple_t>(seq)) | view::persist, std::get<1>(std::forward<_seq_tuple_t>(seq)) | view::persist, config}; return func; } }; } // namespace seqan3::detail
47.391892
117
0.614485
[ "object", "vector", "model" ]
5e0aeb6019c257d390b7941f9361e7d74fe298d1
3,857
hpp
C++
libpharos/znode.hpp
dberlin/pharos
2ff59e71b59725742ab9c53a77ba49316e6fe44e
[ "RSA-MD" ]
3
2015-07-15T08:43:56.000Z
2021-02-28T17:53:52.000Z
libpharos/znode.hpp
dberlin/pharos
2ff59e71b59725742ab9c53a77ba49316e6fe44e
[ "RSA-MD" ]
null
null
null
libpharos/znode.hpp
dberlin/pharos
2ff59e71b59725742ab9c53a77ba49316e6fe44e
[ "RSA-MD" ]
null
null
null
// Copyright 2018 Carnegie Mellon University. See LICENSE file for terms. #ifndef Pharos_Z3_H #define Pharos_Z3_H #include <z3++.h> #include <rose.h> #include <boost/optional.hpp> #include <BinaryZ3Solver.h> #include "misc.hpp" namespace pharos { using CFG = Rose::BinaryAnalysis::ControlFlow::Graph; class FunctionDescriptor; using Z3FixedpointPtr = std::unique_ptr<z3::fixedpoint>; using Z3ExprVector = std::vector<z3::expr>; using Z3QueryResult = std::tuple<z3::check_result, boost::optional<z3::expr>>; // This is JSG's extension of the ROSE Z3 solver, which is close but // not really ideal for what we want. Also note that we've copied the // Rose::BinaryAnalysis::Z3Solver and renamed it class PharosZ3Solver : public Rose::BinaryAnalysis::Z3Solver { private: // a log file for the state of the z3 solver std::ofstream log_file_; std::string log_file_name_; protected: uint64_t get_id_from_string(const std::string & id_str ); public: PharosZ3Solver() : Rose::BinaryAnalysis::Z3Solver(Rose::BinaryAnalysis::SmtSolver::LM_LIBRARY) { // The default log_file_name_ = "znode.log"; } ~PharosZ3Solver() { if (log_file_.is_open()) { log_file_.flush(); log_file_.close(); } } void set_timeout(unsigned int to); void set_seed(int seed); // Convert a z3 expression back to a treenode TreeNodePtr z3_to_treenode(const z3::expr& expr); z3::expr treenode_to_z3(const TreeNodePtr tnp); z3::expr simplify(const z3::expr& e); z3::expr to_bool(z3::expr z3expr); z3::expr to_bv(z3::expr z3expr); // Z3 utility routines because expr vectors are weird z3::expr mk_and(Z3ExprVector& args); z3::expr mk_and(z3::expr_vector& args); z3::expr mk_or(z3::expr_vector& args); z3::expr mk_or(Z3ExprVector& args); z3::expr mk_true(); z3::expr mk_false(); void set_log_name(std::string name); void do_log(std::string msg); // Must expose the cast function to get everything in a uniform type z3::expr z3type_cast(z3::expr z3expr, Rose::BinaryAnalysis::SmtSolver::Type from_type, Rose::BinaryAnalysis::SmtSolver::Type to_type); }; // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // CHC Reasoning // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // These classes are heavily inspired by Seahorn (aka copied). Each // rule is of the form: (=> ( and (pred vars ) (body) ) (head vars))). // The rules are entered into Pharos via the fixedpoint // class. Considerable hoops are jumpted through to make it all fit // together class PharosHornRule { Z3ExprVector vars_; z3::expr body_; z3::expr head_; public: PharosHornRule(Z3ExprVector &v, z3::expr b, z3::expr h) : vars_(boost::begin(v), boost::end (v)), body_(b), head_(h) { } PharosHornRule(z3::expr b, z3::expr h) : body_(b), head_(h) { } // return only the body of the horn clause z3::expr body () const; void set_body (z3::expr v); // return only the head of the horn clause z3::expr head () const; void set_head (z3::expr v); // return the implication body => head z3::expr expr(z3::context& ctx); const Z3ExprVector &vars () const; }; // The primary class for handling fixed point analysis of CHC class PharosHornAnalyzer { using PredMap = std::map<const SgAsmBlock*, z3::expr>; using RelationMap = std::map<const SgAsmBlock*, z3::func_decl>; const std::string goal_name_; PharosZ3Solver z3_; PredMap bb_preds_; RelationMap relations_; Z3FixedpointPtr fixedpoint_; z3::expr hornify_bb(const SgAsmBlock* bb); z3::expr register_goal(z3::expr addr_expr); public: PharosHornAnalyzer(); void hornify(const FunctionDescriptor& fd); Z3QueryResult query(const rose_addr_t goal); std::string to_string() const; }; } // End pharos #endif
27.748201
83
0.67021
[ "vector" ]
5e0d01380243b7763d8f36c734113cf1c58676df
2,582
cpp
C++
libs/scope_exit/example/world.cpp
zyiacas/boost-doc-zh
689e5a3a0a4dbead1a960f7b039e3decda54aa2c
[ "BSL-1.0" ]
11
2015-07-12T13:04:52.000Z
2021-05-30T23:23:46.000Z
libs/scope_exit/example/world.cpp
sdfict/boost-doc-zh
689e5a3a0a4dbead1a960f7b039e3decda54aa2c
[ "BSL-1.0" ]
null
null
null
libs/scope_exit/example/world.cpp
sdfict/boost-doc-zh
689e5a3a0a4dbead1a960f7b039e3decda54aa2c
[ "BSL-1.0" ]
3
2015-12-23T01:51:57.000Z
2019-08-25T04:58:32.000Z
// Copyright Alexander Nasonov 2009 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <vector> #include <ostream> #include <boost/foreach.hpp> #include <boost/scope_exit.hpp> // The following is required for typeof emulation mode: #include <boost/typeof/typeof.hpp> #include <boost/typeof/std/vector.hpp> #include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP() class World; class Person { friend class World; public: typedef unsigned int id_t; typedef unsigned int evolution_t; Person() : m_id(0) , m_evolution(0) {} friend std::ostream& operator<<(std::ostream& o, Person const& p) { return o << "Person(" << p.m_id << ", " << p.m_evolution << ')'; } private: id_t m_id; evolution_t m_evolution; }; BOOST_TYPEOF_REGISTER_TYPE(Person) class World { public: typedef unsigned int id_t; World() : m_next_id(1) {} void addPerson(Person const& aPerson); friend std::ostream& operator<<(std::ostream& o, World const& w) { o << "World(" << w.m_next_id << ", {"; BOOST_FOREACH(Person const& p, w.m_persons) { o << ' ' << p << ','; } return o << "})"; } private: id_t m_next_id; std::vector<Person> m_persons; }; BOOST_TYPEOF_REGISTER_TYPE(World) void World::addPerson(Person const& aPerson) { m_persons.push_back(aPerson); // This block must be no-throw Person& person = m_persons.back(); Person::evolution_t checkpoint = person.m_evolution; BOOST_SCOPE_EXIT( (checkpoint)(&person)(&m_persons) ) { if(checkpoint == person.m_evolution) m_persons.pop_back(); } BOOST_SCOPE_EXIT_END // ... checkpoint = ++person.m_evolution; // Assign new id to the person World::id_t const prev_id = person.m_id; person.m_id = m_next_id++; BOOST_SCOPE_EXIT( (checkpoint)(&person)(&m_next_id)(prev_id) ) { if(checkpoint == person.m_evolution) { m_next_id = person.m_id; person.m_id = prev_id; } } BOOST_SCOPE_EXIT_END // ... checkpoint = ++person.m_evolution; } #include <iostream> int main() { Person adam, eva; std::cout << adam << '\n'; std::cout << eva << '\n'; World w; w.addPerson(adam); w.addPerson(eva); std::cout << w << '\n'; }
22.452174
73
0.587142
[ "vector" ]
5e15a2d3fd60b015437fd648e43fb0a8f1c2dd8f
3,443
cpp
C++
src/window.cpp
kz04px/chip8-interpreter
51476ca70fec25c1657ae94a92a31758b49e195e
[ "MIT" ]
null
null
null
src/window.cpp
kz04px/chip8-interpreter
51476ca70fec25c1657ae94a92a31758b49e195e
[ "MIT" ]
null
null
null
src/window.cpp
kz04px/chip8-interpreter
51476ca70fec25c1657ae94a92a31758b49e195e
[ "MIT" ]
null
null
null
#include "window.hpp" #include <array> #include <cassert> #include <stdexcept> #include "options.hpp" Window::Window(const char *title, const int w, const int h) : width_(w), height_(h) { assert(title); window_ = SDL_CreateWindow(title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width_, height_, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE); if (!window_) { throw std::bad_alloc(); } renderer_ = SDL_CreateRenderer(window_, -1, SDL_RENDERER_ACCELERATED); if (!renderer_) { throw std::bad_alloc(); } SDL_SetRenderDrawBlendMode(renderer_, SDL_BLENDMODE_BLEND); } Window::~Window() { SDL_DestroyRenderer(renderer_); SDL_DestroyWindow(window_); } void Window::resize(const int w, const int h) { assert(renderer_); width_ = w; height_ = h; const auto rect = SDL_Rect(0, 0, width_, height_); SDL_RenderSetViewport(renderer_, &rect); SDL_RenderSetClipRect(renderer_, &rect); } void Window::clear() { assert(window_); assert(renderer_); SDL_SetRenderDrawColor(renderer_, 50, 50, 50, 255); SDL_RenderClear(renderer_); } void Window::render(const Chip8 &chip8) { assert(window_); assert(renderer_); const int pixel_width = width_ / 64; const int pixel_height = height_ / 32; // Draw game SDL_SetRenderDrawColor(renderer_, 0, 191, 255, 255); for (int y = 0; y < 32; ++y) { for (int x = 0; x < 64; ++x) { const bool pixel = chip8.pixel(x, y); if (pixel) { if (options::borders) { const auto rect = SDL_Rect(pixel_width * x + 1, pixel_height * y + 1, pixel_width - 2, pixel_height - 2); SDL_RenderFillRect(renderer_, &rect); } else { const auto rect = SDL_Rect(pixel_width * x, pixel_height * y, pixel_width, pixel_height); SDL_RenderFillRect(renderer_, &rect); } } } } } void Window::render_inputs(const Chip8 &chip8) { assert(window_); assert(renderer_); const int width = 16; const int height = 16; const std::array<Input, 16> order = { Input::Key_1, Input::Key_2, Input::Key_3, Input::Key_4, Input::Key_Q, Input::Key_W, Input::Key_E, Input::Key_R, Input::Key_A, Input::Key_S, Input::Key_D, Input::Key_F, Input::Key_Z, Input::Key_X, Input::Key_C, Input::Key_V, }; for (int i = 0; i < 16; ++i) { const int xpos = i % 4; const int ypos = i / 4; if (chip8.get_key(order[i])) { SDL_SetRenderDrawColor(renderer_, 0, 0, 255, 100); } else { SDL_SetRenderDrawColor(renderer_, 0, 255, 0, 100); } const auto rect = SDL_Rect(width * xpos, height * ypos, width - 2, height - 2); SDL_RenderFillRect(renderer_, &rect); } } void Window::present() { SDL_RenderPresent(renderer_); } void Window::toggle_fullscreen() { fullscreen_ = !fullscreen_; if (fullscreen_) { SDL_SetWindowFullscreen(window_, SDL_WINDOW_FULLSCREEN_DESKTOP); } else { SDL_SetWindowFullscreen(window_, 0); } }
26.083333
111
0.559686
[ "render" ]
5e17c5a5f2ef5fa09957fc3cbaa79363a3dfb78a
21,003
cpp
C++
source/Camera/InfoUtilOther/ZividBenchmark/ZividBenchmark.cpp
marvinx97/zivid-cpp-samples
7be83661adeb48d28286458b1e01b3dde28e0a43
[ "BSD-3-Clause" ]
1
2020-12-21T03:04:34.000Z
2020-12-21T03:04:34.000Z
source/Camera/InfoUtilOther/ZividBenchmark/ZividBenchmark.cpp
marvinx97/zivid-cpp-samples
7be83661adeb48d28286458b1e01b3dde28e0a43
[ "BSD-3-Clause" ]
null
null
null
source/Camera/InfoUtilOther/ZividBenchmark/ZividBenchmark.cpp
marvinx97/zivid-cpp-samples
7be83661adeb48d28286458b1e01b3dde28e0a43
[ "BSD-3-Clause" ]
null
null
null
/* Zividbenchmarks is a sample that will test the average speed of different operations on your computer. It will provide the mean and median for connects, disconnects, single imaging, HDR and filtering. */ #include <Zivid/Zivid.h> #include <algorithm> #include <iostream> #include <numeric> namespace { const int printWidth = 56; using HighResClock = std::chrono::high_resolution_clock; using Duration = std::chrono::nanoseconds; Duration computeAverageDuration(const std::vector<Duration> &durations) { return std::accumulate(durations.begin(), durations.end(), Duration{ 0 }) / durations.size(); } Duration computeMedianDuration(std::vector<Duration> durations) { std::sort(durations.begin(), durations.end()); if(durations.size() % 2 == 0) { return (durations.at(durations.size() / 2 - 1) + durations.at(durations.size() / 2)) / 2; } return durations.at(durations.size() / 2); } template<typename T> std::string valueToStringWithPrecision(const T &value, const size_t precision) { std::ostringstream ss; ss << std::setprecision(precision) << std::fixed << value; return ss.str(); } std::string formatDuration(const Duration &duration) { return valueToStringWithPrecision( std::chrono::duration_cast<std::chrono::duration<double, std::milli>>(duration).count(), 3) + " ms"; } template<typename Target> std::string makeSettingList(const Zivid::Settings &settings) { std::string settingList = "{ "; for(size_t i = 0; i < settings.acquisitions().size(); i++) { settingList += settings.acquisitions().at(i).get<Target>().toString(); if(i + 1 != settings.acquisitions().size()) { settingList += ", "; } } settingList += " }"; return settingList; } std::string makefilterList(const Zivid::Settings &settings) { if(settings.processing().filters().smoothing().gaussian().isEnabled().value()) { std::string gaussianString; gaussianString = std::string{ "Gaussian (Sigma = " } + settings.processing().filters().smoothing().gaussian().sigma().toString() + " )"; if(settings.processing().filters().reflection().removal().isEnabled().value()) { return "{ " + gaussianString + ", Reflection }"; } return "{ " + gaussianString + " }"; } if(settings.processing().filters().reflection().removal().isEnabled().value()) { return "{ Reflection }"; } return {}; } void printSeparationLine(const char &separator, const std::string &followingString) { std::cout << std::left << std::setfill(separator) << std::setw(printWidth) << followingString << std::endl; } void printPrimarySeparationLine() { printSeparationLine('=', ""); } void printSecondarySeparationLine() { printSeparationLine('-', " "); } void printCentered(const std::string &text) { constexpr size_t columns{ printWidth }; std::cout << std::string((columns - text.size()) / 2, ' ') << text << std::endl; } void printFormated(const std::vector<std::string> &stringList) { std::cout << std::left << std::setfill(' ') << std::setw(32) << stringList.at(0) << std::setw(13) << stringList.at(1) << stringList.at(2) << std::endl; } void printHeader(const std::string &firstString) { printPrimarySeparationLine(); std::cout << std::endl; printPrimarySeparationLine(); std::cout << firstString << std::endl; } void printHeaderLine(const std::string &firstString, size_t num, const std::string &secondString) { printPrimarySeparationLine(); std::cout << firstString << num << secondString << std::endl; } void printConnectHeader(const size_t numConnects) { printHeaderLine("Connecting and disconnecting ", numConnects, " times each (be patient):"); } void printSubtestHeader(const std::string &subtest) { printPrimarySeparationLine(); std::cout << subtest << std::endl; } void printCapture3DHeader(const size_t numFrames, const Zivid::Settings &settings) { const auto filterList = makefilterList(settings); printHeaderLine("Capturing ", numFrames, " 3D frames:"); std::cout << " Exposure Time = " << makeSettingList<Zivid::Settings::Acquisition::ExposureTime>(settings) << std::endl; std::cout << " Aperture = " << makeSettingList<Zivid::Settings::Acquisition::Aperture>(settings) << std::endl; if(!filterList.empty()) { std::cout << " Filters = " << filterList << std::endl; } } void printAssistedCapture3DHeader(const size_t numFrames) { printHeaderLine("Running assisted capture ", numFrames, " times:"); } void printCapture2DHeader(const size_t numFrames, const Zivid::Settings2D &settings) { printHeaderLine("Capturing ", numFrames, " 2D frames:"); std::cout << " exposure Time = { " << settings.acquisitions().at(0).exposureTime() << " }" << std::endl; } void printSaveHeader(const size_t numFrames) { printHeaderLine("Saving point cloud ", numFrames, " times each (be patient):"); } void printResultLine(const std::string &name, const Duration &durationMedian, const Duration &durationMean) { printFormated({ name, formatDuration(durationMedian), formatDuration(durationMean) }); } void printResults(const std::vector<std::string> &names, const std::vector<Duration> &durations) { printSecondarySeparationLine(); printFormated({ " Time:", "Median", "Mean" }); for(size_t i = 0; i < names.size(); i++) { printResultLine(names.at(i), durations.at(i + i), durations.at(i + i + 1)); } } void printConnectResults(const std::vector<Duration> &durations) { printResults({ " Connect:", " Disconnect:" }, durations); } void printCapture3DResults(const std::vector<Duration> &durations) { printResults({ " 3D image acquisition time:", " Point cloud processing time:", " Total 3D capture time:" }, durations); } void printAssistedCapture3DResults(const std::vector<Duration> &durations) { printResults({ " Suggest settings time:" }, durations); } void printNegligableFilters() { const std::string negligable = "negligible"; printFormated({ " Noise", negligable, negligable }); printFormated({ " Outlier", negligable, negligable }); } void printFilterResults(const std::vector<Duration> &durations) { printPrimarySeparationLine(); std::cout << "Filter processing time:" << std::endl; printResults({ " Gaussian:", " Reflection:", " Gaussian and Reflection:" }, durations); printSecondarySeparationLine(); printNegligableFilters(); } void printCapture2DResults(const std::vector<Duration> &durations) { printResults({ " Total 2D capture time:" }, durations); } void printSaveResults(const std::vector<Duration> &durations) { printResults({ " Save ZDF:", " Save PLY:", " Save PCD:", " Save XYZ:" }, durations); } void printZividInfo(const Zivid::Camera &camera, const Zivid::Application &zivid) { std::cout << "API: " << Zivid::Version::coreLibraryVersion() << std::endl; std::cout << "OS: " << OS_NAME << std::endl; std::cout << "Camera: " << camera << std::endl; std::cout << "Compute device: " << zivid.computeDevice() << std::endl; printPrimarySeparationLine(); printCentered("Starting Zivid Benchmark"); } Zivid::Camera getFirstCamera(Zivid::Application &zivid) { const auto cameras = zivid.cameras(); if(cameras.size() != 1) { throw std::runtime_error("At least one camera needs to be connected"); } printZividInfo(cameras.at(0), zivid); return cameras.at(0); } std::chrono::microseconds getMinExposureTime(const std::string &modelName) { if(modelName.substr(0, 14) == "Zivid One Plus") { return std::chrono::microseconds{ 6500 }; // Min for Zivid One Plus } return std::chrono::microseconds{ 8333 }; // Min for Zivid One } Zivid::Settings makeSettings(const std::vector<double> &apertures, const std::vector<std::chrono::microseconds> &exposureTimes, const bool enableGaussian, const bool enableReflection) { if(apertures.size() != exposureTimes.size()) { throw std::runtime_error("Unequal input vector size"); } Zivid::Settings settings{ Zivid::Settings::Processing::Filters::Smoothing::Gaussian::Enabled{ enableGaussian }, Zivid::Settings::Processing::Filters::Smoothing::Gaussian::Sigma{ 1.5 }, Zivid::Settings::Processing::Filters::Noise::Removal::Enabled{ true }, Zivid::Settings::Processing::Filters::Outlier::Removal::Enabled{ true }, Zivid::Settings::Processing::Filters::Reflection::Removal::Enabled{ enableReflection } }; for(size_t i = 0; i < apertures.size(); ++i) { const auto acquisitionSettings = Zivid::Settings::Acquisition{ Zivid::Settings::Acquisition::Aperture{ apertures.at(i) }, Zivid::Settings::Acquisition::ExposureTime{ exposureTimes.at(i) }, Zivid::Settings::Acquisition::Brightness{ 1.0 } // Using above 1.0 may cause thermal throttling }; settings.acquisitions().emplaceBack(acquisitionSettings); } return settings; } void benchmarkConnect(Zivid::Camera &camera, const size_t numConnects) { printConnectHeader(numConnects); std::vector<Duration> connectDurations; std::vector<Duration> disconnectDurations; std::vector<Duration> allDurations; for(size_t i = 0; i < numConnects; i++) { const auto beforeConnect = HighResClock::now(); camera.connect(); const auto afterConnect = HighResClock::now(); camera.disconnect(); const auto afterDisconnect = HighResClock::now(); connectDurations.push_back(afterConnect - beforeConnect); disconnectDurations.push_back(afterDisconnect - afterConnect); } allDurations.push_back(computeMedianDuration(connectDurations)); allDurations.push_back(computeAverageDuration(connectDurations)); allDurations.push_back(computeMedianDuration(disconnectDurations)); allDurations.push_back(computeAverageDuration(disconnectDurations)); printConnectResults(allDurations); } std::vector<Duration> benchmarkCapture3D(Zivid::Camera &camera, const Zivid::Settings &settings, const size_t numFrames) { printCapture3DHeader(numFrames, settings); for(size_t i = 0; i < 5; i++) // Warmup frames { const auto data = camera.capture(settings).pointCloud().copyData<Zivid::PointXYZColorRGBA>(); } std::vector<Duration> captureDurations; std::vector<Duration> processDurations; std::vector<Duration> totalDurations; std::vector<Duration> allDurations; for(size_t i = 0; i < numFrames; i++) { const auto beforeCapture = HighResClock::now(); const auto frame = camera.capture(settings); const auto afterCapture = HighResClock::now(); const auto pointCloud = frame.pointCloud(); const auto data = pointCloud.copyData<Zivid::PointXYZColorRGBA>(); const auto afterProcess = HighResClock::now(); captureDurations.push_back(afterCapture - beforeCapture); processDurations.push_back(afterProcess - afterCapture); totalDurations.push_back(afterProcess - beforeCapture); } allDurations.push_back(computeMedianDuration(captureDurations)); allDurations.push_back(computeAverageDuration(captureDurations)); allDurations.push_back(computeMedianDuration(processDurations)); allDurations.push_back(computeAverageDuration(processDurations)); allDurations.push_back(computeMedianDuration(totalDurations)); allDurations.push_back(computeAverageDuration(totalDurations)); printCapture3DResults(allDurations); return totalDurations; } void benchmarkAssistedCapture3D(Zivid::Camera &camera, const size_t numFrames) { printAssistedCapture3DHeader(numFrames); const Zivid::CaptureAssistant::SuggestSettingsParameters suggestSettingsParameters{ Zivid::CaptureAssistant::SuggestSettingsParameters::AmbientLightFrequency::none, Zivid::CaptureAssistant::SuggestSettingsParameters::MaxCaptureTime{ std::chrono::milliseconds{ 1200 } } }; for(size_t i = 0; i < 5; i++) // Warmup { const auto settings{ Zivid::CaptureAssistant::suggestSettings(camera, suggestSettingsParameters) }; } std::vector<Duration> suggestSettingsDurations; for(size_t i = 0; i < numFrames; i++) { const auto beforeSuggestSettings = HighResClock::now(); const auto settings{ Zivid::CaptureAssistant::suggestSettings(camera, suggestSettingsParameters) }; const auto afterSuggestSettings = HighResClock::now(); suggestSettingsDurations.push_back(afterSuggestSettings - beforeSuggestSettings); } std::vector<Duration> allDurations; allDurations.push_back(computeMedianDuration(suggestSettingsDurations)); allDurations.push_back(computeAverageDuration(suggestSettingsDurations)); printAssistedCapture3DResults(allDurations); } std::tuple<Duration, Duration> benchmarkFilterProcessing(const std::vector<Duration> &captureDuration, const std::vector<Duration> &captureDurationFilter) { return std::make_tuple((computeMedianDuration(captureDurationFilter) - computeMedianDuration(captureDuration)), computeAverageDuration(captureDurationFilter) - computeAverageDuration(captureDuration)); } void benchmarkCapture3DAndFilters(Zivid::Camera &camera, const std::vector<double> &apertures, const std::vector<std::chrono::microseconds> &exposureTimes, const size_t numFrames3D) { std::vector<std::string> subtestName{ "Without filters", "With Gaussian filter", "With Reflection filter", "With Gaussian and Reflection filter" }; printSubtestHeader(subtestName.at(0)); const std::vector<Duration> captureDurationWithoutFilter = benchmarkCapture3D(camera, makeSettings(apertures, exposureTimes, false, false), numFrames3D); const std::vector<bool> gaussian{ true, false, true }; const std::vector<bool> reflection{ false, true, true }; std::vector<Duration> filterProcessingDurations; for(size_t i = 0; i < gaussian.size(); i++) { printSubtestHeader(subtestName.at(i + 1)); const std::vector<Duration> captureDurationWithFilter = benchmarkCapture3D(camera, makeSettings(apertures, exposureTimes, gaussian.at(i), reflection.at(i)), numFrames3D); const auto meanAndAverageFilterDurations = benchmarkFilterProcessing(captureDurationWithoutFilter, captureDurationWithFilter); filterProcessingDurations.push_back(std::get<0>(meanAndAverageFilterDurations)); filterProcessingDurations.push_back(std::get<1>(meanAndAverageFilterDurations)); } printFilterResults(filterProcessingDurations); } Zivid::Settings2D makeSettings2D(const std::chrono::microseconds exposureTime) { Zivid::Settings2D settings{ Zivid::Settings2D::Acquisitions{ Zivid::Settings2D::Acquisition{ Zivid::Settings2D::Acquisition::ExposureTime(exposureTime) } } }; return settings; } void benchmarkCapture2D(Zivid::Camera &camera, const Zivid::Settings2D &settings, const size_t numFrames) { printCapture2DHeader(numFrames, settings); for(size_t i = 0; i < 5; i++) // Warmup frames { camera.capture(settings); } std::vector<Duration> captureDurations; std::vector<Duration> allDurations; for(size_t i = 0; i < numFrames; i++) { const auto beforeCapture = HighResClock::now(); const auto frame2D = camera.capture(settings); const auto afterCapture = HighResClock::now(); captureDurations.push_back(afterCapture - beforeCapture); } allDurations.push_back(computeMedianDuration(captureDurations)); allDurations.push_back(computeAverageDuration(captureDurations)); printCapture2DResults(allDurations); } void benchmarkSave(Zivid::Camera &camera, const size_t numFrames) { printSaveHeader(numFrames); const auto frame = camera.capture(Zivid::Settings{ Zivid::Settings::Acquisitions{ Zivid::Settings::Acquisition{} } }); frame.pointCloud(); std::vector<Duration> allDurations; std::vector<std::string> dataFiles{ "Zivid3D.zdf", "Zivid3D.ply", "Zivid3D.pcd", "Zivid3D.xyz" }; for(const auto &dataFile : dataFiles) { std::vector<Duration> durationsPerFormat; for(size_t j = 0; j < numFrames; j++) { const auto beforeSave = HighResClock::now(); frame.save(dataFile); const auto afterSave = HighResClock::now(); durationsPerFormat.push_back(afterSave - beforeSave); } allDurations.push_back(computeMedianDuration(durationsPerFormat)); allDurations.push_back(computeAverageDuration(durationsPerFormat)); } printSaveResults(allDurations); } } // namespace int main() { try { Zivid::Application zivid; auto camera = getFirstCamera(zivid); const size_t numConnects = 10; const size_t numFrames3D = 20; const size_t numFrames2D = 50; const size_t numFramesSave = 10; const std::chrono::microseconds exposureTime = getMinExposureTime(camera.info().modelName().toString()); const std::vector<std::chrono::microseconds> oneExposureTime{ exposureTime }; const std::vector<std::chrono::microseconds> twoExposureTimes{ exposureTime, exposureTime }; const std::vector<std::chrono::microseconds> threeExposureTimes{ exposureTime, exposureTime, exposureTime }; const std::vector<double> oneAperture{ 5.66 }; const std::vector<double> twoApertures{ 8.0, 4.0 }; const std::vector<double> threeApertures{ 11.31, 5.66, 2.83 }; printHeader("TEST 1: Connect/Disconnect"); benchmarkConnect(camera, numConnects); camera.connect(); printHeader("TEST 2: Assisted Capture"); benchmarkAssistedCapture3D(camera, numFrames3D); printHeader("TEST 3: One Acquisition Capture"); benchmarkCapture3DAndFilters(camera, oneAperture, oneExposureTime, numFrames3D); printHeader("TEST 4: Two Acquisitions (HDR) Capture"); benchmarkCapture3D(camera, makeSettings(twoApertures, twoExposureTimes, false, false), numFrames3D); printHeader("TEST 5: Three Acquisitions (HDR) Capture"); benchmarkCapture3DAndFilters(camera, threeApertures, threeExposureTimes, numFrames3D); printHeader("TEST 6: 2D Capture"); benchmarkCapture2D(camera, makeSettings2D(exposureTime), numFrames2D); printHeader("TEST 7: Save"); benchmarkSave(camera, numFramesSave); } catch(const std::exception &e) { std::cerr << "Error: " << Zivid::toString(e) << std::endl; std::cout << "Press enter to exit." << std::endl; std::cin.get(); return EXIT_FAILURE; } }
39.184701
120
0.620054
[ "vector", "3d" ]
5e1ff83ff0f056b96bf071e1268b3688cbf43701
803
cpp
C++
src/modules/sl_urcontrol/URControl/xscal_fEJVUpjd.cpp
DelftDroneControl/Firmware
0bcf7318a8caf5e0d4966fa8635f62d6b1fb8ff6
[ "BSD-3-Clause" ]
1
2018-12-19T10:57:36.000Z
2018-12-19T10:57:36.000Z
src/modules/sl_urcontrol/URControl/xscal_fEJVUpjd.cpp
DelftDroneControl/Firmware
0bcf7318a8caf5e0d4966fa8635f62d6b1fb8ff6
[ "BSD-3-Clause" ]
null
null
null
src/modules/sl_urcontrol/URControl/xscal_fEJVUpjd.cpp
DelftDroneControl/Firmware
0bcf7318a8caf5e0d4966fa8635f62d6b1fb8ff6
[ "BSD-3-Clause" ]
null
null
null
/* * /home/sihao/src/monorepo/simulink_model/.codeGenCache/slprj/grt/_sharedutils/xscal_fEJVUpjd.cpp * * Academic License - for use in teaching, academic research, and meeting * course requirements at degree granting institutions only. Not for * government, commercial, or other organizational use. * * Code generation for model "URControl_att_indi". * * Model version : 1.501 * Simulink Coder version : 9.1 (R2019a) 23-Nov-2018 * C++ source code generated on : Wed Dec 11 10:03:20 2019 * Created for block: URControl_att_indi */ #include "rtwtypes.h" #include "xscal_fEJVUpjd.h" /* Function for MATLAB Function: '<S1>/MATLAB Function6' */ void xscal_fEJVUpjd(real_T a, real_T x[16], int32_T ix0) { int32_T k; for (k = ix0; k <= ix0 + 3; k++) { x[k - 1] *= a; } }
29.740741
98
0.691158
[ "model" ]
5e1ffcda1b1650196f762339085f1fc25fdbedca
508
cpp
C++
0011 Container With Most Water/solution.cpp
Aden-Tao/LeetCode
c34019520b5808c4251cb76f69ca2befa820401d
[ "MIT" ]
1
2019-12-19T04:13:15.000Z
2019-12-19T04:13:15.000Z
0011 Container With Most Water/solution.cpp
Aden-Tao/LeetCode
c34019520b5808c4251cb76f69ca2befa820401d
[ "MIT" ]
null
null
null
0011 Container With Most Water/solution.cpp
Aden-Tao/LeetCode
c34019520b5808c4251cb76f69ca2befa820401d
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; class Solution { public: int maxArea(vector<int>& height) { int res = 0; for (int i = 0, j = height.size() - 1; i < j; ) { res = max(res, min(height[i], height[j]) * (j - i)); if (height[i] > height[j]) j -- ; else i ++ ; } return res; } }; int main(){ Solution s; vector<int> vec{1,8,6,2,5,4,8,3,7}; assert(s.maxArea(vec) == 49); return 0; }
20.32
55
0.448819
[ "vector" ]
5e271fd04f568a14f11dd49263595c5666a1a19d
363
hh
C++
Intra/Math.hh
gammaker/Intra
aed1647cd2cf1781ab0976c2809533d0f347e87e
[ "MIT" ]
8
2017-05-22T12:55:40.000Z
2018-11-11T22:36:56.000Z
Intra/Math.hh
gammaker/Intra
aed1647cd2cf1781ab0976c2809533d0f347e87e
[ "MIT" ]
1
2020-03-14T11:26:17.000Z
2020-03-14T12:31:11.000Z
Intra/Math.hh
devoln/Intra
aed1647cd2cf1781ab0976c2809533d0f347e87e
[ "MIT" ]
1
2017-10-12T10:03:56.000Z
2017-10-12T10:03:56.000Z
#pragma once #include "Math/Bit.h" #include "Math/FixedPoint.h" #include "Math/ExponentRange.h" #include "Math/SineRange.h" #include "Math/HalfFloat.h" #include "Math/Math.h" #include "Math/Geometry.hh" #include "Math/Matrix3.h" #include "Math/Matrix4.h" #include "Math/Quaternion.h" #include "Math/Vector2.h" #include "Math/Vector3.h" #include "Math/Vector4.h"
22.6875
31
0.738292
[ "geometry" ]
5e2966a90f7d8ef2ea688686b70875c44b07b0bb
12,318
cpp
C++
source/msynth/msynth/model/mixer/MDefaultMixer.cpp
MRoc/MSynth
3eb5c6cf0ad6a3d12f555ebca5fbe84c1b255829
[ "MIT" ]
1
2022-01-30T07:40:31.000Z
2022-01-30T07:40:31.000Z
source/msynth/msynth/model/mixer/MDefaultMixer.cpp
MRoc/MSynth
3eb5c6cf0ad6a3d12f555ebca5fbe84c1b255829
[ "MIT" ]
null
null
null
source/msynth/msynth/model/mixer/MDefaultMixer.cpp
MRoc/MSynth
3eb5c6cf0ad6a3d12f555ebca5fbe84c1b255829
[ "MIT" ]
null
null
null
/* MDefaultMixer (C)2001 MRoc hifiShock A mixer is a collection of channels. A channel can be added, removed and the number of channels is given. Because a Mixer has a Master-Section, a Mixer inheritances from MMixerChannel and so its a MixerChannel too. Dont delete MMixerChannels, only Controls!!! */ #include "../mixer/MDefaultMixer.h" #include "../interfaces/MSoundBufferUtils.h" #include <framework/performance/MClock.h> INIT_RTTI( MDefaultMixer, "MDefaultMixer" ); /** * constructor */ MDefaultMixer::MDefaultMixer() : MDefaultMixerChannel(), ivPtSong( 0 ), ivPtFxRack( 0 ) { setChannelName( String( "Master" ) ); } /** * destructor */ MDefaultMixer::~MDefaultMixer() { if( ivPtSong ) { ivPtSong->removeSongListener( this ); ivPtSong = 0; } ivMixerChannels.clear(); } /** * Builds the model from the song */ void MDefaultMixer::buildUpModel( bool sendNotify ) { ASSERT( ivPtSong != 0 ); removeAllMixerChannels(); unsigned int count = ivPtSong->getBarContainerCount(); for( unsigned int i=0;i<count;i++ ) addMixerChannel( ivPtSong->getBarContainer( i )->getInstrument() ); if( sendNotify ) fireMixerModelChanged(); } /** * sets the song and adds this mixer as songlistener */ void MDefaultMixer::setSong( MSong* ptSong ) { if( ivPtSong ) ivPtSong->removeSongListener( this ); ivPtSong = ptSong; if( ivPtSong ) ivPtSong->addSongListener( this ); buildUpModel( true ); } /** * returns the song and adds this mixer as songlistener */ MSong* MDefaultMixer::getSong() { return ivPtSong; } /** * Current number of added Channels */ unsigned int MDefaultMixer::getChannelCount() { return ivMixerChannels.size(); } /** * Pointer to a channel */ IMixerChannel *MDefaultMixer::getMixerChannel( unsigned int index ) { ASSERT( index >= 0 && index < ivMixerChannels.size() ); return ivMixerChannels[ index ]; } /** * Add a channel */ void MDefaultMixer::addMixerChannel( IMixerChannel *ptMixerChannel ) { ivMixerChannels.push_back( ptMixerChannel ); } /** * remove a channel by index */ void MDefaultMixer::removeMixerChannel( unsigned int index ) { ASSERT( index >= 0 && index < ivMixerChannels.size() ); ivMixerChannels.erase( ivMixerChannels.begin() + index ); } /** * remove the given channel */ void MDefaultMixer::removeMixerChannel( IMixerChannel *ptMixerChannel ) { unsigned int count = ivMixerChannels.size(); for( unsigned int i=0; i<count; i++ ) if( ivMixerChannels[i] = ptMixerChannel ) { removeMixerChannel( i ); break; } } /** * removes all channels */ void MDefaultMixer::removeAllMixerChannels() { ivMixerChannels.clear(); } /** * INSTRUMENT ADDED (Inheritanced from ISongListeners) * Called if a instrument was added to the song */ void MDefaultMixer::instrumentAdded( unsigned int index ) { IMixerChannel* ptChannel = ivPtSong->getBarContainer( index )->getInstrument(); ivMixerChannels.insert( ivMixerChannels.begin() + index, ptChannel ); fireChannelAdded( (unsigned int) index ); } /** * INSTRUMENT REMOVED (Inheritanced from ISongListeners) * Called if a instrument was removed from the song */ void MDefaultMixer::instrumentRemoved( unsigned int index ) { ASSERT( index >= 0 && index < ivMixerChannels.size() ); ivMixerChannels.erase( ivMixerChannels.begin() + index ); fireChannelRemoved( (unsigned int) index ); } /** * instrumentsSwapped */ void MDefaultMixer::instrumentsSwapped( unsigned int index1, unsigned int index2 ) { ASSERT( index1 >= 0 && index1 < ivMixerChannels.size() ); ASSERT( index2 >= 0 && index2 < ivMixerChannels.size() ); ASSERT( index1 != index2 ); IMixerChannel* ptTemp = ivMixerChannels[ index1 ]; ivMixerChannels[ index1 ] = ivMixerChannels[ index2 ]; ivMixerChannels[ index2 ] = ptTemp; fireChannelsSwapped( (unsigned int) index1, (unsigned int) index2 ); } /** * SONG MODEL CHANGED (Inheritanced from ISongListeners) * Called if the song-model completely changed */ void MDefaultMixer::songModelChanged() { buildUpModel( true ); } /** * SONG MODEL CHANGED (Inheritanced from ISongListeners) * Called if the song-model is deleted */ void MDefaultMixer::songDestroy() { if( ivPtSong ) ivPtSong->removeSongListener( this ); ivPtSong = 0; } /** * addMixerListener */ void MDefaultMixer::addMixerListener( IMixerListener* ptListener ) { ivMixerListeners.addListener( ptListener ); } /** * removeMixerListener */ void MDefaultMixer::removeMixerListener( IMixerListener* ptListener ) { ivMixerListeners.removeListener( ptListener ); } /** * fireMixerModelChanged */ void MDefaultMixer::fireMixerModelChanged() { unsigned int count = this->ivMixerListeners.getListenerCount(); for( unsigned int i=0;i<count;i++ ) ((IMixerListener*)ivMixerListeners.getListener( i ))->onMixerModelChanged(); } /** * fireChannelAdded */ void MDefaultMixer::fireChannelAdded( unsigned int index ) { unsigned int count = this->ivMixerListeners.getListenerCount(); for( unsigned int i=0;i<count;i++ ) ((IMixerListener*)ivMixerListeners.getListener( i ))->onMixerChannelAdded( index ); } /** * fireChannelRemoved */ void MDefaultMixer::fireChannelRemoved( unsigned int index ) { unsigned int count = this->ivMixerListeners.getListenerCount(); for( unsigned int i=0;i<count;i++ ) ((IMixerListener*)ivMixerListeners.getListener( i ))->onMixerChannelRemoved( index ); } /** * fireChannelsSwapped */ void MDefaultMixer::fireChannelsSwapped( unsigned int index1, unsigned int index2 ) { unsigned int count = this->ivMixerListeners.getListenerCount(); for( unsigned int i=0;i<count;i++ ) ((IMixerListener*)ivMixerListeners.getListener( i ))->onMixerChannelSwapped( index1, index2 ); } /** * processes events */ void MDefaultMixer::processEvent( MEvent* pEvent ) { } /** * renders the effect rack */ void MDefaultMixer::goNext( MSoundBuffer* pBuffer, unsigned int startFrom, unsigned int stopAt ) { unsigned int k; ASSERT( pBuffer ); ASSERT( startFrom <= stopAt ); if( this->getMute() == false ) { MSynchronize cls2( &ivPtFxRack->ivCriticalSection ); MClock cTotal; cTotal.start(); // calculate how many samples to render unsigned int samplesToRun = stopAt - startFrom; // create output tmp... MSoundBuffer masterBuffer( 2, samplesToRun ); // create channel sound buffers... MSoundBuffer **channelBuffer = new MSoundBuffer*[ getChannelCount() ]; for( k=0;k<getChannelCount();k++ ) channelBuffer[ k ] = 0; // create effect sound buffers... MSoundBuffer** fxBuffer = 0; if( ivPtFxRack ) { unsigned int fxCount = ivPtFxRack->getSlotCount(); fxBuffer = new MSoundBuffer*[ fxCount ]; for( unsigned int j=0;j<fxCount;j++ ) fxBuffer[ j ] = 0; } MClock c0; c0.start(); // render instruments and route into effect buffer if nescessary... for( k=0;k<getChannelCount();k++ ) { // render channel IMixerChannel* pChannel = getMixerChannel( k ); if( pChannel->getMute() == false && pChannel->getOffline() == false ) { //MClock singleChannelClock; //singleChannelClock.start(); // allocating mem... //MClock memClock; //memClock.start(); channelBuffer[ k ] = new MSoundBuffer( pChannel->getChannelCount(), samplesToRun ); //memClock.stop(); // render instrument... //MClock goNextClock; //goNextClock.start(); pChannel->goNext( channelBuffer[ k ], 0, samplesToRun ); //goNextClock.stop(); // equing... //MClock eqClock; //eqClock.start(); if( ((MDefaultMixerChannel*)pChannel)->getEqOn() ) { ((MDefaultMixerChannel*)pChannel)->getEq()->goNext( channelBuffer[ k ], 0, channelBuffer[ k ]->getDataLength() ); } //eqClock.stop(); // mix into effect buffer if nescessary (pre fade listening)... //MClock fxSendClock; //fxSendClock.start(); if( ivPtFxRack ) { unsigned int fxCount = ivPtFxRack->getSlotCount(); for( unsigned int j=0;j<fxCount;j++ ) if( ivPtFxRack->getSlot( j )->getTransformer() && pChannel->getFxSend( j ) != 0.0 ) { if( ! fxBuffer[ j ] ) fxBuffer[ j ] = new MSoundBuffer( 2, samplesToRun ); MSoundBufferUtils::add( fxBuffer[ j ], channelBuffer[ k ], pChannel->getFxSend( j ) ); } } //fxSendClock.stop(); // fading... //MClock fadeClock; //fadeClock.start(); MSoundBufferUtils::multiply( channelBuffer[ k ], 0, channelBuffer[k]->getDataLength(), pChannel->getVolume() ); //fadeClock.stop(); // envelope follower... //MClock envClock; //envClock.start(); pChannel->getEnvelopeFollower()->goNext( channelBuffer[ k ], 0, channelBuffer[ k ]->getDataLength() ); //envClock.stop(); // trace... //singleChannelClock.stop(); /*TRACE( "\tinstrument complete(%fms) alloc(%fms) gonext(%fms) eq(%fms) fxSend(%fms) fade(%fms) env(%fms)\n", singleChannelClock.getLastTimeSpan(), memClock.getLastTimeSpan(), goNextClock.getLastTimeSpan(), eqClock.getLastTimeSpan(), fxSendClock.getLastTimeSpan(), fadeClock.getLastTimeSpan(), envClock.getLastTimeSpan() );*/ } } c0.stop(); MClock c1; c1.start(); // master mix... for( k=0;k<getChannelCount();k++ ) if( channelBuffer[ k ] ) { IMixerChannel* pChannel = getMixerChannel( k ); MSoundBufferUtils::addStereo( &masterBuffer, channelBuffer[ k ], 1.0f, pChannel->getPanorama() ); } c1.stop(); MClock c2; c2.start(); // render effects and mix to master buffer... if( ivPtFxRack ) { unsigned int fxCount = ivPtFxRack->getSlotCount(); for( unsigned int j=0;j<fxCount;j++ ) if( fxBuffer[ j ] && ivPtFxRack->getSlot( j )->getTransformer() ) { ivPtFxRack->getSlot( j )->getTransformer()->goNext( fxBuffer[ j ], 0, fxBuffer[ j ]->getDataLength() ); MSoundBufferUtils::add( &masterBuffer, fxBuffer[ j ], 0.5 ); delete fxBuffer[ j ]; } delete fxBuffer; } c2.stop(); // master equing... if( this->getEqOn() ) this->ivPtEq->goNext( &masterBuffer, 0, samplesToRun ); //TRACE( "MDefaultMixer::goNext max=%f\n", MSoundBufferUtils::findMax( &masterBuffer ) ); // master eqing... MDefaultMixerChannel::goNext( &masterBuffer, 0, samplesToRun ); // master fading & panning... MSoundBufferUtils::steroVolume( &masterBuffer, getVolume(), getPanorama() ); // output... MSoundBufferUtils::pasteBuffer( pBuffer, &masterBuffer, startFrom, samplesToRun ); //pBuffer->pasteBuffer( &masterBuffer, startFrom, samplesToRun ); MClock envClock; envClock.start(); // follower... ivEnvelopeFollower.goNext( &masterBuffer, 0, masterBuffer.getDataLength() ); envClock.stop(); // delete channel sound buffers... for( k=0;k<getChannelCount();k++ ) if( channelBuffer[ k ] ) delete channelBuffer[ k ]; delete channelBuffer; cTotal.stop(); /*TRACE( "tps(%f) mixer total: %f rendering: %f msec mixing: %f msec effects: %f envfollower: %f msec samplesToRun: %u\n", cTotal.getLastTimeSpan() / (float)samplesToRun, cTotal.getLastTimeSpan(), c0.getLastTimeSpan(), c1.getLastTimeSpan(), c2.getLastTimeSpan(), envClock.getLastTimeSpan(), samplesToRun );*/ } } /** * sets a optional fx rack */ void MDefaultMixer::setFxRack( MFxRack* pFxRack ) { ivPtFxRack = pFxRack; } /** * returns the optional fx rack, * can be null. */ MFxRack* MDefaultMixer::getFxRack() { return ivPtFxRack; } /** * fires notification, e.g. the peak bar */ void MDefaultMixer::fireNotifications() { unsigned int count = this->getChannelCount(); for( unsigned int i=0;i<count;i++ ) { this->ivMixerChannels[ i ]->getEnvelopeFollower()->fireUpdate(); } ivEnvelopeFollower.fireUpdate(); } void* MDefaultMixer::createInstance() { return new MDefaultMixer(); }
24.784708
125
0.651486
[ "render", "model" ]
5e2b5dba1c9d1261b197194d71f3af4387819362
11,414
cpp
C++
src/io/chemkinReader/source/reactionParser.cpp
sm453/MOpS
f1a706c6552bbdf3ceab504121a02391a1b51ede
[ "MIT" ]
3
2020-09-08T14:06:33.000Z
2020-12-04T07:52:19.000Z
src/io/chemkinReader/source/reactionParser.cpp
sm453/MOpS
f1a706c6552bbdf3ceab504121a02391a1b51ede
[ "MIT" ]
null
null
null
src/io/chemkinReader/source/reactionParser.cpp
sm453/MOpS
f1a706c6552bbdf3ceab504121a02391a1b51ede
[ "MIT" ]
3
2021-11-15T05:18:26.000Z
2022-03-01T13:51:20.000Z
/* * reactionParser.cpp * * Created on: Jun 23, 2011 * Author: gigadot * License: Apache 2.0 */ #include <boost/algorithm/string.hpp> #include "boost/algorithm/string/trim.hpp" #include "reactionParser.h" #include "stringFunctions.h" #include "reaction.h" using namespace std; using namespace boost; const regex IO::ReactionParser::reactionSingleRegex ( "(.*?)\\s*" "(<=>|=>|=)\\s*" "(.*?)" "\\s+((?:[0-9]+|\\.)\\.*[0-9]*(?:[eEgG][-+]?[0-9]*)*)" "\\s+(.*?)" "\\s+(.*?)$|\\n" ); const regex IO::ReactionParser::blankLine ( "\\s*\\n*$" ); const regex IO::ReactionParser::DUPLICATE ( "DUPLICATE|DUP" ); const regex IO::ReactionParser::LOW ( "(LOW)\\s*\\/\\s*(.*?)\\s+(.*?)\\s+(.*?)\\s*\\/" ); const regex IO::ReactionParser::TROE ( "(TROE)\\s*\\/\\s*(.*?)\\s+(.*?)\\s+(.*?)(?:|\\s+(.*?))\\s*\\/" ); const regex IO::ReactionParser::SRI ( "(SRI)\\s*\\/\\s*(.*?)\\s+(.*?)\\s+(.*?)(?:|\\s+(.*?)\\s+(.*?))\\s*\\/" ); const regex IO::ReactionParser::REV ( "(REV)\\s*\\/\\s*(.*?)\\s+(.*?)\\s+(.*?)\\s*\\/" ); const regex IO::ReactionParser::pressureDependent ( "\\(\\+(.*?)\\)" ); const regex IO::ReactionParser::STICK // Checked by mm864! ( "(STICK)" ); const regex IO::ReactionParser::COV // Checked by mm864! ( "(COV)\\s*\\/\\s*(.*?)\\s+(.*?)\\s+(.*?)\\s+(.*?)\\s*\\/" ); const regex IO::ReactionParser::FORD // Checked by mm864! ( "(FORD)\\s*\\/\\s*(.*?)\\s+(.*?)\\s*\\/" ); const regex IO::ReactionParser::MWON// Checked by mm864! ( "(MWON)" ); const regex IO::ReactionParser::MWOFF // Checked by mm864! ( "(MWOFF)" ); // Empty default constructor, can be removed but leave it there just in case. IO::ReactionParser::ReactionParser ( const string reactionString ) : reactionString_(reactionString) { split(reactionStringLines_, reactionString, boost::is_any_of("\n|\r\n")); // Check for a blank line and erase. for (size_t i=0; i<reactionStringLines_.size(); ++i) { if(isBlankLine(reactionStringLines_[i])) { reactionStringLines_.erase(reactionStringLines_.begin()+i); --i; } } } void IO::ReactionParser::setSurfaceReactionUnit(const std::string &units){ surfaceUnits = units; } void IO::ReactionParser::parse(vector<IO::Reaction>& reactions) { for (size_t i=0; i<reactionStringLines_.size(); ++i) { cout << reactionStringLines_[i] << endl; Reaction reaction; // Check for pressure dependency now as it screws up reactionSingleRegex. It is only for gas phase reaction (added comment by mm864) if (checkForPressureDependentReaction(reactionStringLines_[i])) { reactionStringLines_[i] = regex_replace(reactionStringLines_[i], pressureDependent, ""); reaction.setPressureDependent(); } smatch what; string::const_iterator start = reactionStringLines_[i].begin(); string::const_iterator end = reactionStringLines_[i].end(); if (regex_search(start, end, what, reactionSingleRegex)) { reaction.setReactants(parseReactionSpecies(what[1])); if (what[2] == "=>") reaction.setReversible(false); reaction.setProducts(parseReactionSpecies(what[3])); if ((surfaceUnits == "KJOULES/MOL") || (surfaceUnits == "KJOULES/MOLE")){ reaction.setArrhenius ( from_string<double>(what[4]), from_string<double>(what[5]), from_string<double>(what[6])*239.005736 // KJOULES/mol to cal/mol ); } else if ((surfaceUnits == "JOULES/MOL") || (surfaceUnits == "JOULES/MOLE")){ reaction.setArrhenius ( from_string<double>(what[4]), from_string<double>(what[5]), from_string<double>(what[6])*239.005736/1000 // JOULES/mol to cal/mol ); } else { reaction.setArrhenius ( from_string<double>(what[4]), from_string<double>(what[5]), from_string<double>(what[6]) ); } while (i < reactionStringLines_.size()-1) { cout << "Next = " << reactionStringLines_[i+1] << endl; start = reactionStringLines_[i+1].begin(); end = reactionStringLines_[i+1].end(); if (regex_search(start, end, reactionSingleRegex)) { break; } else if (regex_search(start, end, DUPLICATE)) { reaction.setDuplicate(); // Skip one line when looking for the next reaction. ++i; //break; } else if (regex_search(start, end, REV)) { vector<double> reverseArrhenius = parseLOWTROEREV(reactionStringLines_[i+1], REV); reaction.setArrhenius(reverseArrhenius[0],reverseArrhenius[1],reverseArrhenius[2],true); // Skip one line when looking for the next reaction. ++i; //break; } else if (reaction.hasThirdBody() || reaction.isPressureDependent()) { string lineType = findLineType(reactionStringLines_[i+1]); if (lineType == "THIRDBODY") { reaction.setThirdBodies(parseThirdBodySpecies(reactionStringLines_[i+1])); ++i; } if (lineType == "LOW") { reaction.setLOW(parseLOWTROEREV(reactionStringLines_[i+1], LOW)); ++i; } if (lineType == "TROE") { reaction.setTROE(parseLOWTROEREV(reactionStringLines_[i+1], TROE)); ++i; } if (lineType == "SRI") { reaction.setSRI(parseLOWTROEREV(reactionStringLines_[i+1], SRI)); ++i; } } else if (regex_search(start, end, COV)) { smatch result; string::const_iterator start = reactionStringLines_[i+1].begin(); string::const_iterator end = reactionStringLines_[i+1].end(); regex_search(start, end, result, COV); std::string speciesName = result[2]; double eta = from_string<double>(result[3]); double miu = from_string<double>(result[4]); double epsilon = from_string<double>(result[5]); if ((surfaceUnits == "KJOULES/MOL") || (surfaceUnits == "KJOULES/MOLE")) { epsilon = from_string<double>(result[5])*1000; // Convert to Joules } reaction.setCOV(eta, miu, epsilon, speciesName); // Skip one line when looking for the next reaction. ++i; } else if (regex_search(start, end, FORD)) { smatch result; string::const_iterator start = reactionStringLines_[i+1].begin(); string::const_iterator end = reactionStringLines_[i+1].end(); regex_search(start, end, result, FORD); std::string speciesName = result[2]; double coeff = from_string<double>(result[3]); reaction.setFORD(coeff, speciesName); // Skip one line when looking for the next reaction. ++i; } else if (regex_search(start, end, STICK)) { reaction.setSTICK(); // Skip one line when looking for the next reaction. ++i; //break; } else if (regex_search(start, end, MWON)) { reaction.setMWON(); // Skip one line when looking for the next reaction. ++i; //break; } else { throw std::logic_error("Reaction "+reactionStringLines_[i+1]+" is not supported."); } } reactions.push_back(reaction); } } } multimap<string, double> IO::ReactionParser::parseReactionSpecies(string reactionSpecies) { std::multimap<std::string, double> reactionSpeciesMap; regex splitSpecies("\\+"); regex splitStoichiometry("([0-9]*)([A-Z].*)"); sregex_token_iterator i(reactionSpecies.begin(), reactionSpecies.end(), splitSpecies,-1); sregex_token_iterator j; while (i != j) { // *i Gives a reactant species. Now get its stoichiometry. smatch splitStoic; // ++ iterates to the next reactant! string reactionSpecie = *i++; string::const_iterator start = reactionSpecie.begin(); string::const_iterator end = reactionSpecie.end(); regex_search(start, end, splitStoic, splitStoichiometry); string speciesName = splitStoic[2]; if (splitStoic[1] == "") { reactionSpeciesMap.insert ( pair<string,double> ( trim_copy(speciesName), 1.0 ) ); } else { reactionSpeciesMap.insert ( pair<string,double> ( trim_copy(speciesName), from_string<double>(splitStoic[1]) // this is the stoichiometry number ) ); } } return reactionSpeciesMap; } multimap<string, double> IO::ReactionParser::parseThirdBodySpecies(const string& thirdBodies) { string trim_copymed = trim_copy(thirdBodies); multimap<string, double> thirdBodyMap; // Split the next line using / as delimiter. regex splitThirdBodies("\\/"); sregex_token_iterator j ( trim_copymed.begin(), trim_copymed.end(), splitThirdBodies, -1 ); sregex_token_iterator k; while (j != k) { string name = *j++; string trim_copyName = trim_copy(name); double efficiencyFactor = from_string<double>(*j++); thirdBodyMap.insert(pair<string,double>(trim_copyName,efficiencyFactor)); } return thirdBodyMap; } bool IO::ReactionParser::isBlankLine(const string& line) { string::const_iterator start = line.begin(); string::const_iterator end = line.end(); return regex_match(start, end, blankLine); } string IO::ReactionParser::findLineType(const string& line) { string::const_iterator start = line.begin(); string::const_iterator end = line.end(); if (regex_search(start, end, LOW)) return "LOW"; if (regex_search(start, end, TROE)) return "TROE"; if (regex_search(start, end, SRI)) return "SRI"; return "THIRDBODY"; } vector<double> IO::ReactionParser::parseLOWTROEREV(const string& line, const regex& reg) { vector<double> vec; smatch result; regex_search(line.begin(), line.end(), result, reg); for (size_t i=2; i<result.size(); ++i) { if (result[i] != "") vec.push_back(from_string<double>(result[i])); } return vec; } bool IO::ReactionParser::checkForPressureDependentReaction(const string& line) { if (!regex_search(line.begin(), line.end(), pressureDependent)) { return false; } return true; }
26.299539
140
0.544244
[ "vector" ]
5e318d6401963ed4094329b8e588b6287eb10880
5,419
cpp
C++
libmoon/deps/MoonState/tests/helloByeClientDump.cpp
anonReview/Implementation
b86e0c48a1a9183a143687a2875b160504bcb202
[ "MIT" ]
4
2019-04-26T07:33:02.000Z
2019-08-07T12:35:34.000Z
libmoon/deps/MoonState/tests/helloByeClientDump.cpp
anonReview/Implementation
b86e0c48a1a9183a143687a2875b160504bcb202
[ "MIT" ]
null
null
null
libmoon/deps/MoonState/tests/helloByeClientDump.cpp
anonReview/Implementation
b86e0c48a1a9183a143687a2875b160504bcb202
[ "MIT" ]
1
2018-09-27T17:03:30.000Z
2018-09-27T17:03:30.000Z
#ifdef WITH_PCAP #include <array> #include <iostream> #include <string> #include <vector> #include "IPv4_5TupleL2Ident.hpp" #include "helloByeProto.hpp" #include "pcapBackend.hpp" #include "samplePacket.hpp" #include "stateMachine.hpp" #include <netinet/ether.h> #include <pcap/pcap.h> using namespace std; using Ident = IPv4_5TupleL2Ident<SamplePacket>; using Packet = SamplePacket; void printUsage(string str) { cout << "Usage: " << str << " <dumpfile>" << endl; exit(0); } SamplePacket *getPkt() { uint32_t dataLen = 64; void *data = malloc(dataLen); SamplePacket *p = new SamplePacket(data, dataLen); return p; } int main(int argc, char **argv) { if (argc != 2) { printUsage(string(argv[0])); } char errbuf[PCAP_ERRBUF_SIZE]; pcap_t *handler = pcap_open_offline(argv[1], errbuf); if (handler == nullptr) { cout << "pcap_open_offline() failed" << endl; cout << "Reason: " << errbuf << endl; } StateMachine<Ident, SamplePacket> sm; sm.registerEndStateID(HelloBye::HelloByeClient::Terminate); sm.registerFunction( HelloBye::HelloByeClient::Hello, HelloBye::HelloByeClientHello<Ident, Packet>::run); sm.registerFunction( HelloBye::HelloByeClient::Bye, HelloBye::HelloByeClientBye<Ident, Packet>::run); sm.registerFunction(HelloBye::HelloByeClient::RecvBye, HelloBye::HelloByeClientRecvBye<Ident, Packet>::run); sm.registerGetPktCB(getPkt); pcap_pkthdr clientPacket1Hdr; // uint8_t *clientPacket1; pcap_next(handler, &clientPacket1Hdr); // clientPacket1 = reinterpret_cast<uint8_t *>(malloc(clientPacket1Hdr.len)); // memcpy(clientPacket1, pcapC1P_p, clientPacket1Hdr.len); SamplePacket spc1(malloc(100), 100); pcap_pkthdr serverPacket1Hdr; uint8_t *serverPacket1; const uint8_t *pcapS1P_p = pcap_next(handler, &serverPacket1Hdr); serverPacket1 = reinterpret_cast<uint8_t *>(malloc(serverPacket1Hdr.len)); memcpy(serverPacket1, pcapS1P_p, serverPacket1Hdr.len); SamplePacket sps1(serverPacket1, serverPacket1Hdr.len); pcap_pkthdr clientPacket2Hdr; // uint8_t *clientPacket2; pcap_next(handler, &clientPacket2Hdr); // clientPacket2 = reinterpret_cast<uint8_t *>(malloc(clientPacket2Hdr.len)); // memcpy(clientPacket2, pcapC2P_p, clientPacket2Hdr.len); SamplePacket spc2(malloc(100), 100); pcap_pkthdr serverPacket2Hdr; uint8_t *serverPacket2; const uint8_t *pcapS2P_p = pcap_next(handler, &serverPacket2Hdr); serverPacket2 = reinterpret_cast<uint8_t *>(malloc(serverPacket2Hdr.len)); memcpy(serverPacket2, pcapS2P_p, serverPacket2Hdr.len); SamplePacket sps2(serverPacket2, serverPacket2Hdr.len); uint8_t clientCookie = 0; uint8_t serverCookie = 0; HelloBye::HelloByeClientConfig::createInstance(); auto instance = HelloBye::HelloByeClientConfig::getInstance(); instance->setSrcIP(0x7f000001); instance->setDstPort(0x3905); cout << "main(): Processing packets now" << endl; srand(time(nullptr)); try { { SamplePacket **pktsP = reinterpret_cast<SamplePacket **>(malloc(sizeof(void *))); BufArray<SamplePacket> pktsIn(pktsP, 1); pktsP[0] = &spc1; IPv4_5TupleL2Ident<SamplePacket>::ConnectionID cID; cID.dstIP = htonl(0x7f000001); cID.srcIP = htonl(0x7f000001); cID.srcPort = 0x3905; cID.dstPort = 0x0a87; cID.proto = Headers::IPv4::PROTO_UDP; auto obj = new HelloBye::HelloByeClientHello<Ident, Packet>(0x7f000001, 0x3905); StateMachine<Ident, SamplePacket>::State state( HelloBye::HelloByeClient::Hello, obj); pktsIn.addPkt(&spc1); sm.addState(cID, state, pktsIn); clientCookie = reinterpret_cast<uint8_t *>(spc1.getData())[0x37]; cout << "clientCookie: 0x" << hex << static_cast<int>(clientCookie) << endl; assert(pktsIn.getSendCount() == 1); assert(pktsIn.getFreeCount() == 0); cout << "Dump of packet output" << endl; hexdump(spc1.getData(), spc1.getDataLen()); } { // reinterpret_cast<uint8_t *>(sps1.getData())[0x37] = clientCookie; SamplePacket **pktsP = reinterpret_cast<SamplePacket **>(malloc(sizeof(void *))); BufArray<SamplePacket> pktsIn(pktsP, 1); pktsP[0] = &sps1; cout << "Dump of packet input" << endl; hexdump(sps1.getData(), sps1.getDataLen()); sm.runPktBatch(pktsIn); assert(pktsIn.getSendCount() == 1); assert(pktsIn.getFreeCount() == 0); serverCookie = reinterpret_cast<uint8_t *>(sps1.getData())[0x35]; cout << "Dump of packet output" << endl; hexdump(sps1.getData(), sps1.getDataLen()); } { reinterpret_cast<uint8_t *>(sps2.getData())[0x35] = clientCookie; SamplePacket **pktsP = reinterpret_cast<SamplePacket **>(malloc(sizeof(void *))); BufArray<SamplePacket> pktsIn(pktsP, 1); pktsP[0] = &sps2; cout << "Dump of packet input" << endl; hexdump(sps2.getData(), sps2.getDataLen()); sm.runPktBatch(pktsIn); assert(pktsIn.getSendCount() == 0); assert(pktsIn.getFreeCount() == 1); } } catch (exception *e) { // Just catch whatever fails there may be cout << endl << "FATAL:" << endl; cout << e->what() << endl; pcap_close(handler); return 1; } pcap_close(handler); cout << endl << "-----------------------------------------" << endl; cout << "All tests ran through without aborting :)" << endl; cout << "-----------------------------------------" << endl << endl; return 0; } #else #include <iostream> int main(int argc, char **argv) { (void)argc; (void)argv; std::cout << "Built without pcap..." << std::endl; return 0; } #endif
27.095
86
0.695331
[ "vector" ]
5e34321278351b84ebda609694b22d616f811760
912
cpp
C++
C++/1443-Minimum-Time-to-Collect-All-Apples-in-a-Tree/soln.cpp
wyaadarsh/LeetCode-Solutions
3719f5cb059eefd66b83eb8ae990652f4b7fd124
[ "MIT" ]
5
2020-07-24T17:48:59.000Z
2020-12-21T05:56:00.000Z
C++/1443-Minimum-Time-to-Collect-All-Apples-in-a-Tree/soln.cpp
zhangyaqi1989/LeetCode-Solutions
2655a1ffc8678ad1de6c24295071308a18c5dc6e
[ "MIT" ]
null
null
null
C++/1443-Minimum-Time-to-Collect-All-Apples-in-a-Tree/soln.cpp
zhangyaqi1989/LeetCode-Solutions
2655a1ffc8678ad1de6c24295071308a18c5dc6e
[ "MIT" ]
2
2020-07-24T17:49:01.000Z
2020-08-31T19:57:35.000Z
class Solution { public: int minTime(int n, vector<vector<int>>& edges, vector<bool>& hasApple) { // need to know how many vector<vector<int>> tree(n); for(auto & e : edges) { int u = e[0], v = e[1]; tree[u].push_back(v); tree[v].push_back(u); } int n_deletes = 0; Postorder(tree, hasApple, 0, -1, &n_deletes); return (n - n_deletes - 1) * 2; } private: int Postorder(const vector<vector<int>> & tree, const vector<bool> & hasApple, int u, int parent, int * n_deletes) { int n_apples = 0; for(int v : tree[u]) { if(v != parent) { n_apples += Postorder(tree, hasApple, v, u, n_deletes); } } if (hasApple[u]) ++n_apples; if(parent != -1 && n_apples == 0) *n_deletes += 1; return n_apples; } };
30.4
83
0.491228
[ "vector" ]
5e36a9f666fd10f3e082c8d2a8295b1db6fe1421
794
hpp
C++
src/model/package.hpp
TheSonOfDeimos/network-routing-optimization
7030b5cf333f19ab68952b6841463f4cfd664895
[ "MIT" ]
null
null
null
src/model/package.hpp
TheSonOfDeimos/network-routing-optimization
7030b5cf333f19ab68952b6841463f4cfd664895
[ "MIT" ]
null
null
null
src/model/package.hpp
TheSonOfDeimos/network-routing-optimization
7030b5cf333f19ab68952b6841463f4cfd664895
[ "MIT" ]
null
null
null
#ifndef PACKAGE_HPP #define PACKAGE_HPP #include "types.hpp" #include "time.hpp" #include "algorithmBase.hpp" struct Package { Package(hostAddress_t src, hostAddress_t dst, dataVolume_t vol); hostAddress_t source; hostAddress_t destination; dataVolume_t volume; // In bytes TransportProto protocol = TransportProto::UDP; Priority priority = Priority::NONE; ttl_t ttl = INT32_MAX; packageId_t id; std::vector<hostAddress_t> path = {}; // Status modelTime_t inQueue = 0; modelTime_t outQueue = 0; modelTime_t inProcess = 0; modelTime_t outProcess = 0; modelTime_t inSystem = 0; modelTime_t outSystem = 0; bool isReached = false; hostAddress_t lastNode = -1; }; using packagePtr_t = std::unique_ptr<Package>; #endif
20.894737
68
0.698992
[ "vector" ]
5e3ca7128f6700d6daaf6c404e156a13ff87dff6
1,716
cpp
C++
AdventOfCode9-1/Program.cpp
noasoder/AdventOfCode
a570a2bb04026a2d865947232b84b3e80c0554c5
[ "MIT" ]
null
null
null
AdventOfCode9-1/Program.cpp
noasoder/AdventOfCode
a570a2bb04026a2d865947232b84b3e80c0554c5
[ "MIT" ]
null
null
null
AdventOfCode9-1/Program.cpp
noasoder/AdventOfCode
a570a2bb04026a2d865947232b84b3e80c0554c5
[ "MIT" ]
null
null
null
#include "Program.h" #include <iostream> #include <fstream> #include <vector> uint16_t BitsToInt(std::string str) { uint16_t result = 0; for (char c : str) { result = (result << 1) | (c - '0'); } return result; } Program::Program() { std::fstream file; file.open("input.txt", std::ios::in); if (!file.is_open()) return; std::vector<std::string> lines; std::string newLine; while (std::getline(file, newLine)) { lines.push_back(newLine); ProcessInput(newLine); } Solve(); file.close(); } Program::~Program() { } void Program::ProcessInput(std::string line) { int numberOfDigits = 0; std::vector<int> row; for (int j = 0; j < line.size(); j++) { row.push_back(std::stoi(line.substr(j, 1))); } m_grid.push_back(row); } void Program::Solve() { int risk = 0; for (int i = 0; i < m_grid.size(); i++) { for (int j = 0; j < m_grid[i].size(); j++) { if (CheckAround(i, j)) { risk += 1 + m_grid[i][j]; } } } std::cout << "final result: " << risk << std::endl; } bool Program::CheckAround(int row, int coll) { int current = m_grid[row][coll]; int up = -1; int down = -1; int left = -1; int right = -1; if (row - 1 >= 0 && row - 1 < 100) up = m_grid[row - 1][coll]; if (row + 1 >= 0 && row + 1 < 100) down = m_grid[row + 1][coll]; if (coll - 1 >= 0 && coll - 1 < 100) left = m_grid[row][coll - 1]; if(coll + 1 >= 0 && coll + 1 < 100) right = m_grid[row][coll + 1]; if (up != -1) { if (current >= up) return false; } if (down != -1) { if (current >= down) return false; } if (left != -1) { if (current >= left) return false; } if (right != -1) { if (current >= right) return false; } return true; }
14.3
52
0.555361
[ "vector" ]
1e0f533d0efd1881da3cbb14253341ac7247d129
13,475
cpp
C++
ImportantExample/cuteReportView/cutereport/src/plugins/standard/core_plugins/datasets/sql/sqldataset.cpp
xiaohaijin/Qt
54d961c6a8123d8e4daf405b7996aba4be9ab7ed
[ "MIT" ]
3
2018-12-24T19:35:52.000Z
2022-02-04T14:45:59.000Z
ImportantExample/cuteReportView/cutereport/src/plugins/standard/core_plugins/datasets/sql/sqldataset.cpp
xiaohaijin/Qt
54d961c6a8123d8e4daf405b7996aba4be9ab7ed
[ "MIT" ]
null
null
null
ImportantExample/cuteReportView/cutereport/src/plugins/standard/core_plugins/datasets/sql/sqldataset.cpp
xiaohaijin/Qt
54d961c6a8123d8e4daf405b7996aba4be9ab7ed
[ "MIT" ]
1
2019-05-09T02:42:40.000Z
2019-05-09T02:42:40.000Z
/*************************************************************************** * This file is part of the CuteReport project * * Copyright (C) 2012-2015 by Alexander Mikhalov * * alexander.mikhalov@gmail.com * * * ** GNU General Public License Usage ** * * * This library is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * ** GNU Lesser General Public License ** * * * This library is free software: you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License as * * published by the Free Software Foundation, either version 3 of the * * License, or (at your option) any later version. * * You should have received a copy of the GNU Lesser General Public * * License along with this library. * * If not, see <http://www.gnu.org/licenses/>. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * ***************************************************************************/ #include "sqldataset.h" #include "sqldatasethelper.h" #include "reportcore.h" #include "cutereport_functions.h" #include <QSqlDatabase> using namespace CuteReport; SqlDataset::SqlDataset(QObject *parent) : CuteReport::DatasetInterface(parent) { m_currentRow = 0; m_isPopulated = false; m_model = new QSqlQueryModel (this); m_fmodel = new QSortFilterProxyModel(this); m_fmodel->setSourceModel(m_model); m_connectionName = QString("_sqldataset_%1").arg(QTime::currentTime().msec()); } SqlDataset::SqlDataset(const SqlDataset &dd, QObject * parent) : DatasetInterface(parent) { m_currentRow = 0; m_isPopulated = false; m_queryText = dd.m_queryText; m_dbhost = dd.m_dbhost; m_dbname = dd.m_dbname; m_dbuser = dd.m_dbuser; m_dbpasswd = dd.m_dbpasswd; m_driver = dd.m_driver; m_connectionName = dd.m_connectionName; m_lastError = dd.m_lastError; m_model = new QSqlQueryModel(this); m_fmodel = new QSortFilterProxyModel(this); m_fmodel->setSourceModel(m_model); if (dd.m_isPopulated) { populate(); setCurrentRowNumber(dd.m_currentRow); } } SqlDataset::~SqlDataset() { if (m_helper) delete m_helper; } QIcon SqlDataset::icon() { QIcon icon(":/images/sql.png"); return icon; } CuteReport::DatasetInterface * SqlDataset::createInstance(QObject* parent) const { return new SqlDataset(parent); } DatasetInterface *SqlDataset::objectClone() const { return new SqlDataset(*this, parent()); } DatasetHelperInterface * SqlDataset::helper() { if (!m_helper) m_helper = new SqlDatasetHelper(this); return m_helper; } QString SqlDataset::getLastError() { if (!db.isValid() || db.isOpenError() || !db.isOpen()) return m_lastError; return m_model->lastError().text(); } QString SqlDataset::getFieldName(int column ) { if (!m_isPopulated) populate(); return m_model->record().fieldName(column); // } else // return m_model->headerData ( column, Qt::Horizontal).toString(); } QVariant::Type SqlDataset::getFieldType(int column) { return QVariant::String; } QAbstractItemModel * SqlDataset::model() { return m_fmodel; } QString SqlDataset::query() const { return m_queryText; } void SqlDataset::setQuery(const QString &str) { if (m_queryText == str) return; m_queryText = str; emit queryChanged(m_queryText); emit variablesChanged(); emit changed(); } bool SqlDataset::populate() { ReportCore::log(CuteReport::LogDebug, "SqlDataset", QString("\'%1\' populate").arg(objectName())); emit beforePopulate(); reset(); QString script; QString dbHost; QString dbName; QString dbUser; QString dbPassword; QString dbDriver; CuteReport::ReportInterface* report = dynamic_cast<CuteReport::ReportInterface*> (parent()); if (report) { QStringList missedVariables; if (!isStringValued(m_queryText, report->variables(), &missedVariables)) { m_lastError = QString("Variable is not defined: %1").arg(missedVariables.join(", ")); return false; } script = setVariablesValue(m_queryText, report->variables()); if (!isStringValued(m_dbhost, report->variables(), &missedVariables)) { m_lastError = QString("Variable is not defined in \'dbhost\' property: %1").arg(missedVariables.join(", ")); return false; } dbHost = setVariablesValue(m_dbhost, report->variables()); if (!isStringValued(m_dbname, report->variables(), &missedVariables)) { m_lastError = QString("Variable is not defined in \'dbname\' property: %1").arg(missedVariables.join(", ")); return false; } dbName = setVariablesValue(m_dbname, report->variables()); if (!isStringValued(m_dbuser, report->variables(), &missedVariables)) { m_lastError = QString("Variable is not defined in \'dbuser\' property: %1").arg(missedVariables.join(", ")); return false; } dbUser = setVariablesValue(m_dbuser, report->variables()); if (!isStringValued(m_dbpasswd, report->variables(), &missedVariables)) { m_lastError = QString("Variable is not defined in \'dbpassword\' property: %1").arg(missedVariables.join(", ")); return false; } dbPassword = setVariablesValue(m_dbpasswd, report->variables()); if (!isStringValued(m_driver, report->variables(), &missedVariables)) { m_lastError = QString("Variable is not defined in \'driver\' property: %1").arg(missedVariables.join(", ")); return false; } dbDriver = setVariablesValue(m_driver, report->variables()); } else { script = m_queryText; dbHost = m_dbhost; dbName = m_dbname; dbUser = m_dbuser; dbPassword = m_dbpasswd; dbDriver = m_driver; } ReportCore::log(CuteReport::LogDebug, "SqlDataset", QString("query = %1").arg(script)); dbName = dbHost.isEmpty() ? reportCore()->localCachedFileName(dbName, report) : dbName ; if (dbName.isEmpty()) { m_lastError = QString("Database name is empty."); return false; } if (dbDriver.isEmpty()) { m_lastError = QString("Database driver not defined."); return false; } if (script.isEmpty()) { m_lastError = QString("Query text is empty."); return false; } db = QSqlDatabase::database(m_connectionName, false); if (!db.isValid()) { db = QSqlDatabase::addDatabase(dbDriver, m_connectionName); if (!db.isValid()) { m_lastError = db.lastError().text(); return false; } } db.setHostName(dbHost); db.setDatabaseName(dbName); db.setUserName(dbUser); db.setPassword(dbPassword); if (!db.open()) { m_lastError = QString("Can't open database with name \'%1\'").arg(dbName) + db.lastError().text(); return false; } m_model->setQuery(script, db); bool ret = !m_model->lastError().isValid(); if ( ret && !QSqlDatabase::database().driver()->hasFeature(QSqlDriver::QuerySize)) while (m_model->canFetchMore()) m_model->fetchMore(); m_isPopulated = ret; m_fmodel->setSourceModel(m_model); m_currentRow = m_fmodel->rowCount() > 0 ? 0 : -1; emit afterPopulate(); return ret; } bool SqlDataset::isPopulated() { return m_isPopulated; } void SqlDataset::setPopulated(bool b) { m_isPopulated = b; } void SqlDataset::reset() { m_isPopulated = false; m_model->clear(); m_currentRow = -1; m_lastError = ""; db.close(); } void SqlDataset::resetCursor() { m_currentRow = -1; } bool SqlDataset::setFirstRow() { if (!m_isPopulated) populate(); emit(beforeFirst()); m_currentRow = 0; bool ret = getRowCount(); emit(afterFirst()); return ret; } bool SqlDataset::setLastRow() { if (!m_isPopulated) populate(); emit(beforeLast()); m_currentRow = m_fmodel->rowCount(); bool ret = m_fmodel->index(m_currentRow, 0).isValid(); emit(afterLast()); return ret; } bool SqlDataset::setNextRow() { if (!m_isPopulated) populate(); emit(beforeNext()); m_currentRow++; bool ret = m_currentRow < getRowCount(); emit(afterNext()); return ret; } bool SqlDataset::setPreviousRow() { if (!m_isPopulated) populate(); emit(beforePrevious()); m_currentRow--; bool ret = m_currentRow >= 0; emit(afterPrevious()); return ret; } int SqlDataset::getCurrentRowNumber() { return m_currentRow; } bool SqlDataset::setCurrentRowNumber(int index) { if (!m_isPopulated) populate(); emit(beforeSeek(index)); m_currentRow = index; bool ret = m_fmodel->index(m_currentRow, 0).isValid(); emit(afterSeek(index)); return ret; } int SqlDataset::getRowCount() { if (!m_isPopulated) populate(); return m_fmodel->rowCount(); } int SqlDataset::getColumnCount() { if (!m_isPopulated) populate(); return m_fmodel->columnCount(); } QVariant SqlDataset::getValue(int index) { if (!m_isPopulated) populate(); return m_fmodel->data( m_fmodel->index(m_currentRow,index) ); } QVariant SqlDataset::getValue(const QString & field) { if (!m_isPopulated) populate(); // qDebug() << m_currentRow << m_fmodel->data( m_fmodel->index(m_currentRow, m_model->record().indexOf(field) ) ).toString(); return m_fmodel->data( m_fmodel->index(m_currentRow, m_model->record().indexOf(field) ) ); } QVariant SqlDataset::getNextRowValue(int index) { if (!m_isPopulated) populate(); return m_currentRow+1 < m_fmodel->rowCount() && index < m_fmodel->columnCount() ? m_fmodel->data( m_fmodel->index(m_currentRow + 1,index) ) : QVariant::Invalid; } QVariant SqlDataset::getNextRowValue(const QString & field) { if (!m_isPopulated) populate(); return m_currentRow+1 < m_fmodel->rowCount() ? m_fmodel->data( m_fmodel->index(m_currentRow + 1, m_model->record().indexOf(field) ) ) : QVariant::Invalid; } QVariant SqlDataset::getPreviousRowValue(int index) { if (!m_isPopulated) populate(); return m_currentRow-1 < 0 && index < m_fmodel->columnCount() ? m_fmodel->data( m_fmodel->index(m_currentRow - 1,index) ) : QVariant::Invalid; } QVariant SqlDataset::getPreviousRowValue(const QString & field) { if (!m_isPopulated) populate(); return m_currentRow-1 < 0 ? m_fmodel->data( m_fmodel->index(m_currentRow - 1, m_model->record().indexOf(field) ) ) : QVariant::Invalid; } QSet<QString> SqlDataset::variables() const { QSet<QString> set; set.unite( findVariables(m_queryText) ); set.unite( findVariables(m_dbhost) ); set.unite( findVariables(m_dbname) ); set.unite( findVariables(m_dbuser) ); set.unite( findVariables(m_dbpasswd) ); set.unite( findVariables(m_driver) ); return set; } QStringList SqlDataset::drivers() const { return QSqlDatabase::drivers(); } QString SqlDataset::driver() const { return m_driver; } void SqlDataset::setDriver(QString driver) { if (m_driver == driver) return; m_driver = driver; emit driverChanged(m_driver); emit changed(); } QString SqlDataset::dbhost() const { return m_dbhost; } void SqlDataset::setdbhost(QString host) { if (m_dbhost == host) return; m_dbhost = host; emit dbhostChanged(m_dbhost); emit changed(); } QString SqlDataset::dbuser() const { return m_dbuser; } void SqlDataset::setdbuser(QString user) { if (m_dbuser == user) return; m_dbuser = user; emit dbuserChanged(m_dbuser); emit changed(); } QString SqlDataset::dbname() const { return m_dbname; } void SqlDataset::setdbname(QString name) { if (m_dbname == name) return; m_dbname = name; emit dbnameChanged(m_dbname); emit changed(); } QString SqlDataset::dbpasswd() const { return m_dbpasswd; } void SqlDataset::setdbpasswd(QString passwd) { if (m_dbpasswd == passwd) return; m_dbpasswd = passwd; emit dbpasswdChanged(m_dbpasswd); emit changed(); } #if QT_VERSION < 0x050000 Q_EXPORT_PLUGIN2(DatasetSQL, SqlDataset) #endif
24.411232
165
0.616698
[ "model" ]
1e0f93712185850546b856a7aa708fa9c5c8045d
1,158
cpp
C++
Leetcode/L1033.cpp
yanjinbin/Foxconn
d8340d228deb35bd8ec244f6156374da8a1f0aa0
[ "CC0-1.0" ]
8
2021-02-14T01:48:09.000Z
2022-01-29T09:12:55.000Z
Leetcode/L1033.cpp
yanjinbin/Foxconn
d8340d228deb35bd8ec244f6156374da8a1f0aa0
[ "CC0-1.0" ]
null
null
null
Leetcode/L1033.cpp
yanjinbin/Foxconn
d8340d228deb35bd8ec244f6156374da8a1f0aa0
[ "CC0-1.0" ]
null
null
null
#include <algorithm> #include <iostream> #include <map> #include <queue> #include <vector> using namespace std; const int INF = 0x3F3F3F3F; #define debug puts("pigtoria bling bling ⚡️⚡️"); #define FOR(i, a, b) for (int i = a; i < b; i++) #define ll long long #define pii pair<int, int> class Solution { public: // * // * 思路: // * 1、把这三个数字排序 // * 2、找到最大的次数 // * max = 最大数 - 最小数 - 2 // * // * 3、找到最小的次数 // * 3-1:如果三个数是连续的 1 2 3, 最小数 : 0 // * 3-2:如果有两个数之前的差是1、或者2, 最小数 : 1 // * eg: 1 55 56 -> 54 55 56 // * 1 3 56 -> 1 2 3 // * 3-3: 其它的 最小数 : 2 // * eg: 1 23 55 -> 22 23 24 // * vector<int> numMovesStones(int a, int b, int c) { // bubble sort if (b < a) swap(a, b); if (c < b) swap(b, c); if (b < a) swap(a, b); if(b-a==1&&c-b==1) return vector<int>{0,c-a-2}; if(c-b<=2||b-a<=2) return vector<int>{1,c-a-2}; return vector<int>{2,c-a-2}; } }; int main() { return 0; }
28.95
65
0.426598
[ "vector" ]
1e1119d660559dce4c3f10b621d8cb9a8790d5f4
3,168
cpp
C++
unit_tests/core/containers/t4mesh_compute_mesh_quality/src/unit_t4mesh_compute_mesh_quality.cpp
ricortiz/OpenTissue
f8c8ebc5137325b77ba90bed897f6be2795bd6fb
[ "Zlib" ]
76
2018-02-20T11:30:52.000Z
2022-03-31T12:45:06.000Z
unit_tests/core/containers/t4mesh_compute_mesh_quality/src/unit_t4mesh_compute_mesh_quality.cpp
ricortiz/OpenTissue
f8c8ebc5137325b77ba90bed897f6be2795bd6fb
[ "Zlib" ]
27
2018-11-20T14:32:49.000Z
2021-11-24T15:26:45.000Z
unit_tests/core/containers/t4mesh_compute_mesh_quality/src/unit_t4mesh_compute_mesh_quality.cpp
ricortiz/OpenTissue
f8c8ebc5137325b77ba90bed897f6be2795bd6fb
[ "Zlib" ]
24
2018-02-21T01:45:26.000Z
2022-03-07T07:06:49.000Z
// // OpenTissue, A toolbox for physical based simulation and animation. // Copyright (C) 2007 Department of Computer Science, University of Copenhagen // #include <OpenTissue/configuration.h> #include <OpenTissue/core/containers/t4mesh/t4mesh.h> #include <OpenTissue/core/geometry/geometry_compute_inscribed_circumscribed_radius_quality_measure.h> #include <OpenTissue/core/geometry/geometry_compute_volume_length_quality_measure.h> #include <OpenTissue/core/geometry/geometry_compute_inscribed_radius_length_quality_measure.h> #include <OpenTissue/core/containers/t4mesh/util/t4mesh_compute_mesh_quality.h> #define BOOST_AUTO_TEST_MAIN #include <OpenTissue/utility/utility_push_boost_filter.h> #include <boost/test/auto_unit_test.hpp> #include <boost/test/unit_test_suite.hpp> #include <boost/test/floating_point_comparison.hpp> #include <boost/test/test_tools.hpp> #include <OpenTissue/utility/utility_pop_boost_filter.h> BOOST_AUTO_TEST_SUITE(opentissue_t4mesh_compute_mesh_quality); BOOST_AUTO_TEST_CASE(quality_testing) { typedef OpenTissue::math::BasicMathTypes<double, size_t> math_types; typedef OpenTissue::t4mesh::T4Mesh< math_types > mesh_type; typedef math_types::vector3_type vector3_type; typedef vector3_type::value_type real_type; std::vector<vector3_type> c; c.resize( 6 ); c[0] = vector3_type(0,0,0); c[1] = vector3_type(0,0,1); c[2] = vector3_type(0,1,0); c[3] = vector3_type(0,1,1); c[4] = vector3_type(1,0,0); c[5] = vector3_type(1,0,1); mesh_type M; M.insert( c[0] ); M.insert( c[1] ); M.insert( c[2] ); M.insert( c[3] ); M.insert( c[4] ); M.insert( c[5] ); M.insert(0,1,2,3); M.insert(0,1,2,4); { using namespace OpenTissue::geometry; std::vector<real_type> Q; OpenTissue::t4mesh::compute_mesh_quality( M, c, Q, &(compute_inscribed_circumscribed_radius_quality_measure<vector3_type>) ); BOOST_CHECK(Q.size() == 2); } { using namespace OpenTissue::geometry; std::vector<real_type> Q; OpenTissue::t4mesh::compute_mesh_quality( M,Q, &(compute_inscribed_circumscribed_radius_quality_measure<vector3_type>) ); BOOST_CHECK(Q.size() == 2); } { using namespace OpenTissue::geometry; std::vector<real_type> Q; OpenTissue::t4mesh::compute_mesh_quality( M,c, Q, &(compute_volume_length_quality_measure<vector3_type>) ); BOOST_CHECK(Q.size() == 2); } { using namespace OpenTissue::geometry; std::vector<real_type> Q; OpenTissue::t4mesh::compute_mesh_quality( M,Q, &(compute_volume_length_quality_measure<vector3_type>) ); BOOST_CHECK(Q.size() == 2); } { using namespace OpenTissue::geometry; std::vector<real_type> Q; OpenTissue::t4mesh::compute_mesh_quality( M, c, Q, &(compute_inscribed_radius_length_quality_measure<vector3_type>) ); BOOST_CHECK(Q.size() == 2); } { using namespace OpenTissue::geometry; std::vector<real_type> Q; OpenTissue::t4mesh::compute_mesh_quality( M, Q, &(compute_inscribed_radius_length_quality_measure<vector3_type>) ); BOOST_CHECK(Q.size() == 2); } } BOOST_AUTO_TEST_SUITE_END();
33.702128
130
0.723169
[ "geometry", "vector" ]
1e168ff02e702f3c9a0c0f594c8e002f0d3ac88d
26,101
cpp
C++
external/vulkancts/modules/vulkan/subgroups/vktSubgroupsBallotBroadcastTests.cpp
ShabbyX/VK-GL-CTS
74ffed6e0b286e6279ed3db1a6c50aad6b387836
[ "Apache-2.0" ]
null
null
null
external/vulkancts/modules/vulkan/subgroups/vktSubgroupsBallotBroadcastTests.cpp
ShabbyX/VK-GL-CTS
74ffed6e0b286e6279ed3db1a6c50aad6b387836
[ "Apache-2.0" ]
1
2019-09-02T06:26:06.000Z
2019-09-02T06:26:06.000Z
external/vulkancts/modules/vulkan/subgroups/vktSubgroupsBallotBroadcastTests.cpp
ShabbyX/VK-GL-CTS
74ffed6e0b286e6279ed3db1a6c50aad6b387836
[ "Apache-2.0" ]
null
null
null
/*------------------------------------------------------------------------ * Vulkan Conformance Tests * ------------------------ * * Copyright (c) 2019 The Khronos Group Inc. * Copyright (c) 2019 Google Inc. * Copyright (c) 2017 Codeplay Software Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /*! * \file * \brief Subgroups Tests */ /*--------------------------------------------------------------------*/ #include "vktSubgroupsBallotBroadcastTests.hpp" #include "vktSubgroupsTestsUtils.hpp" #include <string> #include <vector> using namespace tcu; using namespace std; using namespace vk; using namespace vkt; namespace { enum OpType { OPTYPE_BROADCAST = 0, OPTYPE_BROADCAST_FIRST, OPTYPE_LAST }; static bool checkVertexPipelineStages(std::vector<const void*> datas, deUint32 width, deUint32) { return vkt::subgroups::check(datas, width, 3); } static bool checkCompute(std::vector<const void*> datas, const deUint32 numWorkgroups[3], const deUint32 localSize[3], deUint32) { return vkt::subgroups::checkCompute(datas, numWorkgroups, localSize, 3); } std::string getOpTypeName(int opType) { switch (opType) { default: DE_FATAL("Unsupported op type"); return ""; case OPTYPE_BROADCAST: return "subgroupBroadcast"; case OPTYPE_BROADCAST_FIRST: return "subgroupBroadcastFirst"; } } struct CaseDefinition { int opType; VkShaderStageFlags shaderStage; VkFormat format; de::SharedPtr<bool> geometryPointSizeSupported; deBool extShaderSubGroupBallotTests; }; std::string getBodySource(CaseDefinition caseDef) { std::ostringstream bdy; bdy << " uvec4 mask = subgroupBallot(true);\n"; bdy << " uint tempResult = 0;\n"; if (OPTYPE_BROADCAST == caseDef.opType) { bdy << " tempResult = 0x3;\n"; for (int i = 0; i < (int)subgroups::maxSupportedSubgroupSize(); i++) { bdy << " {\n" << " const uint id = "<< i << ";\n" << " " << subgroups::getFormatNameForGLSL(caseDef.format) << " op = subgroupBroadcast(data1[gl_SubgroupInvocationID], id);\n" << " if ((id < gl_SubgroupSize) && subgroupBallotBitExtract(mask, id))\n" << " {\n" << " if (op != data1[id])\n" << " {\n" << " tempResult = 0;\n" << " }\n" << " }\n" << " }\n"; } } else { bdy << " uint firstActive = 0;\n" << " for (uint i = 0; i < gl_SubgroupSize; i++)\n" << " {\n" << " if (subgroupBallotBitExtract(mask, i))\n" << " {\n" << " firstActive = i;\n" << " break;\n" << " }\n" << " }\n" << " tempResult |= (subgroupBroadcastFirst(data1[gl_SubgroupInvocationID]) == data1[firstActive]) ? 0x1 : 0;\n" << " // make the firstActive invocation inactive now\n" << " if (firstActive == gl_SubgroupInvocationID)\n" << " {\n" << " for (uint i = 0; i < gl_SubgroupSize; i++)\n" << " {\n" << " if (subgroupBallotBitExtract(mask, i))\n" << " {\n" << " firstActive = i;\n" << " break;\n" << " }\n" << " }\n" << " tempResult |= (subgroupBroadcastFirst(data1[gl_SubgroupInvocationID]) == data1[firstActive]) ? 0x2 : 0;\n" << " }\n" << " else\n" << " {\n" << " // the firstActive invocation didn't partake in the second result so set it to true\n" << " tempResult |= 0x2;\n" << " }\n"; } return bdy.str(); } std::string getBodySourceARB(CaseDefinition caseDef) { std::ostringstream bdy; bdy << " uint64_t mask = ballotARB(true);\n"; bdy << " uint tempResult = 0;\n"; if (OPTYPE_BROADCAST == caseDef.opType) { bdy << " tempResult = 0x3;\n"; for (int i = 0; i < 64; i++) { bdy << " {\n" << " const uint id = "<< i << ";\n" << " " << subgroups::getFormatNameForGLSL(caseDef.format) << " op = readInvocationARB(data1[gl_SubGroupInvocationARB], id);\n" << " if ((id < gl_SubGroupSizeARB) && subgroupBallotBitExtract(mask, id))\n" << " {\n" << " if (op != data1[id])\n" << " {\n" << " tempResult = 0;\n" << " }\n" << " }\n" << " }\n"; } } else { bdy << " uint firstActive = 0;\n" << " for (uint i = 0; i < gl_SubGroupSizeARB; i++)\n" << " {\n" << " if (subgroupBallotBitExtract(mask, i))\n" << " {\n" << " firstActive = i;\n" << " break;\n" << " }\n" << " }\n" << " tempResult |= (readFirstInvocationARB(data1[gl_SubGroupInvocationARB]) == data1[firstActive]) ? 0x1 : 0;\n" << " // make the firstActive invocation inactive now\n" << " if (firstActive == gl_SubGroupInvocationARB)\n" << " {\n" << " for (uint i = 0; i < gl_SubGroupSizeARB; i++)\n" << " {\n" << " if (subgroupBallotBitExtract(mask, i))\n" << " {\n" << " firstActive = i;\n" << " break;\n" << " }\n" << " }\n" << " tempResult |= (readFirstInvocationARB(data1[gl_SubGroupInvocationARB]) == data1[firstActive]) ? 0x2 : 0;\n" << " }\n" << " else\n" << " {\n" << " // the firstActive invocation didn't partake in the second result so set it to true\n" << " tempResult |= 0x2;\n" << " }\n"; } return bdy.str(); } std::string getHelperFunctionARB(CaseDefinition caseDef) { std::ostringstream bdy; if (caseDef.extShaderSubGroupBallotTests == DE_FALSE) return ""; bdy << "bool subgroupBallotBitExtract(uint64_t value, uint index)\n"; bdy << "{\n"; bdy << " if (index > 63)\n"; bdy << " return false;\n"; bdy << " uint64_t mask = uint64_t(1 << index);\n"; bdy << " if (bool((value & mask)) == true)\n"; bdy << " return true;\n"; bdy << " return false;\n"; bdy << "}\n"; return bdy.str(); } void initFrameBufferPrograms(SourceCollections& programCollection, CaseDefinition caseDef) { const vk::ShaderBuildOptions buildOptions (programCollection.usedVulkanVersion, vk::SPIRV_VERSION_1_3, 0u); const string extensionHeader = (caseDef.extShaderSubGroupBallotTests ? "#extension GL_ARB_shader_ballot: enable\n#extension GL_KHR_shader_subgroup_basic: enable\n#extension GL_ARB_gpu_shader_int64: enable\n" : "#extension GL_KHR_shader_subgroup_ballot: enable\n"); subgroups::setFragmentShaderFrameBuffer(programCollection); if (VK_SHADER_STAGE_VERTEX_BIT != caseDef.shaderStage) subgroups::setVertexShaderFrameBuffer(programCollection); std::string bdyStr = (caseDef.extShaderSubGroupBallotTests ? getBodySourceARB(caseDef) : getBodySource(caseDef)); std::string helperStrARB = getHelperFunctionARB(caseDef); if (VK_SHADER_STAGE_VERTEX_BIT == caseDef.shaderStage) { std::ostringstream vertex; vertex << glu::getGLSLVersionDeclaration(glu::GLSL_VERSION_450)<<"\n" << extensionHeader.c_str() << "layout(location = 0) in highp vec4 in_position;\n" << "layout(location = 0) out float out_color;\n" << "layout(set = 0, binding = 0) uniform Buffer1\n" << "{\n" << " " << subgroups::getFormatNameForGLSL(caseDef.format) << " data1[" << subgroups::maxSupportedSubgroupSize() << "];\n" << "};\n" << "\n" << helperStrARB.c_str() << "void main (void)\n" << "{\n" << bdyStr << " out_color = float(tempResult);\n" << " gl_Position = in_position;\n" << " gl_PointSize = 1.0f;\n" << "}\n"; programCollection.glslSources.add("vert") << glu::VertexSource(vertex.str()) << buildOptions; } else if (VK_SHADER_STAGE_GEOMETRY_BIT == caseDef.shaderStage) { std::ostringstream geometry; geometry << glu::getGLSLVersionDeclaration(glu::GLSL_VERSION_450)<<"\n" << extensionHeader.c_str() << "layout(points) in;\n" << "layout(points, max_vertices = 1) out;\n" << "layout(location = 0) out float out_color;\n" << "layout(set = 0, binding = 0) uniform Buffer1\n" << "{\n" << " " << subgroups::getFormatNameForGLSL(caseDef.format) << " data1[" <<subgroups::maxSupportedSubgroupSize() << "];\n" << "};\n" << "\n" << helperStrARB.c_str() << "void main (void)\n" << "{\n" << bdyStr << " out_color = float(tempResult);\n" << " gl_Position = gl_in[0].gl_Position;\n" << (*caseDef.geometryPointSizeSupported ? " gl_PointSize = gl_in[0].gl_PointSize;\n" : "") << " EmitVertex();\n" << " EndPrimitive();\n" << "}\n"; programCollection.glslSources.add("geometry") << glu::GeometrySource(geometry.str()) << buildOptions; } else if (VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT == caseDef.shaderStage) { std::ostringstream controlSource; controlSource << glu::getGLSLVersionDeclaration(glu::GLSL_VERSION_450)<<"\n" << extensionHeader.c_str() << "layout(vertices = 2) out;\n" << "layout(location = 0) out float out_color[];\n" << "layout(set = 0, binding = 0) uniform Buffer2\n" << "{\n" << " " << subgroups::getFormatNameForGLSL(caseDef.format) << " data1[" <<subgroups::maxSupportedSubgroupSize() << "];\n" << "};\n" << "\n" << helperStrARB.c_str() << "void main (void)\n" << "{\n" << " if (gl_InvocationID == 0)\n" << " {\n" << " gl_TessLevelOuter[0] = 1.0f;\n" << " gl_TessLevelOuter[1] = 1.0f;\n" << " }\n" << bdyStr << " out_color[gl_InvocationID ] = float(tempResult);\n" << " gl_out[gl_InvocationID].gl_Position = gl_in[gl_InvocationID].gl_Position;\n" << "}\n"; programCollection.glslSources.add("tesc") << glu::TessellationControlSource(controlSource.str()) << buildOptions; subgroups::setTesEvalShaderFrameBuffer(programCollection); } else if (VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT == caseDef.shaderStage) { std::ostringstream evaluationSource; evaluationSource << glu::getGLSLVersionDeclaration(glu::GLSL_VERSION_450)<<"\n" << extensionHeader.c_str() << "layout(isolines, equal_spacing, ccw ) in;\n" << "layout(location = 0) out float out_color;\n" << "layout(set = 0, binding = 0) uniform Buffer1\n" << "{\n" << " " << subgroups::getFormatNameForGLSL(caseDef.format) << " data1[" <<subgroups::maxSupportedSubgroupSize() << "];\n" << "};\n" << "\n" << helperStrARB.c_str() << "void main (void)\n" << "{\n" << bdyStr << " out_color = float(tempResult);\n" << " gl_Position = mix(gl_in[0].gl_Position, gl_in[1].gl_Position, gl_TessCoord.x);\n" << "}\n"; subgroups::setTesCtrlShaderFrameBuffer(programCollection); programCollection.glslSources.add("tese") << glu::TessellationEvaluationSource(evaluationSource.str()) << buildOptions; } else { DE_FATAL("Unsupported shader stage"); } } void initPrograms(SourceCollections& programCollection, CaseDefinition caseDef) { std::string bdyStr = caseDef.extShaderSubGroupBallotTests ? getBodySourceARB(caseDef) : getBodySource(caseDef); std::string helperStrARB = getHelperFunctionARB(caseDef); const string extensionHeader = (caseDef.extShaderSubGroupBallotTests ? "#extension GL_ARB_shader_ballot: enable\n#extension GL_KHR_shader_subgroup_basic: enable\n#extension GL_ARB_gpu_shader_int64: enable\n" : "#extension GL_KHR_shader_subgroup_ballot: enable\n"); if (VK_SHADER_STAGE_COMPUTE_BIT == caseDef.shaderStage) { std::ostringstream src; src << "#version 450\n" << extensionHeader.c_str() << "layout (local_size_x_id = 0, local_size_y_id = 1, " "local_size_z_id = 2) in;\n" << "layout(set = 0, binding = 0, std430) buffer Buffer1\n" << "{\n" << " uint result[];\n" << "};\n" << "layout(set = 0, binding = 1, std430) buffer Buffer2\n" << "{\n" << " " << subgroups::getFormatNameForGLSL(caseDef.format) << " data1[];\n" << "};\n" << "\n" << helperStrARB.c_str() << "void main (void)\n" << "{\n" << " uvec3 globalSize = gl_NumWorkGroups * gl_WorkGroupSize;\n" << " highp uint offset = globalSize.x * ((globalSize.y * " "gl_GlobalInvocationID.z) + gl_GlobalInvocationID.y) + " "gl_GlobalInvocationID.x;\n" << bdyStr << " result[offset] = tempResult;\n" << "}\n"; programCollection.glslSources.add("comp") << glu::ComputeSource(src.str()) << vk::ShaderBuildOptions(programCollection.usedVulkanVersion, vk::SPIRV_VERSION_1_3, 0u); } else { const string vertex = "#version 450\n" + extensionHeader + "layout(set = 0, binding = 0, std430) buffer Buffer1\n" "{\n" " uint result[];\n" "};\n" "layout(set = 0, binding = 4, std430) readonly buffer Buffer2\n" "{\n" " " + subgroups::getFormatNameForGLSL(caseDef.format) + " data1[];\n" "};\n" "\n" + helperStrARB + "void main (void)\n" "{\n" + bdyStr + " result[gl_VertexIndex] = tempResult;\n" " float pixelSize = 2.0f/1024.0f;\n" " float pixelPosition = pixelSize/2.0f - 1.0f;\n" " gl_Position = vec4(float(gl_VertexIndex) * pixelSize + pixelPosition, 0.0f, 0.0f, 1.0f);\n" " gl_PointSize = 1.0f;\n" "}\n"; const string tesc = "#version 450\n" + extensionHeader + "layout(vertices=1) out;\n" "layout(set = 0, binding = 1, std430) buffer Buffer1\n" "{\n" " uint result[];\n" "};\n" "layout(set = 0, binding = 4, std430) readonly buffer Buffer2\n" "{\n" " " + subgroups::getFormatNameForGLSL(caseDef.format) + " data1[];\n" "};\n" "\n" + helperStrARB + "void main (void)\n" "{\n" + bdyStr + " result[gl_PrimitiveID] = tempResult;\n" " if (gl_InvocationID == 0)\n" " {\n" " gl_TessLevelOuter[0] = 1.0f;\n" " gl_TessLevelOuter[1] = 1.0f;\n" " }\n" " gl_out[gl_InvocationID].gl_Position = gl_in[gl_InvocationID].gl_Position;\n" "}\n"; const string tese = "#version 450\n" + extensionHeader + "layout(isolines) in;\n" "layout(set = 0, binding = 2, std430) buffer Buffer1\n" "{\n" " uint result[];\n" "};\n" "layout(set = 0, binding = 4, std430) readonly buffer Buffer2\n" "{\n" " " + subgroups::getFormatNameForGLSL(caseDef.format) + " data1[];\n" "};\n" "\n" + helperStrARB + "void main (void)\n" "{\n" + bdyStr + " result[gl_PrimitiveID * 2 + uint(gl_TessCoord.x + 0.5)] = tempResult;\n" " float pixelSize = 2.0f/1024.0f;\n" " gl_Position = gl_in[0].gl_Position + gl_TessCoord.x * pixelSize / 2.0f;\n" "}\n"; const string geometry = "#version 450\n" + extensionHeader + "layout(${TOPOLOGY}) in;\n" "layout(points, max_vertices = 1) out;\n" "layout(set = 0, binding = 3, std430) buffer Buffer1\n" "{\n" " uint result[];\n" "};\n" "layout(set = 0, binding = 4, std430) readonly buffer Buffer2\n" "{\n" " " + subgroups::getFormatNameForGLSL(caseDef.format) + " data1[];\n" "};\n" "\n" + helperStrARB + "void main (void)\n" "{\n" + bdyStr + " result[gl_PrimitiveIDIn] = tempResult;\n" " gl_Position = gl_in[0].gl_Position;\n" " EmitVertex();\n" " EndPrimitive();\n" "}\n"; const string fragment = "#version 450\n" + extensionHeader + "layout(location = 0) out uint result;\n" "layout(set = 0, binding = 4, std430) readonly buffer Buffer1\n" "{\n" " " + subgroups::getFormatNameForGLSL(caseDef.format) + " data1[];\n" "};\n" + helperStrARB + "void main (void)\n" "{\n" + bdyStr + " result = tempResult;\n" "}\n"; subgroups::addNoSubgroupShader(programCollection); programCollection.glslSources.add("vert") << glu::VertexSource(vertex) << vk::ShaderBuildOptions(programCollection.usedVulkanVersion, vk::SPIRV_VERSION_1_3, 0u); programCollection.glslSources.add("tesc") << glu::TessellationControlSource(tesc) << vk::ShaderBuildOptions(programCollection.usedVulkanVersion, vk::SPIRV_VERSION_1_3, 0u); programCollection.glslSources.add("tese") << glu::TessellationEvaluationSource(tese) << vk::ShaderBuildOptions(programCollection.usedVulkanVersion, vk::SPIRV_VERSION_1_3, 0u); subgroups::addGeometryShadersFromTemplate(geometry, vk::ShaderBuildOptions(programCollection.usedVulkanVersion, vk::SPIRV_VERSION_1_3, 0u), programCollection.glslSources); programCollection.glslSources.add("fragment") << glu::FragmentSource(fragment)<< vk::ShaderBuildOptions(programCollection.usedVulkanVersion, vk::SPIRV_VERSION_1_3, 0u); } } void supportedCheck (Context& context, CaseDefinition caseDef) { if (!subgroups::isSubgroupSupported(context)) TCU_THROW(NotSupportedError, "Subgroup operations are not supported"); if (!subgroups::isSubgroupFeatureSupportedForDevice(context, VK_SUBGROUP_FEATURE_BALLOT_BIT)) { TCU_THROW(NotSupportedError, "Device does not support subgroup ballot operations"); } if (!subgroups::isFormatSupportedForDevice(context, caseDef.format)) TCU_THROW(NotSupportedError, "Device does not support the specified format in subgroup operations"); if (caseDef.extShaderSubGroupBallotTests && !context.requireDeviceExtension("VK_EXT_shader_subgroup_ballot")) { TCU_THROW(NotSupportedError, "Device does not support VK_EXT_shader_subgroup_ballot extension"); } if (caseDef.extShaderSubGroupBallotTests && !subgroups::isInt64SupportedForDevice(context)) { TCU_THROW(NotSupportedError, "Device does not support int64 data types"); } *caseDef.geometryPointSizeSupported = subgroups::isTessellationAndGeometryPointSizeSupported(context); } tcu::TestStatus noSSBOtest (Context& context, const CaseDefinition caseDef) { if (!subgroups::areSubgroupOperationsSupportedForStage( context, caseDef.shaderStage)) { if (subgroups::areSubgroupOperationsRequiredForStage(caseDef.shaderStage)) { return tcu::TestStatus::fail( "Shader stage " + subgroups::getShaderStageName(caseDef.shaderStage) + " is required to support subgroup operations!"); } else { TCU_THROW(NotSupportedError, "Device does not support subgroup operations for this stage"); } } subgroups::SSBOData inputData[1]; inputData[0].format = caseDef.format; inputData[0].layout = subgroups::SSBOData::LayoutStd140; inputData[0].numElements = caseDef.extShaderSubGroupBallotTests ? 64u : subgroups::maxSupportedSubgroupSize(); inputData[0].initializeType = subgroups::SSBOData::InitializeNonZero; if (VK_SHADER_STAGE_VERTEX_BIT == caseDef.shaderStage) return subgroups::makeVertexFrameBufferTest(context, VK_FORMAT_R32_UINT, inputData, 1, checkVertexPipelineStages); else if (VK_SHADER_STAGE_GEOMETRY_BIT == caseDef.shaderStage) return subgroups::makeGeometryFrameBufferTest(context, VK_FORMAT_R32_UINT, inputData, 1, checkVertexPipelineStages); else if (VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT == caseDef.shaderStage) return subgroups::makeTessellationEvaluationFrameBufferTest(context, VK_FORMAT_R32_UINT, inputData, 1, checkVertexPipelineStages, VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT); else if (VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT == caseDef.shaderStage) return subgroups::makeTessellationEvaluationFrameBufferTest(context, VK_FORMAT_R32_UINT, inputData, 1, checkVertexPipelineStages, VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT); else TCU_THROW(InternalError, "Unhandled shader stage"); } tcu::TestStatus test(Context& context, const CaseDefinition caseDef) { if (VK_SHADER_STAGE_COMPUTE_BIT == caseDef.shaderStage) { if (!subgroups::areSubgroupOperationsSupportedForStage(context, caseDef.shaderStage)) { if (subgroups::areSubgroupOperationsRequiredForStage(caseDef.shaderStage)) { return tcu::TestStatus::fail( "Shader stage " + subgroups::getShaderStageName(caseDef.shaderStage) + " is required to support subgroup operations!"); } else { TCU_THROW(NotSupportedError, "Device does not support subgroup operations for this stage"); } } subgroups::SSBOData inputData[1]; inputData[0].format = caseDef.format; inputData[0].layout = subgroups::SSBOData::LayoutStd430; inputData[0].numElements = caseDef.extShaderSubGroupBallotTests ? 64u : subgroups::maxSupportedSubgroupSize(); inputData[0].initializeType = subgroups::SSBOData::InitializeNonZero; return subgroups::makeComputeTest(context, VK_FORMAT_R32_UINT, inputData, 1, checkCompute); } else { VkPhysicalDeviceSubgroupProperties subgroupProperties; subgroupProperties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_PROPERTIES; subgroupProperties.pNext = DE_NULL; VkPhysicalDeviceProperties2 properties; properties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2; properties.pNext = &subgroupProperties; context.getInstanceInterface().getPhysicalDeviceProperties2(context.getPhysicalDevice(), &properties); VkShaderStageFlagBits stages = (VkShaderStageFlagBits)(caseDef.shaderStage & subgroupProperties.supportedStages); if ( VK_SHADER_STAGE_FRAGMENT_BIT != stages && !subgroups::isVertexSSBOSupportedForDevice(context)) { if ( (stages & VK_SHADER_STAGE_FRAGMENT_BIT) == 0) TCU_THROW(NotSupportedError, "Device does not support vertex stage SSBO writes"); else stages = VK_SHADER_STAGE_FRAGMENT_BIT; } if ((VkShaderStageFlagBits)0u == stages) TCU_THROW(NotSupportedError, "Subgroup operations are not supported for any graphic shader"); subgroups::SSBOData inputData; inputData.format = caseDef.format; inputData.layout = subgroups::SSBOData::LayoutStd430; inputData.numElements = caseDef.extShaderSubGroupBallotTests ? 64u : subgroups::maxSupportedSubgroupSize(); inputData.initializeType = subgroups::SSBOData::InitializeNonZero; inputData.binding = 4u; inputData.stages = stages; return subgroups::allStages(context, VK_FORMAT_R32_UINT, &inputData, 1, checkVertexPipelineStages, stages); } } } namespace vkt { namespace subgroups { tcu::TestCaseGroup* createSubgroupsBallotBroadcastTests(tcu::TestContext& testCtx) { de::MovePtr<tcu::TestCaseGroup> graphicGroup(new tcu::TestCaseGroup( testCtx, "graphics", "Subgroup ballot broadcast category tests: graphics")); de::MovePtr<tcu::TestCaseGroup> computeGroup(new tcu::TestCaseGroup( testCtx, "compute", "Subgroup ballot broadcast category tests: compute")); de::MovePtr<tcu::TestCaseGroup> framebufferGroup(new tcu::TestCaseGroup( testCtx, "framebuffer", "Subgroup ballot broadcast category tests: framebuffer")); de::MovePtr<tcu::TestCaseGroup> graphicGroupARB(new tcu::TestCaseGroup( testCtx, "graphics", "Subgroup ballot broadcast category tests: graphics")); de::MovePtr<tcu::TestCaseGroup> computeGroupARB(new tcu::TestCaseGroup( testCtx, "compute", "Subgroup ballot broadcast category tests: compute")); de::MovePtr<tcu::TestCaseGroup> framebufferGroupARB(new tcu::TestCaseGroup( testCtx, "framebuffer", "Subgroup ballot broadcast category tests: framebuffer")); const VkShaderStageFlags stages[] = { VK_SHADER_STAGE_VERTEX_BIT, VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT, VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT, VK_SHADER_STAGE_GEOMETRY_BIT, }; const std::vector<VkFormat> formats = subgroups::getAllFormats(); for (size_t formatIndex = 0; formatIndex < formats.size(); ++formatIndex) { const VkFormat format = formats[formatIndex]; // Vector, boolean and double types are not supported by functions defined in VK_EXT_shader_subgroup_ballot. const bool formatTypeIsSupportedARB = format == VK_FORMAT_R32_SINT || format == VK_FORMAT_R32_UINT || format == VK_FORMAT_R32_SFLOAT; for (int opTypeIndex = 0; opTypeIndex < OPTYPE_LAST; ++opTypeIndex) { const std::string op = de::toLower(getOpTypeName(opTypeIndex)); const std::string name = op + "_" + subgroups::getFormatNameForGLSL(format); { CaseDefinition caseDef = {opTypeIndex, VK_SHADER_STAGE_COMPUTE_BIT, format, de::SharedPtr<bool>(new bool), DE_FALSE}; addFunctionCaseWithPrograms(computeGroup.get(), name, "", supportedCheck, initPrograms, test, caseDef); caseDef.extShaderSubGroupBallotTests = DE_TRUE; if (formatTypeIsSupportedARB) addFunctionCaseWithPrograms(computeGroupARB.get(), name, "", supportedCheck, initPrograms, test, caseDef); } { CaseDefinition caseDef = {opTypeIndex, VK_SHADER_STAGE_ALL_GRAPHICS, format, de::SharedPtr<bool>(new bool), DE_FALSE}; addFunctionCaseWithPrograms(graphicGroup.get(), name, "", supportedCheck, initPrograms, test, caseDef); caseDef.extShaderSubGroupBallotTests = DE_TRUE; if (formatTypeIsSupportedARB) addFunctionCaseWithPrograms(graphicGroupARB.get(), name, "", supportedCheck, initPrograms, test, caseDef); } for (int stageIndex = 0; stageIndex < DE_LENGTH_OF_ARRAY(stages); ++stageIndex) { CaseDefinition caseDef = {opTypeIndex, stages[stageIndex], format, de::SharedPtr<bool>(new bool), DE_FALSE}; addFunctionCaseWithPrograms(framebufferGroup.get(), name + getShaderStageName(caseDef.shaderStage), "", supportedCheck, initFrameBufferPrograms, noSSBOtest, caseDef); caseDef.extShaderSubGroupBallotTests = DE_TRUE; if (formatTypeIsSupportedARB) addFunctionCaseWithPrograms(framebufferGroupARB.get(), name + getShaderStageName(caseDef.shaderStage), "", supportedCheck, initFrameBufferPrograms, noSSBOtest, caseDef); } } } de::MovePtr<tcu::TestCaseGroup> groupARB(new tcu::TestCaseGroup( testCtx, "ext_shader_subgroup_ballot", "VK_EXT_shader_subgroup_ballot category tests")); groupARB->addChild(graphicGroupARB.release()); groupARB->addChild(computeGroupARB.release()); groupARB->addChild(framebufferGroupARB.release()); de::MovePtr<tcu::TestCaseGroup> group(new tcu::TestCaseGroup( testCtx, "ballot_broadcast", "Subgroup ballot broadcast category tests")); group->addChild(graphicGroup.release()); group->addChild(computeGroup.release()); group->addChild(framebufferGroup.release()); group->addChild(groupARB.release()); return group.release(); } } // subgroups } // vkt
35.754795
266
0.676679
[ "geometry", "vector" ]
1e16b60b799e9864e9399ffd30b868a9c5fd8fdc
7,159
cxx
C++
main/linguistic/source/iprcache.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/linguistic/source/iprcache.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/linguistic/source/iprcache.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_linguistic.hxx" #include <string.h> #include "iprcache.hxx" #include "linguistic/misc.hxx" #include <com/sun/star/linguistic2/DictionaryListEventFlags.hpp> #include <tools/debug.hxx> #include <osl/mutex.hxx> //#define IPR_DEF_CACHE_SIZE 503 #define IPR_DEF_CACHE_MAX 375 #define IPR_DEF_CACHE_MAXINPUT 200 #ifdef DBG_STATISTIC #include <tools/stream.hxx> //#define IPR_CACHE_SIZE nTblSize #define IPR_CACHE_MAX nMax #define IPR_CACHE_MAXINPUT nMaxInput #else //#define IPR_CACHE_SIZE IPR_DEF_CACHE_SIZE #define IPR_CACHE_MAX IPR_DEF_CACHE_MAX #define IPR_CACHE_MAXINPUT IPR_DEF_CACHE_MAXINPUT #endif #include <unotools/processfactory.hxx> #include <linguistic/lngprops.hxx> using namespace utl; using namespace osl; using namespace rtl; using namespace com::sun::star; using namespace com::sun::star::beans; using namespace com::sun::star::lang; using namespace com::sun::star::uno; using namespace com::sun::star::linguistic2; namespace linguistic { /////////////////////////////////////////////////////////////////////////// #define NUM_FLUSH_PROPS 6 static const struct { const char *pPropName; sal_Int32 nPropHdl; } aFlushProperties[ NUM_FLUSH_PROPS ] = { { UPN_IS_USE_DICTIONARY_LIST, UPH_IS_USE_DICTIONARY_LIST }, { UPN_IS_IGNORE_CONTROL_CHARACTERS, UPH_IS_IGNORE_CONTROL_CHARACTERS }, { UPN_IS_SPELL_UPPER_CASE, UPH_IS_SPELL_UPPER_CASE }, { UPN_IS_SPELL_WITH_DIGITS, UPH_IS_SPELL_WITH_DIGITS }, { UPN_IS_SPELL_CAPITALIZATION, UPH_IS_SPELL_CAPITALIZATION } }; static void lcl_AddAsPropertyChangeListener( Reference< XPropertyChangeListener > xListener, Reference< XPropertySet > &rPropSet ) { if (xListener.is() && rPropSet.is()) { for (int i = 0; i < NUM_FLUSH_PROPS; ++i) { rPropSet->addPropertyChangeListener( A2OU(aFlushProperties[i].pPropName), xListener ); } } } static void lcl_RemoveAsPropertyChangeListener( Reference< XPropertyChangeListener > xListener, Reference< XPropertySet > &rPropSet ) { if (xListener.is() && rPropSet.is()) { for (int i = 0; i < NUM_FLUSH_PROPS; ++i) { rPropSet->removePropertyChangeListener( A2OU(aFlushProperties[i].pPropName), xListener ); } } } static sal_Bool lcl_IsFlushProperty( sal_Int32 nHandle ) { int i; for (i = 0; i < NUM_FLUSH_PROPS; ++i) { if (nHandle == aFlushProperties[i].nPropHdl) break; } return i < NUM_FLUSH_PROPS; } FlushListener::FlushListener( Flushable *pFO ) { SetFlushObj( pFO ); } FlushListener::~FlushListener() { } void FlushListener::SetDicList( Reference<XDictionaryList> &rDL ) { MutexGuard aGuard( GetLinguMutex() ); if (xDicList != rDL) { if (xDicList.is()) xDicList->removeDictionaryListEventListener( this ); xDicList = rDL; if (xDicList.is()) xDicList->addDictionaryListEventListener( this, sal_False ); } } void FlushListener::SetPropSet( Reference< XPropertySet > &rPS ) { MutexGuard aGuard( GetLinguMutex() ); if (xPropSet != rPS) { if (xPropSet.is()) lcl_RemoveAsPropertyChangeListener( this, xPropSet ); xPropSet = rPS; if (xPropSet.is()) lcl_AddAsPropertyChangeListener( this, xPropSet ); } } void SAL_CALL FlushListener::disposing( const EventObject& rSource ) throw(RuntimeException) { MutexGuard aGuard( GetLinguMutex() ); if (xDicList.is() && rSource.Source == xDicList) { xDicList->removeDictionaryListEventListener( this ); xDicList = NULL; //! release reference } if (xPropSet.is() && rSource.Source == xPropSet) { lcl_RemoveAsPropertyChangeListener( this, xPropSet ); xPropSet = NULL; //! release reference } } void SAL_CALL FlushListener::processDictionaryListEvent( const DictionaryListEvent& rDicListEvent ) throw(RuntimeException) { MutexGuard aGuard( GetLinguMutex() ); if (rDicListEvent.Source == xDicList) { sal_Int16 nEvt = rDicListEvent.nCondensedEvent; sal_Int16 nFlushFlags = DictionaryListEventFlags::ADD_NEG_ENTRY | DictionaryListEventFlags::DEL_POS_ENTRY | DictionaryListEventFlags::ACTIVATE_NEG_DIC | DictionaryListEventFlags::DEACTIVATE_POS_DIC; sal_Bool bFlush = 0 != (nEvt & nFlushFlags); DBG_ASSERT( pFlushObj, "missing object (NULL pointer)" ); if (bFlush && pFlushObj != NULL) pFlushObj->Flush(); } } void SAL_CALL FlushListener::propertyChange( const PropertyChangeEvent& rEvt ) throw(RuntimeException) { MutexGuard aGuard( GetLinguMutex() ); if (rEvt.Source == xPropSet) { sal_Bool bFlush = lcl_IsFlushProperty( rEvt.PropertyHandle ); DBG_ASSERT( pFlushObj, "missing object (NULL pointer)" ); if (bFlush && pFlushObj != NULL) pFlushObj->Flush(); } } /////////////////////////////////////////////////////////////////////////// SpellCache::SpellCache() { pFlushLstnr = new FlushListener( this ); xFlushLstnr = pFlushLstnr; Reference<XDictionaryList> aDictionaryList(GetDictionaryList()); pFlushLstnr->SetDicList( aDictionaryList ); //! after reference is established Reference<XPropertySet> aPropertySet(GetLinguProperties()); pFlushLstnr->SetPropSet( aPropertySet ); //! after reference is established } SpellCache::~SpellCache() { Reference<XDictionaryList> aEmptyList; Reference<XPropertySet> aEmptySet; pFlushLstnr->SetDicList( aEmptyList ); pFlushLstnr->SetPropSet( aEmptySet ); } void SpellCache::Flush() { MutexGuard aGuard( GetLinguMutex() ); // clear word list LangWordList_t aEmpty; aWordLists.swap( aEmpty ); } bool SpellCache::CheckWord( const OUString& rWord, LanguageType nLang ) { MutexGuard aGuard( GetLinguMutex() ); WordList_t &rList = aWordLists[ nLang ]; const WordList_t::const_iterator aIt = rList.find( rWord ); return aIt != rList.end(); } void SpellCache::AddWord( const OUString& rWord, LanguageType nLang ) { MutexGuard aGuard( GetLinguMutex() ); WordList_t & rList = aWordLists[ nLang ]; // occasional clean-up... if (rList.size() > 500) rList.clear(); rList.insert( rWord ); } /////////////////////////////////////////////////////////////////////////// } // namespace linguistic
25.476868
79
0.690879
[ "object" ]
1e1a1fdd580afdf21cbb05d99fc196f720137349
847
cpp
C++
Lab Sessions/Lab 5/poisonousPlants.cpp
bimalka98/Data-Structures-and-Algorithms
7d358a816561551a5b04af8de378141becda42bd
[ "MIT" ]
1
2021-03-21T07:54:08.000Z
2021-03-21T07:54:08.000Z
Lab Sessions/Lab 5/poisonousPlants.cpp
bimalka98/Data-Structures-and-Algorithms
7d358a816561551a5b04af8de378141becda42bd
[ "MIT" ]
null
null
null
Lab Sessions/Lab 5/poisonousPlants.cpp
bimalka98/Data-Structures-and-Algorithms
7d358a816561551a5b04af8de378141becda42bd
[ "MIT" ]
null
null
null
int poisonousPlants(vector<int> p) { int num_of_plants = p.size(); // Number of plants at the begining. int days = 0; while(true){ // Trying to get the remaining plants after a day. // There's no plant left to the first plant. Therefore it is preserved anyway. vector<int> remaining_plants = {p[0]}; for(int i =1; i< num_of_plants;i++){ // If left pesticide is greater than or equal to peticide of the current plant: the plant remains alive. if(p[i] <= p[i-1]) remaining_plants.push_back(p[i]);} if(remaining_plants.size() == num_of_plants) return days; // plants stops dying. else{ days++; num_of_plants = remaining_plants.size(); // number of remaining plants p = remaining_plants; // remaining plants } } }
35.291667
116
0.606848
[ "vector" ]
1e1b760acde05ce7a5d8f36a2af4c9ec9185dce1
2,180
cpp
C++
Source/EngineProject/Components/RigidBodyComponent/RigidBody.cpp
GBCNewGamePlus/Elasticity
0cc7af3a26e4cacd61aa908877b60937bae99413
[ "MIT" ]
null
null
null
Source/EngineProject/Components/RigidBodyComponent/RigidBody.cpp
GBCNewGamePlus/Elasticity
0cc7af3a26e4cacd61aa908877b60937bae99413
[ "MIT" ]
null
null
null
Source/EngineProject/Components/RigidBodyComponent/RigidBody.cpp
GBCNewGamePlus/Elasticity
0cc7af3a26e4cacd61aa908877b60937bae99413
[ "MIT" ]
null
null
null
#include "../CircleComponent/CircleComponent.h" #include "RigidBody.h" #include "../../Systems/RigidBodySystem.h" #include "../SquareComponent/SquareComponent.h" #include "../TransformComponent/TransformComponent.h" RigidBody::RigidBody() { componentName = "rigidBodyComponent"; id = -1; // -1 = ID not set. ID is set by the RigidBodySystem. mass = 1.0f; bounciness = 1.0f; obeysGravity = true; gravity = sf::Vector2f(0, -9.8f); maxVelocity = sf::Vector2f(10.0f, 10.0f); SetAABB(); rigidBodySystem->AddRigidBody(this); } void RigidBody::AddVelocity(sf::Vector2f v) { currentVelocity += v; } void RigidBody::AddForce(sf::Vector2f force) { totalForces += force; } void RigidBody::Stop() { currentVelocity = sf::Vector2f(0,0); totalForces = sf::Vector2f(0, 0); } bool RigidBody::IsGrounded() { grounded = rigidBodySystem->IsGrounded(*this); return grounded; } void RigidBody::SetAABB() { sf::Vector2f center; sf::Vector2f size; if (transform) { center = transform->GetLocation(); size = transform->GetScale(); } else { center = sf::Vector2f(0, 0); size = sf::Vector2f(0, 0); } if (circleComponent) { size.x = size.x * circleComponent->GetRadius(); size.y = size.y * circleComponent->GetRadius(); } else if (squareComponent) { size.x = size.x * squareComponent->GetLength(); size.y = size.y * squareComponent->GetLength(); } Bounds bound(center, size); aabb.bLeft = sf::Vector2f(bound.center.x - bound.extents.x, bound.center.y - bound.extents.y); aabb.tRight = sf::Vector2f(bound.center.x + bound.extents.x, bound.center.y + bound.extents.y); } void RigidBody::Integrate(float dt) { sf::Vector2f acceleration; if (obeysGravity && !IsGrounded()) { acceleration = gravity; } else { if (abs(currentVelocity.y) < 0.05f) currentVelocity.y = 0; } acceleration += totalForces / mass; if (mass == 0) acceleration = sf::Vector2f(0,0); currentVelocity += acceleration * dt; // TO DO: Access the transform component and update the position! sf::Vector2f temp = transform->GetLocation(); temp += currentVelocity * dt; transform->SetPosition(temp.x, temp.y); SetAABB(); totalForces = sf::Vector2f(0, 0); }
21.8
96
0.686239
[ "transform" ]
1e1e56532494e210043de43fda0b8829f8535c73
4,189
cpp
C++
tc 160+/BestYahtzeeScore.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
3
2015-05-25T06:24:37.000Z
2016-09-10T07:58:00.000Z
tc 160+/BestYahtzeeScore.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
null
null
null
tc 160+/BestYahtzeeScore.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
5
2015-05-25T06:24:40.000Z
2021-08-19T19:22:29.000Z
#include <algorithm> #include <cassert> #include <cstdio> #include <iostream> #include <sstream> #include <string> #include <vector> #include <cstring> using namespace std; int sum(const string &s) { int ret = 0; for (int i=0; i<5; ++i) ret += (s[i]-'0'); return ret; } void makeCnt(const string &s, vector<int> &cnt) { for (int i=0; i<5; ++i) ++cnt[s[i]-'0']; } bool is4ok(const string &s) { vector<int> cnt(7, 0); makeCnt(s, cnt); for (int i=1; i<7; ++i) if (cnt[i] >= 4) return true; return false; } bool isFH(const string &s) { vector<int> cnt(7, 0); makeCnt(s, cnt); for (int i=1; i<7; ++i) { if (cnt[i] == 5) return true; for (int j=i+1; j<7; ++j) if (cnt[i]==3 && cnt[j]==2 || cnt[i]==2 && cnt[j]==3) return true; } return false; } bool isSS(const string &s) { vector<int> cnt(7, 0); makeCnt(s, cnt); for (int i=1; i+3<7; ++i) if (cnt[i]>0 && cnt[i+1]>0 && cnt[i+2]>0 && cnt[i+3]>0) return true; return false; } bool isLS(const string &s) { vector<int> cnt(7, 0); makeCnt(s, cnt); for (int i=1; i+4<7; ++i) if (cnt[i]>0 && cnt[i+1]>0 && cnt[i+2]>0 && cnt[i+3]>0 && cnt[i+4]>0) return true; return false; } bool isYahtzee(const string &s) { vector<int> cnt(7, 0); makeCnt(s, cnt); for (int i=1; i<7; ++i) if (cnt[i] == 5) return true; return false; } int val4ok(const string &s) { return is4ok(s) ? sum(s) : 0; } int valFH(const string &s) { return isFH(s) ? 25 : 0; } int valSS(const string &s) { return isSS(s) ? 30 : 0; } int valLS(const string &s) { return isLS(s) ? 40 : 0; } int valYahtzee(const string &s) { return isYahtzee(s) ? 50 : 0; } int (*F[])(const string &) = { val4ok, valFH, valSS, valLS, valYahtzee }; int getScore(const string &s) { int best = 0; for (int i=0; i<5; ++i) best = max(best, F[i](s)); return best; } string R; int sol; void go(int, int, string&); void maskWith(int round, int next, string &s, int m, int pos) { if (pos == 5) { go(round+1, next, s); return; } if (m & (1<<pos)) { const char c = s[pos]; s[pos] = R[next]; maskWith(round, next+1, s, m, pos+1); s[pos] = c; } else { maskWith(round, next, s, m, pos+1); } } void go(int round, int next, string &s) { if (round == 3) { sol = max(sol, getScore(s)); return; } for (int m=0; m<(1<<5); ++m) maskWith(round, next, s, m, 0); } class BestYahtzeeScore { public: int bestScore(string rolls) { R = rolls; sol = 0; string s = R.substr(0, 5); go(1, 5, s); return sol; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { string Arg0 = "354621111111111"; int Arg1 = 50; verify_case(0, Arg1, bestScore(Arg0)); } void test_case_1() { string Arg0 = "666663213214444"; int Arg1 = 50; verify_case(1, Arg1, bestScore(Arg0)); } void test_case_2() { string Arg0 = "652353235164412"; int Arg1 = 40; verify_case(2, Arg1, bestScore(Arg0)); } void test_case_3() { string Arg0 = "265241155222313"; int Arg1 = 25; verify_case(3, Arg1, bestScore(Arg0)); } void test_case_4() { string Arg0 = "144165526421151"; int Arg1 = 0; verify_case(4, Arg1, bestScore(Arg0)); } // END CUT HERE }; // BEGIN CUT HERE int main() { BestYahtzeeScore ___test; ___test.run_test(-1); } // END CUT HERE
26.18125
309
0.559322
[ "vector" ]
1e200f92519ab61b85444c69e4e0c9ed14561298
1,489
cpp
C++
main.cpp
Budlee/SFML-Graph
00d46393c0e3e31c9905db9942e4fd719f93daa0
[ "WTFPL" ]
null
null
null
main.cpp
Budlee/SFML-Graph
00d46393c0e3e31c9905db9942e4fd719f93daa0
[ "WTFPL" ]
null
null
null
main.cpp
Budlee/SFML-Graph
00d46393c0e3e31c9905db9942e4fd719f93daa0
[ "WTFPL" ]
null
null
null
#include <stdio.h> #include <iostream> #include <thread> #include <inttypes.h> #include "GraphLines.h" #include "OanadaPricePuller.h" #include <SFML/Graphics.hpp> #include <SFML/Window.hpp> #include <SFML/System.hpp> void renderingThread(sf::RenderWindow* window, GraphLines *glines) { // the rendering loop window->setActive(true); while (window->isOpen()) { window->clear(); glines->update(); window->draw(*glines); window->display(); } } void oandaThread(sf::RenderWindow* window, GraphLines *glines, std::string *accessId, std::string *accessToken) { OanadaPricePuller op(glines, *accessId, *accessToken); while (window->isOpen()) { op.getTick(); } } int main(int argc, const char* argv[]) { if(argc != 3) { std::cerr<<"Need id and token\n"; std::exit(1); } std::string aId = argv[1]; std::string aTok = argv[2]; sf::RenderWindow window(sf::VideoMode(800, 800), "SFML works!"); window.setFramerateLimit(60); window.setActive(false); GraphLines glines(window.getSize().x, window.getSize().y); std::thread render(renderingThread, &window, &glines); std::thread oanda(oandaThread, &window, &glines,&aId ,&aTok); while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); } } return 0; }
23.634921
111
0.601075
[ "render" ]
1e224a04c7c3be9e3764e95d4998003cb9a02372
19,235
cpp
C++
oglmanager.cpp
JustLuoxi/HairAirSimulation
ea2558d5a646f6a9abd74511b84a7507c62c1cad
[ "MIT" ]
1
2020-05-22T09:26:24.000Z
2020-05-22T09:26:24.000Z
oglmanager.cpp
JustLuoxi/HairAirSimulation
ea2558d5a646f6a9abd74511b84a7507c62c1cad
[ "MIT" ]
null
null
null
oglmanager.cpp
JustLuoxi/HairAirSimulation
ea2558d5a646f6a9abd74511b84a7507c62c1cad
[ "MIT" ]
null
null
null
#include "oglmanager.h" #include <QPalette> #include "model.h" #include "light.h" #include "air.h" #include "resourcemanager.h" #include <QDebug> #include <mainwindow.h> //#include "quaternion.h" const QVector3D CAMERA_POSITION(0.0f, 0.0f, 3.0f); const QVector3D LIGHT_POSITION(0.0f, 3.0f, 3.0f); const QVector3D AIRGRID_CENTER(0.0f, 0.0f, 0.0f); const int OGLMANAGER_WIDTH = 600; const int OGLMANAGER_HEIGHT = 600; Light *light; Model *objModel; Air *air; extern bool air2hair_flag; OGLManager::OGLManager(QWidget *parent) : QOpenGLWidget(parent){ this->setGeometry(10, 20, OGLMANAGER_WIDTH, OGLMANAGER_HEIGHT); this->frame_matrixs.resize(frame_num); this->temp_rotate_matrixs.resize(frame_num); this->temp_translate_matrixs.resize(frame_num); this->temp_scale_matrixs.resize(frame_num); } OGLManager::~OGLManager(){ if(camera) delete camera; } void OGLManager::handleKeyPressEvent(QKeyEvent *event){ GLuint key = event->key(); if(key >= 0 && key <= 1024) this->keys[key] = GL_TRUE; } void OGLManager::handleKeyReleaseEvent(QKeyEvent *event){ GLuint key = event->key(); if(key >= 0 && key <= 1024) this->keys[key] = GL_FALSE; if(event->key()==Qt::Key_Q) { objModel->Reset(); air->Reset(); } // for air control if(event->key()==Qt::Key_V) air->render_flag = !air->render_flag; if(event->key()==Qt::Key_H) air->hair2air_flag = !air->hair2air_flag; if(event->key()==Qt::Key_J) air2hair_flag = !air2hair_flag; } void OGLManager::changeObjModel(QString fileName){ objModel->init(fileName); key_frame_indices.clear(); temp_translate_matrixs.clear(); temp_rotate_matrixs.clear(); temp_scale_matrixs.clear(); this->frame_matrixs.resize(frame_num); this->temp_rotate_matrixs.resize(frame_num); this->temp_translate_matrixs.resize(frame_num); this->temp_scale_matrixs.resize(frame_num); AddKeyFrame(0); this->window->setdoubleSpinBoxValue(ZOOM_JUST); } void OGLManager::setModelScale() { QMatrix4x4 scaling; scaling.scale(modelScaling); objModel->SetScale(modelScaling); ResourceManager::getShader("model").use().setMatrix4f("model", objModel->getModelMatrix()); } void OGLManager::AddKeyFrame(int frame) { temp_translate_matrixs[frame] = objModel->m_matrix_translate; temp_rotate_matrixs[frame] = objModel->m_matrix_rotate; key_frame_indices.push_back(frame); qDebug("add keyfram : %d \n",frame); qDebug("temp_translate_matrixs size : %d \n",temp_translate_matrixs.size()); } void OGLManager::RuntheAnimation() { run_animation_flag = true; has_run_animation = false; current_frame = 0; // sort indices and erase the duplicate nodes std::sort(key_frame_indices.begin(),key_frame_indices.end()); key_frame_indices.erase(std::unique(key_frame_indices.begin(),key_frame_indices.end()),key_frame_indices.end()); // just. interpolation int a_frame,b_frame; for(int i=0;i<key_frame_indices.size()-1;i++) { qDebug("keyfram : %d \n",key_frame_indices[i]); // find the gap a_frame = key_frame_indices[i]; b_frame = key_frame_indices[i+1]; int t = b_frame+1-a_frame; QVector3D a_translate = _translationMat2Vec3(temp_translate_matrixs[a_frame]); QVector3D b_translate = _translationMat2Vec3(temp_translate_matrixs[b_frame]);; QVector3D t_vec3 = (b_translate - a_translate)/t; Quaternion a_quat,b_quat; a_quat = Matrix4D2Quaternion(temp_rotate_matrixs[a_frame]); b_quat = Matrix4D2Quaternion(temp_rotate_matrixs[b_frame]); QMatrix4x4 interp_mat; for(int j=a_frame;j<=b_frame;j++) { // 1. translation interpolation -- linear temp_translate_matrixs[j] = _translationVec32Mat(a_translate+(j-a_frame)*t_vec3); // 2. rotation interpolation-- linear Quaternion inter_quat = Slerp(a_quat,b_quat,1.0*(j-a_frame)/t); temp_rotate_matrixs[j] = RotationMatrix4D(inter_quat); } } qDebug("keyfram : %d \n",b_frame); // for imcomplete interpolation if(b_frame!=frame_num-1){ a_frame = b_frame; b_frame = frame_num-1; for(int i=a_frame;i<=b_frame;i++) { temp_translate_matrixs[i]=temp_translate_matrixs[a_frame]; temp_rotate_matrixs[i]=temp_rotate_matrixs[a_frame]; } } // temp => frame_matrix for(int i=0;i<frame_num;i++) { frame_matrixs[i] = temp_translate_matrixs[i]*temp_rotate_matrixs[i]; } } void OGLManager::SetFrame(int frame) { if(!has_run_animation) return; current_frame = frame; objModel->getModelMatrix() = frame_matrixs[frame]; // qDebug("set frame matrix :\n %f,%f,%f,%f\n", frame_matrixs[frame](0,0),frame_matrixs[frame](0,1),frame_matrixs[frame](0,2),frame_matrixs[frame](0,3)); // qDebug("%f,%f,%f,%f\n", frame_matrixs[frame](1,0),frame_matrixs[frame](1,1),frame_matrixs[frame](1,2),frame_matrixs[frame](1,3)); // qDebug("%f,%f,%f,%f\n", frame_matrixs[frame](2,0),frame_matrixs[frame](2,1),frame_matrixs[frame](2,2),frame_matrixs[frame](2,3)); // qDebug("%f,%f,%f,%f\n", frame_matrixs[frame](3,0),frame_matrixs[frame](3,1),frame_matrixs[frame](3,2),frame_matrixs[frame](3,3)); } void OGLManager::initializeGL(){ /*********** OGL ***********/ core = QOpenGLContext::currentContext()->versionFunctions<QOpenGLFunctions_3_3_Core>(); // core->glBindBufferRange(); core->glEnable(GL_DEPTH_TEST); /*********** initialization *************/ isOpenLighting = GL_TRUE; isLineMode = GL_FALSE; modelScaling = 0.001f; /*********** interaction *************/ for(GLuint i = 0; i != 1024; ++i) keys[i] = GL_FALSE; deltaTime = 0.0f; lastFrame = 0.0f; isFirstMouse = GL_TRUE; isLeftMousePress = GL_FALSE; isRightMousePress = GL_FALSE; lastX = width() / 2.0f; lastY = height() / 2.0f; time.start(); /************ camera ***********/ camera = new Camera(CAMERA_POSITION); /*********** light *************/ light = new Light(); light->init(); /************ obj ***********/ objModel = new Model(); objModel->init("://res/models/head/Pasha_guard_head_just_hair.obj"); AddKeyFrame(0); // just.air air = new Air(); air->Init(); // /************ shader ***********/ ResourceManager::loadShader("model", ":/shaders/res/shaders/model.vert", ":/shaders/res/shaders/model.frag"); ResourceManager::loadShader("light", ":/shaders/res/shaders/light.vert", ":/shaders/res/shaders/light.frag"); ResourceManager::loadShader("hair", ":/shaders/res/shaders/hair.vert", ":/shaders/res/shaders/hair.frag"); ResourceManager::loadShader("air", ":/shaders/res/shaders/air.vert", ":/shaders/res/shaders/air.frag"); ResourceManager::getShader("model").use().setInteger("material.ambientMap", 0); ResourceManager::getShader("model").use().setInteger("material.diffuseMap", 1); ResourceManager::getShader("model").use().setVector3f("light.position", LIGHT_POSITION); ResourceManager::getShader("hair").use().setVector3f("light.position", LIGHT_POSITION); QMatrix4x4 model_; model_.scale(0.01f); ResourceManager::getShader("model").use().setMatrix4f("model", model_); ResourceManager::getShader("hair").use().setMatrix4f("model", model_); QMatrix4x4 model; model.translate(LIGHT_POSITION); model.scale(3.0f); ResourceManager::getShader("light").use().setMatrix4f("model", model); model.setToIdentity(); model.translate(AIRGRID_CENTER); ResourceManager::getShader("air").use().setMatrix4f("model", model); /************ bg ***********/ core->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); core->glClearColor(0.3f, 0.3f, 0.3f, 1.0f); } void OGLManager::resizeGL(int w, int h){ core->glViewport(0, 0, w, h); } void OGLManager::paintGL(){ /*********** time ***************/ GLfloat currentFrame = (GLfloat)time.elapsed()/1000; deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; // qDebug("fps: %f",1/deltaTime); this->processInput(deltaTime); this->updateGL(); // /********* light ************/ ResourceManager::getShader("light").use(); light->drawLight(); // just.air ResourceManager::getShader("air").use(); air->Draw(); // /********* draw model ************/ ResourceManager::getShader("model").use(); objModel->draw(this->isOpenLighting); // /********* draw hair ************/ ResourceManager::getShader("hair").use(); objModel->m_hair->Draw(this->isOpenLighting); } void OGLManager::processInput(GLfloat dt){ // if (keys[Qt::Key_W]) // camera->processKeyboard(FORWARD, dt); // if (keys[Qt::Key_S]) // camera->processKeyboard(BACKWARD, dt); // if (keys[Qt::Key_A]) // camera->processKeyboard(LEFT, dt); // if (keys[Qt::Key_D]) // camera->processKeyboard(RIGHT, dt); // if (keys[Qt::Key_E]) // camera->processKeyboard(UP, dt); // if (keys[Qt::Key_Q]) // camera->processKeyboard(DOWN, dt); // for air interactionw QVector3D v; if(keys[Qt::Key_W]) { v = QVector3D(0,100.0f,0); air->AddVelocity(RESOLUTION/2,2,RESOLUTION/2,v.x(),v.y(),v.z()); } if(keys[Qt::Key_D]) { v = QVector3D(100.0f,0,0); air->AddVelocity(2,RESOLUTION/2,RESOLUTION/2,v.x(),v.y(),v.z()); } } void OGLManager::updateGL(){ if(this->isLineMode) core->glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); else core->glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); QMatrix4x4 projection, view, model; projection.perspective(camera->zoom, (GLfloat)width()/(GLfloat)height(), 0.1f, 200.f); view = camera->getViewMatrix(); // just.air model = objModel->getModelMatrix(); QMatrix4x4 identity_matrix; identity_matrix.setToIdentity(); if(!run_animation_flag){ // NORMAL STATUS if(has_run_animation) model = frame_matrixs[current_frame]; ResourceManager::getShader("light").use().setMatrix4f("projection", projection); ResourceManager::getShader("light").use().setMatrix4f("view", view); // air->UpdateRenderdata(); air->Simulate(); ResourceManager::getShader("air").use().setMatrix4f("projection", projection); ResourceManager::getShader("air").use().setMatrix4f("view", view); ResourceManager::getShader("air").use().setMatrix4f("model", model); // just.air ResourceManager::getShader("model").use().setMatrix4f("projection", projection); ResourceManager::getShader("model").use().setMatrix4f("view", view); ResourceManager::getShader("model").use().setMatrix4f("model", model); ResourceManager::getShader("model").use().setVector3f("viewPos", camera->position); objModel->m_hair->Update(model); ResourceManager::getShader("hair").use().setMatrix4f("projection", projection); ResourceManager::getShader("hair").use().setMatrix4f("view", view); ResourceManager::getShader("hair").use().setMatrix4f("model", identity_matrix); ResourceManager::getShader("hair").use().setVector3f("viewPos", camera->position); } else // { ResourceManager::getShader("light").use().setMatrix4f("projection", projection); ResourceManager::getShader("light").use().setMatrix4f("view", view); ResourceManager::getShader("model").use().setMatrix4f("projection", projection); ResourceManager::getShader("model").use().setMatrix4f("view", view); ResourceManager::getShader("model").use().setMatrix4f("model", this->frame_matrixs[current_frame]); ResourceManager::getShader("model").use().setVector3f("viewPos", camera->position); objModel->m_hair->Update(this->frame_matrixs[current_frame]); ResourceManager::getShader("hair").use().setMatrix4f("projection", projection); ResourceManager::getShader("hair").use().setMatrix4f("view", view); ResourceManager::getShader("hair").use().setMatrix4f("model", identity_matrix); ResourceManager::getShader("hair").use().setVector3f("viewPos", camera->position); m_deltatime += deltaTime; if(m_deltatime>1.0f/m_fps) { this->window->setSliderValue(current_frame); m_deltatime = 0.0f; current_frame ++; if(current_frame>=frame_num) { run_animation_flag = false; has_run_animation = true; current_frame = frame_num-1; objModel->getModelMatrix() = frame_matrixs[current_frame]; // current_frame = 0; } } } // qDebug("model matrix :\n %f,%f,%f,%f\n", model(0,0),model(0,1),model(0,2),model(0,3)); // qDebug("%f,%f,%f,%f\n", model(1,0),model(1,1),model(1,2),model(1,3)); // qDebug("%f,%f,%f,%f\n", model(2,0),model(2,1),model(2,2),model(2,3)); // qDebug("%f,%f,%f,%f\n", model(3,0),model(3,1),model(3,2),model(3,3)); // QMatrix4x4 scaling; // scaling.scale(modelScaling); // ResourceManager::getShader("model").use().setMatrix4f("model", scaling); // ResourceManager::getShader("model").use().setMatrix4f("model", model); qDebug() << "current FPS: " << 1.0f/deltaTime; } QVector3D OGLManager::_translationMat2Vec3(QMatrix4x4 m) { QVector3D result = QVector3D(m(0,3),m(1,3),m(2,3)); return result; } QMatrix4x4 OGLManager::_translationVec32Mat(QVector3D v) { QMatrix4x4 m; m.setToIdentity(); m.translate(v); return m; } void OGLManager::mouseMoveEvent(QMouseEvent *event){ GLint xpos = event->pos().x(); GLint ypos = event->pos().y(); if(isLeftMousePress){ if (isFirstMouse){ lastX = xpos; lastY = ypos; isFirstMouse = GL_FALSE; } GLint xoffset = xpos - lastX; GLint yoffset = lastY - ypos; // reversed since y-coordinates go from bottom to top lastX = xpos; lastY = ypos; // camera->processMouseMovement(xoffset, yoffset); objModel->processMouseMovement(xoffset,yoffset); } if(isRightMousePress) { if (isFirstMouse){ lastX = xpos; lastY = ypos; isFirstMouse = GL_FALSE; } GLint xoffset = xpos - lastX; GLint yoffset = lastY - ypos; // reversed since y-coordinates go from bottom to top lastX = xpos; lastY = ypos; objModel->processRotateMovement(xoffset,yoffset); } } void OGLManager::mousePressEvent(QMouseEvent *event){ if(event->button() == Qt::LeftButton) isLeftMousePress = GL_TRUE; if(event->button()==Qt::RightButton) isRightMousePress = GL_TRUE; } void OGLManager::mouseReleaseEvent(QMouseEvent *event){ isFirstMouse = GL_TRUE; if(event->button() == Qt::LeftButton){ isLeftMousePress = GL_FALSE; } if(event->button()==Qt::RightButton) isRightMousePress = GL_FALSE; } void OGLManager::wheelEvent(QWheelEvent *event){ QPoint offset = event->angleDelta(); GLfloat t = event->delta(); t/=12000.0f; // qDebug("angleDelta: x- %d , y - %d",offset.x(),offset.y()); // camera->processMouseScroll(offset.y()/20.0f); objModel->processMouseScroll(t); qDebug("offset: %f",t); this->window->setdoubleSpinBoxValue(objModel->zoom); } // The slerp moves a point in space from one position to another spherically using // the general formula p' = p1 + t(p2 - p1) where p' is the current position, // p1 is the original position, p2 is the final position, and time is represented by t Quaternion Slerp(Quaternion a, Quaternion b, double t) { Quaternion q = Quaternion(); a = Normalize(a); b = Normalize(b); // Calculate angle between them double cosHalfTheta = (a.w * b.w) + (a.x * b.x) + (a.y * b.y) + (a.z * b.z); if (abs(cosHalfTheta) >= 1.0) { q.w = a.w; q.x = a.x; q.y = a.y; q.z = a.z; return Normalize(q); } // Calculate temporary values double halfTheta = acos(cosHalfTheta); double sinHalfTheta = sqrt(1.0f - cosHalfTheta * cosHalfTheta); // if theta = 180 degrees then result is not fully defined // we could rotate around any axis normal to a or b if (fabs(sinHalfTheta) < 0.001) { q.w = (a.w * 0.5 + b.w * 0.5); q.x = (a.x * 0.5 + b.x * 0.5); q.y = (a.y * 0.5 + b.y * 0.5); q.z = (a.z * 0.5 + b.z * 0.5); return Normalize(q); } double ratioA = sin((1 - t) * halfTheta) / sinHalfTheta; double ratioB = sin(t * halfTheta) / sinHalfTheta; // Calculate Quaternion q.w = (a.w * ratioA + b.w * ratioB); q.x = (a.x * ratioA + b.x * ratioB); q.y = (a.y * ratioA + b.y * ratioB); q.z = (a.z * ratioA + b.z * ratioB); q = Normalize(q); return q; } QMatrix4x4 RotationMatrix4D(Quaternion q) { float n00 = 1 - (2 * q.y*q.y) - (2 * q.z*q.z); float n01 = 2 * ((q.x * q.y) - (q.w * q.z)); float n02 = 2 * ((q.x * q.z) + (q.w * q.y)); float n10 = 2 * ((q.x * q.y) + (q.w * q.z)); float n11 = 1 - (2 * q.x*q.x) - (2 * q.z*q.z); float n12 = 2 * ((q.y * q.z) - (q.w * q.x)); float n20 = 2 * ((q.x * q.z) - (q.w * q.y)); float n21 = 2 * ((q.y * q.z) + (q.w * q.x)); float n22 = 1 - (2 * q.x*q.x) - (2 * q.y*q.y); QMatrix4x4 result; result(0,0)=n00; result(0,1)=n01; result(0,2)=n02; result(0,3)=0.0f; result(1,0)=n10; result(1,1)=n11; result(1,2)=n12; result(1,3)=0.0f; result(2,0)=n20; result(2,1)=n21; result(2,2)=n22; result(2,3)=0.0f; result(3,0)=0.0f;result(3,1)=0.0f;result(3,2)=0.0f;result(3,3)=1.0f; return QMatrix4x4(result); } Quaternion Matrix4D2Quaternion(QMatrix4x4 m) { Quaternion q; float tr = m(0,0) + m(1,1) + m(2,2); if (tr > 0) { float S = std::sqrt(tr+1.0) * 2; // S=4*qw q.w = 0.25 * S; q.x = (m(2,1) - m(1,2)) / S; q.y = (m(0,2) - m(2,0)) / S; q.z = (m(1,0) - m(0,1)) / S; } else if ((m(0,0) > m(1,1))&(m(0,0) > m(2,2))) { float S = std::sqrt(1.0 + m(0,0) - m(1,1) - m(2,2)) * 2; // S=4*qx q.w = (m(2,1) - m(1,2)) / S; q.x = 0.25 * S; q.y = (m(0,1) + m(1,0)) / S; q.z = (m(0,2) + m(2,0)) / S; } else if (m(1,1) > m(2,2)) { float S = std::sqrt(1.0 + m(1,1) - m(0,0) - m(2,2)) * 2; // S=4*qy q.w = (m(0,2) - m(2,0)) / S; q.x = (m(0,1) + m(1,0)) / S; q.y = 0.25 * S; q.z = (m(1,2) + m(2,1)) / S; } else { float S = std::sqrt(1.0 + m(2,2) - m(0,0) - m(1,1)) * 2; // S=4*qz q.w = (m(1,0) - m(0,1)) / S; q.x = (m(0,2) + m(2,0)) / S; q.y = (m(1,2) + m(2,1)) / S; q.z = 0.25 * S; } return q; } float Norm(Quaternion q) { return (q.w*q.w + q.x*q.x + q.y*q.y + q.z*q.z); } Quaternion Normalize(Quaternion q) { float Magnitude = std::sqrt(Norm(q)); return Quaternion(q.w /Magnitude,q.x/Magnitude,q.y/Magnitude,q.z/Magnitude ); }
32.993139
162
0.604211
[ "model" ]
1e2fff5c9871c36b8692245c8f94d50d62cf5077
6,340
cc
C++
src/operator/contrib/hawkes_ll.cc
mchoi8739/incubator-mxnet
cff583250479b31c394f568ffb835b720cb84dc4
[ "Apache-2.0" ]
211
2016-06-06T08:32:36.000Z
2021-07-03T16:50:16.000Z
src/operator/contrib/hawkes_ll.cc
mchoi8739/incubator-mxnet
cff583250479b31c394f568ffb835b720cb84dc4
[ "Apache-2.0" ]
82
2016-03-29T02:40:02.000Z
2021-02-06T22:20:40.000Z
src/operator/contrib/hawkes_ll.cc
mchoi8739/incubator-mxnet
cff583250479b31c394f568ffb835b720cb84dc4
[ "Apache-2.0" ]
58
2016-10-27T07:37:08.000Z
2021-07-03T16:50:17.000Z
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2018 by Contributors * \file hawkes_ll.cc * \brief Log likelihood of a marked self-exciting Hawkes process * \author Caner Turkmen <turkmen.ac@gmail.com> */ #include "./hawkes_ll-inl.h" #include "../tensor/init_op.h" namespace mxnet { namespace op { NNVM_REGISTER_OP(_contrib_hawkesll) .describe(R"code(Computes the log likelihood of a univariate Hawkes process. The log likelihood is calculated on point process observations represented as *ragged* matrices for *lags* (interarrival times w.r.t. the previous point), and *marks* (identifiers for the process ID). Note that each mark is considered independent, i.e., computes the joint likelihood of a set of Hawkes processes determined by the conditional intensity: .. math:: \lambda_k^*(t) = \lambda_k + \alpha_k \sum_{\{t_i < t, y_i = k\}} \beta_k \exp(-\beta_k (t - t_i)) where :math:`\lambda_k` specifies the background intensity ``lda``, :math:`\alpha_k` specifies the *branching ratio* or ``alpha``, and :math:`\beta_k` the delay density parameter ``beta``. ``lags`` and ``marks`` are two NDArrays of shape (N, T) and correspond to the representation of the point process observation, the first dimension corresponds to the batch index, and the second to the sequence. These are "left-aligned" *ragged* matrices (the first index of the second dimension is the beginning of every sequence. The length of each sequence is given by ``valid_length``, of shape (N,) where ``valid_length[i]`` corresponds to the number of valid points in ``lags[i, :]`` and ``marks[i, :]``. ``max_time`` is the length of the observation period of the point process. That is, specifying ``max_time[i] = 5`` computes the likelihood of the i-th sample as observed on the time interval :math:`(0, 5]`. Naturally, the sum of all valid ``lags[i, :valid_length[i]]`` must be less than or equal to 5. The input ``state`` specifies the *memory* of the Hawkes process. Invoking the memoryless property of exponential decays, we compute the *memory* as .. math:: s_k(t) = \sum_{t_i < t} \exp(-\beta_k (t - t_i)). The ``state`` to be provided is :math:`s_k(0)` and carries the added intensity due to past events before the current batch. :math:`s_k(T)` is returned from the function where :math:`T` is ``max_time[T]``. Example:: # define the Hawkes process parameters lda = nd.array([1.5, 2.0, 3.0]).tile((N, 1)) alpha = nd.array([0.2, 0.3, 0.4]) # branching ratios should be < 1 beta = nd.array([1.0, 2.0, 3.0]) # the "data", or observations ia_times = nd.array([[6, 7, 8, 9], [1, 2, 3, 4], [3, 4, 5, 6], [8, 9, 10, 11]]) marks = nd.zeros((N, T)).astype(np.int32) # starting "state" of the process states = nd.zeros((N, K)) valid_length = nd.array([1, 2, 3, 4]) # number of valid points in each sequence max_time = nd.ones((N,)) * 100.0 # length of the observation period A = nd.contrib.hawkesll( lda, alpha, beta, states, ia_times, marks, valid_length, max_time ) References: - Bacry, E., Mastromatteo, I., & Muzy, J. F. (2015). Hawkes processes in finance. Market Microstructure and Liquidity , 1(01), 1550005. )code" ADD_FILELINE) .set_num_inputs(8) .set_num_outputs(2) .set_attr<nnvm::FListInputNames>("FListInputNames", [](const NodeAttrs& attrs) { return std::vector<std::string>{ "lda", "alpha", "beta", "state", "lags", "marks", "valid_length", "max_time" }; }) .set_attr<nnvm::FListOutputNames>("FListOutputNames", [](const NodeAttrs& attrs) { return std::vector<std::string>{"output", "out_state"}; }) .set_attr<mxnet::FInferShape>("FInferShape", HawkesLLOpShape) .set_attr<nnvm::FInferType>("FInferType", HawkesLLOpType) .set_attr<FCompute>("FCompute<cpu>", HawkesLLForward<cpu>) .set_attr<nnvm::FGradient>( "FGradient", ElemwiseGradUseIn{"_contrib_backward_hawkesll"} ) .set_attr<FResourceRequest>("FResourceRequest", [](const NodeAttrs& n) { return std::vector<ResourceRequest>{ResourceRequest::Type::kTempSpace}; }) .set_attr<THasDeterministicOutput>("THasDeterministicOutput", true) .add_argument( "lda", "NDArray-or-Symbol", "Shape (N, K) The intensity for each of the K processes, for each sample" ) .add_argument( "alpha", "NDArray-or-Symbol", "Shape (K,) The infectivity factor (branching ratio) for each process" ) .add_argument( "beta", "NDArray-or-Symbol", "Shape (K,) The decay parameter for each process" ) .add_argument( "state", "NDArray-or-Symbol", "Shape (N, K) the Hawkes state for each process" ) .add_argument( "lags", "NDArray-or-Symbol", "Shape (N, T) the interarrival times" ) .add_argument( "marks", "NDArray-or-Symbol", "Shape (N, T) the marks (process ids)" ) .add_argument( "valid_length", "NDArray-or-Symbol", "The number of valid points in the process" ) .add_argument( "max_time", "NDArray-or-Symbol", "the length of the interval where the processes were sampled"); NNVM_REGISTER_OP(_contrib_backward_hawkesll) .set_num_inputs(10) .set_num_outputs(8) .set_attr<nnvm::TIsBackward>("TIsBackward", true) .set_attr<FCompute>("FCompute<cpu>", HawkesLLBackward<cpu>) .set_attr<FResourceRequest>("FResourceRequest", [](const NodeAttrs& n) { return std::vector<ResourceRequest>{ResourceRequest::Type::kTempSpace}; }); } // namespace op } // namespace mxnet
42.266667
509
0.682492
[ "shape", "vector" ]
1e3e76fd1f5b119c9f504016d42d0f51a7115d85
11,395
cpp
C++
test/lua/main.cpp
Loghorn/ponder
6026163debce834b6460799b8907caf331d3246d
[ "MIT" ]
null
null
null
test/lua/main.cpp
Loghorn/ponder
6026163debce834b6460799b8907caf331d3246d
[ "MIT" ]
null
null
null
test/lua/main.cpp
Loghorn/ponder
6026163debce834b6460799b8907caf331d3246d
[ "MIT" ]
null
null
null
/**************************************************************************** ** ** This file is part of the Ponder library. ** ** The MIT License (MIT) ** ** Copyright (C) 2015-2020 Nick Trout. ** ** Permission is hereby granted, free of charge, to any person obtaining a copy ** of this software and associated documentation files (the "Software"), to deal ** in the Software without restriction, including without limitation the rights ** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ** copies of the Software, and to permit persons to whom the Software is ** furnished to do so, subject to the following conditions: ** ** The above copyright notice and this permission notice shall be included in ** all copies or substantial portions of the Software. ** ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN ** THE SOFTWARE. ** ****************************************************************************/ #define PONDER_USES_LUA_IMPL #include <ponder/class.hpp> #include <ponder/classbuilder.hpp> #include <ponder/value.hpp> // TODO: should this be in lua.hpp? #include <ponder/uses/lua.hpp> #include <cstdio> #include <cmath> extern "C" { #include <lualib.h> } static_assert(LUA_VERSION_NUM==503, "Expecting Lua 5.3"); namespace lib { static constexpr float FLOAT_EPSILON = 1e-5f; struct Vec { float x,y; static int instanceCount; Vec() : x(0), y(0) { ++instanceCount; } Vec(float x_, float y_) : x(x_), y(y_) { ++instanceCount; } Vec(const Vec& o) : x(o.x), y(o.y) { ++instanceCount; } Vec(Vec&& o) noexcept : x(o.x), y(o.y) { ++instanceCount; } ~Vec() { --instanceCount; } Vec& operator=(const Vec& o) = default; bool operator == (const Vec& o) const { const float dx = x - o.x, dy = y - o.y; return std::abs(dx) < FLOAT_EPSILON && std::abs(dy) < FLOAT_EPSILON; } [[nodiscard]] std::tuple<float,float> get() const { return std::make_tuple(x,y); } void set(float x_, float y_) { x = x_; y = y_; } Vec operator + (const Vec& o) const { return {x + o.x, y + o.y}; } const Vec& operator += (const Vec& o) { x += o.x; y += o.y; return *this; } [[nodiscard]] float length() const { return std::sqrt(x*x + y*y); } [[nodiscard]] float dot(const Vec &o) const { return x*o.x + y*o.y; } static Vec up() { return {0, 1.f}; } // static function Vec& ref() { return *this; } // return ref }; int Vec::instanceCount = 0; struct Holder { Holder() = default; Holder(const Holder&) = delete; Holder(Holder&&) = default; Vec vec; Holder* ptrRef() { return this; } Holder& refRef() { return *this; } }; struct Types { struct Obj { Obj(const Obj&) = delete; } o; static int len(const ponder::string_view str) { return static_cast<int>(str.length()); } Obj* retPtr() { return &o; } void passPtr(Obj *po) {} static const char* getString() { return "blah"; } }; struct Static { static int halve(int x) { return x/2; } }; int twice(int x) { return 2*x; } enum class Colour { Red, Green, Blue }; struct Parsing { int a{0}; std::string b; void init(ponder_ext::LuaTable lt) { assert(lua_istable(lt.L, -1)); // should be guaranteed by conversion lua_getfield(lt.L, -1, "a"); a = static_cast<int>(luaL_checknumber(lt.L, -1)); lua_pop(lt.L, 1); lua_getfield(lt.L, -1, "b"); b = luaL_checkstring(lt.L, -1); lua_pop(lt.L, 1); } }; void declare() { using namespace ponder; Class::declare<Vec>() .constructor() .constructor<float, float>() .constructor<const Vec&>() .property("x", &Vec::x) .property("y", &Vec::y) .function("get", &Vec::get, policy::ReturnMultiple()) // tuple .function("set", &Vec::set) .function("add", &Vec::operator+=) .function("add2", &Vec::operator+) //.tag("+") .function("length", &Vec::length) .function("dot", &Vec::dot) .function("up", &Vec::up) // static .function("funcRef", &Vec::ref, policy::ReturnInternalRef()) // ref function .property("propRef", &Vec::ref) // ref property ; Class::declare<std::tuple<float,float>>(); Class::declare<Holder>() .constructor() // .property("pref", &Holder::ptrRef) // TODO - fix for self ref pointers .function("rref", &Holder::refRef, policy::ReturnInternalRef()) .property("vec", &Holder::vec) ; Class::declare<Types>() .function("len", &Types::len) .function("retp", &Types::retPtr, policy::ReturnInternalRef()) .function("passp", &Types::passPtr) .function("getStr", &Types::getString) ; Class::declare<Static>() .function("halve", &Static::halve) .function("twice", &twice) ; Enum::declare<Colour>() .value("red", Colour::Red) .value("green", Colour::Green) .value("blue", Colour::Blue) ; Class::declare<Parsing>() .constructor() .function("init", &Parsing::init) .property("a", &Parsing::a) .property("b", &Parsing::b) ; } } // namespace lib PONDER_TYPE(lib::Vec) PONDER_TYPE(std::tuple<float,float>) PONDER_TYPE(lib::Holder) PONDER_TYPE(lib::Types) PONDER_TYPE(lib::Types::Obj) PONDER_TYPE(lib::Static) PONDER_TYPE(lib::Colour) PONDER_TYPE(lib::Parsing) static bool luaTest(lua_State *L, const char *source, int lineNb, bool success = true) { std::printf("l:%d------------------------------------------------------\n", lineNb); std::printf("Test%s: %s\n", success ? "" : "(should fail)", source); const bool ok = ponder::lua::runString(L, source); if (ok != success) { std::printf("FAILED"); exit(EXIT_FAILURE); } std::printf("\n"); return true; } #define LUA_PASS(SRC) luaTest(L,SRC,__LINE__,true) #define LUA_FAIL(SRC) luaTest(L,SRC,__LINE__,false) static bool Test(bool test, const char msg[]) { std::printf("Test: %s : %s\n", msg, test ? "PASSED" : "FAILED"); return test; } #define TEST(T) if (!Test((T), #T)) return EXIT_FAILURE int main() { std::printf("Lua version %s\n", LUA_VERSION); lua_State *L = luaL_newstate(); luaopen_base(L); lib::declare(); ponder::lua::expose<lib::Vec>(L, "Vec2"); ponder::lua::expose<lib::Holder>(L, "Holder"); ponder::lua::expose<lib::Types>(L, "Types"); ponder::lua::expose<lib::Static>(L, "Static"); ponder::lua::expose<lib::Colour>(L, "Colour"); ponder::lua::expose<lib::Parsing>(L, "Parsing"); //------------------------------------------------------------------ TEST(lib::Vec::instanceCount == 0); // class defined LUA_PASS("print(Vec2); assert(Vec2 ~= nil)"); // instance LUA_PASS("v = Vec2(); assert(v ~= nil)"); LUA_PASS("assert(type(v) == 'userdata')"); // property read LUA_PASS("assert(v.x == 0)"); LUA_PASS("assert(v.y == 0)"); // property write LUA_PASS("v.x = 7; assert(v.x == 7)"); LUA_PASS("v.y = -3; assert(v.y == -3)"); LUA_PASS("assert(type(v.x) == 'number'); assert(type(v.y) == 'number')"); LUA_PASS("v.x = 1.25"); LUA_PASS("v.x = 1.76e6"); LUA_FAIL("v.x = 'fail'"); // method call with args LUA_PASS("v:set(12, 8.5); assert(v.x == 12 and v.y == 8.5)"); LUA_PASS("v:set(1, 2); assert(v.x == 1 and v.y == 2)"); LUA_FAIL("v:set('fail'); print(v.x, v.y)"); LUA_FAIL("v:set(); print(v.x, v.y)"); // method call return args LUA_PASS("l = Vec2(3,0); assert(l:length() == 3)"); // method call with object arg LUA_PASS("a,b = Vec2(2,3), Vec2(3,4); c = a:dot(b); print(c); assert(c == 2*3+3*4)"); // method call (:) with return object (immutable) LUA_PASS("c = a:add2(b); assert(c ~= nil); print(c.x, c.y);"); LUA_PASS("assert(c.x == 5); assert(c.y == 7);"); // method call (:) with return object (mutable) LUA_PASS("c = a:add(b); assert(c ~= nil); print(c.x, c.y);"); LUA_PASS("assert(c.x == 5); assert(c.y == 7);"); // static func LUA_PASS("assert(type(Vec2.up) == 'function')"); LUA_PASS("up = Vec2.up(7); assert(type(up) == 'userdata')"); LUA_PASS("assert(type(up.x) == 'number')"); // Vec return ref (func) LUA_PASS("r = Vec2(7,8); assert(r.x == 7)"); LUA_PASS("r.x = 9; assert(r.x == 9)"); LUA_PASS("r:funcRef().x = 19; assert(r.x == 19)"); // Vec return ref (prop) LUA_PASS("r = Vec2(17,8); assert(r.x == 17)"); LUA_PASS("r.x = 9; assert(r.x == 9)"); LUA_PASS("r.propRef.x = 19; assert(r.x == 19)"); // Vec return tuple or multiple values. LUA_PASS("t = Vec2(11,22); x,y = t:get(); print(x,y); assert(x == 11); assert(y == 22)"); //------------------------------------------------------------------ // Non-copyable return ref LUA_PASS("h = Holder()"); LUA_PASS("h:rref().vec.x = 9; assert(h:rref().vec.x == 9)"); //------------------------------------------------------------------ // Types LUA_PASS("assert(type(Types) == 'userdata')"); LUA_PASS("x = Types.len('two'); assert(type(x) == 'number' and x == 3)"); LUA_PASS("assert(Types.len('1234567890') ~= 11)"); LUA_PASS("assert(Types.getStr() == 'blah')"); //------------------------------------------------------------------ // Class static function LUA_PASS("assert(type(Static) == 'userdata')"); LUA_PASS("assert(type(Static.halve) == 'function')"); LUA_PASS("x = Static.halve(16); assert(x == 8)"); // Non-class function LUA_PASS("assert(type(Static) == 'userdata')"); LUA_PASS("assert(type(Static.twice) == 'function')"); LUA_PASS("x = Static.twice(7); assert(x == 14)"); //------------------------------------------------------------------ // Enum LUA_PASS("assert(type(Colour) == 'table')"); LUA_PASS("assert(Colour.red == 0)"); LUA_PASS("assert(Colour.green == 1)"); LUA_PASS("assert(Colour.blue == 2)"); //------------------------------------------------------------------ // Parsing LUA_PASS("p = Parsing(); assert(type(p)=='userdata')"); LUA_PASS("p:init{a=77, b='w00t'}; assert(p.a == 77 and p.b == 'w00t')"); lua_close(L); //printf("lib::Vec::instanceCount = %d\n", lib::Vec::instanceCount); TEST(lib::Vec::instanceCount == 0); return EXIT_SUCCESS; }
32.008427
96
0.52681
[ "object" ]
1e41b1d5ba2c7e46a19e0a9d18eae6d5dee07b0c
8,232
cpp
C++
Tutorial0/application_draw.cpp
asm128/gpftw_expert
8dbed3d0466f273d60f390c98be1389396784141
[ "MIT" ]
null
null
null
Tutorial0/application_draw.cpp
asm128/gpftw_expert
8dbed3d0466f273d60f390c98be1389396784141
[ "MIT" ]
null
null
null
Tutorial0/application_draw.cpp
asm128/gpftw_expert
8dbed3d0466f273d60f390c98be1389396784141
[ "MIT" ]
null
null
null
#include "application.h" #include "llc_bitmap_target.h" ::llc::error_t drawBoxes (::SApplication& applicationInstance) { // --- This function will draw some coloured symbols in each cell of the ASCII screen. ::llc::SFramework & framework = applicationInstance.Framework; ::llc::SFramework::TOffscreen & offscreen = framework.Offscreen; const ::llc::SCoord2<uint32_t> & offscreenMetrics = offscreen.View.metrics(); ::memset(offscreen.Texels.begin(), 0, sizeof(::llc::SFramework::TOffscreen::TTexel) * offscreen.Texels.size()); // Clear target. ::SRenderCache & renderCache = applicationInstance.RenderCache; const ::llc::SMatrix4<float> & projection = applicationInstance.XProjection ; const ::llc::SMatrix4<float> & viewMatrix = applicationInstance.XView ; ::llc::SMatrix4<float> xViewProjection = viewMatrix * projection; ::llc::SMatrix4<float> xWorld = {}; ::llc::SMatrix4<float> xRotation = {}; const double & fFar = applicationInstance.Camera.Range.Far ; const double & fNear = applicationInstance.Camera.Range.Near ; int32_t & pixelsDrawn = applicationInstance.RenderCache.PixelsDrawn = 0; int32_t & pixelsSkipped = applicationInstance.RenderCache.PixelsSkipped = 0; renderCache.WireframePixelCoords.clear(); for(uint32_t iBox = 0; iBox < 20; ++iBox) { applicationInstance.BoxPivot.Position.x = (float)iBox; applicationInstance.BoxPivot.Scale.z = iBox / 10.0f + .1f; applicationInstance.BoxPivot.Scale.y = iBox / 20.0f + .1f; xWorld .Scale (applicationInstance.BoxPivot.Scale, true); xRotation .SetOrientation ((applicationInstance.BoxPivot.Orientation + ::llc::SQuaternion<float>{0, (float)(iBox / ::llc::math_2pi), 0, 0}).Normalize()); xWorld = xWorld * xRotation; xWorld .SetTranslation(applicationInstance.BoxPivot.Position, false); ::llc::clear ( renderCache.Triangle3dToDraw , renderCache.Triangle2dToDraw , renderCache.Triangle3dIndices , renderCache.Triangle2dIndices , renderCache.Triangle2d23dIndices ); const ::llc::SCoord2<int32_t> offscreenMetricsI = offscreenMetrics.Cast<int32_t>(); const ::llc::SCoord3<float> & cameraFront = applicationInstance.Camera.Vectors.Front; for(uint32_t iTriangle = 0; iTriangle < 12; ++iTriangle) { ::llc::STriangle3D<float> transformedTriangle3D = applicationInstance.Box.Positions[iTriangle]; ::llc::transform(transformedTriangle3D, xWorld * xViewProjection); if(transformedTriangle3D.A.z >= fFar && transformedTriangle3D.B.z >= fFar && transformedTriangle3D.C.z >= fFar ) continue; if(transformedTriangle3D.A.z <= fNear && transformedTriangle3D.B.z <= fNear && transformedTriangle3D.C.z <= fNear) continue; llc_necall(renderCache.Triangle3dToDraw .push_back(transformedTriangle3D) , "Out of memory?"); llc_necall(renderCache.Triangle3dIndices .push_back((int16_t)iTriangle) , "Out of memory?"); } for(uint32_t iTriangle = 0, triCount = renderCache.Triangle3dIndices.size(); iTriangle < triCount; ++iTriangle) { const ::llc::STriangle3D<float> & transformedTriangle3D = renderCache.Triangle3dToDraw[iTriangle]; if(transformedTriangle3D.A.x < 0 && transformedTriangle3D.B.x < 0 && transformedTriangle3D.C.x < 0) continue; if(transformedTriangle3D.A.y < 0 && transformedTriangle3D.B.y < 0 && transformedTriangle3D.C.y < 0) continue; if( transformedTriangle3D.A.x >= offscreenMetricsI.x && transformedTriangle3D.B.x >= offscreenMetricsI.x && transformedTriangle3D.C.x >= offscreenMetricsI.x ) continue; if( transformedTriangle3D.A.y >= offscreenMetricsI.y && transformedTriangle3D.B.y >= offscreenMetricsI.y && transformedTriangle3D.C.y >= offscreenMetricsI.y ) continue; const ::llc::STriangle2D<int32_t> transformedTriangle2D = { {(int32_t)transformedTriangle3D.A.x, (int32_t)transformedTriangle3D.A.y} , {(int32_t)transformedTriangle3D.B.x, (int32_t)transformedTriangle3D.B.y} , {(int32_t)transformedTriangle3D.C.x, (int32_t)transformedTriangle3D.C.y} }; llc_necall(renderCache.Triangle2dToDraw .push_back(transformedTriangle2D) , "Out of memory?"); llc_necall(renderCache.Triangle2dIndices .push_back(renderCache.Triangle3dIndices[iTriangle]), "Out of memory?"); llc_necall(renderCache.Triangle2d23dIndices .push_back((int16_t)iTriangle) , "Out of memory?"); } llc_necall(renderCache.TransformedNormals .resize(renderCache.Triangle2dToDraw.size()), "Out of memory?"); llc_necall(renderCache.Triangle3dColorList .resize(renderCache.Triangle2dToDraw.size()), "Out of memory?"); for(uint32_t iTriangle = 0, triCount = renderCache.Triangle2dToDraw.size(); iTriangle < triCount; ++iTriangle) // transform normals renderCache.TransformedNormals[iTriangle] = xWorld.TransformDirection(applicationInstance.Box.NormalsTriangle[renderCache.Triangle3dIndices[renderCache.Triangle2d23dIndices[iTriangle]]]).Normalize(); const ::llc::SCoord3<float> & lightDir = applicationInstance.LightDirection; for(uint32_t iTriangle = 0, triCount = renderCache.Triangle2dToDraw.size(); iTriangle < triCount; ++iTriangle) { // calculate lighting const double lightFactor = renderCache.TransformedNormals[iTriangle].Dot(lightDir); renderCache.Triangle3dColorList[iTriangle] = ((0 == (iBox % 2)) ? ::llc::GREEN : ::llc::MAGENTA) * lightFactor; } renderCache.TrianglePixelCoords.clear(); for(uint32_t iTriangle = 0, triCount = renderCache.Triangle2dIndices.size(); iTriangle < triCount; ++iTriangle) { // const double cameraFactor = renderCache.TransformedNormals[iTriangle].Dot(cameraFront); if(cameraFactor > .35) continue; //error_if(errored(::llc::drawTriangle(offscreen.View, triangle3dColorList[iTriangle], triangle2dToDraw[iTriangle])), "Not sure if these functions could ever fail"); renderCache.TrianglePixelCoords.clear(); error_if(errored(::llc::drawTriangle(offscreenMetrics, renderCache.Triangle2dToDraw[iTriangle], renderCache.TrianglePixelCoords)), "Not sure if these functions could ever fail"); for(uint32_t iPixel = 0, pixCount = renderCache.TrianglePixelCoords.size(); iPixel < pixCount; ++iPixel) { const ::llc::SCoord2<int32_t> & pixelCoord = renderCache.TrianglePixelCoords[iPixel]; if( offscreen.View[pixelCoord.y][pixelCoord.x] != renderCache.Triangle3dColorList[iTriangle] ) { offscreen.View[pixelCoord.y][pixelCoord.x] = renderCache.Triangle3dColorList[iTriangle]; ++pixelsDrawn; } else ++pixelsSkipped; } error_if(errored(::llc::drawLine(offscreenMetrics, ::llc::SLine2D<int32_t>{renderCache.Triangle2dToDraw[iTriangle].A, renderCache.Triangle2dToDraw[iTriangle].B}, renderCache.WireframePixelCoords)), "Not sure if these functions could ever fail"); error_if(errored(::llc::drawLine(offscreenMetrics, ::llc::SLine2D<int32_t>{renderCache.Triangle2dToDraw[iTriangle].B, renderCache.Triangle2dToDraw[iTriangle].C}, renderCache.WireframePixelCoords)), "Not sure if these functions could ever fail"); error_if(errored(::llc::drawLine(offscreenMetrics, ::llc::SLine2D<int32_t>{renderCache.Triangle2dToDraw[iTriangle].C, renderCache.Triangle2dToDraw[iTriangle].A}, renderCache.WireframePixelCoords)), "Not sure if these functions could ever fail"); } } static constexpr const ::llc::SColorBGRA color = ::llc::YELLOW; for(uint32_t iPixel = 0, pixCount = renderCache.WireframePixelCoords.size(); iPixel < pixCount; ++iPixel) { const ::llc::SCoord2<int32_t> & pixelCoord = renderCache.WireframePixelCoords[iPixel]; if( offscreen.View[pixelCoord.y][pixelCoord.x] != color ) { offscreen.View[pixelCoord.y][pixelCoord.x] = color; ++pixelsDrawn; } else ++pixelsSkipped; } return pixelsDrawn; }
69.176471
248
0.698494
[ "transform" ]
1e42a5b7e068d63879e0449750b1628faa28b4bb
778
cpp
C++
day01b.cpp
Fossegrimen/advent-of-code
d9323346c167435fe461214e9eae990a1940c78e
[ "MIT" ]
null
null
null
day01b.cpp
Fossegrimen/advent-of-code
d9323346c167435fe461214e9eae990a1940c78e
[ "MIT" ]
null
null
null
day01b.cpp
Fossegrimen/advent-of-code
d9323346c167435fe461214e9eae990a1940c78e
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> typedef std::vector<size_t> Vector; int main() { Vector expenses; size_t expense = 0; while (std::cin >> expense) { expenses.push_back(expense); } for (size_t i = 0; i < expenses.size(); i++) { for (size_t j = i + 1; j < expenses.size(); j++) { for (size_t k = j + 1; k < expenses.size(); k++) { const size_t sum = expenses[i] + expenses[j] + expenses[k]; if (sum == 2020) { const size_t product = expenses[i] * expenses[j] * expenses[k]; std::cout << product << std::endl; return 0; } } } } return 1; }
20.473684
83
0.437018
[ "vector" ]
1e4b91c2ef06c9fe108b8c549ad37b6eeeb31e96
2,628
cc
C++
garnet/bin/test_runner/run_integration_tests/test_runner_config.cc
opensource-assist/fuschia
66646c55b3d0b36aae90a4b6706b87f1a6261935
[ "BSD-3-Clause" ]
3
2020-08-02T04:46:18.000Z
2020-08-07T10:10:53.000Z
garnet/bin/test_runner/run_integration_tests/test_runner_config.cc
opensource-assist/fuschia
66646c55b3d0b36aae90a4b6706b87f1a6261935
[ "BSD-3-Clause" ]
16
2020-09-04T19:01:11.000Z
2021-05-28T03:23:09.000Z
garnet/bin/test_runner/run_integration_tests/test_runner_config.cc
OpenTrustGroup/fuchsia
647e593ea661b8bf98dcad2096e20e8950b24a97
[ "BSD-3-Clause" ]
1
2020-08-07T10:11:49.000Z
2020-08-07T10:11:49.000Z
// Copyright 2017 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "garnet/bin/test_runner/run_integration_tests/test_runner_config.h" #include <sys/socket.h> #include <iostream> #include <string> #include "src/lib/files/file.h" #include "src/lib/files/unique_fd.h" #include "src/lib/fxl/logging.h" #include "src/lib/fxl/strings/split_string.h" #include "src/lib/fxl/strings/string_printf.h" #include "rapidjson/document.h" namespace test_runner { TestRunnerConfig::TestRunnerConfig(const std::string& json_path) { std::string json; FXL_CHECK(files::ReadFileToString(json_path, &json)); rapidjson::Document doc; doc.Parse(json); FXL_CHECK(doc.IsObject()); auto& tests = doc["tests"]; FXL_CHECK(tests.IsArray()); for (auto& test : tests.GetArray()) { FXL_CHECK(test.IsObject()); FXL_CHECK(test.HasMember("name")); FXL_CHECK(test["name"].IsString()); FXL_CHECK(test.HasMember("exec")); FXL_CHECK(test["exec"].IsString() || test["exec"].IsArray()); FXL_CHECK(!test.HasMember("disabled") || test["disabled"].IsBool()); std::string test_name = test["name"].GetString(); bool test_is_disabled = test.HasMember("disabled") && test["disabled"].GetBool(); if (test_is_disabled) { disabled_test_names_.push_back(test_name); continue; } test_names_.push_back(test_name); if (test["exec"].IsString()) { std::string test_exec = test["exec"].GetString(); std::vector<std::string> test_exec_args = fxl::SplitStringCopy(test_exec, " ", fxl::kTrimWhitespace, fxl::kSplitWantNonEmpty); FXL_CHECK(!test_exec_args.empty()) << test_name << ": " << test_exec; test_commands_[test_name] = test_exec_args; } else if (test["exec"].IsArray()) { for (auto& arg : test["exec"].GetArray()) { FXL_CHECK(arg.IsString()) << test_name; test_commands_[test_name].push_back(arg.GetString()); } FXL_CHECK(!test_commands_[test_name].empty()) << test_name; FXL_CHECK(!test_commands_[test_name].front().empty()) << test_name; } } } bool TestRunnerConfig::HasTestNamed(const std::string& test_name) const { return test_commands_.find(test_name) != test_commands_.end(); } const std::vector<std::string>& TestRunnerConfig::GetTestCommand( const std::string& test_name) const { static const std::vector<std::string> empty; const auto& i = test_commands_.find(test_name); if (i == test_commands_.end()) { return empty; } return i->second; } } // namespace test_runner
32.04878
94
0.686834
[ "vector" ]
1e4daeb0dd89447e06907aa70789af5749e204c1
832
cpp
C++
leetcode/0071_Simplify_Path/result.cpp
theck17/notes
f32f0f4b8f821b1ed38d173ef0913efddd094b91
[ "MIT" ]
null
null
null
leetcode/0071_Simplify_Path/result.cpp
theck17/notes
f32f0f4b8f821b1ed38d173ef0913efddd094b91
[ "MIT" ]
null
null
null
leetcode/0071_Simplify_Path/result.cpp
theck17/notes
f32f0f4b8f821b1ed38d173ef0913efddd094b91
[ "MIT" ]
null
null
null
/** * Copyright (C) 2021 All rights reserved. * * FileName :result.cpp * Author :C.K * Email :theck17@163.com * DateTime :2021-08-08 18:13:25 * Description : */ #include <vector> //STL 动态数组容器 #include <valarray> //对包含值的数组的操作 #include <ctime> //定义关于时间的函数 using namespace std; class Solution { public: string simplifyPath(string path) { string res, tmp; vector<string> stk; stringstream ss(path); while(getline(ss,tmp,'/')) { if (tmp == "" or tmp == ".") continue; if (tmp == ".." and !stk.empty()) stk.pop_back(); else if (tmp != "..") stk.push_back(tmp); } for(auto str : stk) res += "/"+str; return res.empty() ? "/" : res; } }; int main(){ return 0; }
25.212121
61
0.504808
[ "vector" ]
1e5581e6cf67d7e759b3aeb7d723ed36b80fc127
13,355
hxx
C++
src/include/sk/posix/detail/io_uring_reactor.hxx
sikol/sk-async
fc8fb2dbfa119b8b8d68c203459b8ca676576076
[ "BSL-1.0" ]
3
2021-04-08T12:47:39.000Z
2021-09-25T11:43:41.000Z
src/include/sk/posix/detail/io_uring_reactor.hxx
sikol/sk-cio
fc8fb2dbfa119b8b8d68c203459b8ca676576076
[ "BSL-1.0" ]
null
null
null
src/include/sk/posix/detail/io_uring_reactor.hxx
sikol/sk-cio
fc8fb2dbfa119b8b8d68c203459b8ca676576076
[ "BSL-1.0" ]
null
null
null
/* * Copyright (c) 2019, 2020, 2021 SiKol Ltd. * * Boost Software License - Version 1.0 - August 17th, 2003 * * Permission is hereby granted, free of charge, to any person or organization * obtaining a copy of the software and accompanying documentation covered by * this license (the "Software") to use, reproduce, display, distribute, * execute, and transmit the Software, and to prepare derivative works of the * Software, and to permit third-parties to whom the Software is furnished to * do so, all subject to the following: * * The copyright notices in the Software and this entire statement, including * the above license grant, this restriction and the following disclaimer, * must be included in all copies of the Software, in whole or in part, and * all derivative works of the Software, unless such copies or derivative * works are solely in the form of machine-executable object code generated by * a source language processor. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #ifndef SK_CIO_POSIX_IO_URING_REACTOR_HXX_INCLUDED #define SK_CIO_POSIX_IO_URING_REACTOR_HXX_INCLUDED #include <sys/types.h> #include <sys/epoll.h> #include <sys/mman.h> #include <sys/uio.h> #include <linux/io_uring.h> #include <atomic> #include <cstring> #include <deque> #include <iostream> #include <system_error> #include <thread> #include <liburing.h> #include <sk/executor.hxx> #include <sk/posix/fd.hxx> namespace sk::posix::detail { struct io_uring_reactor final { // Try to create a new io_uring_reactor; returns NULL if we can't // use io_uring on this system. static auto make() noexcept -> expected<std::unique_ptr<io_uring_reactor>, std::error_code>; io_uring_reactor(io_uring_reactor const &) = delete; auto operator=(io_uring_reactor const &) -> io_uring_reactor & = delete; io_uring_reactor(io_uring_reactor &&) noexcept = delete; auto operator=(io_uring_reactor &&) noexcept -> io_uring_reactor & = delete; ~io_uring_reactor() = default; // Start this reactor. [[nodiscard]] auto start() noexcept -> expected<void, std::error_code>; // Stop this reactor. auto stop() noexcept -> void; // POSIX async API [[nodiscard]] auto async_fd_open(char const *path, int flags, int mode) noexcept -> task<expected<int, std::error_code>>; [[nodiscard]] auto async_fd_close(int fd) noexcept -> task<expected<int, std::error_code>>; [[nodiscard]] auto async_fd_read(int fd, void *buf, std::size_t n) noexcept -> task<expected<ssize_t, std::error_code>>; [[nodiscard]] auto async_fd_pread(int fd, void *buf, std::size_t n, off_t offs) noexcept -> task<expected<ssize_t, std::error_code>>; [[nodiscard]] auto async_fd_write(int fd, void const *buf, std::size_t n) noexcept -> task<expected<ssize_t, std::error_code>>; [[nodiscard]] auto async_fd_pwrite(int fd, void const *buf, std::size_t n, off_t offs) noexcept -> task<expected<ssize_t, std::error_code>>; // Possibly shouldn't be public. [[nodiscard]] auto _put_sq(io_uring_sqe *sqe) noexcept -> expected<void, std::error_code>; private: explicit io_uring_reactor() noexcept; std::mutex _sq_mutex; void io_uring_thread_fn() noexcept; std::thread io_uring_thread; io_uring ring{}; // must be called with _sq_mutex held [[nodiscard]] auto _try_put_sq(io_uring_sqe *sqe) noexcept -> bool; // This is the queue size we request, it may be smaller in practice. static constexpr unsigned _max_queue_size = 512; std::deque<io_uring_sqe *> _pending; }; struct co_sqe_wait final { co_sqe_wait(io_uring_reactor *reactor_, io_uring_sqe *sqe_) noexcept : reactor(reactor_), sqe(sqe_) { io_uring_sqe_set_data(sqe, this); } io_uring_reactor *reactor; io_uring_sqe *sqe; std::int32_t ret = -1; std::uint32_t flags = 0; coroutine_handle<> coro_handle; executor *task_executor = nullptr; std::mutex mutex; // NOLINTNEXTLINE(readability-convert-member-functions-to-static) auto await_ready() noexcept -> bool { return false; } template <typename P> auto await_suspend(coroutine_handle<P> coro_handle_) noexcept -> bool { coro_handle = coro_handle_; task_executor = coro_handle_.promise().task_executor; SK_CHECK(task_executor != nullptr, "suspending a task with no executor"); std::lock_guard lock(mutex); if (auto pret = reactor->_put_sq(sqe); !pret) { errno = pret.error().value(); ret = -1; return false; } return true; } auto await_resume() noexcept -> int { // Don't allow the wait object to be destroyed until the reactor // has released the lock. std::lock_guard lock(mutex); return ret; } }; inline auto io_uring_reactor::make() noexcept -> expected<std::unique_ptr<io_uring_reactor>, std::error_code> { // Create the ring. auto reactor = std::unique_ptr<io_uring_reactor>( new (std::nothrow) io_uring_reactor()); if (!reactor) return make_unexpected( std::make_error_code(std::errc::not_enough_memory)); auto ret = io_uring_queue_init( _max_queue_size, &reactor->ring, IORING_SETUP_CLAMP); if (ret < 0) return nullptr; // Check the ring supports the features we need. unsigned required_features = IORING_FEAT_NODROP | IORING_FEAT_RW_CUR_POS; if ((reactor->ring.features & required_features) != required_features) return nullptr; std::unique_ptr<io_uring_probe, void (*)(io_uring_probe *)> probe( io_uring_get_probe_ring(&reactor->ring), io_uring_free_probe); if (!probe) return nullptr; // Check the ring supports the opcodes we need. if (io_uring_opcode_supported(probe.get(), IORING_OP_NOP) == 0) return nullptr; if (io_uring_opcode_supported(probe.get(), IORING_OP_OPENAT) == 0) return nullptr; if (io_uring_opcode_supported(probe.get(), IORING_OP_CLOSE) == 0) return nullptr; if (io_uring_opcode_supported(probe.get(), IORING_OP_READ) == 0) return nullptr; if (io_uring_opcode_supported(probe.get(), IORING_OP_WRITE) == 0) return nullptr; // Reactor is okay. return reactor; } // Caller must call io_uring_submit(). inline auto io_uring_reactor::_try_put_sq(io_uring_sqe *newsqe) noexcept -> bool { auto *sqe = io_uring_get_sqe(&ring); if (sqe == nullptr) return false; std::memcpy(sqe, newsqe, sizeof(*sqe)); return true; } inline auto io_uring_reactor::_put_sq(io_uring_sqe *newsqe) noexcept -> expected<void, std::error_code> { // Lock here to avoid a race between multiple threads calling // io_uring_submit(). std::lock_guard _(_sq_mutex); if (_try_put_sq(newsqe)) { auto r = io_uring_submit(&ring); if (r >= 0 || r == -EBUSY) return {}; return make_unexpected(get_errno()); } try { _pending.push_back(newsqe); return {}; } catch (std::bad_alloc const &) { return make_unexpected( std::make_error_code(std::errc::not_enough_memory)); } } inline io_uring_reactor::io_uring_reactor() noexcept = default; inline auto io_uring_reactor::io_uring_thread_fn() noexcept -> void { io_uring_cqe *cqe{}; for (;;) { int did_requests = 0; // Process any pending CQEs. auto r = io_uring_wait_cqe(&ring, &cqe); SK_CHECK(r == 0, "io_uring_wait_cqe failed"); std::ignore = r; do { // user_data == null means a shutdown request. if (cqe->user_data == 0) return; // Resume the queued coro. // Cast is required because io_uring only gives us the data as // a __u64. // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) auto *cstate = reinterpret_cast<co_sqe_wait *>(cqe->user_data); std::lock_guard h_lock(cstate->mutex); cstate->ret = cqe->res; cstate->flags = cqe->flags; cstate->task_executor->post( [&handle = cstate->coro_handle] { handle.resume(); }); io_uring_cqe_seen(&ring, cqe); ++did_requests; } while (io_uring_peek_cqe(&ring, &cqe) == 0); { // Queue any pending SQEs. std::lock_guard sq_lock(_sq_mutex); while (!_pending.empty()) { if (_try_put_sq(_pending.front())) _pending.pop_front(); else break; } io_uring_submit(&ring); } } } inline auto io_uring_reactor::start() noexcept -> expected<void, std::error_code> { try { io_uring_thread = std::thread(&io_uring_reactor::io_uring_thread_fn, this); } catch (std::system_error const &e) { return make_unexpected(e.code()); } return {}; } inline auto io_uring_reactor::stop() noexcept -> void { io_uring_sqe shutdown_sqe{}; io_uring_prep_nop(&shutdown_sqe); shutdown_sqe.fd = -1; // XXX - decide what to do here (shutdown flag?) std::ignore = _put_sq(&shutdown_sqe); if (io_uring_thread.joinable()) io_uring_thread.join(); } /************************************************************************* * * POSIX async API. * */ inline auto io_uring_reactor::async_fd_open(char const *path, int flags, int mode) noexcept -> task<expected<int, std::error_code>> { io_uring_sqe sqe{}; io_uring_prep_openat(&sqe, AT_FDCWD, path, flags, mode); co_return co_await co_sqe_wait(this, &sqe); } inline auto io_uring_reactor::async_fd_close(int fd) noexcept -> task<expected<int, std::error_code>> { io_uring_sqe sqe{}; io_uring_prep_close(&sqe, fd); co_return co_await co_sqe_wait(this, &sqe); } inline auto io_uring_reactor::async_fd_read(int fd, void *buf, std::size_t n) noexcept -> task<expected<ssize_t, std::error_code>> { io_uring_sqe sqe{}; io_uring_prep_read(&sqe, fd, buf, n, -1); co_return co_await co_sqe_wait(this, &sqe); } inline auto io_uring_reactor::async_fd_pread(int fd, void *buf, std::size_t n, off_t offs) noexcept -> task<expected<ssize_t, std::error_code>> { io_uring_sqe sqe{}; io_uring_prep_read(&sqe, fd, buf, n, offs); co_return co_await co_sqe_wait(this, &sqe); } inline auto io_uring_reactor::async_fd_write(int fd, void const *buf, std::size_t n) noexcept -> task<expected<ssize_t, std::error_code>> { io_uring_sqe sqe{}; io_uring_prep_write(&sqe, fd, buf, n, -1); co_return co_await co_sqe_wait(this, &sqe); } inline auto io_uring_reactor::async_fd_pwrite(int fd, void const *buf, std::size_t n, off_t offs) noexcept -> task<expected<ssize_t, std::error_code>> { io_uring_sqe sqe{}; io_uring_prep_write(&sqe, fd, buf, n, offs); co_return co_await co_sqe_wait(this, &sqe); } } // namespace sk::posix::detail #endif // SK_CIO_POSIX_IO_URING_REACTOR_HXX_INCLUDED
34.24359
80
0.573119
[ "object" ]
1e603502f8e3134df73907bc437ef1fd3c4dd623
22,969
cpp
C++
Eudora71/Eudora/QCTaskManager.cpp
dusong7/eudora-win
850a6619e6b0d5abc770bca8eb5f3b9001b7ccd2
[ "BSD-3-Clause-Clear" ]
10
2018-05-23T10:43:48.000Z
2021-12-02T17:59:48.000Z
Eudora71/Eudora/QCTaskManager.cpp
dusong7/eudora-win
850a6619e6b0d5abc770bca8eb5f3b9001b7ccd2
[ "BSD-3-Clause-Clear" ]
1
2019-03-19T03:56:36.000Z
2021-05-26T18:36:03.000Z
Eudora71/Eudora/QCTaskManager.cpp
evilneuro/eudora-win
850a6619e6b0d5abc770bca8eb5f3b9001b7ccd2
[ "BSD-3-Clause-Clear" ]
11
2018-05-23T10:43:53.000Z
2021-12-27T15:42:58.000Z
// QCTaskManager.cpp: impementation file for QCTaskManager // // Copyright (c) 1997-2000 by QUALCOMM, Incorporated /* Copyright (c) 2016, Computer History Museum All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the limitations in the disclaimer below) provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Computer History Museum nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // #include "stdafx.h" #include "QCWorkerThreadMT.h" #include "TaskStatusView.h" #include "QCTaskManager.h" #include "eudora.h" //for CEudoraApp #include "TaskInfo.h" #include "TaskErrorMT.h" #include "QCRasConnection.h" #include "QCRas.h" //For CloseConnection #include "resource.h" #include "rs.h" //GetIniLong #include "persona.h" #include "QCWorkerSocket.h" // for Network #include "QCSSL.h" // for CertData struct #ifdef EXPIRING #include "timestmp.h" #include "mainfrm.h" extern CTimeStamp g_TimeStamp; #endif #include "DebugNewHelpers.h" CTrustCertDlg::CTrustCertDlg(CWnd *pwndParent, CString &strCertText, CString &strReasonText) : CHelpxDlg(CTrustCertDlg::IDD, pwndParent) { m_strCertText = strCertText; m_strReasonText = strReasonText; } void CTrustCertDlg::DoDataExchange(CDataExchange *pDX) { CHelpxDlg::DoDataExchange(pDX); //{{AFX_DATA_MAP(CMakeFilter) DDX_Text(pDX, IDC_EDIT_CERT, m_strCertText); DDX_Text(pDX, IDC_REASON_TEXT, m_strReasonText); //}}AFX_DATA_MAP } // -------------------------------------------------------------------------- QCTaskManager *g_TaskManager = NULL; // -------------------------------------------------------------------------- int QCTaskManager::s_nGroupID = 0; //Group IDs start at 0 //Global helper function to get the one and only QCTaskManager object QCTaskManager *QCGetTaskManager() { ASSERT(g_TaskManager!=NULL); return g_TaskManager; } QCTaskManager::QCTaskManager() : m_nActiveTasks(0), m_nActiveDialupTasks(0), m_bDelayQueuing(false), m_bIgnoreIdle(false), m_nStartIdle(0), m_bPostProcessInProgress(false) { // Retrieve the maximum number of concurrent tasks, where 0 will mean no limit m_nMaxConcurrentTasks = GetIniLong(IDS_INI_MAX_CONCURRENT_TASKS); m_nMaxConcurrentDialupTasks = GetIniLong(IDS_INI_MAX_CONCURRENT_DIALUP_TASKS); } bool QCTaskManager::DelayTasks(GroupCallback gc /*NULL*/, bool bIgnoreIdle /*=false*/) { CSingleLock lock(&m_Guard_TaskInfoList, TRUE); if(!m_bDelayQueuing) { m_bDelayQueuing = true; m_bIgnoreIdle = bIgnoreIdle; //new Group ID if(gc != NULL) { s_nGroupID++; m_GroupMap[s_nGroupID] = gc; } return true; } return false; //false means already delayed } void QCTaskManager::StartTasks() { CSingleLock lock(&m_Guard_TaskInfoList, TRUE); ASSERT(m_bDelayQueuing == true); m_bDelayQueuing = false; //reset m_bIgnoreIdle = false; //reset CTaskInfoMT *task = NULL; for(TaskIterator ti=m_TaskInfoList.begin(); ti != m_TaskInfoList.end(); ++ti) { task = (*ti); if(task->GetState() == TSS_WAITING_TO_QUEUE) task->SetState(TSS_QUEUED); } m_nStartIdle = ((CEudoraApp *)AfxGetApp())->GetStartIdle(); ScheduleTasks(); } QCTaskManager *QCTaskManager::Create() { ASSERT(g_TaskManager==NULL); g_TaskManager = DEBUG_NEW_NOTHROW QCTaskManager; return g_TaskManager; } void QCTaskManager::Destroy() { if(g_TaskManager) { delete g_TaskManager; g_TaskManager = NULL; } } void QCTaskManager::Register(CTaskInfoMT *pTaskInfo) { ASSERT(m_DispWndMap[pTaskInfo->GetObjectType()]); CSingleLock lock(&m_Guard_TaskInfoList, TRUE); bool bInserted = false; if(pTaskInfo->NeedsDialup()) { //If task needs dialup, place it after the last dailup connection with the same dialup entry //if any exists+ CString strEntry = pTaskInfo->GetDialupEntryName(); for(RTI ri = m_TaskInfoList.rbegin(); ri != m_TaskInfoList.rend(); ++ri) { if( (*ri)->NeedsDialup()) { if( (*ri)->GetDialupEntryName() == strEntry) { m_TaskInfoList.insert(ri.base(), 1, pTaskInfo); bInserted = true; break; } } } } if(!bInserted) m_TaskInfoList.push_back(pTaskInfo); CSingleLock objlock(&m_ObjGuard, TRUE); // Lock for access to object member variable pTaskInfo->SetDisplayWnd(m_DispWndMap[pTaskInfo->GetObjectType()], true); // Set display window for info and have it nitify the window immediately //Tell that the task is waiting to be run //pTaskInfo->SetMainText("Waiting in the task queue to be started ..."); pTaskInfo->SetMainText(CRString(IDS_TASK_WAITING_TO_START)); } void QCTaskManager::Register(CTaskErrorMT *pTaskError) { ASSERT(m_DispWndMap[pTaskError->GetObjectType()]); CSingleLock lock(&m_Guard_TaskErrorList, TRUE); m_TaskErrorList.push_back(pTaskError); CSingleLock objlock(&m_ObjGuard, TRUE); // Lock for access to object member variable pTaskError->SetDisplayWnd(m_DispWndMap[pTaskError->GetObjectType()], true); // Set display window for info and have it nitify the window immediately PutDebugLog(DEBUG_MASK_DIALOG, pTaskError->GetErrText()); } void QCTaskManager::RequestAllThreadsToStop() { CSingleLock lock(&m_Guard_TaskInfoList, TRUE); for(TaskIterator ti=m_TaskInfoList.begin(); ti != m_TaskInfoList.end(); ++ti) { // Request that the task info stop the "thread", because not all // task info's have an actual m_pThread. (*ti)->RequestThreadStop(); } } CTaskInfoMT *QCTaskManager::GetTaskInfo(QCWorkerThreadMT *pThread) { CSingleLock lock(&m_Guard_TaskInfoList, TRUE); for(TaskIterator ti=m_TaskInfoList.begin(); ti != m_TaskInfoList.end(); ++ti) if( (*ti)->m_pThread == pThread) return (*ti); return NULL; } bool QCTaskManager::QueueWorkerThread(QCWorkerThreadMT *pThread) { CTaskInfoMT *pTaskInfo = pThread->GetTaskInfo(); if( m_bDelayQueuing) { pTaskInfo->SetGroupID(s_nGroupID); pTaskInfo->SetState( TSS_WAITING_TO_QUEUE ); if(m_bIgnoreIdle) pTaskInfo->IgnoreIdle(); } else pTaskInfo->SetState( TSS_QUEUED ); //StartWorkerThread(pTaskInfo); if(CanScheduleTask(pTaskInfo) == false) { return false; } //Clear previous Network errors for this task type ClearTaskErrors(pTaskInfo->GetPersona(), pTaskInfo->GetTaskType()); // Add to the internal Task List Register(pTaskInfo); ScheduleTasks(); //which calls StartWorkerThread return true; } bool QCTaskManager::CanScheduleTask(CTaskInfoMT *pTaskInfo) { CSingleLock lock(&m_Guard_TaskInfoList, TRUE); #ifdef EXPIRING // this is the first line of defense if ( g_TimeStamp.IsExpired0() ) { AfxGetMainWnd()->PostMessage(WM_USER_EVAL_EXPIRED); return false; } #endif int nScheduleTypes = pTaskInfo->GetScheduleTypes(); //pTaskInfo isn't yet inserted into the TaskList if( (pTaskInfo->GetTaskType() == TASK_TYPE_RECEIVING) && (nScheduleTypes & TT_USES_POP) ) { CTaskInfoMT *task = NULL; for(TaskIterator ti=m_TaskInfoList.begin(); ti != m_TaskInfoList.end(); ++ti) { task = (*ti); if( (task->GetTaskType() == TASK_TYPE_RECEIVING) && (task->m_strPersona == pTaskInfo->m_strPersona) ) return false; } } return true; } int QCTaskManager::GetTaskCount(const char* strPersona) { CSingleLock lock(&m_Guard_TaskInfoList, TRUE); int num = 0; CTaskInfoMT *pTaskInfo = NULL; for(TaskIterator ti=m_TaskInfoList.begin(); ti != m_TaskInfoList.end(); ++ti) { pTaskInfo = *ti; if ( pTaskInfo->m_bCountTask && (!strPersona || pTaskInfo->GetPersona().CompareNoCase(strPersona) == 0) ) { num++; } } return num; } bool QCTaskManager::IsTaskRunning(const char* strPersona, int ScheduleBits) { CSingleLock lock(&m_Guard_TaskInfoList, TRUE); CTaskInfoMT *pTaskInfo = NULL; for(TaskIterator ti=m_TaskInfoList.begin(); ti != m_TaskInfoList.end(); ++ti) { pTaskInfo = *ti; if(pTaskInfo->GetPersona().CompareNoCase(strPersona) != 0) continue; TaskStatusState ts = pTaskInfo->GetState(); if( ts == TSS_RUNNING || ts == TSS_COMPLETE) { int nScheduleTypes = pTaskInfo->GetScheduleTypes(); if( nScheduleTypes & ScheduleBits) return true; } } return false; } bool QCTaskManager::LookupTask(int ScheduleBits) { CSingleLock lock(&m_Guard_TaskInfoList, TRUE); for(TaskIterator ti=m_TaskInfoList.begin(); ti != m_TaskInfoList.end(); ++ti) { int nScheduleTypes = (*ti)->GetScheduleTypes(); if( nScheduleTypes & ScheduleBits) return true; } return false; } bool QCTaskManager::ScheduleTasks() { CSingleLock lock(&m_Guard_TaskInfoList, TRUE); CTaskInfoMT *pTaskInfo = NULL; for(TaskIterator ti=m_TaskInfoList.begin(); ti != m_TaskInfoList.end(); ++ti) { pTaskInfo = *ti; int nScheduler = pTaskInfo->GetScheduleTypes(); //Need a task thats queued if(pTaskInfo->GetState() != TSS_QUEUED) continue; //Rule 1 - Only allow specified number of Max concurrent tasks ASSERT( (m_nActiveTasks <= m_nMaxConcurrentTasks) || (m_nMaxConcurrentTasks == 0) ); // Did we reach the max limit (where 0 means no limit)? if ( (m_nMaxConcurrentTasks != 0) && (m_nActiveTasks == m_nMaxConcurrentTasks) ) break; //Rule Don't allow more than one POP connection per persona concurrently if( nScheduler & TT_USES_POP ) { if( IsTaskRunning(pTaskInfo->GetPersona(), TT_USES_POP) ) continue; } //Rule 2 Allow only one dilaup task at any time if (nScheduler & TT_USES_DIALUP) { //if reached max allowed connections on a dialup, stop here if ( (m_nMaxConcurrentDialupTasks != 0) && (m_nActiveDialupTasks == m_nMaxConcurrentDialupTasks) ) continue; } //TRACE("Starting the task by tid %d\n", GetCurrentThreadId()); StartWorkerThread(pTaskInfo); } return true; } bool QCTaskManager::StartWorkerThread(CTaskInfoMT *pTaskInfo) { if (pTaskInfo) { QCWorkerThreadMT *pThread = pTaskInfo->m_pThread; if (pThread) { TRACE("Starting task: %d: %s for %s\n", pTaskInfo->GetUID(), pTaskInfo->GetTitle(), pTaskInfo->GetPersona()); CWinThread *pWinThread = AfxBeginThread(ThreadStartupFunc, (LPVOID)pThread, THREAD_PRIORITY_BELOW_NORMAL, 0, CREATE_SUSPENDED); if (pWinThread) { //pWinThread->m_bAutoDelete = FALSE; pTaskInfo->m_pWinThread = pWinThread; pWinThread->ResumeThread(); pTaskInfo->SetState(TSS_RUNNING); m_nActiveTasks++; if (pTaskInfo->NeedsDialup()) m_nActiveDialupTasks++; //WaitForSingleObject(pThreadID->m_hThread, INFINITE); return true; } } // Make sure we clean up this task when something bad happened pTaskInfo->SetState(TSS_COMPLETE); pTaskInfo->SetPostProcessing(true); RequestPostProcessing(pTaskInfo); } ASSERT(0); return false; } void QCTaskManager::RemoveWorkerThread(QCWorkerThreadMT *pThread) { CSingleLock lock(&m_Guard_TaskInfoList, TRUE); static DWORD EudoraAppThreadID = AfxGetApp()->m_nThreadID; CTaskInfoMT *pTaskInfo = GetTaskInfo(pThread); if(!pTaskInfo) { ASSERT(pTaskInfo); return; } //Set the thread state to done pTaskInfo->SetState(TSS_COMPLETE); unsigned long IdleTime = ((CEudoraApp *)AfxGetApp())->GetStartIdle(); if( pTaskInfo->IsIgnoreIdleSet() || (m_nStartIdle == IdleTime) ) { RequestPostProcessing(pTaskInfo); } } bool QCTaskManager::NeedsPostProcessing() { for(TaskIterator ti=m_TaskInfoList.begin(); ti != m_TaskInfoList.end(); ++ti) { if((*ti)->NeedsPostProcessing()) return true; } return false; } //Should only get called from OnIdle loop //Pop a command from the PostProcess Request queue and do post processing on the requested tasks void QCTaskManager::DoPostProcessing() { ASSERT(::IsMainThreadMT()); CSingleLock lock(&m_Guard_TaskInfoList, TRUE); if(m_bPostProcessInProgress == true || m_PostProcessList.empty()) { TRACE("Refused to do PostProcessing due to Reentrancy\n"); ASSERT(0); return; } CTaskInfoMT *pTaskInfo = NULL; { CSingleLock lock(&m_PostProcessListGuard, TRUE); pTaskInfo = *(m_PostProcessList.begin()); m_PostProcessList.pop_front(); }//m_PostProcessListGuard lock removed try { m_bPostProcessInProgress = true; if(pTaskInfo) { //Task might have been processed already. Check for validity of the task info TaskIterator ti= find(m_TaskInfoList.begin(), m_TaskInfoList.end(), pTaskInfo); if(ti != m_TaskInfoList.end() && pTaskInfo->NeedsPostProcessing()) { //TRACE("Doing postprocessing for %d\n", pTaskInfo->GetUID()); pTaskInfo->DoPostProcessing(); } } else { for(TaskIterator ti=m_TaskInfoList.begin(); ti != m_TaskInfoList.end(); ++ti) { pTaskInfo = (*ti); if(pTaskInfo->NeedsPostProcessing()) { //TRACE("Doing postprocessing for %d\n", pTaskInfo->GetUID()); pTaskInfo->DoPostProcessing(); } } } m_bPostProcessInProgress = false; } catch (CException * /* pException */) { // Catch and rethrow MFC exceptions ASSERT( !"Rethrowing CException in QCTaskManager::DoPostProcessing" ); m_bPostProcessInProgress = false; throw; } catch (std::exception & /* exception */) { // Catch and rethrow standard C++ derived exception ASSERT( !"Rethrowing std::exception in QCTaskManager::DoPostProcessing" ); m_bPostProcessInProgress = false; throw; } } bool QCTaskManager::IsPostProcessingRequested() { CSingleLock lock(&m_PostProcessListGuard, TRUE); return !m_PostProcessList.empty(); } void QCTaskManager::RequestPostProcessing(CTaskInfoMT *pTaskInfo /*= NULL*/) { { CSingleLock lock(&m_PostProcessListGuard, TRUE); //TRACE("Add PostProcess cmd\n"); m_PostProcessList.push_back( pTaskInfo); } //Lock destroyed here } // -------------------------------------------------------------------------- // [PUBLIC] GetTaskInfo // // Find and return a pointer to the TaskInfo identified by the UID. NULL // indicates not found. // CTaskInfoMT *QCTaskManager::GetTaskInfo(unsigned long int nUID) { CSingleLock lock(&m_Guard_TaskInfoList, TRUE); for(TaskIterator ti=m_TaskInfoList.begin(); ti != m_TaskInfoList.end(); ++ti) if( (*ti)->GetUID() == nUID) return (*ti); return NULL; } // -------------------------------------------------------------------------- // [PUBLIC] GetTaskError // // Find and return a pointer to the ErrorInfo identified by the UID. NULL // indicates not found. // CTaskErrorMT *QCTaskManager::GetTaskError(unsigned long int nUID) { CSingleLock lock(&m_Guard_TaskErrorList, TRUE); for(TaskErrorIterator ti=m_TaskErrorList.begin(); ti != m_TaskErrorList.end(); ++ti) if( (*ti)->GetUID() == nUID) return (*ti); return NULL; } int QCTaskManager::GetNumTaskErrors(CTime afterThisTime, TaskType tt) { CSingleLock lock(&m_Guard_TaskErrorList, TRUE); int nErrors = 0; for(TaskErrorIterator ti=m_TaskErrorList.begin(); ti != m_TaskErrorList.end(); ++ti) { if( ((*ti)->GetTaskType() == tt) && ((*ti)->GetInfoTimeStamp() >= afterThisTime) ) nErrors++; } return nErrors; } // -------------------------------------------------------------------------- // [PUBLIC] RemoveTaskInfo // // Removes and deletes the TaskInfo object from the task manager list. // Returns true if successful. // bool QCTaskManager::RemoveTaskInfo(unsigned long int nUID) { CSingleLock lock(&m_Guard_TaskInfoList, TRUE); bool bRemoved = false; CTaskInfoMT *pTaskInfo = NULL; for(TaskIterator ti=m_TaskInfoList.begin(); ti != m_TaskInfoList.end(); ++ti) { pTaskInfo = *ti; if( pTaskInfo->GetUID() == nUID) { m_TaskInfoList.erase(ti); //do some bookkeeping m_nActiveTasks--; if (pTaskInfo->NeedsDialup()) { m_nActiveDialupTasks--; if(!m_nActiveDialupTasks && !LookupTask(TT_USES_DIALUP)) { ASSERT(::IsMainThreadMT()); CString Cache = g_Personalities.GetCurrent(); g_Personalities.SetCurrent(pTaskInfo->GetPersona()); if( GetIniShort(IDS_INI_RAS_CLOSE_AFTER_DONE)) QCRasLibrary::CloseConnection(); g_Personalities.SetCurrent(Cache); } } if(pTaskInfo->GetGroupID()) { //we are a group. If the last one in the group call the Group Callback bool bLastInGroup = true; int gid = pTaskInfo->GetGroupID(); //Are we the last task in the group for(TaskIterator IT=m_TaskInfoList.begin(); IT != m_TaskInfoList.end(); ++IT) { if((*IT)->GetGroupID() == gid) { bLastInGroup = false; break; } } if( bLastInGroup) { // we are the last task. Find our Callback function GroupIter gi = m_GroupMap.find(gid); if( gi != m_GroupMap.end()) { GroupCallback gc = (*gi).second; //Run the callback if(gc) gc(); } } } // If the error is a certificate error, ask user if they want to trust the cert anyway. if ((pTaskInfo->GetSSLError() > 0) && pTaskInfo->GetSSLCert()) { CString strRejection = pTaskInfo->GetSSLCertRejection(); CString strCertText = pTaskInfo->GetSSLCertText(); CTrustCertDlg trustCertDlg(NULL, strCertText, strRejection); if (trustCertDlg.DoModal() == IDOK) { FPNQCSSLAddTrustedUserCert fnAddTrustedUserCert = NULL; if (Network::GetQCSSLDll() != NULL) { fnAddTrustedUserCert = Network::GetQCSSLAddTrustedUserCert(); if(fnAddTrustedUserCert) { fnAddTrustedUserCert((CertData*)(pTaskInfo->GetSSLCert()), NULL/*ignored*/, NULL/*ignored*/); } } } } //cleanup resources delete pTaskInfo->m_pThread; delete pTaskInfo; // Do we have to delete? I think so. bRemoved = true; //without this break, the next iterator will be invalid and crashes break; } } //Schedule tasks that might wating for this task to be completed.. ScheduleTasks(); return bRemoved; } // -------------------------------------------------------------------------- bool QCTaskManager::ClearTaskErrors(const char* strPersona, TaskType tt) { CSingleLock lock(&m_Guard_TaskErrorList, TRUE); CTaskErrorMT *pTaskError = NULL; for(TaskErrorIterator ti=m_TaskErrorList.begin(); ti != m_TaskErrorList.end(); ++ti) { pTaskError = *ti; if( pTaskError->GetPersona().CompareNoCase(strPersona) == 0 && pTaskError->GetTaskType() == tt) { TaskErrorType terr = pTaskError->GetErrorType(); if(terr & TERR_WINSOCK || terr & TERR_RAS) pTaskError->Kill(); } } return true; } // [PUBLIC] RemoveTaskError // // Removes and deletes the TaskError object from the list. // Returns true if successful. // bool QCTaskManager::RemoveTaskError(unsigned long int nUID) { CSingleLock lock(&m_Guard_TaskErrorList, TRUE); for(TaskErrorIterator ti=m_TaskErrorList.begin(); ti != m_TaskErrorList.end(); ++ti) if( (*ti)->GetUID() == nUID) { delete (*ti); // Do we have to delete? I think so. m_TaskErrorList.erase(ti); return (true); } return (false); } // -------------------------------------------------------------------------- // [PUBLIC] SetDisplayWindow // // Assigns this TaskManager a display window. All tasks managed by this // manager should post messages to this window. // // CWnd *SetDisplayWindow(CTaskObjectMT::TaskObjectType type, CWnd *pWnd); CWnd *QCTaskManager::SetDisplayWindow(CTaskObjectMT::TaskObjectType type, CWnd *pWnd) { CSingleLock lock(&m_ObjGuard, TRUE); // Lock for access to object member variable CWnd *pOldWnd = m_DispWndMap[type]; m_DispWndMap[type] = pWnd; // If we're replacing an old window, we need to tell the task objects // that their window is being replaced with a different one. if (pOldWnd) { if (type == CTaskObjectMT::TOBJ_INFO) { CSingleLock lock(&m_Guard_TaskInfoList, TRUE); for(TaskIterator ti=m_TaskInfoList.begin(); ti != m_TaskInfoList.end(); ++ti) { CTaskInfoMT* pTaskInfo = *ti; if (pTaskInfo->GetDisplayWnd() == pOldWnd) pTaskInfo->SetDisplayWnd(pWnd, true); } } else if (type == CTaskObjectMT::TOBJ_ERROR) { CSingleLock lock(&m_Guard_TaskErrorList, TRUE); for(TaskErrorIterator ti=m_TaskErrorList.begin(); ti != m_TaskErrorList.end(); ++ti) { CTaskErrorMT* pTaskError = *ti; if (pTaskError->GetDisplayWnd() == pOldWnd) pTaskError->SetDisplayWnd(pWnd, true); } } else ASSERT(0); // Uh oh, unkown task type } return (pOldWnd); } // -------------------------------------------------------------------------- // Global THREAD function UINT ThreadStartupFunc(LPVOID lpv) { // Catch most exceptions that could occur in any thread other // than the main thread so that they don't cause Eudora to quit. bool bExceptionOccurred = false; int nResult = 0; try { QCWorkerThreadMT * pWorkThread = (QCWorkerThreadMT *)lpv; if (pWorkThread) { pWorkThread->DoWork(); QCGetTaskManager()->RemoveWorkerThread(pWorkThread); } } catch (CMemoryException * pMemoryException) { // MFC currently makes operator new throw a CMemoryException pMemoryException->Delete(); bExceptionOccurred = true; // We can use the return code here to pass back information to the // main thread. The information can be retrieved via GetExitCodeThread. nResult = -1; } catch (std::bad_alloc & /* exception */) { // I don't think we can currently get this given MFC's overriding of // operator new, but perhaps they'll be standards compliant in the future. bExceptionOccurred = true; // We can use the return code here to pass back information to the // main thread. The information can be retrieved via GetExitCodeThread. nResult = -1; } ASSERT(!bExceptionOccurred); return nResult; } QCTaskGroup::QCTaskGroup(GroupCallback gc, bool bIgnoreIdle) { m_bTopLevel = QCGetTaskManager()->DelayTasks(gc, bIgnoreIdle); } QCTaskGroup::~QCTaskGroup() { if(m_bTopLevel) QCGetTaskManager()->StartTasks(); }
25.807865
149
0.693892
[ "object" ]
1e6e597c826df7aed4b226aa737439d3180f63b4
4,009
cpp
C++
src/IStrategizer/MoveAction.cpp
ogail/IStrategizer
d214f150fdfee3c3a865a826546058d131dd9100
[ "Apache-2.0" ]
1
2017-12-20T13:53:09.000Z
2017-12-20T13:53:09.000Z
src/IStrategizer/MoveAction.cpp
ogail/IStrategizer
d214f150fdfee3c3a865a826546058d131dd9100
[ "Apache-2.0" ]
null
null
null
src/IStrategizer/MoveAction.cpp
ogail/IStrategizer
d214f150fdfee3c3a865a826546058d131dd9100
[ "Apache-2.0" ]
null
null
null
#include "MoveAction.h" #include "EngineAssist.h" #include "GameEntity.h" #include "AbstractAdapter.h" #include "OnlineCaseBasedPlannerEx.h" #include "CaseBasedReasonerEx.h" #include "RtsGame.h" #include "GamePlayer.h" #include "And.h" #include "EntityClassExist.h" #include "EntityClassNearArea.h" #include <math.h> #include "AdapterEx.h" using namespace IStrategizer; using namespace Serialization; using namespace std; MoveAction::MoveAction() : Action(ACTIONEX_Move) { _params[PARAM_EntityClassId] = ECLASS_START; _params[PARAM_ObjectStateType] = OBJSTATE_START; CellFeature::Null().To(_params); } //---------------------------------------------------------------------------------------------- MoveAction::MoveAction(const PlanStepParameters& p_parameters) : Action(ACTIONEX_Move,p_parameters) { } //---------------------------------------------------------------------------------------------- void MoveAction::Copy(IClonable* p_dest) { Action::Copy(p_dest); } //---------------------------------------------------------------------------------------------- void MoveAction::HandleMessage(RtsGame& game, Message* p_msg, bool& p_consumed) { } //---------------------------------------------------------------------------------------------- bool MoveAction::AliveConditionsSatisfied(RtsGame& game) { bool satisfied = false; if (g_Assist.DoesEntityObjectExist(_entityId)) { GameEntity* pEntity = game.Self()->GetEntity(_entityId); _ASSERTE(pEntity); satisfied = (pEntity->P(OP_IsMoving) > 0 ? true : false); } else { ConditionEx* failedCondition = new EntityClassExist( PLAYER_Self, (EntityClassType)_params[PARAM_EntityClassId], 1); m_history.Add(ESTATE_Failed, failedCondition); } return satisfied; } //---------------------------------------------------------------------------------------------- bool MoveAction::SuccessConditionsSatisfied(RtsGame& game) { return g_Assist.IsEntityCloseToPoint(_entityId, _position, ENTITY_DEST_ARRIVAL_THRESHOLD_DISTANCE); } //---------------------------------------------------------------------------------------------- bool MoveAction::Execute(RtsGame& game, const WorldClock& p_clock) { AbstractAdapter *pAdapter = g_OnlineCaseBasedPlanner->Reasoner()->Adapter(); EntityClassType entityType = (EntityClassType)_params[PARAM_EntityClassId]; //Adapt Entity _entityId = pAdapter->GetEntityObjectId(entityType, AdapterEx::EntityToMoveStatesRank); bool executed = false; if(_entityId != INVALID_TID) { //Adapt position _position = pAdapter->AdaptPosition(Parameters()); _pEntity = game.Self()->GetEntity(_entityId); _pEntity->Lock(this); _ASSERTE(_pEntity); executed = _pEntity->Move(_position); } return executed; } //---------------------------------------------------------------------------------------------- void MoveAction::InitializePostConditions() { vector<Expression*> m_terms; EntityClassType entityType = (EntityClassType)_params[PARAM_EntityClassId]; m_terms.push_back(new EntityClassNearArea(PLAYER_Self, entityType, new CellFeature(_params), 0)); _postCondition = new And(m_terms); } //---------------------------------------------------------------------------------------------- void MoveAction::InitializePreConditions() { EntityClassType entity = (EntityClassType)_params[PARAM_EntityClassId]; vector<Expression*> m_terms; m_terms.push_back(new EntityClassExist(PLAYER_Self, entity, 1)); _preCondition = new And(m_terms); } //---------------------------------------------------------------------------------------------- bool MoveAction::Equals(PlanStepEx* p_planStep) { return StepTypeId() == p_planStep->StepTypeId() && _params[PARAM_ResourceId] == p_planStep->Parameter(PARAM_ResourceId) && _params[PARAM_ObjectStateType] == p_planStep->Parameter(PARAM_ObjectStateType); }
36.117117
103
0.569219
[ "vector" ]
1e748eb474502f0a655fd7e0097188dd44db2999
11,256
hpp
C++
include/Btk/widget.hpp
BusyStudent/Btk
27b23aa77e4fbcc48bdfe566ce7cae46183c289c
[ "MIT" ]
2
2021-06-19T08:21:38.000Z
2021-08-15T21:37:30.000Z
include/Btk/widget.hpp
BusyStudent/Btk
27b23aa77e4fbcc48bdfe566ce7cae46183c289c
[ "MIT" ]
null
null
null
include/Btk/widget.hpp
BusyStudent/Btk
27b23aa77e4fbcc48bdfe566ce7cae46183c289c
[ "MIT" ]
1
2021-04-03T14:27:39.000Z
2021-04-03T14:27:39.000Z
#if !defined(_BTK_WIDGET_HPP_) #define _BTK_WIDGET_HPP_ #include <cstdio> #include <list> #include "function.hpp" #include "signal.hpp" #include "themes.hpp" #include "font.hpp" #include "rect.hpp" #include "defs.hpp" namespace Btk{ class Font; class Theme; class Window; class Renderer; //Event forward decl class Event; class Widget; class Container; class WindowImpl; struct KeyEvent; struct DragEvent; struct DropEvent; struct MouseEvent; struct WheelEvent; struct MotionEvent; struct ResizeEvent; struct TextInputEvent; enum class FocusPolicy:Uint8{ None = 0, KeyBoard = 1, Mouse = 2,//< The widget will get focus by mouse and lost focus by mouse Wheel = 3 }; //Alignment enum class Align:unsigned int{ Center,//<V and H //Vertical Alignment Top, Bottom, Baseline,//< Only for TextAlign //Horizontal Alignment Right, Left }; inline constexpr auto AlignCenter = Align::Center; inline constexpr auto AlignBottom = Align::Bottom; inline constexpr auto AlignRight = Align::Right; inline constexpr auto AlignLeft = Align::Left; inline constexpr auto AlignTop = Align::Top; //Attribute for Widget struct WidgetAttr{ bool hide = false;//<Is hide bool window = false;//<Is window bool user_rect = false;//<Using user defined position bool container = false;//<Is container bool laoyout = false;//<Is layout? bool disable = false;//<The widget is disabled? FocusPolicy focus = FocusPolicy::None;//<Default the widget couldnot get focus }; class BTKAPI Widget:public HasSlots{ public: /** * @brief Construct a new Widget object * @note All data will be inited to 0 */ Widget(); Widget(const Widget &) = delete; virtual ~Widget(); virtual void draw(Renderer &render) = 0; /** * @brief Process event * * @return true if widget processed it * @return false if widget unprocessed it */ virtual bool handle(Event &); virtual void set_rect(const Rect &rect); /** * @brief Set the parent (you can overload it) * * @param parent The pointer to the parent */ virtual void set_parent(Widget *parent); //Resize void resize(int w,int h,bool is_sizing = false); //Hide and show void hide(); void show(); bool visible() const noexcept{ return not attr.hide; }; Vec2 position() const noexcept{ return { rect.x, rect.y }; }; /** * @brief Return The widget's master * * @return Window ref */ Window &master() const; //Set widget rect void set_rect(int x,int y,int w,int h){ set_rect({x,y,w,h}); } void set_rectangle(int x,int y,int w,int h){ set_rect({x,y,w,h}); } void set_rectangle(const Rect &r){ set_rect(r); } void set_position(const Vec2 &vec2){ set_rect(vec2.x,vec2.y,rect.w,rect.h); } int x() const noexcept{ return rect.x; } int y() const noexcept{ return rect.y; } int w() const noexcept{ return rect.w; } int h() const noexcept{ return rect.h; } bool is_enable() const noexcept{ return not attr.disable; } /** * @brief A function for getting rect * @return Rect */ Rect rectangle() const noexcept{ return rect; } /** * @brief A template for get FRect like this rectangle<float>() * * @tparam T * @tparam RetT * @return RetT */ template<class T,class RetT = FRect> RetT rectangle() const noexcept; /** * @brief Show the widget tree * */ void dump_tree(FILE *output = stderr); Widget *parent() const noexcept{ return _parent; } /** * @brief Delete all childrens * */ void clear_childrens(); auto &get_childrens(){ return childrens; } WidgetAttr attribute() const noexcept{ return attr; } //TypeCheck bool is_window() const noexcept{ return attr.window; } bool is_layout() const noexcept{ return attr.laoyout; } /** * @brief Send a redraw request to the window * */ void redraw() const; protected: /** * @brief Get current window * * @return WindowImpl* */ WindowImpl *window() const noexcept; /** * @brief Get current window's renderer * * @return Renderer* (failed on nullptr) */ Renderer *renderer() const; /** * @brief Find children by position * * @return Widget* */ Widget *find_children(const Vec2 position) const; /** * @brief Set theme and font from parent * */ void inhert_style(); const Font &font() const noexcept{ return _font; } const Theme &theme() const noexcept{ return _theme; } void set_font(const Font &font){ _font = font; redraw(); } void set_theme(const Theme &theme){ _theme = theme; redraw(); } public: //Event Handle Method,It will be called in Widget::handle() /** * @brief Called in Drag(type Is Drag DragBegin DragEnd) * * @return true * @return false */ virtual bool handle_drag(DragEvent &){return false;} virtual bool handle_drop(DropEvent &){return false;} virtual bool handle_mouse(MouseEvent &){return false;} virtual bool handle_wheel(WheelEvent &){return false;} virtual bool handle_resize(ResizeEvent &){return false;} virtual bool handle_motion(MotionEvent &){return false;} virtual bool handle_keyboard(KeyEvent &){return false;} virtual bool handle_textinput(TextInputEvent &){return false;} protected: WidgetAttr attr;//Widget attributes Rect rect = {0,0,0,0};//Widget rect std::list<Widget*> childrens; private: void dump_tree_impl(FILE *output,int depth); Font _font; Theme _theme; Widget *_parent = nullptr;//< Parent mutable WindowImpl *_window = nullptr;//<Window pointer friend class Window; friend class Layout; friend class WindowImpl; friend class Container; friend void PushEvent(Event *,Widget &); }; /** * @brief A Container of Widget(Abstract) * */ class BTKAPI Container:public Widget{ public: Container(){ attr.container = true; } Container(const Container &) = delete; ~Container() = default; public: /** * @brief Add a widget to the Container * * @tparam T * @tparam Args * @param args * @return The new widget ref */ template<class T,class ...Args> T& add(Args &&...args){ T *ptr = new T( std::forward<Args>(args)... ); add(static_cast<Widget*>(ptr)); return *ptr; } /** * @brief Add child * * @param w * @return true * @return false */ virtual bool add(Widget *w); /** * @brief Destroy all widget * */ virtual void clear(); /** * @brief Remove the widget in the container * * @param widget The widget pointer * @return true Successed to remove it * @return false The widget pointer is invaid */ virtual bool remove(Widget *widget); /** * @brief Detach the widget in the container * * @param widget The widget pointer * @return true Successed to Detach it * @return false The widget pointer is invaid */ virtual bool detach(Widget *widget); /** * @brief For each widget * * @tparam Callable * @tparam Args * @param callable * @param args */ template<class Callable,class ...Args> void for_each(Callable &&callable,Args &&...args){ if constexpr(std::is_same_v<std::invoke_result_t<Callable,Args...>,bool>){ //Has bool return type for(auto w:childrens){ if(not callable(w,std::forward<Args>(args)...)){ return; } } } else{ for(auto w:childrens){ callable(w,std::forward<Args>(args)...); } } } }; template<> inline FRect Widget::rectangle<float,FRect>() const noexcept{ return FRect(rect); } inline Widget *Widget::find_children(Vec2 position) const{ for(auto widget:childrens){ if(widget->rect.has_point(position)){ return widget; } } return nullptr; } class BTKAPI Line:public Widget{ public: Line(Orientation); Line(int x,int y,int w,int h,Orientation); ~Line(); void draw(Renderer &); private: Orientation orientation; }; } #endif // _BTK_WIDGET_HPP_
30.016
90
0.46322
[ "render", "object" ]
1e7bcd6c023d60810efd4936a766babdc2d0015a
688
cpp
C++
http-server/src/http-body-parser.cpp
cprkv/http-server
788ff90744846d29e0b60136eaca833f9e4c8702
[ "MIT" ]
null
null
null
http-server/src/http-body-parser.cpp
cprkv/http-server
788ff90744846d29e0b60136eaca833f9e4c8702
[ "MIT" ]
null
null
null
http-server/src/http-body-parser.cpp
cprkv/http-server
788ff90744846d29e0b60136eaca833f9e4c8702
[ "MIT" ]
null
null
null
#include "http-server/http-body-parser.hpp" using namespace http; //--------------------------------------------------------------- bool HttpBodyJson::parse(const std::string& body) { try { object = json::parse(body); } catch (...) { return false; } return true; } //--------------------------------------------------------------- std::unique_ptr<HttpBody> HttpBodyParser::parse(const std::string& content_type) { if (content_type.starts_with("application/json")) { auto body = std::make_unique<HttpBodyJson>(); if (body->parse(buffer_)) { return body; } } return nullptr; } //---------------------------------------------------------------
22.933333
82
0.465116
[ "object" ]
1e7cf4b5d0054c837a7bba1affb98d8570326c41
1,348
cpp
C++
hdu-winter-2020/problems/团与婚姻匹配/1001.cpp
songhn233/Algorithm-Packages
56d6f3c2467c175ab8a19b82bdfb25fc881e2206
[ "CC0-1.0" ]
1
2020-08-10T21:40:21.000Z
2020-08-10T21:40:21.000Z
hdu-winter-2020/problems/团与婚姻匹配/1001.cpp
songhn233/Algorithm-Packages
56d6f3c2467c175ab8a19b82bdfb25fc881e2206
[ "CC0-1.0" ]
null
null
null
hdu-winter-2020/problems/团与婚姻匹配/1001.cpp
songhn233/Algorithm-Packages
56d6f3c2467c175ab8a19b82bdfb25fc881e2206
[ "CC0-1.0" ]
null
null
null
#include<cstdio> #include<algorithm> #include<cstring> #include<iostream> #include<vector> #include<queue> #include<cmath> #include<map> #include<set> #define ll long long #define F(i,a,b) for(int i=(a);i<=(b);i++) #define mst(a,b) memset((a),(b),sizeof(a)) #define PII pair<int,int> using namespace std; template<class T>inline void read(T &x) { x=0; int ch=getchar(),f=0; while(ch<'0'||ch>'9'){if (ch=='-') f=1;ch=getchar();} while (ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+(ch^48);ch=getchar();} if(f)x=-x; } const int inf=0x3f3f3f3f; const int maxn=55; int n; int a[maxn][maxn],f[maxn],temp[maxn][maxn],ans,tot; bool dfs(int d,int num) { if(num==0) { if(d>ans) { ans=d; return true; } else return false; } for(int i=1;i<=num;i++) { if(d+num-i+1<=ans) return false; int v=temp[d][i]; if(d+f[v]<=ans) return false; int cnt=0; for(int j=i+1;j<=num;j++) { int vv=temp[d][j]; if(a[v][vv]) temp[d+1][++cnt]=vv; } if(dfs(d+1,cnt)) return true; } return false; } int main() { while(~scanf("%d",&n)) { if(n==0) break; memset(f,0,sizeof(f)); for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) read(a[i][j]); f[n]=ans=1; for(int i=n-1;i>=1;i--) { tot=0; for(int j=i+1;j<=n;j++) { if(a[i][j]) temp[1][++tot]=j; } dfs(1,tot); f[i]=ans; } cout<<ans<<endl; } return 0; }
18.465753
67
0.553412
[ "vector" ]
1e84be71e5291be08cc05407734a81af190ef3d3
4,230
cpp
C++
lib/InputDevice/DataFromMR3.cpp
mcx/rtosim
e8831e4e4b0ce2d82ffcb35b58387a1d4693c36f
[ "Apache-2.0" ]
21
2016-07-06T17:03:25.000Z
2022-03-17T02:18:53.000Z
lib/InputDevice/DataFromMR3.cpp
mcx/rtosim
e8831e4e4b0ce2d82ffcb35b58387a1d4693c36f
[ "Apache-2.0" ]
17
2016-07-06T06:14:58.000Z
2022-02-17T07:24:34.000Z
lib/InputDevice/DataFromMR3.cpp
mcx/rtosim
e8831e4e4b0ce2d82ffcb35b58387a1d4693c36f
[ "Apache-2.0" ]
14
2016-07-06T17:03:33.000Z
2022-02-09T11:36:56.000Z
#include "rtosim/DataFromMR3.h" #include "rtosim/EndOfData.h" using std::begin; using std::end; /* Components names from MR3 player device.player.player.mm_gait;line.human.head;type.input.motion.rot; device.player.player.mm_gait;line.human.spine.upper;type.input.motion.rot; device.player.player.mm_gait;line.human.lt.arm.upper;type.input.motion.rot; device.player.player.mm_gait;line.human.lt.arm.fore;type.input.motion.rot; device.player.player.mm_gait;line.human.lt.arm.hand;type.input.motion.rot; device.player.player.mm_gait;line.human.rt.arm.upper;type.input.motion.rot; device.player.player.mm_gait;line.human.rt.arm.fore;type.input.motion.rot; device.player.player.mm_gait;line.human.rt.arm.hand;type.input.motion.rot; device.player.player.mm_gait;line.human.spine.lower;type.input.motion.rot; device.player.player.mm_gait;line.human.pelvis;type.input.motion.rot; device.player.player.mm_gait;line.human.lt.leg.thigh;type.input.motion.rot; device.player.player.mm_gait;line.human.lt.leg.shank;type.input.motion.rot; device.player.player.mm_gait;line.human.lt.leg.foot;type.input.motion.rot; device.player.player.mm_gait;line.human.rt.leg.thigh;type.input.motion.rot; device.player.player.mm_gait;line.human.rt.leg.shank;type.input.motion.rot; device.player.player.mm_gait;line.human.rt.leg.foot;type.input.motion.rot; */ namespace rtosim { DataFromMR3::DataFromMR3( OrientationSetQueue& outputOrientationSetQueue, ScalarVectorQueue& outputEmgQueue, rtb::Concurrency::Latch& doneWithSubscriptions, rtb::Concurrency::Latch& doneWithExecution, FlowControl& runCondition, const std::vector<std::string>& orientationNames, const std::vector<std::string>& emgNames) : outputOrientationSetQueue_(outputOrientationSetQueue), outputEmgQueue_(outputEmgQueue), doneWithSubscriptions_(doneWithSubscriptions), doneWithExecution_(doneWithExecution), runCondition_(runCondition), orientationNames_(orientationNames), emgNames_(emgNames) {} void DataFromMR3::operator()() { MR3tools::DeviceInterface device(true); device.connect(); device.enableMotionData(); device.enableEmgData(); auto orientationNamesFromDevice(device.getEnabledMotionComponentNames()); if (orientationNames_.empty()) orientationNames_ = orientationNamesFromDevice; std::cout << "MotionData names from device\n"; for (auto& n : orientationNamesFromDevice) std::cout << n << std::endl; orientationMapper_.setNames(orientationNamesFromDevice, orientationNames_); auto emgNamesFromDevice(device.getEnabledEmgComponentNames()); if (emgNames_.empty()) emgNames_= emgNamesFromDevice; std::cout << "EmgData names from device\n"; for (auto& n : emgNamesFromDevice) std::cout << n << std::endl; emgMapper_.setNames(emgNamesFromDevice, emgNames_); device.activate(); doneWithSubscriptions_.wait(); while (runCondition_.getRunCondition()) { auto data = device.getData(); pushOrientationData(data); pushEmgData(data); } outputOrientationSetQueue_.push(EndOfData::get<OrientationSetFrame>()); device.disconnect(); doneWithExecution_.wait(); } void DataFromMR3::pushEmgData(const MR3tools::MR3Frame& dataFrame) { ScalarVectorFrame emgFrame; if (!dataFrame.emgData.empty()) { emgFrame.time = dataFrame.time; std::transform(begin(dataFrame.emgData), end(dataFrame.emgData), std::back_inserter(emgFrame.data), [](auto& e) { return e[0]; }); emgFrame.data = emgMapper_.map(emgFrame.data); outputEmgQueue_.push(emgFrame); } } void DataFromMR3::pushOrientationData(const MR3tools::MR3Frame& dataFrame) { OrientationSetFrame orientationFrame; if (!dataFrame.motionData.empty()) { orientationFrame.time = dataFrame.time; std::transform(begin(dataFrame.motionData), end(dataFrame.motionData), std::back_inserter(orientationFrame.data), [](auto& e) { return DataFromMR3::getFullQuaterion(e); }); orientationFrame.data = orientationMapper_.map(orientationFrame.data); outputOrientationSetQueue_.push(orientationFrame); } } }
37.767857
79
0.735934
[ "vector", "transform" ]
1e9025c3e76b36a884f98a45a26b299a6759a0be
3,170
cpp
C++
2018/0421_ARC096/E.cpp
kazunetakahashi/atcoder
16ce65829ccc180260b19316e276c2fcf6606c53
[ "MIT" ]
7
2019-03-24T14:06:29.000Z
2020-09-17T21:16:36.000Z
2018/0421_ARC096/E.cpp
kazunetakahashi/atcoder
16ce65829ccc180260b19316e276c2fcf6606c53
[ "MIT" ]
null
null
null
2018/0421_ARC096/E.cpp
kazunetakahashi/atcoder
16ce65829ccc180260b19316e276c2fcf6606c53
[ "MIT" ]
1
2020-07-22T17:27:09.000Z
2020-07-22T17:27:09.000Z
/** * File : E.cpp * Author : Kazune Takahashi * Created : 2018-5-16 21:22:53 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <random> // random_device rd; mt19937 mt(rd()); #include <chrono> // std::chrono::system_clock::time_point start_time, end_time; // start = std::chrono::system_clock::now(); // double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count(); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; const int MAX_SIZE = 1000010; long long MOD; long long inv[MAX_SIZE]; long long fact[MAX_SIZE]; long long factinv[MAX_SIZE]; void init() { inv[1] = 1; for (int i = 2; i < MAX_SIZE; i++) { inv[i] = ((MOD - inv[MOD % i]) * (MOD / i)) % MOD; } fact[0] = factinv[0] = 1; for (int i = 1; i < MAX_SIZE; i++) { fact[i] = (i * fact[i - 1]) % MOD; factinv[i] = (inv[i] * factinv[i - 1]) % MOD; } } long long C(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return ((fact[n] * factinv[k]) % MOD * factinv[n - k]) % MOD; } return 0; } long long power(long long x, long long n) { if (n == 0) { return 1; } else if (n % 2 == 1) { return (x * power(x, n - 1)) % MOD; } else { long long half = power(x, n / 2); return (half * half) % MOD; } } long long power_2_power(ll n) { if (n == 0) { return 2 % MOD; } ll half = power_2_power(n - 1); return (half * half) % MOD; } long long gcm(long long a, long long b) { if (a < b) { return gcm(b, a); } if (b == 0) return a; return gcm(b, a % b); } ll N; ll DP[3010][3010]; ll calc(ll n, ll k) { if (DP[n][k] != -1) { return DP[n][k]; } if (k == 0) { return DP[n][k] = 1; } else if (k == n) { return DP[n][k] = calc(n - 1, k - 1); } else { ll ans = calc(n - 1, k - 1); ans += ((k + 1) * calc(n - 1, k)) % MOD; ans %= MOD; return DP[n][k] = ans; } } ll f(ll k) { ll ans = power_2_power(N - k); ll sum = 0; for (auto x = 0; x <= k; x++) { sum += (calc(k, x) * power(2, x * (N - k))) % MOD; sum %= MOD; } return (ans * sum) % MOD; } int main() { cin >> N >> MOD; init(); fill(&DP[0][0], &DP[0][0] + 3010 * 3010, -1); ll X = 0; for (auto k = 0; k <= N; k++) { ll t = (C(N, k) * f(k)) % MOD; if (N < 100) { cerr << "k = " << k << ", t = " << t << endl; cerr << "f(" << k << ") = " << f(k) << endl; } if (k % 2 == 0) { X += t; } else { X += MOD - t; } X %= MOD; } cout << X << endl; }
18.430233
103
0.502839
[ "vector" ]
1e906f7a2c142acc87777d2a70000f0a6a47baa6
5,811
cpp
C++
libvvhd/src/XStreamfunction.cpp
rosik/vvflow
87caadf3973b31058a16a1372365ae8a7a157cdb
[ "MIT" ]
29
2020-08-05T16:08:35.000Z
2022-02-21T06:43:01.000Z
libvvhd/src/XStreamfunction.cpp
rosik/vvflow
87caadf3973b31058a16a1372365ae8a7a157cdb
[ "MIT" ]
6
2021-01-07T21:29:57.000Z
2021-06-28T20:54:04.000Z
libvvhd/src/XStreamfunction.cpp
rosik/vvflow
87caadf3973b31058a16a1372365ae8a7a157cdb
[ "MIT" ]
6
2020-07-24T06:53:54.000Z
2022-01-06T06:12:45.000Z
#include "XStreamfunction.hpp" #include "MFlowmove.hpp" #include "MEpsilonFast.hpp" #include "elementary.h" #include <cmath> #include <limits> using std::vector; XStreamfunction::XStreamfunction( const Space &S, double xmin, double ymin, double dxdy, int xres, int yres ): XField(xmin, ymin, dxdy, xres, yres), eps_mult(), ref_frame(), S(S), ref_frame_speed(), dl(S.average_segment_length()), rd2(sqr(0.2*dl)) {} inline static double _4pi_psi_g(TVec dr, double rd2, double g) { return -g * log(dr.abs2() + rd2); } inline static double _2pi_psi_q(TVec dr, double q) { return q * atan2(dr.y, dr.x); } inline static double _2pi_psi_qatt(TVec p, TVec att, TVec cofm, double q) { TVec v1 = cofm-p; TVec v2 = att-p; return -q * atan2(rotl(v2)*v1, v2*v1); } void XStreamfunction::evaluate() { if (eps_mult <= 0) throw std::invalid_argument("XStreamfunction(): eps_mult must be positive"); switch (ref_frame) { case 'o': ref_frame_speed = TVec(0, 0); break; case 'f': ref_frame_speed = S.inf_speed(); break; case 'b': ref_frame_speed = S.BodyList[0]->speed_slae.r; break; default: throw std::invalid_argument("XStreamfunction(): bad ref_frame"); } if (evaluated) return; S.HeatList.clear(); S.StreakList.clear(); S.StreakSourceList.clear(); // flowmove fm(&S); // fm.VortexShed(); double min_node_size = dl>0 ? dl*10 : 0; double max_node_size = dl>0 ? dl*20 : 1.0l/0.0l; TSortedTree tree(&S, 8, min_node_size, max_node_size); tree.build(); const vector<TSortedNode*>& bnodes = tree.getBottomNodes(); #pragma omp parallel { #pragma omp for for (auto llbnode = bnodes.cbegin(); llbnode < bnodes.cend(); llbnode++) { for (TObj *lobj = (**llbnode).vRange.first; lobj < (**llbnode).vRange.last; lobj++) { lobj->v.x = sqr(eps_mult)*std::max(MEpsilonFast::eps2h(**llbnode, lobj->r)*0.25, sqr(0.2*dl)); } } #pragma omp barrier // Calculate field ******************************************************** #pragma omp for collapse(2) schedule(dynamic, 256) for (int yj=0; yj<yres; yj++) { for (int xi=0; xi<xres; xi++) { TVec p = TVec(xmin, ymin) + dxdy*TVec(xi, yj); // double x = xmin + double(xi)*spacing; // double y = ymin + double(yj)*spacing; double psi_gap = 0; // mem[xi*dims[1]+yj] = streamfunction(S, &tree, TVec(x, y), spacing, psi_gap); const TSortedNode& bnode = *tree.findNode(p); map[yj*xres+xi] = streamfunction(bnode, p, &psi_gap); if (psi_gap) { #pragma omp critical gaps.emplace_back(xi, yj, psi_gap); } } } } evaluated = true; } // static double XStreamfunction::streamfunction(const Space &S, TVec p) { double tmp_4pi_psi_g = 0.0; double tmp_2pi_psi_q = 0.0; const double dl = S.average_segment_length(); const double rd2 = sqr(0.2*dl); for (auto& lbody: S.BodyList) { for (auto& latt: lbody->alist) { tmp_4pi_psi_g += _4pi_psi_g(p-latt.r, rd2, latt.g); } if (lbody->speed_slae.iszero()) continue; for (TAtt& latt: lbody->alist) { TVec Vs = lbody->speed_slae.r + lbody->speed_slae.o * rotl(latt.r - lbody->get_axis()); double g = -Vs * latt.dl; double q = -rotl(Vs) * latt.dl; tmp_4pi_psi_g += _4pi_psi_g(p-latt.r, rd2, g); tmp_2pi_psi_q += _2pi_psi_qatt(p, latt.r, lbody->get_cofm(), q); } } for (const TObj& src: S.SourceList) { tmp_2pi_psi_q += _2pi_psi_q(p-src.r, src.g); } for (const TObj& vrt: S.VortexList) { tmp_4pi_psi_g += _4pi_psi_g(p-vrt.r, rd2, vrt.g); } return tmp_4pi_psi_g*C_1_4PI + tmp_2pi_psi_q*C_1_2PI + p*rotl(S.inf_speed()); } double XStreamfunction::streamfunction(const TSortedNode &node, TVec p, double* psi_gap) const { double tmp_4pi_psi_g = 0.0; double tmp_2pi_psi_q = 0.0; *psi_gap = 0.0; for (auto& lbody: S.BodyList) { for (auto& latt: lbody->alist) { tmp_4pi_psi_g += _4pi_psi_g(p-latt.r, rd2, latt.g); } if (lbody->speed_slae.iszero()) continue; for (TAtt& latt: lbody->alist) { TVec Vs = lbody->speed_slae.r + lbody->speed_slae.o * rotl(latt.r - lbody->get_axis()); double g = -Vs * latt.dl; double q = -rotl(Vs) * latt.dl; tmp_4pi_psi_g += _4pi_psi_g(p-latt.r, rd2, g); tmp_2pi_psi_q += _2pi_psi_qatt(p, latt.r, lbody->get_cofm(), q); } } for (const auto& src: S.SourceList) { tmp_2pi_psi_q += _2pi_psi_q(p-src.r, src.g); if (p.x < src.r.x && src.r.x <= p.x+dxdy && p.y < src.r.y && src.r.y <= p.y+dxdy) { *psi_gap += src.g; } } for (TSortedNode* lfnode: *node.FarNodes) { tmp_4pi_psi_g += _4pi_psi_g(p-lfnode->CMp.r, rd2, lfnode->CMp.g); tmp_4pi_psi_g += _4pi_psi_g(p-lfnode->CMm.r, rd2, lfnode->CMm.g); } for (TSortedNode* lnnode: *node.NearNodes) { for (TObj *lobj = lnnode->vRange.first; lobj < lnnode->vRange.last; lobj++) { tmp_4pi_psi_g += _4pi_psi_g(p-lobj->r, lobj->v.x, lobj->g); // v.x stores eps^2 } } // printf("GAP %lf\n", psi_gap); return tmp_4pi_psi_g*C_1_4PI + tmp_2pi_psi_q*C_1_2PI + p*rotl(S.inf_speed() - ref_frame_speed); }
27.28169
110
0.548443
[ "vector" ]
1e9a55a0e4dd8c951ec14f172106344f4a77a410
11,768
cpp
C++
Win32xx/samples/ToolBarDemo/src/Mainfrm.cpp
mufunyo/VisionRGBApp
c09092770032150083eda171a22b1a3ef0914dab
[ "Unlicense" ]
2
2021-03-25T04:19:22.000Z
2021-05-03T03:23:30.000Z
Win32xx/samples/ToolBarDemo/src/Mainfrm.cpp
mufunyo/VisionRGBApp
c09092770032150083eda171a22b1a3ef0914dab
[ "Unlicense" ]
null
null
null
Win32xx/samples/ToolBarDemo/src/Mainfrm.cpp
mufunyo/VisionRGBApp
c09092770032150083eda171a22b1a3ef0914dab
[ "Unlicense" ]
1
2020-12-28T08:53:42.000Z
2020-12-28T08:53:42.000Z
//////////////////////////////////////////////////// // Mainfrm.cpp #include "stdafx.h" #include "mainfrm.h" #include "resource.h" // Definitions for the CMainFrame class CMainFrame::CMainFrame() : m_useBigIcons(FALSE) { // Constructor for CMainFrame. Its called after CFrame's constructor //Set m_View as the view window of the frame SetView(m_view); // Set the registry key name, and load the initial window position // Use a registry key name like "CompanyName\\Application" LoadRegistrySettings(_T("Win32++\\ToolBarDemo")); } CMainFrame::~CMainFrame() { // Destructor for CMainFrame. } LRESULT CMainFrame::OnBeginAdjust(LPNMTOOLBAR pNMTB) // Called when the user has begun customizing a toolbar. Here we save // a copy of the ToolBar layout so it can be restored when the user // selects the reset button. { CToolBar* pToolBar = static_cast<CToolBar*>(GetCWndPtr(pNMTB->hdr.hwndFrom)); assert (dynamic_cast<CToolBar*> (pToolBar)); int nResetCount = pToolBar->GetButtonCount(); m_resetButtons.clear(); for (int i = 0; i < nResetCount; i++) { TBBUTTON tbb; pToolBar->GetButton(i, tbb); m_resetButtons.push_back(tbb); } return TRUE; } BOOL CMainFrame::OnCommand(WPARAM wparam, LPARAM lparam) { // OnCommand responds to menu and and toolbar input UNREFERENCED_PARAMETER(lparam); UINT id = LOWORD(wparam); switch(id) { case IDM_FILE_OPEN: return OnFileOpen(); case IDM_FILE_SAVE: return OnFileSave(); case IDM_FILE_SAVEAS: return OnFileSave(); case IDM_FILE_PRINT: return OnFilePrint(); case IDM_FILE_EXIT: return OnFileExit(); case IDW_VIEW_STATUSBAR: return OnViewStatusBar(); case IDW_VIEW_TOOLBAR: return OnViewToolBar(); case IDM_TOOLBAR_CUSTOMIZE: return OnTBCustomize(); case IDM_TOOLBAR_DEFAULT: return OnTBDefault(); case IDM_TOOLBAR_BIGICONS: return OnTBBigIcons(); case IDM_HELP_ABOUT: return OnHelp(); } return FALSE; } int CMainFrame::OnCreate(CREATESTRUCT& cs) { // OnCreate controls the way the frame is created. // Overriding CFrame::OnCreate is optional. // A menu is added if the IDW_MAIN menu resource is defined. // Frames have all options enabled by default. // Use the following functions to disable options. // UseIndicatorStatus(FALSE); // Don't show keyboard indicators in the StatusBar // UseMenuStatus(FALSE); // Don't show menu descriptions in the StatusBar // UseReBar(FALSE); // Don't use a ReBar // UseStatusBar(FALSE); // Don't use a StatusBar // UseThemes(FALSE); // Don't use themes // UseToolBar(FALSE); // Don't use a ToolBar // call the base class function CFrame::OnCreate(cs); // Add the CCS_ADJUSTABLE style to the ToolBar DWORD style = GetToolBar().GetStyle(); GetToolBar().SetStyle(CCS_ADJUSTABLE|style); // Untick the Large Icons menu item GetFrameMenu().CheckMenuItem(IDM_TOOLBAR_BIGICONS, MF_BYCOMMAND | MF_UNCHECKED); return 0; } LRESULT CMainFrame::OnCustHelp(LPNMHDR pNMHDR) // Called when the help button on the customize dialog is pressed { UNREFERENCED_PARAMETER(pNMHDR); MessageBox(_T("Help Button Pressed"), _T("Help"), MB_ICONINFORMATION | MB_OK); return 0; } LRESULT CMainFrame::OnEndAdjust(LPNMHDR pNMHDR) // Called when the user has stopped customizing a toolbar. { UNREFERENCED_PARAMETER(pNMHDR); return TRUE; } BOOL CMainFrame::OnFileExit() { // Issue a close request to the frame PostMessage(WM_CLOSE); return TRUE; } BOOL CMainFrame::OnFileOpen() { CFileDialog fileDlg(TRUE); // Bring up the file open dialog retrieve the selected filename if (fileDlg.DoModal(*this) == IDOK) { // TODO: // Add your own code here. Refer to the tutorial for additional information } return TRUE; } BOOL CMainFrame::OnFileSave() { CFileDialog fileDlg(FALSE); // Bring up the file save dialog retrieve the selected filename if (fileDlg.DoModal(*this) == IDOK) { // TODO: // Add your own code here. Refer to the tutorial for additional information } return TRUE; } BOOL CMainFrame::OnFilePrint() { // Bring up a dialog to choose the printer CPrintDialog printdlg; try { INT_PTR result = printdlg.DoModal(*this); // Retrieve the printer DC // CDC dcPrinter = printdlg.GetPrinterDC(); // TODO: // Add your own code here. Refer to the tutorial for additional information return (result == IDOK); // boolean expression } catch (const CWinException& /* e */) { // No default printer MessageBox(_T("Unable to display print dialog"), _T("Print Failed"), MB_OK); return FALSE; } } void CMainFrame::OnInitialUpdate() { // The frame is now created. // Place any additional startup code here. TRACE("Frame created\n"); //Store the current ToolBar SaveTBDefault(); } LRESULT CMainFrame::OnNotify(WPARAM wparam, LPARAM lparam) // Process notification messages sent by child windows { LPNMTOOLBAR pNMTB = (LPNMTOOLBAR)lparam; switch(pNMTB->hdr.code) { case TBN_QUERYDELETE: return OnQueryDelete(pNMTB); case TBN_QUERYINSERT: return OnQueryInsert(pNMTB); case TBN_CUSTHELP: return OnCustHelp((LPNMHDR)lparam); case TBN_GETBUTTONINFO: return OnGetButtonInfo(pNMTB); case TBN_BEGINADJUST: return OnBeginAdjust(pNMTB); case TBN_ENDADJUST: return OnEndAdjust((LPNMHDR)lparam); case TBN_TOOLBARCHANGE: return OnToolBarChange(pNMTB); case TBN_RESET: return OnReset(pNMTB); } // Some notifications should return a value when handled return CFrame::OnNotify(wparam, lparam); } LRESULT CMainFrame::OnGetButtonInfo(LPNMTOOLBAR pNMTB) // Called once for each button during toolbar customization to populate the list // of available buttons. Return FALSE when all buttons have been added. { // An array of TBBUTTON that contains all possible buttons TBBUTTON buttonInfo[] = { { 0, IDM_FILE_NEW, TBSTATE_ENABLED, 0, {0}, 0, 0 }, { 1, IDM_FILE_OPEN, TBSTATE_ENABLED, 0, {0}, 0, 0 }, { 2, IDM_FILE_SAVE, TBSTATE_ENABLED, 0, {0}, 0, 0 }, { 3, IDM_EDIT_CUT, 0, 0, {0}, 0, 0 }, { 4, IDM_EDIT_COPY, 0, 0, {0}, 0, 0 }, { 5, IDM_EDIT_PASTE, 0, 0, {0}, 0, 0 }, { 6, IDM_FILE_PRINT, TBSTATE_ENABLED, 0, {0}, 0, 0 }, { 7, IDM_HELP_ABOUT, TBSTATE_ENABLED, 0, {0}, 0, 0 } }; // An array of Button text strings (LPCTSTRs). // These are displayed in the customize dialog. LPCTSTR buttonText[] = { _T("New Document"), _T("Open File"), _T("Save File"), _T("Cut"), _T("Copy"), _T("Paste"), _T("Print"), _T("Help About") }; // Pass the next button from the array. There is no need to filter out buttons // that are already used. They will be ignored. int buttons = sizeof(buttonInfo) / sizeof(TBBUTTON); if (pNMTB->iItem < buttons) { pNMTB->tbButton = buttonInfo[pNMTB->iItem]; StrCopy(pNMTB->pszText, buttonText[pNMTB->iItem], pNMTB->cchText); return TRUE; // Load the next button. } return FALSE; // No more buttons. } LRESULT CMainFrame::OnQueryDelete(LPNMTOOLBAR pNMTB) // Called when a button may be deleted from a toolbar while the user is customizing the toolbar. // Return TRUE to permit button deletion, and FALSE to prevent it. { UNREFERENCED_PARAMETER(pNMTB); // Permit all buttons to be deleted return TRUE; } LRESULT CMainFrame::OnQueryInsert(LPNMTOOLBAR pNMTB) // Called when a button may be inserted to the left of the specified button while the user // is customizing a toolbar. Return TRUE to permit button deletion, and FALSE to prevent it. { UNREFERENCED_PARAMETER(pNMTB); // Permit all buttons to be inserted return TRUE; } LRESULT CMainFrame::OnReset(LPNMTOOLBAR pNMTB) // Called when the user presses the Reset button on teh ToolBar customize dialog. // Here we restore the Toolbar to the settings saved in OnBeginAdjust. { CToolBar* pToolBar = static_cast<CToolBar*>(GetCWndPtr(pNMTB->hdr.hwndFrom)); assert (dynamic_cast<CToolBar*> (pToolBar)); // Remove all current buttons int nCount = pToolBar->GetButtonCount(); for (int i = nCount - 1; i >= 0; i--) { pToolBar->DeleteButton(i); } // Restore buttons from info stored in m_vTBBReset int nResetCount = static_cast<int>(m_resetButtons.size()); for (int j = 0; j < nResetCount; j++) { TBBUTTON tbb = m_resetButtons[j]; pToolBar->InsertButton(j, tbb); } RecalcLayout(); return TRUE; } LRESULT CMainFrame::OnToolBarChange(LPNMTOOLBAR pNMTB) // Called when the toolbar has been changed during customization. { UNREFERENCED_PARAMETER(pNMTB); // Reposition the toolbar RecalcLayout(); return TRUE; } BOOL CMainFrame::OnTBBigIcons() // Toggle the Image size for the ToolBar by changing Image Lists. { m_useBigIcons = !m_useBigIcons; GetFrameMenu().CheckMenuItem(IDM_TOOLBAR_BIGICONS, MF_BYCOMMAND | (m_useBigIcons ? MF_CHECKED : MF_UNCHECKED)); if (m_useBigIcons) { // Set Large Images. 3 Imagelists - Normal, Hot and Disabled SetToolBarImages(RGB(192,192,192), IDB_NORMAL, IDB_HOT, IDB_DISABLED); } else { // Set Small icons SetToolBarImages(RGB(192,192,192), IDW_MAIN, 0, 0); } RecalcLayout(); GetToolBar().Invalidate(); return TRUE; } BOOL CMainFrame::OnTBCustomize() { // Customize CFrame's Toolbar GetToolBar().Customize(); return TRUE; } BOOL CMainFrame::OnTBDefault() // Set the Toolbar back to its intial settings. { // Remove all current buttons int count = GetToolBar().GetButtonCount(); for (int i = count - 1; i >= 0; i--) { GetToolBar().DeleteButton(i); } // Restore buttons from info stored in m_vTBBDefault int nDefaultCount = static_cast<int>(m_defaultButtons.size()); for (int j = 0; j < nDefaultCount; j++) { TBBUTTON tbb = m_defaultButtons[j]; GetToolBar().InsertButton(j, tbb); } RecalcLayout(); return TRUE; } void CMainFrame::SaveTBDefault() // Saves the initial Toolbar configuration in a vector of TBBUTTON { int nCount = GetToolBar().GetButtonCount(); for (int i = 0; i < nCount; i++) { TBBUTTON tbb; GetToolBar().GetButton(i, tbb); m_defaultButtons.push_back(tbb); } } void CMainFrame::SetupToolBar() { // Set the Resource IDs for the toolbar buttons AddToolBarButton( IDM_FILE_NEW ); AddToolBarButton( IDM_FILE_OPEN ); AddToolBarButton( IDM_FILE_SAVE ); AddToolBarButton( 0 ); // Separator AddToolBarButton( IDM_EDIT_CUT, FALSE ); // disabled button AddToolBarButton( IDM_EDIT_COPY, FALSE ); // disabled button AddToolBarButton( IDM_EDIT_PASTE, FALSE ); // disabled button AddToolBarButton( 0 ); // Separator AddToolBarButton( IDM_FILE_PRINT ); AddToolBarButton( 0 ); // Separator AddToolBarButton( IDM_HELP_ABOUT ); } LRESULT CMainFrame::WndProc(UINT msg, WPARAM wparam, LPARAM lparam) { // switch (msg) // { // Add case statements for each messages to be handled here // } // pass unhandled messages on for default processing return WndProcDefault(msg, wparam, lparam); }
28.702439
115
0.652787
[ "vector" ]
1ea1b5b741b0a3102606fcb62b74f5bc42c65457
2,477
hpp
C++
rclpy/src/rclpy/action_goal_handle.hpp
RoboStack/rclpy
c67e43a69a1580eeac4a90767e24ceeea31a298e
[ "Apache-2.0" ]
121
2015-11-19T19:46:09.000Z
2022-03-17T16:36:52.000Z
rclpy/src/rclpy/action_goal_handle.hpp
RoboStack/rclpy
c67e43a69a1580eeac4a90767e24ceeea31a298e
[ "Apache-2.0" ]
759
2016-01-29T01:44:19.000Z
2022-03-30T13:37:26.000Z
rclpy/src/rclpy/action_goal_handle.hpp
RoboStack/rclpy
c67e43a69a1580eeac4a90767e24ceeea31a298e
[ "Apache-2.0" ]
160
2016-01-12T16:56:21.000Z
2022-03-22T23:20:35.000Z
// Copyright 2021 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef RCLPY__ACTION_GOAL_HANDLE_HPP_ #define RCLPY__ACTION_GOAL_HANDLE_HPP_ #include <pybind11/pybind11.h> #include <rcl_action/rcl_action.h> #include <memory> #include "action_server.hpp" #include "destroyable.hpp" namespace py = pybind11; namespace rclpy { class ActionServer; class ActionGoalHandle : public Destroyable, public std::enable_shared_from_this<ActionGoalHandle> { public: /// Create an action goal handle /** * This function will create an action goal handle for the given info message from the action server. * This action goal handle will use the typesupport defined in the service module * provided as pysrv_type to send messages. * * Raises RCLError if the action goal handle could not be created * * \param[in] pyaction_server handle to the action server that is accepting the goal * \param[in] pygoal_info_msg a message containing info about the goal being accepted */ ActionGoalHandle(rclpy::ActionServer & action_server, py::object pygoal_info_msg); ~ActionGoalHandle() = default; rcl_action_goal_state_t get_status(); void update_goal_state(rcl_action_goal_event_t event); /// Check if the goal is still active bool is_active() { return rcl_action_goal_handle_is_active(rcl_ptr()); } /// Get rcl_action goal handle_t pointer rcl_action_goal_handle_t * rcl_ptr() const { return rcl_action_goal_handle_.get(); } /// Force an early destruction of this object void destroy() override; private: ActionServer action_server_; std::shared_ptr<rcl_action_goal_handle_t> rcl_action_goal_handle_; }; /// Define a pybind11 wrapper for an rclpy::ActionGoalHandle /** * \param[in] module a pybind11 module to add the definition to */ void define_action_goal_handle(py::module module); } // namespace rclpy #endif // RCLPY__ACTION_GOAL_HANDLE_HPP_
27.522222
103
0.754945
[ "object" ]
1ea3c2f7fc6407f92fbadda757596445355afa20
63,439
cpp
C++
Entregas/ACM_Proyecto01/sudoku.cpp
cesar-magana/Advanced_Programming
7b5ff09cd2816b67ca9f68d5ede211c73fb73de5
[ "MIT" ]
null
null
null
Entregas/ACM_Proyecto01/sudoku.cpp
cesar-magana/Advanced_Programming
7b5ff09cd2816b67ca9f68d5ede211c73fb73de5
[ "MIT" ]
null
null
null
Entregas/ACM_Proyecto01/sudoku.cpp
cesar-magana/Advanced_Programming
7b5ff09cd2816b67ca9f68d5ede211c73fb73de5
[ "MIT" ]
null
null
null
/*------------------------------------------------------------ PROGRAMACIÓN AVANZADA I PROYECTO SUDOKU César Magaña cesar@cimat.mx --------------------------------------------------------------*/ //#include "config.h" #include <iostream> #include <string> #include <map> #include <set> #include <stdlib.h> #include <sys/time.h> #include <vector> #define GRID_SIZE 3 #define COL_HEIGHT (GRID_SIZE*GRID_SIZE) #define ROW_LENGTH (GRID_SIZE*GRID_SIZE) #define SEC_SIZE (GRID_SIZE*GRID_SIZE) #define SEC_COUNT (GRID_SIZE*GRID_SIZE) #define SEC_GROUP_SIZE (SEC_SIZE*GRID_SIZE) #define NUM_POSS (GRID_SIZE*GRID_SIZE) #define BOARD_SIZE (ROW_LENGTH*COL_HEIGHT) #define POSSIBILITY_SIZE (BOARD_SIZE*NUM_POSS) #define FOR(i, n) for( int i = 0, _n = (n); i < _n; i++ ) using namespace std; class Sudoku; class Log; string IntToString(int num); long Time(); void ShuffleArray(int* array, int size); bool ReadBoardFromStdIn(int* grid); int main(int argc, char *argv[]); void PrintHelp(char* programName); void PrintVersion(); void PrintAbout(); static inline int CellToColumn(int cell); static inline int CellToRow(int cell); static inline int CellToSectionStartCell(int cell); static inline int CellToSection(int cell); static inline int RowToFirstCell(int row); static inline int ColumnToFirstCell(int column); static inline int SectionToFirstCell(int section); static inline int GetPossibilityIndex(int valueIndex, int cell); static inline int RowColumnToCell(int row, int column); static inline int SectionToCell(int section, int offset); /** * Esta estructura contiene funciones para generar y * resolver tableros de sudoku. */ //------------------------------------------------------------ class Sudoku { public: //Variables públicas. enum Difficulty {UNKNOWN,SIMPLE,EASY,INTERMEDIATE,EXPERT}; enum ConsolePrintStyle {ONE_LINE,COMPACT,READABLE,CSV}; //Funciones públicas. Sudoku(); ~Sudoku(); bool Solve(); bool IsSolved(); bool CreateBoard(); bool SetBoard(int* initPuzzle); int CountSolutions(); int GetGivenCount(); int GetSingleCount(); int GetHiddenSingleCount(); int GetNakedPairCount(); int GetHiddenPairCount(); int GetBoxLineReductionCount(); int GetPointingPairTripleCount(); int GetGuessCount(); int GetBacktrackCount(); void SetRecordHistory(bool rec_history); void SetLogHistory(bool logHist); void SetConsolePrintStyle(ConsolePrintStyle ps); void Show(); void ShowSolution(); void PrintPossibilities(); void PrintSolveHistory(); void PrintSolveInstructions(); Sudoku::Difficulty GetDifficulty(); string GetDifficultyAsString(); private: //Variables privadas: /** * Los 81 enteros que forman el tablero de sudoku. * Valores dados son 1-9, desconocidos 0. * Una vez inicializado no se vuelve a mover. */ int* grid; /** * Los 81 enteros que forman el tablero de sudoku. * Aquí se presenta la solución. * Se llena con valores de 1-9. */ int* solution; /** * Profundidad de la recursión a la cual cada uno de los números * en la solución fueron colocados. Useful for backing * out solve branches that don't lead to a solution. */ int* solution_round; /** * Los 729 enteros que forman las posibles soluciones * para un tablero de sudoku. (9 posibilidades * por cada uno de las 81 casillas). Si vpossibilities[i] * es 0, entonces la casilla todavía puede ser * llenada de acuerdo a las reglas del sudoku. */ int* possibilities; /** * Un vector del tamaño del tablero (81) conteniendo cada uno * los números 0-n exactamente una vez. */ int* random_board_array; /** * Un vector con un elemento por cada posición (9) en * orden aleatorio. */ int* random_possibility_array; /** * Cuando guardar historia o no. */ bool record_history; /** * Whether or not to print history as it happens */ bool log_history; /** * Lista de movimientos usados para resolver el sudoku. * Esta lista contiene todos los movientos, incluso * ramas que no llevan a una solución. */ vector<Log*>* vsolve_history; /** * Lista de movimientos usados para resolver el sudoku. * Esta lista contiene sólamente los movimientos usados * para resolver el sudoku, pero no contiene * información de "bad guesses". */ vector<Log*>* vsolve_instructions; ConsolePrintStyle print_style; int last_solve_round; //Funciones privadas void ClearBoard(); int CountSolutions(int round, bool limit_to_two); bool Guess(int round, int guess_number); bool IsImpossible(); void RollbackRound(int round); bool PointingRowReduction(int round); bool RowBoxReduction(int round); bool ColBoxReduction(int round); bool PointingColumnReduction(int round); bool HiddenPairInRow(int round); bool HiddenPairInColumn(int round); bool HiddenPairInSection(int round); void Mark(int position, int round, int value); int FindPositionWithFewestPossibilities(); bool HandleNakedPairs(int round); int CountPossibilities(int position); bool ArePossibilitiesSame(int position1, int position2); void AddHistoryItem(Log* l); void MarkRandomPossibility(int round); void ShuffleRandomArrays(); void Print(int* sudoku); void RollbackNonGuesses(); bool OnlyPossibilityForCell(int round); bool OnlyValueInRow(int round); bool OnlyValueInColumn(int round); bool OnlyValueInSection(int round); void ShowHistory(vector<Log*>* v); bool RemovePossibilitiesInOneFromTwo(int position1, int position2, int round); bool SingleSolveMove(int round); bool Solve(int round); bool Reset(); }; /** * Clase para guardar los logs. * */ //------------------------------------------------------------ class Log { public: //Variables públicas. enum LogType { GIVEN, SINGLE, HIDDEN_SINGLE_ROW, HIDDEN_SINGLE_COLUMN, HIDDEN_SINGLE_SECTION, GUESS, ROLLBACK, NAKED_PAIR_ROW, NAKED_PAIR_COLUMN, NAKED_PAIR_SECTION, POINTING_PAIR_TRIPLE_ROW, POINTING_PAIR_TRIPLE_COLUMN, ROW_BOX, COLUMN_BOX, HIDDEN_PAIR_ROW, HIDDEN_PAIR_COLUMN, HIDDEN_PAIR_SECTION, }; //Funciones públicas int GetRound(); void Print(); LogType getType(); Log(int round, LogType type); Log(int round, LogType type, int value, int position); ~Log(); private: //Variables privadas. int round; LogType type; int value; int position; //Funciones privadas. void init(int round, LogType type, int value, int position); }; int GetLogCount(vector<Log*>* v, Log::LogType type); //------------------------------------------------------------ void PrintVersion(){ } //------------------------------------------------------------ void PrintAbout(){ } /** * Función para modo consola. Muestra la ayuda. */ //------------------------------------------------------------ void PrintHelp(char* name){ cout << name << " <opciones>" << endl; cout << "Lista de comandos disponibles." << endl; cout << " --generate <#> Genera uno varios tablero de sudoku." << endl; cout << " --solve Resuelve los tableros de sudoku de stdin." << endl; cout << " --difficulty <D> Cambia la dificultad cuando se genera: very_easy, easy, normal, hard." << endl; cout << " --show Muestra el tablero (por default cuando se genera)." << endl; cout << " --dontshow No muestra el tablero (por default cuando se soluciona)." << endl; cout << " --solution Muestra la solucion (por default cuando se soluciona)." << endl; cout << " --nosolution No se muestra la solucion (por default cuando se genera)." << endl; cout << " --stats Muestra estadisticas" << endl; cout << " --nostats No muestra estadisticas (por default)" << endl; cout << " --time Muestra el tiempo de generacion o solucion de un tablero." << endl; cout << " --count-solutions Cuenta el numero de soluciones." << endl; cout << " --history Muestra ensayo y error." << endl; cout << " --instructions Muestra los pasos." << endl; cout << " --log-history Muestra ensayo y error conforme sucede." << endl; cout << " --one-line Muestra el tablero en una linea de 81 caracteres." << endl; cout << " --compact Muestra el tablero en nueve lineas de nueve caracteres" << endl; cout << " --board Muestra el tablero de manera legible." << endl; cout << " --csv Muestra el tablero en formato csv." << endl; cout << " --help Muestra la ayuda." << endl; cout << " --about Visualiza informacion del proyecto." << endl; cout << " --version Muestra Version" << endl; } /** * Constructor de la clase. Crea un nuevo tablero de Sudoku. */ //------------------------------------------------------------ Sudoku::Sudoku(){ grid = new int[BOARD_SIZE]; solution = new int[BOARD_SIZE]; solution_round = new int[BOARD_SIZE]; possibilities = new int[POSSIBILITY_SIZE]; record_history = false; print_style = READABLE; random_board_array = new int[BOARD_SIZE]; random_possibility_array = new int[NUM_POSS]; vsolve_history = new vector<Log*>(); vsolve_instructions = new vector<Log*>(); FOR (i,BOARD_SIZE) random_board_array[i] = i; FOR (i,NUM_POSS) random_possibility_array[i] = i; } /** * Número de celdas que están * fijas en el tablero */ //------------------------------------------------------------ int Sudoku::GetGivenCount(){ int count = 0; FOR (i,BOARD_SIZE) if (grid[i] != 0) count++; return count; } /** * Llena el tablero. */ //------------------------------------------------------------ bool Sudoku::SetBoard(int* init_grid){ FOR (i,BOARD_SIZE) grid[i] = (init_grid==NULL)?0:init_grid[i]; return Reset(); } /** * Inicializa el tablero a su estado inicial */ //------------------------------------------------------------ bool Sudoku::Reset(){ FOR (i,BOARD_SIZE) { solution[i] = 0; solution_round[i] = 0; } FOR (i,POSSIBILITY_SIZE) possibilities[i] = 0; FOR (i,vsolve_history->size()) delete vsolve_history->at(i); vsolve_history->clear(); vsolve_instructions->clear(); int round = 1; FOR (position,BOARD_SIZE) { if (grid[position] > 0) { int val_index = grid[position]-1; int val_pos = GetPossibilityIndex(val_index,position); int value = grid[position]; if (possibilities[val_pos] != 0) return false; Mark(position,round,value); if (log_history || record_history) AddHistoryItem(new Log(round, Log::GIVEN, value, position)); } } return true; } /** * Regresa el nivel de dificultad. */ //------------------------------------------------------------ Sudoku::Difficulty Sudoku::GetDifficulty(){ if (GetGuessCount() > 0) return Sudoku::EXPERT; if (GetBoxLineReductionCount() > 0) return Sudoku::INTERMEDIATE; if (GetPointingPairTripleCount() > 0) return Sudoku::INTERMEDIATE; if (GetHiddenPairCount() > 0) return Sudoku::INTERMEDIATE; if (GetNakedPairCount() > 0) return Sudoku::INTERMEDIATE; if (GetHiddenSingleCount() > 0) return Sudoku::EASY; if (GetSingleCount() > 0) return Sudoku::SIMPLE; return Sudoku::UNKNOWN; } /** * Regresa la dificultad como string. */ //------------------------------------------------------------ string Sudoku::GetDifficultyAsString(){ Sudoku::Difficulty difficulty = GetDifficulty(); switch (difficulty){ case Sudoku::EXPERT: return "Hard"; break; case Sudoku::INTERMEDIATE: return "Normal"; break; case Sudoku::EASY: return "Easy"; break; case Sudoku::SIMPLE: return "Very easy"; break; default: return "Unknown"; break; } } /** * Regresa el número de celdas para las cuales la solución ya fue determinada */ //------------------------------------------------------------ int Sudoku::GetSingleCount(){ return GetLogCount(vsolve_instructions, Log::SINGLE); } //------------------------------------------------------------ int Sudoku::GetHiddenSingleCount(){ return GetLogCount(vsolve_instructions, Log::HIDDEN_SINGLE_ROW) + GetLogCount(vsolve_instructions, Log::HIDDEN_SINGLE_COLUMN) + GetLogCount(vsolve_instructions, Log::HIDDEN_SINGLE_SECTION); } //------------------------------------------------------------ int Sudoku::GetNakedPairCount(){ return GetLogCount(vsolve_instructions, Log::NAKED_PAIR_ROW) + GetLogCount(vsolve_instructions, Log::NAKED_PAIR_COLUMN) + GetLogCount(vsolve_instructions, Log::NAKED_PAIR_SECTION); } //------------------------------------------------------------ int Sudoku::GetHiddenPairCount(){ return GetLogCount(vsolve_instructions, Log::HIDDEN_PAIR_ROW) + GetLogCount(vsolve_instructions, Log::HIDDEN_PAIR_COLUMN) + GetLogCount(vsolve_instructions, Log::HIDDEN_PAIR_SECTION); } //------------------------------------------------------------ int Sudoku::GetPointingPairTripleCount(){ return GetLogCount(vsolve_instructions, Log::POINTING_PAIR_TRIPLE_ROW)+ GetLogCount(vsolve_instructions, Log::POINTING_PAIR_TRIPLE_COLUMN); } //------------------------------------------------------------ int Sudoku::GetBoxLineReductionCount(){ return GetLogCount(vsolve_instructions, Log::ROW_BOX)+ GetLogCount(vsolve_instructions, Log::COLUMN_BOX); } //------------------------------------------------------------ int Sudoku::GetGuessCount(){ return GetLogCount(vsolve_instructions, Log::GUESS); } //------------------------------------------------------------ int Sudoku::GetBacktrackCount(){ return GetLogCount(vsolve_history, Log::ROLLBACK); } //------------------------------------------------------------ void Sudoku::MarkRandomPossibility(int round){ int remaining_possibilities = 0; FOR(i,POSSIBILITY_SIZE) if (possibilities[i] == 0) remaining_possibilities++; int random_possibility = rand()%remaining_possibilities; int possibility_to_mark = 0; FOR(i,POSSIBILITY_SIZE) { if (possibilities[i] == 0) { if (possibility_to_mark == random_possibility) { int position = i/NUM_POSS; int value = i%NUM_POSS+1; Mark(position, round, value); return; } possibility_to_mark++; } } } //------------------------------------------------------------ void Sudoku::ShuffleRandomArrays(){ ShuffleArray(random_board_array, BOARD_SIZE); ShuffleArray(random_possibility_array, NUM_POSS); } /** * Borra cualquier tablero existente anteriormente. */ //------------------------------------------------------------ void Sudoku::ClearBoard() { FOR (i,BOARD_SIZE) grid[i]=0; Reset(); } /** * Inicializa el tablero de sudoku aleatoriamente. */ //------------------------------------------------------------ bool Sudoku::CreateBoard(){ bool rec_history = record_history; SetRecordHistory(false); bool l_history = log_history; SetLogHistory(false); ClearBoard(); ShuffleRandomArrays(); Solve(); RollbackNonGuesses(); FOR (i,BOARD_SIZE) grid[i] = solution[i]; ShuffleRandomArrays(); FOR (i,BOARD_SIZE) { int position = random_board_array[i]; if (grid[position] > 0) { int savedValue = grid[position]; grid[position] = 0; Reset(); if (CountSolutions(2, true) > 1) grid[position] = savedValue; } } Reset(); SetRecordHistory(rec_history); SetLogHistory(l_history); return true; } //------------------------------------------------------------ void Sudoku::RollbackNonGuesses(){ for (int i=2; i<=last_solve_round; i+=2) RollbackRound(i); } //------------------------------------------------------------ void Sudoku::SetConsolePrintStyle(ConsolePrintStyle ps){ print_style = ps; } //------------------------------------------------------------ void Sudoku::SetRecordHistory(bool rec_history){ record_history = rec_history; } //------------------------------------------------------------ void Sudoku::SetLogHistory(bool logHist){ log_history = logHist; } //------------------------------------------------------------ void Sudoku::AddHistoryItem(Log* l){ if (log_history) { l->Print(); cout << endl; } if (record_history) { vsolve_history->push_back(l); vsolve_instructions->push_back(l); } else delete l; } //------------------------------------------------------------ void Sudoku::ShowHistory(vector<Log*>* v){ if (!record_history) { cout << "No se guardo la historia."; if (print_style == CSV) cout << " -- "; else cout << endl; } FOR (i,v->size()) { cout << i+1 << ". "; v->at(i)->Print(); if (print_style == CSV) cout << " -- "; else cout << endl; } if (print_style == CSV) cout << ","; else cout << endl; } //------------------------------------------------------------ void Sudoku::PrintSolveInstructions(){ if (IsSolved()) ShowHistory(vsolve_instructions); else cout << "No existe solucion." << endl; } //------------------------------------------------------------ void Sudoku::PrintSolveHistory(){ ShowHistory(vsolve_history); } //------------------------------------------------------------ bool Sudoku::Solve(){ Reset(); ShuffleRandomArrays(); return Solve(2); } //------------------------------------------------------------ bool Sudoku::Solve(int round){ last_solve_round = round; while (SingleSolveMove(round)) { if (IsSolved()) return true; if (IsImpossible()) return false; } int next_guess_round = round+1; int next_round = round+2; for (int guess_number=0; Guess(next_guess_round, guess_number); guess_number++) { if (IsImpossible() || !Solve(next_round)) { RollbackRound(next_round); RollbackRound(next_guess_round); } else return true; } return false; } //------------------------------------------------------------ int Sudoku::CountSolutions(){ bool rec_history = record_history; SetRecordHistory(false); bool l_history = log_history; SetLogHistory(false); Reset(); int solution_count = CountSolutions(2, false); SetRecordHistory(rec_history); SetLogHistory(l_history); return solution_count; } //------------------------------------------------------------ int Sudoku::CountSolutions(int round, bool limit_to_two){ while (SingleSolveMove(round)) { if (IsSolved()) { RollbackRound(round); return 1; } if (IsImpossible()) { RollbackRound(round); return 0; } } int solutions = 0; int next_round = round+1; for (int guess_number=0; Guess(next_round, guess_number); guess_number++) { solutions += CountSolutions(next_round, limit_to_two); if (limit_to_two && solutions >=2) { RollbackRound(round); return solutions; } } RollbackRound(round); return solutions; } //------------------------------------------------------------ void Sudoku::RollbackRound(int round){ if (log_history || record_history) AddHistoryItem(new Log(round, Log::ROLLBACK)); FOR (i,BOARD_SIZE) { if (solution_round[i] == round) { solution_round[i] = 0; solution[i] = 0; } } FOR (i,POSSIBILITY_SIZE) { if (possibilities[i] == round) possibilities[i] = 0; } while(vsolve_instructions->size() > 0 && vsolve_instructions->back()->GetRound() == round) vsolve_instructions->pop_back(); } //------------------------------------------------------------ bool Sudoku::IsSolved(){ FOR (i,BOARD_SIZE) { if (solution[i] == 0) return false; } return true; } //------------------------------------------------------------ bool Sudoku::IsImpossible(){ FOR (position,BOARD_SIZE) { if (solution[position] == 0) { int count = 0; FOR (val_index,NUM_POSS) { int val_pos = GetPossibilityIndex(val_index,position); if (possibilities[val_pos] == 0) count++; } if (count == 0) return true; } } return false; } //------------------------------------------------------------ int Sudoku::FindPositionWithFewestPossibilities(){ int min_possibilities = 10; int best_position = 0; FOR (i,BOARD_SIZE) { int position = random_board_array[i]; if (solution[position] == 0) { int count = 0; FOR (val_index,NUM_POSS) { int val_pos = GetPossibilityIndex(val_index,position); if (possibilities[val_pos] == 0) count++; } if (count < min_possibilities) { min_possibilities = count; best_position = position; } } } return best_position; } //------------------------------------------------------------ bool Sudoku::Guess(int round, int guess_number){ int local_guess_count = 0; int position = FindPositionWithFewestPossibilities(); FOR(i,NUM_POSS) { int val_index = random_possibility_array[i]; int val_pos = GetPossibilityIndex(val_index,position); if (possibilities[val_pos] == 0) { if (local_guess_count == guess_number) { int value = val_index+1; if (log_history || record_history) AddHistoryItem(new Log(round, Log::GUESS, value, position)); Mark(position, round, value); return true; } local_guess_count++; } } return false; } //------------------------------------------------------------ bool Sudoku::SingleSolveMove(int round){ if (OnlyPossibilityForCell(round)) return true; if (OnlyValueInSection(round)) return true; if (OnlyValueInRow(round)) return true; if (OnlyValueInColumn(round)) return true; if (HandleNakedPairs(round)) return true; if (PointingRowReduction(round)) return true; if (PointingColumnReduction(round)) return true; if (RowBoxReduction(round)) return true; if (ColBoxReduction(round)) return true; if (HiddenPairInRow(round)) return true; if (HiddenPairInColumn(round)) return true; if (HiddenPairInSection(round)) return true; return false; } //------------------------------------------------------------ bool Sudoku::ColBoxReduction(int round){ FOR (val_index,NUM_POSS) { FOR(col,9) { int col_start = ColumnToFirstCell(col); bool in_one_box = true; int col_box = -1; FOR (i,3) { FOR(j,3) { int row = i*3+j; int position = RowColumnToCell(row, col); int val_pos = GetPossibilityIndex(val_index,position); if(possibilities[val_pos] == 0) { if (col_box == -1 || col_box == i) col_box = i; else in_one_box = false; } } } if (in_one_box && col_box != -1) { bool finish_something = false; int row = 3*col_box; int sec_start = CellToSectionStartCell(RowColumnToCell(row, col)); int sec_start_row = CellToRow(sec_start); int sec_start_col = CellToColumn(sec_start); FOR (i,3) { FOR(j,3) { int row2 = sec_start_row+i; int col2 = sec_start_col+j; int position = RowColumnToCell(row2, col2); int val_pos = GetPossibilityIndex(val_index,position); if (col != col2 && possibilities[val_pos] == 0) { possibilities[val_pos] = round; finish_something = true; } }//FOR j }//FOR i if (finish_something) { if (log_history || record_history) AddHistoryItem(new Log(round, Log::COLUMN_BOX, val_index+1, col_start)); return true; } } }//FOR col }//FOR val_index return false; } //------------------------------------------------------------ bool Sudoku::RowBoxReduction(int round){ FOR (val_index,NUM_POSS) { FOR(row,9) { int row_start = RowToFirstCell(row); bool in_one_box = true; int rowBox = -1; FOR(i,3) { FOR (j,3) { int column = i*3+j; int position = RowColumnToCell(row, column); int val_pos = GetPossibilityIndex(val_index,position); if(possibilities[val_pos] == 0) { if (rowBox == -1 || rowBox == i) rowBox = i; else in_one_box = false; } }//FOR j }//FOR i if (in_one_box && rowBox != -1) { bool finish_something = false; int column = 3*rowBox; int sec_start = CellToSectionStartCell(RowColumnToCell(row, column)); int sec_start_row = CellToRow(sec_start); int sec_start_col = CellToColumn(sec_start); FOR (i,3) { FOR(j,3) { int row2 = sec_start_row+i; int col2 = sec_start_col+j; int position = RowColumnToCell(row2, col2); int val_pos = GetPossibilityIndex(val_index,position); if (row != row2 && possibilities[val_pos] == 0) { possibilities[val_pos] = round; finish_something = true; } }//FOR j }//FOR i if (finish_something) { if (log_history || record_history) AddHistoryItem(new Log(round, Log::ROW_BOX, val_index+1, row_start)); return true; } } }//FOR row }//FOR val_index return false; } //------------------------------------------------------------ bool Sudoku::PointingRowReduction(int round){ FOR (val_index,NUM_POSS) { FOR (section,9) { int sec_start = SectionToFirstCell(section); bool in_one_row = true; int boxRow = -1; FOR(j,3) { FOR (i,3) { int sec_val=sec_start+i+(9*j); int val_pos = GetPossibilityIndex(val_index,sec_val); if(possibilities[val_pos] == 0) { if (boxRow == -1 || boxRow == j) boxRow = j; else in_one_row = false; } } }//FOR j if (in_one_row && boxRow != -1) { bool finish_something = false; int row = CellToRow(sec_start) + boxRow; int row_start = RowToFirstCell(row); FOR (i,9) { int position = row_start+i; int section2 = CellToSection(position); int val_pos = GetPossibilityIndex(val_index,position); if (section != section2 && possibilities[val_pos] == 0) { possibilities[val_pos] = round; finish_something = true; } } if (finish_something){ if (log_history || record_history) AddHistoryItem(new Log(round, Log::POINTING_PAIR_TRIPLE_ROW, val_index+1, row_start)); return true; } } }//FOR section }//FOR val_index return false; } //------------------------------------------------------------ bool Sudoku::PointingColumnReduction(int round){ FOR (val_index,NUM_POSS) { FOR(section,9) { int sec_start = SectionToFirstCell(section); bool in_one_col = true; int box_col = -1; FOR (i,3) { FOR(j,3) { int sec_val=sec_start+i+(9*j); int val_pos = GetPossibilityIndex(val_index,sec_val); if(possibilities[val_pos] == 0) { if (box_col == -1 || box_col == i) box_col = i; else in_one_col = false; } }//FOR j }//FOR i if (in_one_col && box_col != -1) { bool finish_something = false; int col = CellToColumn(sec_start) + box_col; int col_start = ColumnToFirstCell(col); FOR(i,9) { int position = col_start+(9*i); int section2 = CellToSection(position); int val_pos = GetPossibilityIndex(val_index,position); if (section != section2 && possibilities[val_pos] == 0) { possibilities[val_pos] = round; finish_something = true; } }//FOR i if (finish_something) { if (log_history || record_history) AddHistoryItem(new Log(round, Log::POINTING_PAIR_TRIPLE_COLUMN, val_index+1, col_start)); return true; } } }//FOR section }//FOR val_index return false; } //------------------------------------------------------------ int Sudoku::CountPossibilities(int position){ int count = 0; FOR (val_index,NUM_POSS) { int val_pos = GetPossibilityIndex(val_index,position); if (possibilities[val_pos] == 0) count++; } return count; } //------------------------------------------------------------ bool Sudoku::ArePossibilitiesSame(int position1, int position2){ FOR (val_index,NUM_POSS) { int val_pos1 = GetPossibilityIndex(val_index,position1); int val_pos2 = GetPossibilityIndex(val_index,position2); if ((possibilities[val_pos1] == 0 || possibilities[val_pos2] == 0) && (possibilities[val_pos1] != 0 || possibilities[val_pos2] != 0)) return false; } return true; } //------------------------------------------------------------ bool Sudoku::RemovePossibilitiesInOneFromTwo(int position1, int position2, int round){ bool finish_something = false; FOR (val_index,NUM_POSS) { int val_pos1 = GetPossibilityIndex(val_index,position1); int val_pos2 = GetPossibilityIndex(val_index,position2); if (possibilities[val_pos1] == 0 && possibilities[val_pos2] == 0) { possibilities[val_pos2] = round; finish_something = true; } } return finish_something; } //------------------------------------------------------------ bool Sudoku::HiddenPairInColumn(int round){ FOR (column,9) { FOR (val_index,9) { int r1 = -1; int r2 = -1; int val_count = 0; FOR (row,9) { int position = RowColumnToCell(row,column); int val_pos = GetPossibilityIndex(val_index,position); if (possibilities[val_pos] == 0) { if (r1 == -1 || r1 == row) r1 = row; else if (r2 == -1 || r2 == row) r2 = row; val_count++; } }//FOR row if (val_count==2) { for (int val_index2=val_index+1; val_index2<9; val_index2++) { int r3 = -1; int r4 = -1; int val_count2 = 0; FOR (row,9) { int position = RowColumnToCell(row,column); int val_pos = GetPossibilityIndex(val_index2,position); if (possibilities[val_pos] == 0) { if (r3 == -1 || r3 == row) r3 = row; else if (r4 == -1 || r4 == row) r4 = row; val_count2++; } }//FOR row if (val_count2==2 && r1==r3 && r2==r4) { bool finish_something = false; FOR (val_index3,9) { if (val_index3 != val_index && val_index3 != val_index2) { int position1 = RowColumnToCell(r1,column); int position2 = RowColumnToCell(r2,column); int val_pos1 = GetPossibilityIndex(val_index3,position1); int val_pos2 = GetPossibilityIndex(val_index3,position2); if (possibilities[val_pos1] == 0) { possibilities[val_pos1] = round; finish_something = true; } if (possibilities[val_pos2] == 0) { possibilities[val_pos2] = round; finish_something = true; } } }//FOR val_index3 if (finish_something) { if (log_history || record_history) AddHistoryItem(new Log(round, Log::HIDDEN_PAIR_COLUMN, val_index+1, RowColumnToCell(r1,column))); return true; } } }//for val_index2 }//if }//FOR val_index }//FOR column return false; } //------------------------------------------------------------ bool Sudoku::HiddenPairInSection(int round){ FOR (section,9) { FOR (val_index,9) { int si1 = -1; int si2 = -1; int val_count = 0; FOR (sec_ind,9) { int position = SectionToCell(section,sec_ind); int val_pos = GetPossibilityIndex(val_index,position); if (possibilities[val_pos] == 0) { if (si1 == -1 || si1 == sec_ind) si1 = sec_ind; else if (si2 == -1 || si2 == sec_ind) si2 = sec_ind; val_count++; } } if (val_count==2) { for (int val_index2=val_index+1; val_index2<9; val_index2++) { int si3 = -1; int si4 = -1; int val_count2 = 0; FOR (sec_ind,9) { int position = SectionToCell(section,sec_ind); int val_pos = GetPossibilityIndex(val_index2,position); if (possibilities[val_pos] == 0) { if (si3 == -1 || si3 == sec_ind) si3 = sec_ind; else if (si4 == -1 || si4 == sec_ind) si4 = sec_ind; val_count2++; } }//FOR sec_ind if (val_count2==2 && si1==si3 && si2==si4) { bool finish_something = false; FOR (val_index3,9) { if (val_index3 != val_index && val_index3 != val_index2) { int position1 = SectionToCell(section,si1); int position2 = SectionToCell(section,si2); int val_pos1 = GetPossibilityIndex(val_index3,position1); int val_pos2 = GetPossibilityIndex(val_index3,position2); if (possibilities[val_pos1] == 0) { possibilities[val_pos1] = round; finish_something = true; } if (possibilities[val_pos2] == 0) { possibilities[val_pos2] = round; finish_something = true; } } } if (finish_something) { if (log_history || record_history) AddHistoryItem(new Log(round, Log::HIDDEN_PAIR_SECTION, val_index+1, SectionToCell(section,si1))); return true; } } }//for val_index2 }//if }//FOR val_index }//FOR section return false; } //------------------------------------------------------------ bool Sudoku::HiddenPairInRow(int round){ FOR (row,9) { FOR(val_index,9) { int c1 = -1; int c2 = -1; int val_count = 0; FOR (column,9) { int position = RowColumnToCell(row,column); int val_pos = GetPossibilityIndex(val_index,position); if (possibilities[val_pos] == 0) { if (c1 == -1 || c1 == column) c1 = column; else if (c2 == -1 || c2 == column) c2 = column; val_count++; } }//FOR column if (val_count==2) { for (int val_index2=val_index+1; val_index2<9; val_index2++) { int c3 = -1; int c4 = -1; int val_count2 = 0; FOR (column,9) { int position = RowColumnToCell(row,column); int val_pos = GetPossibilityIndex(val_index2,position); if (possibilities[val_pos] == 0) { if (c3 == -1 || c3 == column) c3 = column; else if (c4 == -1 || c4 == column) c4 = column; val_count2++; } }//FOR column if (val_count2==2 && c1==c3 && c2==c4) { bool finish_something = false; FOR (val_index3,9) { if (val_index3 != val_index && val_index3 != val_index2) { int position1 = RowColumnToCell(row,c1); int position2 = RowColumnToCell(row,c2); int val_pos1 = GetPossibilityIndex(val_index3,position1); int val_pos2 = GetPossibilityIndex(val_index3,position2); if (possibilities[val_pos1] == 0) { possibilities[val_pos1] = round; finish_something = true; } if (possibilities[val_pos2] == 0) { possibilities[val_pos2] = round; finish_something = true; } } }//FOR val_index3 if (finish_something) { if (log_history || record_history) AddHistoryItem(new Log(round, Log::HIDDEN_PAIR_ROW, val_index+1, RowColumnToCell(row,c1))); return true; } }//if val_count2 }//for val_index2 } }//FOR val_index }//FOR row return false; } //------------------------------------------------------------ bool Sudoku::HandleNakedPairs(int round){ FOR (position,BOARD_SIZE) { int possibilities = CountPossibilities(position); if (possibilities == 2) { int row = CellToRow(position); int column = CellToColumn(position); int section = CellToSectionStartCell(position); FOR (position2,BOARD_SIZE) { if (position != position2) { int possibilities2 = CountPossibilities(position2); if (possibilities2 == 2 && ArePossibilitiesSame(position, position2)) { if (row == CellToRow(position2)) { bool finish_something = false; FOR (column2,9) { int position3 = RowColumnToCell(row,column2); if (position3 != position && position3 != position2 && RemovePossibilitiesInOneFromTwo(position, position3, round)) finish_something = true; }//FOR column2 if (finish_something) { if (log_history || record_history) AddHistoryItem(new Log(round, Log::NAKED_PAIR_ROW, 0, position)); return true; } } if (column == CellToColumn(position2)) { bool finish_something = false; FOR (row2,9) { int position3 = RowColumnToCell(row2,column); if (position3 != position && position3 != position2 && RemovePossibilitiesInOneFromTwo(position, position3, round)) finish_something = true; }//FOR row2 if (finish_something) { if (log_history || record_history) AddHistoryItem(new Log(round, Log::NAKED_PAIR_COLUMN, 0, position)); return true; } } if (section == CellToSectionStartCell(position2)) { bool finish_something = false; int sec_start = CellToSectionStartCell(position); FOR(i,3) { FOR(j,3) { int position3=sec_start+i+(9*j); if (position3 != position && position3 != position2 && RemovePossibilitiesInOneFromTwo(position, position3, round)) finish_something = true; }//FOR j }//FOR i if (finish_something) { if (log_history || record_history) AddHistoryItem(new Log(round, Log::NAKED_PAIR_SECTION, 0, position)); return true; } } } }//if }//position2 }//if }//FOR position return false; } /** * Marca la celda de un valor que deba estar en una fila dada * si la celda existe. * Es la celda llamada "hidden single" */ //------------------------------------------------------------ bool Sudoku::OnlyValueInRow(int round){ FOR (row,ROW_LENGTH) { FOR (val_index,NUM_POSS) { int count = 0; int last_position = 0; FOR (col,COL_HEIGHT) { int position = (row*ROW_LENGTH)+col; int val_pos = GetPossibilityIndex(val_index,position); if (possibilities[val_pos] == 0) { count++; last_position = position; } } if (count == 1) { int value = val_index+1; if (log_history || record_history) AddHistoryItem(new Log(round, Log::HIDDEN_SINGLE_ROW, value, last_position)); Mark(last_position, round, value); return true; } }//FOR val_index }//FOR row return false; } /** * Marca la ceda que es el valor único para una columna, si * la celda existe. * Este tipo de celda es llamado "hidden single". */ //------------------------------------------------------------ bool Sudoku::OnlyValueInColumn(int round){ FOR (col,COL_HEIGHT) { FOR (val_index,NUM_POSS) { int count = 0; int last_position = 0; FOR (row,ROW_LENGTH) { int position = RowColumnToCell(row,col); int val_pos = GetPossibilityIndex(val_index,position); if (possibilities[val_pos] == 0) { count++; last_position = position; } }//FOR row if (count == 1) { int value = val_index+1; if (log_history || record_history) AddHistoryItem(new Log(round, Log::HIDDEN_SINGLE_COLUMN, value, last_position)); Mark(last_position, round, value); return true; } } //FOR val_index }//FOR col return false; } /** * Marca la ceda que es el valor único para una sección, si * la celda existe. * Este tipo de celda es llamado "hidden single". */ //------------------------------------------------------------ bool Sudoku::OnlyValueInSection(int round){ FOR (sec,SEC_COUNT) { int sec_pos = SectionToFirstCell(sec); FOR (val_index,NUM_POSS) { int count = 0; int last_position = 0; FOR(i,3) { FOR(j,3) { int position = sec_pos + i + 9*j; int val_pos = GetPossibilityIndex(val_index,position); if (possibilities[val_pos] == 0) { count++; last_position = position; } }//FOR j }//FOR i if (count == 1) { int value = val_index+1; if (log_history || record_history) AddHistoryItem(new Log(round, Log::HIDDEN_SINGLE_SECTION, value, last_position)); Mark(last_position, round, value); return true; } }//FOR val_index }//FOR sec return false; } /** * Marca la celda que tiene una única posibilidad, si dicha celda existe. * Este tipo de celda es llamada "single". */ //------------------------------------------------------------ bool Sudoku::OnlyPossibilityForCell(int round){ FOR (position,BOARD_SIZE) { if (solution[position] == 0) { int count = 0; int last_value = 0; FOR (val_index,NUM_POSS) { int val_pos = GetPossibilityIndex(val_index,position); if (possibilities[val_pos] == 0) { count++; last_value=val_index+1; } } if (count == 1) { Mark(position, round, last_value); if (log_history || record_history) AddHistoryItem(new Log(round, Log::SINGLE, last_value, position)); return true; } } } return false; } /** * Marca un valor dado en la posición dada. */ //------------------------------------------------------------ void Sudoku::Mark(int position, int round, int value){ if (solution[position] != 0) throw ("Posicion ya marcada."); if (solution_round[position] !=0) throw ("Posicion ya marcada en otra ronda."); int val_index = value-1; solution[position] = value; int poss_ind = GetPossibilityIndex(val_index,position); if (possibilities[poss_ind] != 0) throw ("Posicion imposible."); // Quita este valor de las posibilidades en la file. solution_round[position] = round; int row_start = CellToRow(position)*9; FOR (col,COL_HEIGHT) { int row_val=row_start+col; int val_pos = GetPossibilityIndex(val_index,row_val); if (possibilities[val_pos] == 0) possibilities[val_pos] = round; } // Quita este valor de las posibilidades en la columna. int col_start = CellToColumn(position); FOR (i,9) { int colVal=col_start+(9*i); int val_pos = GetPossibilityIndex(val_index,colVal); if (possibilities[val_pos] == 0) possibilities[val_pos] = round; } // Quita este valor de las posibilidades en la sección. int sec_start = CellToSectionStartCell(position); FOR (i,3) { FOR (j,3) { int sec_val=sec_start+i+(9*j); int val_pos = GetPossibilityIndex(val_index,sec_val); if (possibilities[val_pos] == 0) possibilities[val_pos] = round; } } FOR(val_index,9) { int val_pos = GetPossibilityIndex(val_index,position); if (possibilities[val_pos] == 0) possibilities[val_pos] = round; } } /** * Muestra una lista de celdas que no han sido llenadas */ //------------------------------------------------------------ void Sudoku::PrintPossibilities(){ int pos_val = 0; int value = 0; FOR (i,BOARD_SIZE) { cout << " "; FOR (val_index,NUM_POSS) { pos_val = (9*i)+val_index; value = val_index+1; if (possibilities[pos_val]==0) cout << value; else cout << "."; } if (i != BOARD_SIZE-1 && i%SEC_GROUP_SIZE==SEC_GROUP_SIZE-1) cout << endl << "-------------------------------|-------------------------------|-------------------------------" << endl; else if (i%9==8) cout << endl; else if (i%3==2) cout << " |"; } cout << endl; } /** * Pinta un arreglo de enteros como tablero. * Usa las opciones de impresión dadas en los argmumentos. */ //------------------------------------------------------------ void Sudoku::Print(int* sudoku){ FOR (i,BOARD_SIZE) { if (print_style == READABLE) cout << " "; if (sudoku[i]==0) cout << '.'; else cout << sudoku[i]; if (i == BOARD_SIZE-1) { if (print_style == CSV) cout << ","; else cout << endl; if (print_style == READABLE || print_style == COMPACT) cout << endl; } else if (i%9==8) { if (print_style == READABLE || print_style == COMPACT) cout << endl; if (i%SEC_GROUP_SIZE==SEC_GROUP_SIZE-1) if (print_style == READABLE) cout << "-------|-------|-------" << endl; } else if (i%3==2) { if (print_style == READABLE) cout << " |"; } } } /** * Muestra el tablero de sudoku. */ //------------------------------------------------------------ void Sudoku::Show(){ Print(grid); } /** * Muestra la solución en pantalla. */ //------------------------------------------------------------ void Sudoku::ShowSolution(){ Print(solution); } //------------------------------------------------------------ Sudoku::~Sudoku(){ ClearBoard(); delete grid; delete solution; delete possibilities; delete solution_round; delete random_board_array; delete random_possibility_array; delete vsolve_history; delete vsolve_instructions; } //------------------------------------------------------------ Log::Log(int r, LogType t){ init(r,t,0,-1); } //------------------------------------------------------------ Log::Log(int r, LogType t, int v, int p){ init(r,t,v,p); } //------------------------------------------------------------ void Log::init(int r, LogType t, int v, int p){ round = r; type = t; value = v; position = p; } //------------------------------------------------------------ Log::~Log(){ } //------------------------------------------------------------ int Log::GetRound(){ return round; } //------------------------------------------------------------ Log::LogType Log::getType(){ return type; } /** * Muestra un elemento del log . El mensaje usado es * determinado por el timpo de elemento log. */ //------------------------------------------------------------ void Log::Print(){ bool printed; cout << "Ronda: " << GetRound() << " - "; switch(type) { case GIVEN: cout << "Elemento marcado como 'given'"; break; case ROLLBACK: cout << "Roll back round"; break; case GUESS: cout << "Guess (ronda inicial)."; break; case HIDDEN_SINGLE_ROW: cout << "Posibilidad unica para un valor en la fila."; break; case HIDDEN_SINGLE_COLUMN: cout << "Posibilidad unica para un valor en la columna."; break; case HIDDEN_SINGLE_SECTION: cout << "Posibilidad unica para un valor en la seccion."; break; case SINGLE: cout << "Posibilidad unica para una celda."; break; case NAKED_PAIR_ROW: cout << "Remueve posibilidadades para 'naked pair' en la fila."; break; case NAKED_PAIR_COLUMN: cout << "Remueve posibilidadades para 'naked pair' en la columna."; break; case NAKED_PAIR_SECTION: cout << "Remueve posibilidadades para 'naked pair' en la seccion."; break; case POINTING_PAIR_TRIPLE_ROW: cout << "Remueve posibilidades para una fila porque los valores estan en una seccion."; break; case POINTING_PAIR_TRIPLE_COLUMN: cout << "Remueve posibilidades para una columna porque los valores estan en una seccion."; break; case ROW_BOX: cout << "Remueve posibilidades para una seccion porque todos los valores estan en una fila."; break; case COLUMN_BOX: cout << "Remueve posibilidades para una seccion porque todos los valores estan en una columna."; break; case HIDDEN_PAIR_ROW: cout << "Remueve posibilidades de 'hidden pair' en una fila."; break; case HIDDEN_PAIR_COLUMN: cout << "Remueve posibilidades de 'hidden pair' en una columna."; break; case HIDDEN_PAIR_SECTION: cout << "Remueve posibilidades de 'hidden pair' en una seccion."; break; default: cout << "!!! ??? !!!"; break; } if (value > 0 || position > -1) { cout << " ("; printed = false; if (position > -1) { if (printed) cout << " - "; cout << "Fila: " << CellToRow(position)+1 << " - Columna: " << CellToColumn(position)+1; printed = true; } if (value > 0) { if (printed) cout << " - "; cout << "Valor: " << value; printed = true; } cout << ")"; } } /** * Dado un vector de Logs, esta función determina * cuando logs en el vector son del tipo especificado. */ //------------------------------------------------------------ int GetLogCount(vector<Log*>* v, Log::LogType type){ int count = 0; for (unsigned int i=0; i<v->size(); i++) if(v->at(i)->getType() == type) count++; return count; } /** * Tiempo del programa en microsegundos. */ //------------------------------------------------------------ long Time(){ struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec*1000000+tv.tv_usec; } /** * Intercambia los valores de dos variables. */ //------------------------------------------------------------ void Swap( int &x, int &y ){ x=x+y; y=x-y; x=x-y; } /** * Reestructura los valores de un vector. */ //------------------------------------------------------------ void ShuffleArray(int* array, int size){ FOR (i,size) { int tsize = size-i; int rand_pos = rand()%tsize+i; swap(array[i],array[rand_pos]); } } /** * Se lee un table desde STDIN. * Se procesa un caracter a la vez * hasta que se llena el tablero. * Se utilizan (0-9) y (.) */ //------------------------------------------------------------ bool ReadBoardFromStdIn(int* grid){ int read = 0; while (read < BOARD_SIZE) { //char c = getchar(); int c = getchar(); if (c == EOF) return false; if (c >= '1' && c <='9') { grid[read] = c-'0'; read++; } if (c == '.' || c == '0') { grid[read] = 0; read++; } } return true; } /** * Dado el índice de una celda (0-80) calcula * la columna (0-8) en la que se encuentra. */ //------------------------------------------------------------ static inline int CellToColumn(int cell){ return cell%COL_HEIGHT; } /** * Dado el índice de una celda (0-80) calcula * la fila (0-8) en la que se encuentra. */ //------------------------------------------------------------ static inline int CellToRow(int cell){ return cell/ROW_LENGTH; } /** * Dado el índice de una celda (0-80) calcula * la sección (0-8) en la que se encuentra. */ //------------------------------------------------------------ static inline int CellToSection(int cell){ return (cell/SEC_GROUP_SIZE*GRID_SIZE) + (CellToColumn(cell)/GRID_SIZE); } /** * Dado el índice de una celda (0-80) calcula * la celda (0-80) que está en la esquina superior izquierda * de su sección. */ //------------------------------------------------------------ static inline int CellToSectionStartCell(int cell){ return (cell/SEC_GROUP_SIZE*SEC_GROUP_SIZE) + (CellToColumn(cell)/GRID_SIZE*GRID_SIZE); } /** * Dada una fila (0-8) calcula la primera celda (0-80) * de esa fila. */ //------------------------------------------------------------ static inline int RowToFirstCell(int row){ return 9*row; } /** * Dada una columna (0-8) calcula la primera celda (0-80) * de esa columna. */ //------------------------------------------------------------ static inline int ColumnToFirstCell(int column){ return column; } /** * Dada una sección (0-8) calcula la primera celda (0-80) * de esa sección. */ //------------------------------------------------------------ static inline int SectionToFirstCell(int section){ return (section%GRID_SIZE*GRID_SIZE) + (section/GRID_SIZE*SEC_GROUP_SIZE); } /** * Dado el valor de una celda (0-8) y una celda (0-80) * calcula el 'offset' en el arreglo de posibilidades (0-728). */ //------------------------------------------------------------ static inline int GetPossibilityIndex(int valueIndex, int cell){ return valueIndex+(NUM_POSS*cell); } /** * Dada una fila (0-8) y una columna (0-8) calcula la * celda (0-80). */ //------------------------------------------------------------ static inline int RowColumnToCell(int row, int column){ return (row*COL_HEIGHT)+column; } /** * Dada una sección (0-8) y un offset en la sección (0-8) * calcula la celda (0-80) */ //------------------------------------------------------------ static inline int SectionToCell(int section, int offset){ return SectionToFirstCell(section) + ((offset/GRID_SIZE)*SEC_SIZE) + (offset%GRID_SIZE); } //------------------------------------------------------------ //------------------------------------------------------------ int main(int argc, char *argv[]){ // Declaración de variables. enum Action {NONE, GENERATE, SOLVE}; Action action = NONE; //Dificultad y modo de impresión por default. Sudoku::Difficulty difficulty = Sudoku::UNKNOWN; Sudoku::ConsolePrintStyle print_style = Sudoku::READABLE; // Número de tableros para ser generados y resueltos. Número de soluciones. int number_generated = 0; int number_to_generate = 1; int board_counter = 0; int solutions = 0; // Inicializa el generador de números aleatorios. int time_seed = time(NULL); // Variables para mostrar las estadísticas. int given_count = 0; int single_count = 0; int hidden_single_count = 0; int naked_pair_count = 0; int hidden_pair_count = 0; int pointing_pair_triple_count = 0; int box_reduction_count = 0; int guess_count = 0; int backtrack_count = 0; // Tiempos de ejecucion por tablero long board_start_time; long board_finish_time; // Tiempo de ejecucion del programa completo long program_start_time; long program_finish_time; // Muestra tablero, tiempo, solución, historia, instrucciones, estadísticas. bool show = false; bool show_time = false; bool show_history = false; bool show_solution = false; bool show_instructions = false; bool show_stats = false; // Cuenta las soluciones. bool count_solutions = false; //Registra eventos en un log. bool log_history = false; // Variable que dice cuando ya terminó. bool finish = false; bool printed_something = false; bool have_grid; try { program_start_time = Time(); // Lee los argumentos for (int i=1; i<argc; i++) { if (!strcmp(argv[i],"--board")) show = true; else if (!strcmp(argv[i],"--solution")) show_solution = true; else if (!strcmp(argv[i],"--nosolution")) show_solution = false; else if (!strcmp(argv[i],"--history")) show_history = true; else if (!strcmp(argv[i],"--nohistory")) show_history = false; else if (!strcmp(argv[i],"--instructions")) show_instructions = true; else if (!strcmp(argv[i],"--noinstructions")) show_instructions = false; else if (!strcmp(argv[i],"--stats")) show_stats = true; else if (!strcmp(argv[i],"--nostats")) show_stats = false; else if (!strcmp(argv[i],"--time")) show_time = true; else if (!strcmp(argv[i],"--count-solutions")) count_solutions = true; else if (!strcmp(argv[i],"--generate")) { action = GENERATE; show = true; if (i+1 < argc && argv[i+1][0] >= '1' && argv[i+1][0] <= '9') { number_to_generate = atoi(argv[i+1]); i++; } } else if (!strcmp(argv[i],"--difficulty")) { if (argc < i+1) { cout << "Por favor especificar una dificultad." << endl; return 1; } else if (!strcmp(argv[i+1],"very_easy")) difficulty = Sudoku::SIMPLE; else if (!strcmp(argv[i+1],"easy")) difficulty = Sudoku::EASY; else if (!strcmp(argv[i+1],"normal")) difficulty = Sudoku::INTERMEDIATE; else if (!strcmp(argv[i+1],"hard")) difficulty = Sudoku::EXPERT; else { cout << "La dificultad debe ser simple, easy, intermediate, o expert, no " << argv[i+1] << endl; return 1; } i++; } else if (!strcmp(argv[i],"--solve")) { action = SOLVE; show_solution = true; } else if (!strcmp(argv[i],"--log-history")) log_history = true; else if (!strcmp(argv[i],"--nolog-history")) log_history = false; else if (!strcmp(argv[i],"--one-line")) print_style=Sudoku::ONE_LINE; else if (!strcmp(argv[i],"--compact")) print_style=Sudoku::COMPACT; else if (!strcmp(argv[i],"--readable")) print_style=Sudoku::READABLE; else if (!strcmp(argv[i],"--csv")) print_style=Sudoku::CSV; else if (!strcmp(argv[i],"-n") || !strcmp(argv[i],"--number")) { if (i+1 < argc) number_to_generate = atoi(argv[(i++)+1]); else { cout << "Especificar un numero." << endl; return 1; } } else if (!strcmp(argv[i],"-h") || !strcmp(argv[i],"--help") || !strcmp(argv[i],"help") || !strcmp(argv[i],"?")) { PrintHelp(argv[0]); return 0; } else if (!strcmp(argv[i],"--version")) { PrintVersion(); return 0; } else if (!strcmp(argv[i],"--about")) { PrintAbout(); return 0; } else { cout << "Argumento desconocido: '" << argv[i] << "'" << endl; PrintHelp(argv[0]); return 1; } }//FOR arg if (action == NONE) { cout << "Se tiene que ingresar alguna accion como --solve o --generate." << endl; PrintHelp(argv[0]); return 1; } srand(time_seed); // Muestra un encabezado si se quiere salida CSV. if (print_style == Sudoku::CSV) { if (show) cout << "Tablero,"; if (show_solution) cout << "Solucion,"; if (show_history) cout << "Historial de solucion,"; if (show_instructions) cout << "Intrucciones para la solucion,"; if (count_solutions) cout << "Numero de soluciones,"; if (show_time) cout << "Tiempo (milisegundos),"; if (show_stats) cout << "Givens,Singles,Hidden Singles,Naked Pairs,Hidden Pairs,Pointing Pairs/Triples,Box/Line Intersections,Guesses,Backtracks,Dificultad"; cout << "" << endl; } //Crea un nuevo tablero de sudoku. Inicializa las variables. Sudoku* sudoku_board = new Sudoku(); sudoku_board->SetRecordHistory(show_history || show_instructions || show_stats || difficulty!=Sudoku::UNKNOWN); sudoku_board->SetLogHistory(log_history); sudoku_board->SetConsolePrintStyle(print_style); // Resuelve tableros hasta dejar de ingresar datos. // Genera el número especificado de tableros. finish = false; number_generated = 0; while (!finish) { board_start_time = Time(); printed_something = false; have_grid = false; if (action == GENERATE) { //Crea un tablero de sudoku. have_grid = sudoku_board->CreateBoard(); if (!have_grid && show) { cout << "No fue posible generar el tablero."; if (print_style==Sudoku::CSV) cout << ","; else cout << endl; printed_something = true; } } else { // Lee el tablero en STDIN int* grid = new int[BOARD_SIZE]; if (ReadBoardFromStdIn(grid)) { have_grid = sudoku_board->SetBoard(grid); if (!have_grid) { if (show) { sudoku_board->Show(); printed_something = true; } if (show_solution) { cout << "Tablero imposible."; if (print_style==Sudoku::CSV) cout << ","; else cout << endl; printed_something = true; } } } else { // Si no queda nada en STDIN termina el ciclo have_grid = false; finish = true; } //delete grid; } solutions = 0; if (have_grid) { // Cuenta soluciones si fue requerido. if (count_solutions) solutions = sudoku_board->CountSolutions(); // Resuelve el tablero if (show_solution || show_history || show_stats || show_instructions || difficulty!=Sudoku::UNKNOWN) sudoku_board->Solve(); // Tira el tablero si no cumple la exigencias de dificultad if (action == GENERATE) { if (difficulty!=Sudoku::UNKNOWN && difficulty!=sudoku_board->GetDifficulty()) have_grid = false; else { number_generated++; // Termina ciclo si han sido generados suficientes. if (number_generated >= number_to_generate) finish = true; } } } if (have_grid) { // Ya teniendo el tablero // muestra solución, estadísticas, etc. printed_something = true; // Finaliza el tiempo de ejecución del tablero. board_finish_time = Time(); // Muestra el tablero. if (show) sudoku_board->Show(); // Muestra la solución si existe. if (show_solution) { if (sudoku_board->IsSolved()) sudoku_board->ShowSolution(); else { cout << "El tablero no tiene solucion."; if (print_style==Sudoku::CSV) cout << ","; else cout << endl; } } //Muestra los pasos tomados para resolver o intentar resolver un tablero. if (show_history) sudoku_board->PrintSolveHistory(); // Muestra las instrucciones para resolver un tablero. if (show_instructions) sudoku_board->PrintSolveInstructions(); // Muestra el número de soluciones. if (count_solutions) { if (print_style == Sudoku::CSV) cout << solutions << ","; else { if (solutions == 0) cout << "No hay soluciones para este tablero." << endl; else if (solutions == 1) cout << "La solucion para este tablero es unica." << endl; else cout << "Hay " << solutions << " soluciones al tablero." << endl; } } // Muestra el tiempo que tomó resolver el tablero. if (show_time) { double t = ((double)(board_finish_time - board_start_time))/1000.0; if (print_style == Sudoku::CSV) cout << t << ","; else cout << "Tiempo: " << t << " milisegundos." << endl; } // Muestra las estadísticas. if (show_stats) { given_count = sudoku_board->GetGivenCount(); single_count = sudoku_board->GetSingleCount(); hidden_single_count = sudoku_board->GetHiddenSingleCount(); naked_pair_count = sudoku_board->GetNakedPairCount(); hidden_pair_count = sudoku_board->GetHiddenPairCount(); pointing_pair_triple_count = sudoku_board->GetPointingPairTripleCount(); box_reduction_count = sudoku_board->GetBoxLineReductionCount(); guess_count = sudoku_board->GetGuessCount(); backtrack_count = sudoku_board->GetBacktrackCount(); string difficultyString = sudoku_board->GetDifficultyAsString(); if (print_style == Sudoku::CSV) { cout << given_count << "," << single_count << "," << hidden_single_count << "," << naked_pair_count << "," << hidden_pair_count << "," << pointing_pair_triple_count << "," << box_reduction_count << "," << guess_count << "," << backtrack_count << "," << difficultyString << ","; } else { cout << "Givens: " << given_count << endl; cout << "Singles: " << single_count << endl; cout << "Hidden Singles: " << hidden_single_count << endl; cout << "Naked Pairs: " << naked_pair_count << endl; cout << "Hidden Pairs: " << hidden_pair_count << endl; cout << "Pointing Pairs/Triples: " << pointing_pair_triple_count << endl; cout << "Box/Line Intersections: " << box_reduction_count << endl; cout << "Guesses: " << guess_count << endl; cout << "Backtracks: " << backtrack_count << endl; cout << "Dificultad: " << difficultyString << endl; } } board_counter++; } if (printed_something && print_style == Sudoku::CSV) cout << endl; } delete sudoku_board; program_finish_time = Time(); // Muestra el tiempo que tomó la aplicacion completa. if (show_time) { double t = ((double)(program_finish_time - program_start_time))/1000.0; cout << board_counter << " tablero" << ((board_counter==1)?"":"s") << " " << (action==GENERATE?"generado":"resuelto") << ((board_counter==1)?"":"s") << " en " << t << " milisegundos." << endl; } } catch (char const* s) { cout << s << endl; return 1; } return 0; } //------------------------------------------------------------
26.3451
195
0.575167
[ "vector" ]
1ea49b2a99a69d064c3cd37677d7d1ea8c8a6020
2,855
cc
C++
src/visualisers/HeightTechnique.cc
b8raoult/magics
eb2c86ec6e392e89c90044128dc671f22283d6ad
[ "ECL-2.0", "Apache-2.0" ]
41
2018-12-07T23:10:50.000Z
2022-02-19T03:01:49.000Z
src/visualisers/HeightTechnique.cc
b8raoult/magics
eb2c86ec6e392e89c90044128dc671f22283d6ad
[ "ECL-2.0", "Apache-2.0" ]
59
2019-01-04T15:43:30.000Z
2022-03-31T09:48:15.000Z
src/visualisers/HeightTechnique.cc
b8raoult/magics
eb2c86ec6e392e89c90044128dc671f22283d6ad
[ "ECL-2.0", "Apache-2.0" ]
13
2019-01-07T14:36:33.000Z
2021-09-06T14:48:36.000Z
/* * (C) Copyright 1996-2016 ECMWF. * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. * In applying this licence, ECMWF does not waive the privileges and immunities * granted to it by virtue of its status as an intergovernmental organisation nor * does it submit to any jurisdiction. */ /*! \file HeightSelection.cc \brief Implementation of the Template class HeightSelection. Magics Team - ECMWF 2004 Started: Thu 20-May-2004 Changes: */ #include "HeightTechnique.h" #include "LevelSelection.h" using namespace magics; HeightTechnique::HeightTechnique() {} HeightTechnique::~HeightTechnique() {} /*! Class information are given to the output-stream. */ void HeightTechnique::print(ostream& out) const { out << "HeightTechnique["; out << "]"; } void HeightTechnique::set(const HeightTechniqueInterface&) {} ListHeightTechnique::ListHeightTechnique() {} ListHeightTechnique::~ListHeightTechnique() {} void ListHeightTechnique::set(const HeightTechniqueInterface& interface) { list_ = interface.getHeights(); policy_ = interface.getHeightPolicy(); } void ListHeightTechnique::prepare(LevelSelection& levels) { heights_.clear(); if (list_.empty()) list_.push_back(0.2); if (levels.size() == 1) { heights_[Interval(levels.front(), levels.front())] = list_.front(); return; } LevelSelection::const_iterator level = levels.begin(); vector<double>::const_iterator height = list_.begin(); while (true) { heights_[Interval(*level, *(level + 1))] = *height; height++; level++; if (level == levels.end()) break; if (height == list_.end()) { if (policy_ != ListPolicy::LASTONE) height = list_.begin(); else --height; } } } CalculateHeightTechnique::CalculateHeightTechnique() {} CalculateHeightTechnique::~CalculateHeightTechnique() {} void CalculateHeightTechnique::set(const HeightTechniqueInterface& interface) { min_ = interface.getMinHeight(); max_ = interface.getMaxHeight(); } void CalculateHeightTechnique::prepare(LevelSelection& levels) { ASSERT(levels.size() > 1); heights_.clear(); double step = (levels.size() == 2) ? (max_ - min_) : (max_ - min_) / (levels.size() - 2); LevelSelection::const_iterator level = levels.begin(); double height = min_; while (true) { MagLog::debug() << "[" << *level << ", " << *(level + 1) << "]=" << height << "(height)" << endl; heights_[Interval(*level, *(level + 1))] = height; height += step; level++; if (level == levels.end()) break; } }
26.933962
118
0.629422
[ "vector" ]
1eaf82da3d426e372d68ebda08a927faaecd9947
5,166
cpp
C++
examples/roadef2020_main.cpp
fontanf/localsearchsolver
68fa39189660a7ce0673df44943862362681f98c
[ "MIT" ]
1
2021-10-30T11:42:30.000Z
2021-10-30T11:42:30.000Z
examples/roadef2020_main.cpp
fontanf/localsearchsolver
68fa39189660a7ce0673df44943862362681f98c
[ "MIT" ]
null
null
null
examples/roadef2020_main.cpp
fontanf/localsearchsolver
68fa39189660a7ce0673df44943862362681f98c
[ "MIT" ]
null
null
null
#include "examples/roadef2020.hpp" #include "localsearchsolver/read_args.hpp" #include <boost/program_options.hpp> using namespace localsearchsolver; using namespace localsearchsolver::roadef2020; int main(int argc, char *argv[]) { namespace po = boost::program_options; // Parse program options std::string instance_path = ""; std::string format = ""; std::string output_path = ""; std::string i_path = ""; std::string c_path = ""; std::string certificate_path = ""; std::string team_id = "S19"; Counter number_of_threads_1 = 1; Counter number_of_threads_2 = 1; Counter initial_solution_id = 0; int seed = 0; double time_limit = std::numeric_limits<double>::infinity(); po::options_description desc("Allowed options"); desc.add_options() ("help,h", "produce help message") ("name", "Team ID") (",p", po::value<std::string>(&instance_path), "set input file (required)") (",o", po::value<std::string>(&certificate_path), "set certificate file") (",t", po::value<double>(&time_limit), "time limit in seconds") (",w", po::value<Counter>(&initial_solution_id), "set initial solution id") (",x", po::value<Counter>(&number_of_threads_1), "set thread number 1") (",y", po::value<Counter>(&number_of_threads_2), "set thread number 2") (",s", po::value<int>(&seed), "set seed") (",i", po::value<std::string>(&i_path), "") (",c", po::value<std::string>(&c_path), "") (",e", "Only write output and certificate files at the end") ("verbose", "set verbosity") ; po::variables_map vm; boost::program_options::store( boost::program_options::command_line_parser(argc, argv) .options(desc) .style( boost::program_options::command_line_style::unix_style | boost::program_options::command_line_style::allow_long_disguise) .run(), vm); if (vm.count("name")) { std::cout << team_id << std::endl;; return 1; } if (vm.count("help")) { std::cout << desc << std::endl;; return 1; } try { po::notify(vm); } catch (const po::required_option& e) { std::cout << desc << std::endl;; return 1; } // If option -i has been used, then consider that it is not the challenge // configuration. if (!i_path.empty()) { // Get the instance from option -i. instance_path = i_path; // Get the json output form option -o. output_path = certificate_path; // Get the solution file from option -c. certificate_path = c_path; } // Run algorithm optimizationtools::Info info = optimizationtools::Info() .set_json_output_path(output_path) .set_verbose(true) .set_time_limit(time_limit) .set_certificate_path(certificate_path) .set_only_write_at_the_end(false) ; std::mt19937_64 generator(0); // Read instance. Instance instance(instance_path, format); VER(info, instance << std::endl); // Create LocalScheme. LocalScheme::Parameters parameters_local_scheme; LocalScheme local_scheme(instance, parameters_local_scheme); // Run A*. BestFirstLocalSearchOptionalParameters<LocalScheme> parameters_best_first_local_search; parameters_best_first_local_search.info.set_verbose(true); parameters_best_first_local_search.info.set_time_limit(info.remaining_time()); parameters_best_first_local_search.number_of_threads_1 = number_of_threads_1; parameters_best_first_local_search.number_of_threads_2 = number_of_threads_2; parameters_best_first_local_search.initial_solution_ids = std::vector<Counter>( number_of_threads_2, initial_solution_id); parameters_best_first_local_search.new_solution_callback = [&local_scheme, &info]( const LocalScheme::Solution& solution) { std::cout << " " << local_scheme.real_cost(solution) << std::endl; if (local_scheme.feasible(solution)) { info.output->number_of_solutions++; double t = info.elapsed_time(); std::string sol_str = "Solution" + std::to_string(info.output->number_of_solutions); PUT(info, sol_str, "Value", local_scheme.real_cost(solution)); PUT(info, sol_str, "Time", t); if (!info.output->only_write_at_the_end) { info.write_json_output(); local_scheme.write(solution, info.output->certificate_path); } } }; auto output = best_first_local_search(local_scheme, parameters_best_first_local_search); const LocalScheme::Solution& solution = output.solution_pool.best(); double t = info.elapsed_time(); std::string sol_str = "Solution"; PUT(info, sol_str, "Time", t); PUT(info, sol_str, "Value", local_scheme.real_cost(solution)); info.write_json_output(); local_scheme.write(solution, info.output->certificate_path); return 0; }
37.434783
100
0.631823
[ "vector" ]
1eb08f499768adc547ef3422dde56ed2fe686330
8,860
cpp
C++
src/O2FS/IO/BeMusicReader.cpp
SirusDoma/O2FS
3ffa2d5476b8ee883be145c275df5e7759c1e520
[ "MIT" ]
1
2022-02-16T12:36:32.000Z
2022-02-16T12:36:32.000Z
src/O2FS/IO/BeMusicReader.cpp
SirusDoma/O2FS
3ffa2d5476b8ee883be145c275df5e7759c1e520
[ "MIT" ]
null
null
null
src/O2FS/IO/BeMusicReader.cpp
SirusDoma/O2FS
3ffa2d5476b8ee883be145c275df5e7759c1e520
[ "MIT" ]
null
null
null
#include <O2FS/IO/BeMusicReader.hpp> #include <fstream> #include <sstream> #include <unordered_map> #include <filesystem> #include <boolinq.h> namespace O2FS { static std::vector<std::string> SplitString(const std::string &s, char delim) { std::vector<std::string> result; std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) result.push_back(item); return result; } static int ParseId(const std::string &fileName) { auto path = std::filesystem::path(fileName); auto fn = path.filename().string(); std::stringstream ss(fn.substr(4, 4)); // skip "o2ma" part std::string id; std::getline(ss, id, '.'); // stop at ".ojn" return std::stoi(id); } static Genre ParseGenre(std::string genre) { if (genre.find("ballad") != std::string::npos) return Genre::Ballad; else if (genre.find("rock") != std::string::npos) return Genre::Rock; else if (genre.find("dance") != std::string::npos) return Genre::Dance; else if (genre.find("techno") != std::string::npos) return Genre::Techno; else if (genre.find("hipHop") != std::string::npos) return Genre::HipHop; else if (genre.find("soul") != std::string::npos) return Genre::Soul; else if (genre.find("jazz") != std::string::npos) return Genre::Jazz; else if (genre.find("funk") != std::string::npos) return Genre::Funk; else if (genre.find("classical") != std::string::npos) return Genre::Classical; else if (genre.find("traditional") != std::string::npos) return Genre::Traditional; return Genre::Etc; }; Chart BeMusicReader::Deserialize(const std::string& fileName) { auto chart = Chart(); auto stream = std::ifstream(fileName); auto line = std::string(); chart.id = ParseId(fileName); bool holdStates[10]; memset(holdStates, false, sizeof(holdStates)); while(std::getline(stream, line)) { // Skip empty or comment line if (line.empty() || line[0] == '*') continue; // Parse chart metadata and keysounds auto params = SplitString(line, ' '); if (params.size() >= 2) { auto property = params[0]; std::string value; for (int i = 1; i < params.size(); i++) value += params[i] + " "; value = value.substr(0, value.size() - 1); if (property == "#TITLE") chart.title = value; if (property == "#ARTIST") chart.artist = value; if (property == "#PATTERN") chart.noteDesigner = value; if (property == "#GENRE") chart.genre = ParseGenre(value); if (property == "#BPM") chart.bpm = std::stod(value); if (property == "#DURATION") { chart.durations = std::unordered_map<Difficulty, int>(); for (int l = 0; l < 3; l++) chart.durations[(Difficulty)l] = std::stoi(value); } if (property == "#PLAYLEVEL") { chart.levels = std::unordered_map<Difficulty, int>(); for (int l = 0; l < 3; l++) chart.levels[(Difficulty)l] = std::stoi(value); } if (property == "#STAGEFILE") { // Resolve path auto path = std::filesystem::path(fileName); auto coverFileName = path.parent_path().string() + "/" + value; if (fileName.size() > 2 && fileName[0] == '\\' && fileName[1] == '\\') coverFileName = coverFileName.substr(4, coverFileName.size() - 4); // Open stream and initialize data auto coverStream = std::ifstream(coverFileName, std::ios::binary | std::ios::ate); auto coverSize = coverStream.tellg(); auto coverData = std::vector<char>(coverSize); // Load cover data coverStream.seekg(0, std::ios::beg); coverStream.read(coverData.data(), coverSize); coverStream.close(); // Attach cover data into chart chart.coverData = coverData; } if (property == "#THUMBFILE") { // Resolve path auto path = std::filesystem::path(fileName); auto thumbFileName = path.parent_path().string() + "/" + value; if (fileName.size() > 2 && fileName[0] == '\\' && fileName[1] == '\\') thumbFileName = thumbFileName.substr(4, thumbFileName.size() - 4); // Open stream and initialize data auto thumbnailStream = std::ifstream(thumbFileName, std::ios::binary | std::ios::ate); auto thumbnailSize = thumbnailStream.tellg(); auto thumbnailData = std::vector<char>(thumbnailSize); // Load thumbnail data thumbnailStream.seekg(0, std::ios::beg); thumbnailStream.read(thumbnailData.data(), thumbnailSize); thumbnailStream.close(); // Attach thumbnail data into chart chart.thumbnailData = thumbnailData; } // Keysound / Sample note handling if (property.substr(0, 4) == "#WAV") { auto sampleId = property.substr(4, 2); chart.samples[sampleId] = chart.samples.size() + 1; } } // Parse chart note data params = SplitString(line, ':'); if (params.size() == 2) { // Format: // MMMCC: IDIDIDIDIDID // // M: Measure // C: Channel // ID: Sample ID (0 mean empty space) auto time = params[0]; auto note = params[1]; int measure = std::stoi(time.substr(1, 3)); int rawchan = std::stoi(time.substr(4, 2)); int tempo = note.size() / 2; ChannelType channel = ChannelType::SampleNote; NoteType type = NoteType::Auto; const int bmsChanIndex = 10; const int bmsLnChanIndex = 50; int channels[7] = { 1, 2, 3, 4, 5, 8, 9 }; bool ln = false; for (int c = 0; c < sizeof(channels); c++) { int ch = channels[c]; if (rawchan == ch + bmsChanIndex || rawchan == ch + bmsLnChanIndex) { channel = (ChannelType)(c + 2); type = NoteType::Normal; ln = rawchan == ch + bmsLnChanIndex; break; } } auto block = EventBlock { measure, channel, tempo }; for (int i = 0; i < note.size(); i += 2) { auto sampleId = note.substr(i, 2); short id = sampleId == "00" ? 0 : chart.samples[sampleId]; if (id == 0) continue; if (ln) { holdStates[(int)channel] = !holdStates[(int)channel]; type = holdStates[(int)channel] ? NoteType::HoldStart : NoteType::HoldEnd; } auto ev = Event(); ev.id = id; ev.type = type; ev.channel = channel; ev.tempo = note.size() / 2; ev.measure = measure; ev.beat = (int)((i / 2) * (192.f / ev.tempo)); ev.cell = i / 2; block.events.push_back(ev); } if (!block.events.empty()) { for (int l = 0; l < 3; l++) chart.blocks[(Difficulty)l].push_back(block); } } } return chart; } }
35.15873
106
0.441084
[ "vector" ]
1eb10a5956c6e718d9287dc5cc1010d160fb9191
9,813
cpp
C++
src/plugins/lmp/collectionwidget.cpp
0xd34df00d/leechcraft
c599858ffcf59f0626f07f677362fc4538cc6552
[ "BSL-1.0" ]
120
2015-01-22T14:10:39.000Z
2021-11-25T12:57:16.000Z
src/plugins/lmp/collectionwidget.cpp
0xd34df00d/leechcraft
c599858ffcf59f0626f07f677362fc4538cc6552
[ "BSL-1.0" ]
8
2015-02-07T19:38:19.000Z
2017-11-30T20:18:28.000Z
src/plugins/lmp/collectionwidget.cpp
0xd34df00d/leechcraft
c599858ffcf59f0626f07f677362fc4538cc6552
[ "BSL-1.0" ]
33
2015-02-07T16:59:55.000Z
2021-10-12T00:36:40.000Z
/********************************************************************** * LeechCraft - modular cross-platform feature rich internet client. * Copyright (C) 2006-2014 Georg Rudoy * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt) **********************************************************************/ #include "collectionwidget.h" #include <QSortFilterProxyModel> #include <QMessageBox> #include <QMenu> #include <util/gui/clearlineeditaddon.h> #include <util/xpc/defaulthookproxy.h> #include <interfaces/core/iiconthememanager.h> #include "core.h" #include "localcollection.h" #include "palettefixerfilter.h" #include "collectiondelegate.h" #include "audiopropswidget.h" #include "util.h" #include "albumartmanagerdialog.h" #include "collectionsmanager.h" #include "hookinterconnector.h" #include "player.h" namespace LC { namespace LMP { namespace { class CollectionFilterModel : public QSortFilterProxyModel { public: CollectionFilterModel (QObject *parent = nullptr) : QSortFilterProxyModel { parent } { setDynamicSortFilter (true); setRecursiveFilteringEnabled (true); } protected: bool filterAcceptsRow (int sourceRow, const QModelIndex& sourceParent) const { const auto& source = sourceModel ()->index (sourceRow, 0, sourceParent); if (source.data (LocalCollectionModel::Role::IsTrackIgnored).toBool ()) return false; const auto type = source.data (LocalCollectionModel::Role::Node).toInt (); const bool isTrack = type == LocalCollectionModel::NodeType::Track; const auto childrenCount = sourceModel ()->rowCount (source); if (!isTrack) for (int i = 0; i < childrenCount; ++i) if (filterAcceptsRow (i, source)) return true; const auto& pattern = filterRegExp ().pattern (); if (pattern.isEmpty () && !isTrack && childrenCount) return false; auto check = [&source, &pattern] (int role) { return source.data (role).toString ().contains (pattern, Qt::CaseInsensitive); }; return check (Qt::DisplayRole) || check (LocalCollectionModel::Role::ArtistName) || check (LocalCollectionModel::Role::AlbumName) || check (LocalCollectionModel::Role::TrackTitle) || check (LocalCollectionModel::Role::AlbumYear); } }; } CollectionWidget::CollectionWidget (QWidget *parent) : QWidget { parent } , Player_ { Core::Instance ().GetPlayer () } , CollectionFilterModel_ { new CollectionFilterModel { this } } { Ui_.setupUi (this); new Util::ClearLineEditAddon (Core::Instance ().GetProxy (), Ui_.CollectionFilter_); new PaletteFixerFilter (Ui_.CollectionTree_); connect (Core::Instance ().GetLocalCollection (), &LocalCollection::scanStarted, Ui_.ScanProgress_, &QProgressBar::setMaximum); connect (Core::Instance ().GetLocalCollection (), &LocalCollection::scanProgressChanged, this, &CollectionWidget::HandleScanProgress); connect (Core::Instance ().GetLocalCollection (), &LocalCollection::scanFinished, Ui_.ScanProgress_, &QProgressBar::hide); Ui_.ScanProgress_->hide (); Ui_.CollectionTree_->setItemDelegate (new CollectionDelegate (Ui_.CollectionTree_)); auto collMgr = Core::Instance ().GetCollectionsManager (); CollectionFilterModel_->setSourceModel (collMgr->GetModel ()); Ui_.CollectionTree_->setModel (CollectionFilterModel_); connect (Ui_.CollectionTree_, &QTreeView::doubleClicked, this, &CollectionWidget::LoadFromCollection); connect (Ui_.CollectionFilter_, &QLineEdit::textChanged, CollectionFilterModel_, &QSortFilterProxyModel::setFilterFixedString); Core::Instance ().GetHookInterconnector ()->RegisterHookable (this); } void CollectionWidget::ShowCollectionTrackProps () { const auto& index = Ui_.CollectionTree_->currentIndex (); const auto& info = index.data (LocalCollectionModel::Role::TrackPath).toString (); if (info.isEmpty ()) return; AudioPropsWidget::MakeDialog ()->SetProps (info); } void CollectionWidget::ShowCollectionAlbumArt () { const auto& index = Ui_.CollectionTree_->currentIndex (); const auto& path = index.data (LocalCollectionModel::Role::AlbumArt).toString (); if (path.isEmpty ()) return; ShowAlbumArt (path, QCursor::pos ()); } void CollectionWidget::ShowAlbumArtManager () { auto aamgr = Core::Instance ().GetLocalCollection ()->GetAlbumArtManager (); const auto& index = Ui_.CollectionTree_->currentIndex (); const auto& album = index.data (LocalCollectionModel::Role::AlbumName).toString (); const auto& artist = index.data (LocalCollectionModel::Role::ArtistName).toString (); auto dia = new AlbumArtManagerDialog (artist, album, aamgr, this); dia->setAttribute (Qt::WA_DeleteOnClose); dia->show (); } void CollectionWidget::ShowInArtistBrowser () { const auto& index = Ui_.CollectionTree_->currentIndex (); const auto& artist = index.data (LocalCollectionModel::Role::ArtistName).toString (); Core::Instance ().RequestArtistBrowser (artist); } namespace { template<typename T> QList<T> CollectFromModel (const QModelIndex& root, int role) { QList<T> result; const auto& var = root.data (role); if (!var.isNull ()) result << var.value<T> (); auto model = root.model (); for (int i = 0; i < model->rowCount (root); ++i) result += CollectFromModel<T> (model->index (i, 0, root), role); return result; } } void CollectionWidget::HandleCollectionRemove () { const auto& index = Ui_.CollectionTree_->currentIndex (); const auto& paths = CollectFromModel<QString> (index, LocalCollectionModel::Role::TrackPath); if (paths.isEmpty ()) return; auto collection = Core::Instance ().GetLocalCollection (); for (const auto& path : paths) collection->IgnoreTrack (path); } void CollectionWidget::HandleCollectionDelete () { const auto& index = Ui_.CollectionTree_->currentIndex (); const auto& paths = CollectFromModel<QString> (index, LocalCollectionModel::Role::TrackPath); if (paths.isEmpty ()) return; auto response = QMessageBox::question (this, "LeechCraft", tr ("Are you sure you want to erase %n track(s)? This action cannot be undone.", 0, paths.size ()), QMessageBox::Yes | QMessageBox::No); if (response != QMessageBox::Yes) return; for (const auto& path : paths) QFile::remove (path); } void CollectionWidget::LoadFromCollection () { const auto& idxs = Ui_.CollectionTree_->selectionModel ()->selectedRows (); QModelIndexList mapped; for (const auto& src : idxs) { const auto& index = CollectionFilterModel_->mapToSource (src); if (index.isValid ()) mapped << index; } Core::Instance ().GetCollectionsManager ()->Enqueue (mapped, Player_); } namespace { MediaInfo ColIndex2MediaInfo (const QModelIndex& index) { return { index.data (LocalCollectionModel::Role::TrackPath).toString (), index.data (LocalCollectionModel::Role::ArtistName).toString (), index.data (LocalCollectionModel::Role::AlbumName).toString (), index.data (LocalCollectionModel::Role::TrackTitle).toString (), index.data (LocalCollectionModel::Role::TrackGenres).toStringList (), index.data (LocalCollectionModel::Role::TrackLength).toInt (), index.data (LocalCollectionModel::Role::AlbumYear).toInt (), index.data (LocalCollectionModel::Role::TrackNumber).toInt () }; } } void CollectionWidget::on_CollectionTree__customContextMenuRequested (const QPoint& point) { const auto& index = Ui_.CollectionTree_->indexAt (point); if (!index.isValid ()) return; const int nodeType = index.data (LocalCollectionModel::Role::Node).value<int> (); QMenu menu; auto addToPlaylist = menu.addAction (tr ("Add to playlist"), this, &CollectionWidget::LoadFromCollection); addToPlaylist->setProperty ("ActionIcon", "list-add"); menu.addAction (tr ("Replace playlist"), [this] { Player_->clear (); LoadFromCollection (); }); if (nodeType == LocalCollectionModel::NodeType::Track) { auto showTrackProps = menu.addAction (tr ("Show track properties"), this, &CollectionWidget::ShowCollectionTrackProps); showTrackProps->setProperty ("ActionIcon", "document-properties"); } if (nodeType == LocalCollectionModel::NodeType::Album) { auto showAlbumArt = menu.addAction (tr ("Show album art"), this, &CollectionWidget::ShowCollectionAlbumArt); showAlbumArt->setProperty ("ActionIcon", "media-optical"); menu.addAction (tr ("Album art manager..."), this, &CollectionWidget::ShowAlbumArtManager); } auto showInArtistBrowser = menu.addAction (tr ("Show in artist browser"), this, &CollectionWidget::ShowInArtistBrowser); showInArtistBrowser->setIcon (QIcon { "lcicons:/lmp/resources/images/lmp_artist_browser.svg" }); menu.addSeparator (); auto remove = menu.addAction (tr ("Remove from collection..."), this, &CollectionWidget::HandleCollectionRemove); remove->setProperty ("ActionIcon", "list-remove"); auto del = menu.addAction (tr ("Delete from disk..."), this, &CollectionWidget::HandleCollectionDelete); del->setProperty ("ActionIcon", "edit-delete"); emit hookCollectionContextMenuRequested (std::make_shared<Util::DefaultHookProxy> (), &menu, ColIndex2MediaInfo (index)); Core::Instance ().GetProxy ()->GetIconThemeManager ()->ManageWidget (&menu); menu.exec (Ui_.CollectionTree_->viewport ()->mapToGlobal (point)); } void CollectionWidget::HandleScanProgress (int progress) { if (progress >= Ui_.ScanProgress_->maximum ()) { Ui_.ScanProgress_->hide (); return; } if (!Ui_.ScanProgress_->isVisible ()) Ui_.ScanProgress_->show (); Ui_.ScanProgress_->setValue (progress); } } }
31.654839
115
0.697748
[ "model" ]
1eb48e3d113ffbb370b00b7c8ecd9ed0ae186480
1,319
hpp
C++
src/ContinuousCondition.hpp
Nolnocn/Bayesian-Inference
76ee29171c6e3a4a69b752c1f68ae3fef2526f92
[ "MIT" ]
1
2021-07-07T02:45:55.000Z
2021-07-07T02:45:55.000Z
src/ContinuousCondition.hpp
Nolnocn/Bayes-Classifier
76ee29171c6e3a4a69b752c1f68ae3fef2526f92
[ "MIT" ]
null
null
null
src/ContinuousCondition.hpp
Nolnocn/Bayes-Classifier
76ee29171c6e3a4a69b752c1f68ae3fef2526f92
[ "MIT" ]
null
null
null
#ifndef ContinuousCondition_hpp #define ContinuousCondition_hpp #include <string> #include <vector> #include "BayesOutcomeDefs.h" namespace Bayes { // Forward dec class BayesAction; /* * Class representing a single continuous condition of a BayesDecider * Stores data for values that fall into a range */ class ContinuousCondition { public: ContinuousCondition( const std::string& name ); // Accessors for data members needed by BayesDecider double getMeanForOutcome( OutcomeType outcome ) const; double getStdDevForOutcome( OutcomeType outcome ) const; // Increases the sum for a given outcome by a given amount // (Also increases squared sum by squared amount) void addToSumForOutcome( OutcomeType outcome, float amount ); // Calculates mean and standard deviation // Used after sums have been set void buildStats( int totalOutcomeCount ); // Prints formatted member data to the console void printData() const; private: void calculateMeans( int total ); void calculateStdDevs( int total ); std::string m_name; // Primarily for debug convenience // Data members std::vector<float> m_sums; std::vector<float> m_sumsSquared; std::vector<double> m_means; std::vector<double> m_standardDeviations; }; } #endif /* ContinuousCondition_hpp */
24.425926
70
0.739196
[ "vector" ]
1eb6b00356271f58ea3ca76de68dac4cef27d36a
2,270
cpp
C++
Strings/WordCombinations.cpp
JanaSabuj/cses-fi
5879e4d936cddb0f0f0a3850daefd6e4a98babcf
[ "MIT" ]
3
2021-06-11T14:40:35.000Z
2021-10-10T12:06:40.000Z
Strings/WordCombinations.cpp
JanaSabuj/cses-fi
5879e4d936cddb0f0f0a3850daefd6e4a98babcf
[ "MIT" ]
null
null
null
Strings/WordCombinations.cpp
JanaSabuj/cses-fi
5879e4d936cddb0f0f0a3850daefd6e4a98babcf
[ "MIT" ]
null
null
null
/* Sabuj Jana / @greenindia https://www.janasabuj.github.io */ #include <bits/stdc++.h> using namespace std; #define crap ios::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL) #define int long long int #define double long double typedef vector<int> vi; typedef vector<vector<int>> vvi; typedef pair<int, int> pii; #define endl "\n" void print1d(const vector<int>& vec) {for (auto val : vec) {cout << val << " ";} cout << endl;} void print2d(const vector<vector<int>>& vec) {for (auto row : vec) {for (auto val : row) {cout << val << " ";} cout << endl;}} const int mod = 1e9 + 7; const int N = 5005; // Dictionary Trie with prefix search from the end struct trieNode { trieNode* child[26]; bool isEnd; trieNode() { for (int i = 0; i < 26; ++i) { child[i] = NULL; } isEnd = false; } }; int dp[N]; class Trie { trieNode* root; public: Trie() { root = new trieNode(); } void insert(string str) { trieNode* curr = root; for (auto c : str) { int x = c - 'a'; if (curr->child[x] == NULL) curr->child[x] = new trieNode(); curr = curr->child[x]; } curr->isEnd = true; } int search(int idx, int n, string str) { trieNode* curr = root; int ans = 0; // keep on searching for prefixes for (int i = idx; i < n; i++) { int x = str[i] - 'a'; if (curr->child[x] == NULL) break; curr = curr->child[x]; if (curr->isEnd) (ans += dp[i + 1] % mod) %= mod; } return ans; } }; void solve() { string str; cin >> str; Trie root;// trie int k; cin >> k; string s; // insert dictionary into trie while (k--) { cin >> s; root.insert(s); } int n = str.size(); dp[n] = 1; for (int i = n - 1; i >= 0; i--) { dp[i] = root.search(i, n, str); } cout << dp[0] << endl; } #define SABUJ_JANA_WxF 1 signed main() { crap; #ifdef SABUJ_JANA_WF auto start = chrono::high_resolution_clock::now(); freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); freopen("error.txt", "w", stderr); #endif int t = 1; // cin >> t; while (t--) solve(); #ifdef SABUJ_JANA_WF auto stop = chrono::high_resolution_clock::now(); auto duration = chrono::duration_cast<chrono::microseconds>(stop - start); cerr << "Time taken :\n" << duration.count() / 1000000.0 << "s" << "\n"; #endif return 0; }
20.267857
126
0.597797
[ "vector" ]
1eb7766c22cc1c13946446b3933e39a4897a3e68
3,679
cpp
C++
test_angle.cpp
possibly-wrong/angle
77c50720c8983788dfbe68f37ad7746d5594fde4
[ "Unlicense" ]
null
null
null
test_angle.cpp
possibly-wrong/angle
77c50720c8983788dfbe68f37ad7746d5594fde4
[ "Unlicense" ]
null
null
null
test_angle.cpp
possibly-wrong/angle
77c50720c8983788dfbe68f37ad7746d5594fde4
[ "Unlicense" ]
null
null
null
#include "math_angle.h" #include <random> #include <limits> #include <iostream> using namespace math; // Compute and display angle between vectors u and v. bool show(int region, double log10_offset, int rotate, const Vector& u, const Vector& v) { Rational truth = angle_exact(u, v); if (std::isfinite(log10_offset) && truth == 0) { return true; } std::cout << region << " " << log10_offset << " " << rotate << std::endl << " " << Rational(u.x) << std::endl << " " << Rational(u.y) << std::endl << " " << Rational(u.z) << std::endl << " " << Rational(v.x) << std::endl << " " << Rational(v.y) << std::endl << " " << Rational(v.z) << std::endl << " " << truth.to_string(80) << std::endl << " " << Rational(angle(u, v)) << std::endl << " " << Rational(angle0(u, v)) << std::endl << " " << Rational(angle1(u, v)) << std::endl << " " << Rational(angle2(u, v)) << std::endl << " " << Rational(angle3(u, v)) << std::endl; return false; } int main() { std::mt19937 rng; rng.seed(5489); std::normal_distribution<double> randn(0.0, 1.0); // Evaluate a range of magnitudes of "small" angle offsets over // [0, 10^(-18:0.125:-0.5)] radians. std::vector<double> log10_offsets; log10_offsets.push_back(-std::numeric_limits<double>::infinity()); for (double log10_offset = -18; log10_offset <= -0.5; log10_offset += 0.125) { log10_offsets.push_back(log10_offset); } // Evaluate angles in the regions // (0+offset, pi/4-offset, pi/2-offset, pi-offset). for (int region = 0; region < 4; ++region) { for (auto&& log10_offset : log10_offsets) { double offset = std::pow(10.0, log10_offset); Rational vx = cos(offset, 20); // ~200 bits Rational vy = sin(offset, 20); if (region == 1) { vx += vy; // near pi/4 vy = vx - 2 * vy; } else if (region == 2) { std::swap(vx, vy); // near pi/2 } else if (region == 3) { vx = -vx; // near pi } // Evaluate "2D" problem u=(1,0,0) and v=(vx,vy,0). Vector u{1.0, 0.0, 0.0}; Vector v{vx.to_double(), vy.to_double(), 0.0}; show(region, log10_offset, 0, u, v); // Randomly rotate u and v, repeatedly as needed until angle > 0. bool searching = true; while (searching) { // Generate uniform random quaternion rotation. Rational w = randn(rng), x = randn(rng), y = randn(rng), z = randn(rng); Rational inv_mag = inv_sqrt(w*w + x*x + y*y + z*z); w *= inv_mag; x *= inv_mag; y *= inv_mag; z *= inv_mag; // Rotate vectors and evaluate. u.x = (w*w + x*x - y*y - z*z).to_double(); u.y = (2 * (x*y + w*z)).to_double(); u.z = (2 * (x*z - w*y)).to_double(); v.x = ((w*w + x*x - y*y - z*z)*vx + 2 * (x*y - w*z)*vy).to_double(); v.y = ((w*w - x*x + y*y - z*z)*vy + 2 * (x*y + w*z)*vx).to_double(); v.z = (2 * ((w*x + y*z)*vy - (w*y - x*z)*vx)).to_double(); searching = show(region, log10_offset, 1, u, v); } } } }
36.425743
85
0.444958
[ "vector" ]
1ebd0dac4e4bb76da8a048037b6f6f1e333660e6
2,604
cpp
C++
source/main.cpp
GeertArien/mantis-tools
919506e4081a6c9a8f982bdbb1c18cab751d6cc2
[ "MIT" ]
null
null
null
source/main.cpp
GeertArien/mantis-tools
919506e4081a6c9a8f982bdbb1c18cab751d6cc2
[ "MIT" ]
null
null
null
source/main.cpp
GeertArien/mantis-tools
919506e4081a6c9a8f982bdbb1c18cab751d6cc2
[ "MIT" ]
null
null
null
#include <iostream> #include <iomanip> #include <Parser.h> #include <Argument.h> #include <spirv_glsl.hpp> static std::vector<uint32_t> ReadSpirvFile(const char *path) { FILE *file = fopen(path, "rb"); if (!file) { fprintf(stderr, "Failed to open SPIRV file: %s\n", path); return {}; } fseek(file, 0, SEEK_END); size_t len = ftell(file) / sizeof(uint32_t); rewind(file); std::vector<uint32_t> spirv(len); if (fread(spirv.data(), sizeof(uint32_t), len, file) != len) spirv.clear(); fclose(file); return spirv; } static bool WriteStringToFile(const char *path, const char *string) { FILE *file = fopen(path, "w"); if (!file) { fprintf(stderr, "Failed to write file: %s\n", path); return false; } fprintf(file, "%s", string); fclose(file); return true; } bool CrossCompile(const std::string& input_file, const std::string& output_file, const std::string& language) { // Set some options. spirv_cross::CompilerGLSL::Options options; if (language == "glsl-100-es") { options.version = 100; options.es = true; } else if (language == "glsl-330") { options.version = 330; options.es = false; } else { std::cerr << "Invalid target language '" << language << "'" << std::endl; return false; } std::vector<uint32_t> spirv_binary = ReadSpirvFile(input_file.data()); std::string source; try { spirv_cross::CompilerGLSL glsl(std::move(spirv_binary)); glsl.set_common_options(options); source = glsl.compile(); } catch (const std::exception& e) { std::cerr << "Invalid SPIR-V file: " << input_file << std::endl; return false; } return WriteStringToFile(output_file.data(), source.data()); } int main(int argc, const char** argv) { CMD::Argument show_help(CMD::Argument::Type::Bool, "--help", "show help", false); CMD::Argument input(CMD::Argument::Type::String, "--input", "SPIR-V input file", std::string(), true); CMD::Argument output(CMD::Argument::Type::String, "--output", "output file", std::string(), true); CMD::Argument lang(CMD::Argument::Type::String, "--lang", "output language (glsl-100-es, glsl-330)", std::string(), true); CMD::Parser cmd_parser("--input flat.spv --output flat.frag --lang glsl-100-es"); cmd_parser.SetArguments({ &show_help, &input, &output, &lang }); if (!cmd_parser.Parse(argc, argv)) { if (!show_help.GetBoolValue()) { cmd_parser.PrintErrors(std::cerr); return 1; } } if (show_help.GetBoolValue()) { cmd_parser.PrintHelp(std::cout); return 0; } if (CrossCompile(input.GetStringValue(), output.GetStringValue(), lang.GetStringValue())) { return 0; } else { return 1; } }
25.782178
123
0.667435
[ "vector" ]
363487a4d1bf3689a29d893a3cca2e50aa9531d5
63,888
cpp
C++
test/crypto_Aes192Encryptor_TestClass.cpp
toolbrew/libtoolchain
fd98be60d1c5ca62871c16c88b8e59be05d7f0ac
[ "MIT" ]
4
2019-01-30T21:04:33.000Z
2022-03-20T04:24:34.000Z
test/crypto_Aes192Encryptor_TestClass.cpp
toolbrew/libtoolchain
fd98be60d1c5ca62871c16c88b8e59be05d7f0ac
[ "MIT" ]
2
2021-11-18T09:07:53.000Z
2021-11-19T13:25:20.000Z
test/crypto_Aes192Encryptor_TestClass.cpp
toolbrew/libtoolchain
fd98be60d1c5ca62871c16c88b8e59be05d7f0ac
[ "MIT" ]
1
2021-11-18T09:11:04.000Z
2021-11-18T09:11:04.000Z
#include <iostream> #include <sstream> #include <fstream> #include <mbedtls/aes.h> #include "crypto_Aes192Encryptor_TestClass.h" #include <tc/Exception.h> #include <tc/crypto/AesEncryptor.h> #include <tc/cli/FormatUtil.h> #include <tc/io/PaddingSource.h> void crypto_Aes192Encryptor_TestClass::runAllTests(void) { std::cout << "[tc::crypto::Aes192Encryptor] START" << std::endl; test_Constants(); test_UseClassEnc(); test_UseClassDec(); test_DoesNothingWhenNotInit(); test_InitializeThrowsExceptionOnBadInput(); test_EncryptThrowsExceptionOnBadInput(); test_DecryptThrowsExceptionOnBadInput(); std::cout << "[tc::crypto::Aes192Encryptor] END" << std::endl; } void crypto_Aes192Encryptor_TestClass::test_Constants() { std::cout << "[tc::crypto::Aes192Encryptor] test_Constants : " << std::flush; try { try { std::stringstream ss; // check block size static const size_t kExpectedBlockSize = 16; if (tc::crypto::Aes192Encryptor::kBlockSize != kExpectedBlockSize) { ss << "kBlockSize had value " << std::dec << tc::crypto::Aes192Encryptor::kBlockSize << " (expected " << kExpectedBlockSize << ")"; throw tc::Exception(ss.str()); } // check key size static const size_t kExpectedKeySize = 24; if (tc::crypto::Aes192Encryptor::kKeySize != kExpectedKeySize) { ss << "kKeySize had value " << std::dec << tc::crypto::Aes192Encryptor::kKeySize << " (expected " << kExpectedKeySize << ")"; throw tc::Exception(ss.str()); } std::cout << "PASS" << std::endl; } catch (const tc::Exception& e) { std::cout << "FAIL (" << e.error() << ")" << std::endl; } } catch (const std::exception& e) { std::cout << "UNHANDLED EXCEPTION (" << e.what() << ")" << std::endl; } } void crypto_Aes192Encryptor_TestClass::test_UseClassEnc() { std::cout << "[tc::crypto::Aes192Encryptor] test_UseClassEnc : " << std::flush; try { try { std::stringstream ss; // create tests std::vector<TestCase> tests; util_Setup_TestCases(tests); tc::crypto::Aes192Encryptor cryptor; for (auto test = tests.begin(); test != tests.end(); test++) { tc::ByteData data = tc::ByteData(test->plaintext.size()); // initialize key cryptor.initialize(test->key.data(), test->key.size()); // clear data memset(data.data(), 0xff, data.size()); // encrypt data cryptor.encrypt(data.data(), test->plaintext.data()); // validate cipher text if (memcmp(data.data(), test->ciphertext.data(), data.size()) != 0) { ss << "Test \"" << test->test_name << "\" Failed: " << tc::cli::FormatUtil::formatBytesAsString(data, true, "") << " (expected " << tc::cli::FormatUtil::formatBytesAsString(test->ciphertext, true, ""); throw tc::Exception(ss.str()); } } std::cout << "PASS" << std::endl; } catch (const tc::Exception& e) { std::cout << "FAIL (" << e.error() << ")" << std::endl; } } catch (const std::exception& e) { std::cout << "UNHANDLED EXCEPTION (" << e.what() << ")" << std::endl; } } void crypto_Aes192Encryptor_TestClass::test_UseClassDec() { std::cout << "[tc::crypto::Aes192Encryptor] test_UseClassDec : " << std::flush; try { try { std::stringstream ss; // create tests std::vector<TestCase> tests; util_Setup_TestCases(tests); tc::crypto::Aes192Encryptor cryptor; for (auto test = tests.begin(); test != tests.end(); test++) { tc::ByteData data = tc::ByteData(test->plaintext.size()); // initialize key cryptor.initialize(test->key.data(), test->key.size()); // clear data memset(data.data(), 0xff, data.size()); // decrypt data cryptor.decrypt(data.data(), test->ciphertext.data()); // test plain text if (memcmp(data.data(), test->plaintext.data(), data.size()) != 0) { ss << "Test \"" << test->test_name << "\" Failed: " << tc::cli::FormatUtil::formatBytesAsString(data, true, "") << " (expected " << tc::cli::FormatUtil::formatBytesAsString(test->plaintext, true, ""); throw tc::Exception(ss.str()); } } std::cout << "PASS" << std::endl; } catch (const tc::Exception& e) { std::cout << "FAIL (" << e.error() << ")" << std::endl; } } catch (const std::exception& e) { std::cout << "UNHANDLED EXCEPTION (" << e.what() << ")" << std::endl; } } void crypto_Aes192Encryptor_TestClass::test_DoesNothingWhenNotInit() { std::cout << "[tc::crypto::Aes192Encryptor] test_DoesNothingWhenNotInit : " << std::flush; try { try { std::stringstream ss; tc::crypto::Aes192Encryptor cryptor; // create data tc::ByteData control_data = tc::io::PaddingSource(0xee, tc::crypto::Aes192Encryptor::kBlockSize).pullData(0, tc::crypto::Aes192Encryptor::kBlockSize); tc::ByteData data = tc::ByteData(control_data.data(), control_data.size()); // try to decrypt without calling initialize() cryptor.decrypt(data.data(), data.data()); // test plain text if (memcmp(data.data(), control_data.data(), data.size()) != 0) { ss << "Failed: decrypt() operated on data when not initialized"; throw tc::Exception(ss.str()); } // try to encrypt without calling initialize() cryptor.encrypt(data.data(), data.data()); // test plain text if (memcmp(data.data(), control_data.data(), data.size()) != 0) { ss << "Failed: encrypt() operated on data when not initialized"; throw tc::Exception(ss.str()); } std::cout << "PASS" << std::endl; } catch (const tc::Exception& e) { std::cout << "FAIL (" << e.error() << ")" << std::endl; } } catch (const std::exception& e) { std::cout << "UNHANDLED EXCEPTION (" << e.what() << ")" << std::endl; } } void crypto_Aes192Encryptor_TestClass::test_InitializeThrowsExceptionOnBadInput() { std::cout << "[tc::crypto::Aes192Encryptor] test_InitializeThrowsExceptionOnBadInput : " << std::flush; try { try { std::stringstream ss; // create tests std::vector<TestCase> tests; util_Setup_TestCases(tests); tc::crypto::Aes192Encryptor cryptor; try { cryptor.initialize(nullptr, tests[0].key.size()); throw tc::Exception("Failed to throw ArgumentNullException where key==nullptr"); } catch(const tc::ArgumentNullException&) { // all good if this was thrown. } try { cryptor.initialize(tests[0].key.data(), 0); throw tc::Exception("Failed to throw ArgumentOutOfRangeException where key_size==0"); } catch(const tc::ArgumentOutOfRangeException&) { // all good if this was thrown. } try { cryptor.initialize(tests[0].key.data(), tc::crypto::Aes192Encryptor::kKeySize-1); throw tc::Exception("Failed to throw ArgumentOutOfRangeException where key_size==tc::crypto::Aes192Encryptor::kKeySize-1"); } catch(const tc::ArgumentOutOfRangeException&) { // all good if this was thrown. } try { cryptor.initialize(tests[0].key.data(), tc::crypto::Aes192Encryptor::kKeySize+1); throw tc::Exception("Failed to throw ArgumentOutOfRangeException where key_size==tc::crypto::Aes192Encryptor::kKeySize+1"); } catch(const tc::ArgumentOutOfRangeException&) { // all good if this was thrown. } std::cout << "PASS" << std::endl; } catch (const tc::Exception& e) { std::cout << "FAIL (" << e.error() << ")" << std::endl; } } catch (const std::exception& e) { std::cout << "UNHANDLED EXCEPTION (" << e.what() << ")" << std::endl; } } void crypto_Aes192Encryptor_TestClass::test_EncryptThrowsExceptionOnBadInput() { std::cout << "[tc::crypto::Aes192Encryptor] test_EncryptThrowsExceptionOnBadInput : " << std::flush; try { try { std::stringstream ss; // create tests std::vector<TestCase> tests; util_Setup_TestCases(tests); tc::crypto::Aes192Encryptor cryptor; cryptor.initialize(tests[0].key.data(), tests[0].key.size()); tc::ByteData data = tc::ByteData(tests[0].plaintext.size()); // reference encrypt call //cryptor.encrypt(data.data(), tests[0].plaintext.data()); try { cryptor.encrypt(nullptr, tests[0].plaintext.data()); throw tc::Exception("Failed to throw ArgumentNullException where dst==nullptr"); } catch(const tc::ArgumentNullException&) { // all good if this was thrown. } try { cryptor.encrypt(data.data(), nullptr); throw tc::Exception("Failed to throw ArgumentNullException where src==nullptr"); } catch(const tc::ArgumentNullException&) { // all good if this was thrown. } std::cout << "PASS" << std::endl; } catch (const tc::Exception& e) { std::cout << "FAIL (" << e.error() << ")" << std::endl; } } catch (const std::exception& e) { std::cout << "UNHANDLED EXCEPTION (" << e.what() << ")" << std::endl; } } void crypto_Aes192Encryptor_TestClass::test_DecryptThrowsExceptionOnBadInput() { std::cout << "[tc::crypto::Aes192Encryptor] test_DecryptThrowsExceptionOnBadInput : " << std::flush; try { try { std::stringstream ss; // create tests std::vector<TestCase> tests; util_Setup_TestCases(tests); tc::crypto::Aes192Encryptor cryptor; cryptor.initialize(tests[0].key.data(), tests[0].key.size()); tc::ByteData data = tc::ByteData(tests[0].plaintext.size()); // reference decrypt call //cryptor.decrypt(data.data(), tests[0].ciphertext.data()); try { cryptor.decrypt(nullptr, tests[0].ciphertext.data()); throw tc::Exception("Failed to throw ArgumentNullException where dst==nullptr"); } catch(const tc::ArgumentNullException&) { // all good if this was thrown. } try { cryptor.decrypt(data.data(), nullptr); throw tc::Exception("Failed to throw ArgumentNullException where src==nullptr"); } catch(const tc::ArgumentNullException&) { // all good if this was thrown. } std::cout << "PASS" << std::endl; } catch (const tc::Exception& e) { std::cout << "FAIL (" << e.error() << ")" << std::endl; } } catch (const std::exception& e) { std::cout << "UNHANDLED EXCEPTION (" << e.what() << ")" << std::endl; } } void crypto_Aes192Encryptor_TestClass::util_Setup_TestCases(std::vector<crypto_Aes192Encryptor_TestClass::TestCase>& test_cases) { TestCase tmp; test_cases.clear(); // Variable Key Known Answer Tests // taken from "ecb_vk.txt" from https://csrc.nist.gov/archive/aes/rijndael/rijndael-vals.zip tmp.plaintext = tc::cli::FormatUtil::hexStringToBytes("00000000000000000000000000000000"); tmp.test_name = "Variable Key Known Answer Test 1"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("800000000000000000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("DE885DC87F5A92594082D02CC1E1B42C"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 2"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("400000000000000000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("C749194F94673F9DD2AA1932849630C1"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 3"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("200000000000000000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("0CEF643313912934D310297B90F56ECC"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 4"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("100000000000000000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("C4495D39D4A553B225FBA02A7B1B87E1"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 5"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("080000000000000000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("636D10B1A0BCAB541D680A7970ADC830"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 6"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("040000000000000000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("07CF045786BD6AFCC147D99E45A901A7"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 7"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("020000000000000000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("6A8E3F425A7599348F95398448827976"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 8"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("010000000000000000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("5518276836148A00D91089A20D8BFF57"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 9"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("008000000000000000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("F267E07B5E87E3BC20B969C61D4FCB06"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 10"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("004000000000000000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("5A1CDE69571D401BFCD20DEBADA2212C"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 11"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("002000000000000000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("70A9057263254701D12ADD7D74CD509E"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 12"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("001000000000000000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("35713A7E108031279388A33A0FE2E190"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 13"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000800000000000000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("E74EDE82B1254714F0C7B4B243108655"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 14"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000400000000000000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("39272E3100FAA37B55B862320D1B3EB3"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 15"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000200000000000000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("6D6E24C659FC5AEF712F77BCA19C9DD0"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 16"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000100000000000000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("76D18212F972370D3CC2C6C372C6CF2F"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 17"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000080000000000000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("B21A1F0BAE39E55C7594ED570A7783EA"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 18"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000040000000000000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("77DE202111895AC48DD1C974B358B458"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 19"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000020000000000000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("67810B311969012AAF7B504FFAF39FD1"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 20"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000010000000000000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("C22EA2344D3E9417A6BA07843E713AEA"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 21"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000008000000000000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("C79CAF4B97BEE0BD0630AB354539D653"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 22"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000004000000000000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("135FD1AF761D9AE23DF4AA6B86760DB4"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 23"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000002000000000000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("D4659D0B06ACD4D56AB8D11A16FD83B9"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 24"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000001000000000000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("F7D270028FC188E4E4F35A4AAA25D4D4"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 25"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000800000000000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("345CAE5A8C9620A9913D5473985852FF"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 26"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000400000000000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("4E8980ADDE60B0E42C0B287FEA41E729"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 27"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000200000000000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("F11B6D74E1F15155633DC39743C1A527"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 28"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000100000000000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("9C87916C0180064F9D3179C6F5DD8C35"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 29"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000080000000000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("71AB186BCAEA518E461D4F7FAD230E6A"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 30"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000040000000000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("C4A31BBC3DAAF742F9141C2A5001A49C"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 31"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000020000000000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("E7C47B7B1D40F182A8928C8A55671D07"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 32"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000010000000000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("8E17F294B28FA373C6249538868A7EEF"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 33"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000008000000000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("754404096A5CBC08AF09491BE249141A"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 34"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000004000000000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("101CB56E55F05D86369B6D1069204F0A"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 35"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000002000000000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("73F19BB6604205C6EE227B9759791E41"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 36"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000001000000000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("6270C0028F0D136C37A56B2CB64D24D6"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 37"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000800000000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("A3BF7C2C38D1114A087ECF212E694346"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 38"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000400000000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("49CABFF2CEF7D9F95F5EFB1F7A1A7DDE"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 39"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000200000000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("EC7F8A47CC59B849469255AD49F62752"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 40"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000100000000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("68FAE55A13EFAF9B07B3552A8A0DC9D1"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 41"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000080000000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("211E6B19C69FAEF481F64F24099CDA65"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 42"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000040000000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("DBB918C75BC5732416F79FB0C8EE4C5C"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 43"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000020000000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("98D494E5D963A6C8B92536D3EC35E3FD"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 44"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000010000000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("C9A873404D403D6F074190851D67781A"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 45"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000008000000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("073AEF4A7C77D921928CB0DD9D27CAE7"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 46"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000004000000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("89BDE25CEE36FDE769A10E52298CF90F"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 47"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000002000000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("26D0842D37EAD38557C65E0A5E5F122E"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 48"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000001000000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("F8294BA375AF46B3F22905BBAFFAB107"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 49"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000800000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("2AD63EB4D0D43813B979CF72B35BDB94"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 50"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000400000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("7710C171EE0F4EFA39BE4C995180181D"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 51"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000200000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("C0CB2B40DBA7BE8C0698FAE1E4B80FF8"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 52"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000100000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("97970E505194622FD955CA1B80B784E9"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 53"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000080000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("7CB1824B29F850900DF2CAD9CF04C1CF"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 54"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000040000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("FDF4F036BB988E42F2F62DE63FE19A64"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 55"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000020000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("08908CFE2C82606B2C15DF61B75CF3E2"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 56"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000010000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("B3AA689EF2D07FF365ACB9ADBA2AF07A"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 57"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000008000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("F2672CD8EAA3B98776660D0263656F5C"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 58"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000004000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("5BDEAC00E986687B9E1D94A0DA7BF452"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 59"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000002000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("E6D57BD66EA1627363EE0C4B711B0B21"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 60"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000001000000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("03730DD6ACB4AD9996A63BE7765EC06F"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 61"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000800000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("A470E361AA5437B2BE8586D2F78DE582"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 62"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000400000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("7567FEEFA559911FD479670246B484E3"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 63"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000200000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("29829DEA15A4E7A4C049045E7B106E29"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 64"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000100000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("A407834C3D89D48A2CB7A152208FA4ED"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 65"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000080000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("68F948053F78FEF0D8F9FE7EF3A89819"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 66"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000040000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("B605174CAB13AD8FE3B20DA3AE7B0234"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 67"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000020000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("CCAB8F0AEBFF032893996D383CBFDBFA"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 68"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000010000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("AF14BB8428C9730B7DC17B6C1CBEBCC8"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 69"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000008000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("5A41A21332040877EB7B89E8E80D19FE"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 70"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000004000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("AC1BA52EFCDDE368B1596F2F0AD893A0"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 71"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000002000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("41B890E31B9045E6ECDC1BC3F2DB9BCC"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 72"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000001000000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("4D54A549728E55B19A23660424A0F146"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 73"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000800000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("A917581F41C47C7DDCFFD5285E2D6A61"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 74"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000400000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("604DF24BA6099B93A7405A524D764FCB"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 75"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000200000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("78D9D156F28B190E232D1B7AE7FC730A"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 76"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000100000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("5A12C39E442CD7F27B3CD77F5D029582"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 77"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000080000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("FF2BF2F47CF7B0F28EE25AF95DBF790D"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 78"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000040000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("1863BB7D193BDA39DF090659EB8AE48B"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 79"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000020000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("38178F2FB4CFCF31E87E1ABCDC023EB5"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 80"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000010000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("F5B13DC690CC0D541C6BA533023DC8C9"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 81"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000008000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("48EC05238D7375D126DC9D08884D4827"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 82"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000004000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("ACD0D81139691B310B92A6E377BACC87"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 83"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000002000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("9A4AA43578B55CE9CC178F0D2E162C79"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 84"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000001000000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("08AD94BC737DB3C87D49B9E01B720D81"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 85"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000800000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("3BCFB2D5D210E8332900C5991D551A2A"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 86"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000400000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("C5F0C6B9397ACB29635CE1A0DA2D8D96"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 87"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000200000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("844A29EFC693E2FA9900F87FBF5DCD5F"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 88"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000100000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("5126A1C41051FEA158BE41200E1EA59D"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 89"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000080000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("302123CA7B4F46D667FFFB0EB6AA7703"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 90"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000040000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("A9D16BCE7DB5C024277709EE2A88D91A"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 91"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000020000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("F013C5EC123A26CFC34B598C992A996B"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 92"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000010000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("E38A825CD971A1D2E56FB1DBA248F2A8"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 93"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000008000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("6E701773C0311E0BD4C5A097406D22B3"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 94"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000004000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("754262CEF0C64BE4C3E67C35ABE439F7"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 95"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000002000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("C9C2D4C47DF7D55CFA0EE5F1FE5070F4"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 96"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000001000000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("6AB4BEA85B172573D8BD2D5F4329F13D"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 97"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000800000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("11F03EF28E2CC9AE5165C587F7396C8C"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 98"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000400000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("0682F2EB1A68BAC7949922C630DD27FA"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 99"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000200000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("ABB0FEC0413D659AFE8E3DCF6BA873BB"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 100"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000100000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("FE86A32E19F805D6569B2EFADD9C92AA"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 101"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000080000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("E434E472275D1837D3D717F2EECC88C3"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 102"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000040000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("74E57DCD12A21D26EF8ADAFA5E60469A"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 103"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000020000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("C275429D6DAD45DDD423FA63C816A9C1"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 104"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000010000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("7F6EC1A9AE729E86F7744AED4B8F4F07"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 105"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000008000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("48B5A71AB9292BD4F9E608EF102636B2"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 106"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000004000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("076FB95D5F536C78CBED3181BCCF3CF1"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 107"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000002000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("BFA76BEA1E684FD3BF9256119EE0BC0F"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 108"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000001000000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("7D395923D56577F3FF8670998F8C4A71"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 109"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000800000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("BA02C986E529AC18A882C34BA389625F"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 110"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000400000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("3DFCF2D882AFE75D3A191193013A84B5"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 111"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000200000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("FAD1FDE1D0241784B63080D2C74D236C"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 112"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000100000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("7D6C80D39E41F007A14FB9CD2B2C15CD"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 113"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000080000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("7975F401FC10637BB33EA2DB058FF6EC"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 114"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000040000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("657983865C55A818F02B7FCD52ED7E99"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 115"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000020000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("B32BEB1776F9827FF4C3AC9997E84B20"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 116"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000010000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("2AE2C7C374F0A41E3D46DBC3E66BB59F"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 117"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000008000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("4D835E4ABDD4BDC6B88316A6E931A07F"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 118"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000004000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("E07EFABFF1C353F7384EBB87B435A3F3"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 119"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000002000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("ED3088DC3FAF89AD87B4356FF1BB09C2"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 120"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000001000000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("4324D01140C156FC898C2E32BA03FB05"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 121"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000800000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("BE15D016FACB5BAFBC24FA9289132166"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 122"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000400000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("AC9B7048EDB1ACF4D97A5B0B3F50884B"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 123"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000200000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("448BECE1F86C7845DFA9A4BB2A016FB3"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 124"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000100000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("10DD445E87686EB46EA9B1ABC49257F0"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 125"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000080000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("B7FCCF7659FA756D4B7303EEA6C07458"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 126"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000040000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("289117115CA3513BAA7640B1004872C2"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 127"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000020000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("57CB42F7EE7186051F50B93FFA7B35BF"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 128"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000010000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("F2741BFBFB81663B9136802FB9C3126A"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 129"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000008000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("E32DDDC5C7398C096E3BD535B31DB5CE"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 130"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000004000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("81D3C204E608AF9CC713EAEBCB72433F"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 131"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000002000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("D4DEEF4BFC36AAA579496E6935F8F98E"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 132"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000001000000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("C356DB082B97802B038571C392C5C8F6"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 133"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000800000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("A3919ECD4861845F2527B77F06AC6A4E"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 134"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000400000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("A53858E17A2F802A20E40D44494FFDA0"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 135"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000200000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("5D989E122B78C758921EDBEEB827F0C0"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 136"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000100000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("4B1C0C8F9E7830CC3C4BE7BD226FA8DE"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 137"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000080000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("82C40C5FD897FBCA7B899C70713573A1"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 138"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000040000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("ED13EE2D45E00F75CCDB51EA8E3E36AD"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 139"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000020000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("F121799EEFE8432423176A3CCF6462BB"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 140"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000010000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("4FA0C06F07997E98271DD86F7B355C50"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 141"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000008000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("849EB364B4E81D058649DC5B1BF029B9"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 142"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000004000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("F48F9E0DE8DE7AD944A207809335D9B1"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 143"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000002000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("E59E9205B5A81A4FD26DFCF308966022"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 144"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000001000000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("3A91A1BE14AAE9ED700BDF9D70018804"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 145"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000000800000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("8ABAD78DCB79A48D79070E7DA89664EC"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 146"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000000400000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("B68377D98AAE6044938A7457F6C649D9"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 147"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000000200000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("E4E1275C42F5F1B63D662C099D6CE33D"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 148"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000000100000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("7DEF32A34C6BE668F17DA1BB193B06EF"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 149"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000000080000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("78B6000CC3D30CB3A74B68D0EDBD2B53"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 150"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000000040000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("0A47531DE88DD8AE5C23EAE4F7D1F2D5"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 151"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000000020000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("667B24E8000CF68231EC484581D922E5"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 152"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000000010000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("39DAA5EBD4AACAE130E9C33236C52024"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 153"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000000008000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("E3C88760B3CB21360668A63E55BB45D1"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 154"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000000004000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("F131EE903C1CDB49D416866FD5D8DE51"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 155"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000000002000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("7A1916135B0447CF4033FC13047A583A"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 156"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000000001000000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("F7D55FB27991143DCDFA90DDF0424FCB"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 157"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000000000800000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("EA93E7D1CA1111DBD8F7EC111A848C0C"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 158"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000000000400000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("2A689E39DFD3CBCBE221326E95888779"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 159"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000000000200000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("C1CE399CA762318AC2C40D1928B4C57D"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 160"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000000000100000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("D43FB6F2B2879C8BFAF0092DA2CA63ED"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 161"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000000000080000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("224563E617158DF97650AF5D130E78A5"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 162"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000000000040000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("6562FDF6833B7C4F7484AE6EBCC243DD"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 163"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000000000020000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("93D58BA7BED22615D661D002885A7457"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 164"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000000000010000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("9A0EF559003AD9E52D3E09ED3C1D3320"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 165"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000000000008000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("96BAF5A7DC6F3DD27EB4C717A85D261C"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 166"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000000000004000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("B8762E06884900E8452293190E19CCDB"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 167"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000000000002000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("785416A22BD63CBABF4B1789355197D3"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 168"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000000000001000000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("A0D20CE1489BAA69A3612DCE90F7ABF6"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 169"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000000000000800000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("700244E93DC94230CC607FFBA0E48F32"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 170"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000000000000400000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("85329E476829F872A2B4A7E59F91FF2D"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 171"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000000000000200000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("E4219B4935D988DB719B8B8B2B53D247"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 172"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000000000000100000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("6ACDD04FD13D4DB4409FE8DD13FD737B"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 173"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000000000000080000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("9EB7A670AB59E15BE582378701C1EC14"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 174"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000000000000040000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("29DF2D6935FE657763BC7A9F22D3D492"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 175"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000000000000020000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("99303359D4A13AFDBE6C784028CE533A"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 176"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000000000000010000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("FF5C70A6334545F33B9DBF7BEA0417CA"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 177"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000000000000008000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("289F58A17E4C50EDA4269EFB3DF55815"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 178"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000000000000004000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("EA35DCB416E9E1C2861D1682F062B5EB"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 179"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000000000000002000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("3A47BF354BE775383C50B0C0A83E3A58"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 180"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000000000000001000"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("BF6C1DC069FB95D05D43B01D8206D66B"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 181"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000000000000000800"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("046D1D580D5898DA6595F32FD1F0C33D"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 182"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000000000000000400"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("5F57803B7B82A110F7E9855D6A546082"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 183"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000000000000000200"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("25336ECF34E7BE97862CDFF715FF05A8"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 184"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000000000000000100"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("ACBAA2A943D8078022D693890E8C4FEF"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 185"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000000000000000080"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("3947597879F6B58E4E2F0DF825A83A38"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 186"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000000000000000040"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("4EB8CC3335496130655BF3CA570A4FC0"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 187"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000000000000000020"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("BBDA7769AD1FDA425E18332D97868824"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 188"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000000000000000010"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("5E7532D22DDB0829A29C868198397154"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 189"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000000000000000008"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("E66DA67B630AB7AE3E682855E1A1698E"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 190"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000000000000000004"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("4D93800F671B48559A64D1EA030A590A"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 191"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000000000000000002"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("F33159FCC7D9AE30C062CD3B322AC764"); test_cases.push_back(tmp); tmp.test_name = "Variable Key Known Answer Test 192"; tmp.key = tc::cli::FormatUtil::hexStringToBytes("000000000000000000000000000000000000000000000001"); tmp.ciphertext = tc::cli::FormatUtil::hexStringToBytes("8BAE4EFB70D33A9792EEA9BE70889D72"); test_cases.push_back(tmp); }
47.820359
206
0.776891
[ "vector" ]
3635bb4ecd80358132b68bdfa144427f8bbeaa19
46,319
cpp
C++
solid/frame/mprpc/src/mprpcmessagewriter.cpp
solidoss/solidframe
92fa8ce5737b9e88f3df3f549a38e9df79b7bf96
[ "BSL-1.0" ]
4
2020-12-05T23:33:32.000Z
2021-10-04T02:59:41.000Z
solid/frame/mprpc/src/mprpcmessagewriter.cpp
solidoss/solidframe
92fa8ce5737b9e88f3df3f549a38e9df79b7bf96
[ "BSL-1.0" ]
1
2020-03-22T20:38:05.000Z
2020-03-22T20:38:05.000Z
solid/frame/mprpc/src/mprpcmessagewriter.cpp
solidoss/solidframe
92fa8ce5737b9e88f3df3f549a38e9df79b7bf96
[ "BSL-1.0" ]
2
2021-01-30T09:08:52.000Z
2021-02-20T03:33:33.000Z
// solid/frame/ipc/src/ipcmessagereader.cpp // // Copyright (c) 2015 Valentin Palade (vipalade @ gmail . com) // // This file is part of SolidFrame framework. // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt. // #include "mprpcmessagewriter.hpp" #include "mprpcutility.hpp" #include "solid/frame/mprpc/mprpcconfiguration.hpp" #include "solid/frame/mprpc/mprpcerror.hpp" #include "solid/system/cassert.hpp" #include "solid/system/log.hpp" namespace solid { namespace frame { namespace mprpc { namespace { const LoggerT logger("solid::frame::mprpc::writer"); } //----------------------------------------------------------------------------- MessageWriter::MessageWriter() : current_message_type_id_(InvalidIndex()) , write_queue_sync_index_(InvalidIndex()) , write_queue_back_index_(InvalidIndex()) , write_queue_async_count_(0) , write_queue_direct_count_(0) , order_inner_list_(message_vec_) , write_inner_list_(message_vec_) , cache_inner_list_(message_vec_) { } //----------------------------------------------------------------------------- MessageWriter::~MessageWriter() {} //----------------------------------------------------------------------------- void MessageWriter::prepare(WriterConfiguration const& _rconfig) { //WARNING: message_vec_ MUST NOT be resized later //as it would interfere with pointers stored in serializer. message_vec_.reserve(_rconfig.max_message_count_multiplex + _rconfig.max_message_count_response_wait); message_vec_.resize(message_vec_.capacity()); for (size_t i = 0; i < message_vec_.size(); ++i) { cache_inner_list_.pushBack(i); } } //----------------------------------------------------------------------------- void MessageWriter::unprepare() { } //----------------------------------------------------------------------------- bool MessageWriter::full(WriterConfiguration const& _rconfig) const { return write_inner_list_.size() >= _rconfig.max_message_count_multiplex; } //----------------------------------------------------------------------------- void MessageWriter::doWriteQueuePushBack(const size_t _msgidx, const int _line) { if (write_inner_list_.size() <= 1) { //"(size() <= 1)" because write_queue_back_index_ may be -1 when write_inner_list_.size() == 1 write_inner_list_.pushBack(_msgidx); write_queue_back_index_ = _msgidx; } else { solid_assert_log(write_queue_back_index_ != InvalidIndex(), logger, " msgidx = " << _msgidx << " write_inner_list.size = " << write_inner_list_.size()); write_inner_list_.insertAfter(write_queue_back_index_, _msgidx); write_queue_back_index_ = _msgidx; } MessageStub& rmsgstub(message_vec_[_msgidx]); solid_dbg(logger, Info, this << " code line = " << _line << " idx = " << _msgidx << " is_relay = " << rmsgstub.isRelay()); if (!rmsgstub.isRelay()) { ++write_queue_direct_count_; } if (!rmsgstub.isSynchronous()) { ++write_queue_async_count_; } } //----------------------------------------------------------------------------- void MessageWriter::doWriteQueueErase(const size_t _msgidx, const int _line) { MessageStub& rmsgstub(message_vec_[_msgidx]); solid_dbg(logger, Info, this << " code line = " << _line << " idx = " << _msgidx << " is_relay = " << rmsgstub.isRelay()); if (!rmsgstub.isRelay()) { --write_queue_direct_count_; } if (!rmsgstub.isSynchronous()) { --write_queue_async_count_; } if (_msgidx == write_queue_sync_index_) { write_queue_sync_index_ = InvalidIndex(); } if (_msgidx == write_queue_back_index_) { write_queue_back_index_ = write_inner_list_.nextIndex(_msgidx); if (write_queue_back_index_ == InvalidIndex()) { write_queue_back_index_ = write_inner_list_.backIndex(); } } write_inner_list_.erase(_msgidx); } //----------------------------------------------------------------------------- bool MessageWriter::enqueue( WriterConfiguration const& _rconfig, MessageBundle& _rmsgbundle, MessageId const& _rpool_msg_id, MessageId& _rconn_msg_id) { //see if we can accept the message if (full(_rconfig) || cache_inner_list_.empty()) { return false; } //see if we have too many messages waiting for responses if ( Message::is_awaiting_response(_rmsgbundle.message_flags) && ((order_inner_list_.size() - write_inner_list_.size()) >= _rconfig.max_message_count_response_wait)) { return false; } solid_assert_log(_rmsgbundle.message_ptr.get(), logger); //clear all disrupting flags _rmsgbundle.message_flags.reset(MessageFlagsE::StartedSend).reset(MessageFlagsE::DoneSend); const size_t idx = cache_inner_list_.popFront(); MessageStub& rmsgstub(message_vec_[idx]); rmsgstub.msgbundle_ = std::move(_rmsgbundle); rmsgstub.pool_msg_id_ = _rpool_msg_id; rmsgstub.msgbundle_.message_flags = Message::update_state_flags(Message::clear_state_flags(rmsgstub.msgbundle_.message_flags) | Message::state_flags(rmsgstub.msgbundle_.message_ptr->flags())); _rconn_msg_id = MessageId(idx, rmsgstub.unique_); order_inner_list_.pushBack(idx); doWriteQueuePushBack(idx, __LINE__); solid_dbg(logger, Verbose, "is_relayed = " << Message::is_relayed(rmsgstub.msgbundle_.message_ptr->flags()) << ' ' << MessageWriterPrintPairT(*this, PrintInnerListsE)); return true; } //----------------------------------------------------------------------------- bool MessageWriter::enqueue( WriterConfiguration const& _rconfig, RelayData*& _rprelay_data, MessageId const& _rengine_msg_id, MessageId& _rconn_msg_id, bool& _rmore) { if (full(_rconfig)) { _rmore = false; return false; } size_t msgidx; //see if we have too many messages waiting for responses if (_rconn_msg_id.isInvalid()) { //front message data if (cache_inner_list_.empty()) { _rmore = false; return false; } if ( _rprelay_data->isRequest() && ((order_inner_list_.size() - write_inner_list_.size()) >= _rconfig.max_message_count_response_wait)) { return false; } msgidx = cache_inner_list_.popFront(); _rconn_msg_id = MessageId(msgidx, message_vec_[msgidx].unique_); order_inner_list_.pushBack(msgidx); } else { msgidx = _rconn_msg_id.index; solid_assert_log(message_vec_[msgidx].unique_ == _rconn_msg_id.unique, logger); if (message_vec_[msgidx].unique_ != _rconn_msg_id.unique || message_vec_[msgidx].prelay_data_ != nullptr) { solid_dbg(logger, Verbose, "Relay Data cannot be accepted righ now for msgidx = " << msgidx); //the relay data cannot be accepted right now - will be tried later return false; } } solid_assert_log(_rprelay_data, logger); MessageStub& rmsgstub(message_vec_[msgidx]); if (_rprelay_data->pdata_ != nullptr) { solid_dbg(logger, Verbose, msgidx << " relay_data.flags " << _rprelay_data->flags_ << ' ' << MessageWriterPrintPairT(*this, PrintInnerListsE)); if (_rprelay_data->isMessageBegin()) { rmsgstub.state_ = MessageStub::StateE::RelayedStart; _rprelay_data->pmessage_header_->flags_ = _rprelay_data->message_flags_; } rmsgstub.prelay_data_ = _rprelay_data; rmsgstub.prelay_pos_ = rmsgstub.prelay_data_->pdata_; rmsgstub.relay_size_ = rmsgstub.prelay_data_->data_size_; rmsgstub.pool_msg_id_ = _rengine_msg_id; _rprelay_data = nullptr; doWriteQueuePushBack(msgidx, __LINE__); } else if (rmsgstub.state_ < MessageStub::StateE::RelayedWait) { solid_assert_log(rmsgstub.relay_size_ == 0, logger); solid_dbg(logger, Error, "" << msgidx << " uid = " << rmsgstub.unique_ << " state = " << (int)rmsgstub.state_); //called from relay engine on cancel request from the reader (RR - see mprpcrelayengine.cpp) side of the link. //after the current function call, the MessageStub in the RelayEngine is distroyed. //we need to forward the cancel on the connection rmsgstub.state_ = MessageStub::StateE::RelayedCancel; doWriteQueuePushBack(msgidx, __LINE__); solid_dbg(logger, Verbose, "relayedcancel msg " << msgidx); //we do not need the relay_data - leave it to the relay engine to delete it. } else if (rmsgstub.state_ == MessageStub::StateE::RelayedWait) { solid_dbg(logger, Verbose, "relayedcancel erase msg " << msgidx << " state = " << (int)rmsgstub.state_); //do nothing - we cannot erase a message stub waiting for response } else { solid_dbg(logger, Verbose, "relayedcancel erase msg " << msgidx << " state = " << (int)rmsgstub.state_); order_inner_list_.erase(msgidx); doUnprepareMessageStub(msgidx); } return true; } //----------------------------------------------------------------------------- void MessageWriter::doUnprepareMessageStub(const size_t _msgidx) { MessageStub& rmsgstub(message_vec_[_msgidx]); rmsgstub.clear(); cache_inner_list_.pushFront(_msgidx); } //----------------------------------------------------------------------------- void MessageWriter::cancel( MessageId const& _rmsguid, Sender& _rsender, const bool _force) { if (_rmsguid.isValid() && _rmsguid.index < message_vec_.size() && _rmsguid.unique == message_vec_[_rmsguid.index].unique_) { doCancel(_rmsguid.index, _rsender, _force); } } //----------------------------------------------------------------------------- MessagePointerT MessageWriter::fetchRequest(MessageId const& _rmsguid) const { if (_rmsguid.isValid() && _rmsguid.index < message_vec_.size() && _rmsguid.unique == message_vec_[_rmsguid.index].unique_) { const MessageStub& rmsgstub = message_vec_[_rmsguid.index]; return MessagePointerT(rmsgstub.msgbundle_.message_ptr); } return MessagePointerT(); } //----------------------------------------------------------------------------- ResponseStateE MessageWriter::checkResponseState(MessageId const& _rmsguid, MessageId& _rrelay_id, const bool _erase_request) { if (_rmsguid.isValid() && _rmsguid.index < message_vec_.size() && _rmsguid.unique == message_vec_[_rmsguid.index].unique_) { MessageStub& rmsgstub = message_vec_[_rmsguid.index]; switch (rmsgstub.state_) { case MessageStub::StateE::WriteWait: return ResponseStateE::Wait; case MessageStub::StateE::RelayedWait: _rrelay_id = rmsgstub.pool_msg_id_; if (_erase_request) { order_inner_list_.erase(_rmsguid.index); doUnprepareMessageStub(_rmsguid.index); } return ResponseStateE::RelayedWait; case MessageStub::StateE::WriteCanceled: solid_assert_log(write_inner_list_.size(), logger); order_inner_list_.erase(_rmsguid.index); doWriteQueueErase(_rmsguid.index, __LINE__); doUnprepareMessageStub(_rmsguid.index); return ResponseStateE::Cancel; case MessageStub::StateE::WriteWaitCanceled: order_inner_list_.erase(_rmsguid.index); doUnprepareMessageStub(_rmsguid.index); return ResponseStateE::Cancel; default: solid_assert_log(false, logger); //solid_check(false, "Unknown state for response: "<<(int)rmsgstub.state_<<" for messageid: "<<_rmsguid); return ResponseStateE::Invalid; } } return ResponseStateE::None; } //----------------------------------------------------------------------------- void MessageWriter::cancelOldest(Sender& _rsender) { if (!order_inner_list_.empty()) { doCancel(order_inner_list_.frontIndex(), _rsender, true); } } //----------------------------------------------------------------------------- void MessageWriter::doCancel( const size_t _msgidx, Sender& _rsender, const bool _force) { solid_dbg(logger, Verbose, "" << _msgidx); MessageStub& rmsgstub = message_vec_[_msgidx]; if (rmsgstub.state_ == MessageStub::StateE::WriteWaitCanceled) { solid_dbg(logger, Verbose, "" << _msgidx << " already canceled"); if (_force) { order_inner_list_.erase(_msgidx); doUnprepareMessageStub(_msgidx); } return; //already canceled } if (rmsgstub.state_ == MessageStub::StateE::WriteCanceled) { solid_dbg(logger, Verbose, "" << _msgidx << " already canceled"); if (_force) { solid_assert_log(write_inner_list_.size(), logger); order_inner_list_.erase(_msgidx); doWriteQueueErase(_msgidx, __LINE__); doUnprepareMessageStub(_msgidx); } return; //already canceled } if (rmsgstub.msgbundle_.message_ptr) { //called on explicit user request or on peer request (via reader) or on response received rmsgstub.msgbundle_.message_flags.set(MessageFlagsE::Canceled); if (_rsender.cancelMessage(rmsgstub.msgbundle_, rmsgstub.pool_msg_id_)) { if (rmsgstub.serializer_ptr_) { //the message is being sent rmsgstub.serializer_ptr_->clear(); _rsender.protocol().reconfigure(*rmsgstub.serializer_ptr_, _rsender.configuration()); rmsgstub.state_ = MessageStub::StateE::WriteCanceled; } else if (!_force && rmsgstub.state_ == MessageStub::StateE::WriteWait) { //message is waiting response rmsgstub.state_ = MessageStub::StateE::WriteWaitCanceled; } else if (rmsgstub.state_ == MessageStub::StateE::WriteWait || rmsgstub.state_ == MessageStub::StateE::WriteWaitCanceled) { order_inner_list_.erase(_msgidx); doUnprepareMessageStub(_msgidx); } else { //message is waiting to be sent solid_assert_log(write_inner_list_.size(), logger); order_inner_list_.erase(_msgidx); doWriteQueueErase(_msgidx, __LINE__); doUnprepareMessageStub(_msgidx); } } else { rmsgstub.msgbundle_.message_flags.reset(MessageFlagsE::Canceled); } } else { //usually called when reader receives a cancel request switch (rmsgstub.state_) { case MessageStub::StateE::RelayedHeadStart: case MessageStub::StateE::RelayedHeadContinue: rmsgstub.serializer_ptr_->clear(); _rsender.protocol().reconfigure(*rmsgstub.serializer_ptr_, _rsender.configuration()); case MessageStub::StateE::RelayedBody: rmsgstub.state_ = MessageStub::StateE::RelayedCancelRequest; _rsender.cancelRelayed(rmsgstub.prelay_data_, rmsgstub.pool_msg_id_); if (rmsgstub.prelay_data_ == nullptr) { //message not in write_inner_list_ doWriteQueuePushBack(_msgidx, __LINE__); } rmsgstub.prelay_data_ = nullptr; break; case MessageStub::StateE::RelayedStart: //message not yet started case MessageStub::StateE::RelayedWait: //message waiting for response _rsender.cancelRelayed(rmsgstub.prelay_data_, rmsgstub.pool_msg_id_); rmsgstub.prelay_data_ = nullptr; order_inner_list_.erase(_msgidx); doUnprepareMessageStub(_msgidx); break; case MessageStub::StateE::RelayedCancelRequest: if (_force) { doWriteQueueErase(_msgidx, __LINE__); order_inner_list_.erase(_msgidx); doUnprepareMessageStub(_msgidx); return; } default: solid_assert_log(false, logger); return; } } } //----------------------------------------------------------------------------- bool MessageWriter::empty() const { return order_inner_list_.empty(); } //----------------------------------------------------------------------------- // Does: // prepare message // serialize messages on buffer // completes messages - those that do not need wait for response // keeps a serializer for every message that is multiplexed // compress the filled buffer // // Needs: // ErrorConditionT MessageWriter::write( WriteBuffer& _rbuffer, const WriteFlagsT& _flags, uint8_t& _rackd_buf_count, RequestIdVectorT& _cancel_remote_msg_vec, uint8_t& _rrelay_free_count, Sender& _rsender) { char* pbufpos = _rbuffer.data(); char* pbufend = _rbuffer.end(); size_t freesz = _rbuffer.size(); bool more = true; ErrorConditionT error; while (more && freesz >= (PacketHeader::SizeOfE + _rsender.protocol().minimumFreePacketDataSize())) { PacketHeader packet_header(PacketHeader::TypeE::Data, 0, 0); PacketOptions packet_options; char* pbufdata = pbufpos + PacketHeader::SizeOfE; size_t fillsz = doWritePacketData(pbufdata, pbufend, packet_options, _rackd_buf_count, _cancel_remote_msg_vec, _rrelay_free_count, _rsender, error); if (fillsz != 0u) { if (!packet_options.force_no_compress) { ErrorConditionT compress_error; size_t compressed_size = _rsender.configuration().inplace_compress_fnc(pbufdata, fillsz, compress_error); if (compressed_size != 0u) { packet_header.flags(packet_header.flags() | static_cast<uint8_t>(PacketHeader::FlagE::Compressed)); fillsz = compressed_size; } else if (!compress_error) { //the buffer was not modified, we can send it uncompressed } else { //there was an error and the inplace buffer was changed - exit with error more = false; error = compress_error; break; } } if (packet_options.request_accept) { solid_assert_log(_rrelay_free_count != 0, logger); solid_dbg(logger, Verbose, "send AckRequestFlagE"); --_rrelay_free_count; packet_header.flags(packet_header.flags() | static_cast<uint8_t>(PacketHeader::FlagE::AckRequest)); more = false; //do not allow multiple packets per relay buffer } solid_assert_log(static_cast<size_t>(fillsz) < static_cast<size_t>(0xffffUL), logger); packet_header.size(static_cast<uint32_t>(fillsz)); pbufpos = packet_header.store(pbufpos, _rsender.protocol()); pbufpos = pbufdata + fillsz; freesz = pbufend - pbufpos; } else { more = false; } } if (!error && _rbuffer.data() == pbufpos) { if (_flags.has(WriteFlagsE::ShouldSendKeepAlive)) { PacketHeader packet_header(PacketHeader::TypeE::KeepAlive); pbufpos = packet_header.store(pbufpos, _rsender.protocol()); } } _rbuffer.resize(pbufpos - _rbuffer.data()); return error; } //----------------------------------------------------------------------------- //NOTE: // Objectives for doFindEligibleMessage: // - be fast // - try to fill up the package // - be fair with all messages bool MessageWriter::doFindEligibleMessage(Sender& _rsender, const bool _can_send_relay, const size_t /*_size*/) { solid_dbg(logger, Verbose, "wq_back_index_ = " << write_queue_back_index_ << " wq_sync_index_ = " << write_queue_sync_index_ << " wq_async_count_ = " << write_queue_async_count_ << " wq_direct_count_ = " << write_queue_direct_count_ << " wq.size = " << write_inner_list_.size() << " _can_send_relay = " << _can_send_relay); //fail fast if (!_can_send_relay && write_queue_direct_count_ == 0) { return false; } size_t qsz = write_inner_list_.size(); size_t async_postponed = 0; while (qsz != 0u) { --qsz; const size_t msgidx = write_inner_list_.frontIndex(); MessageStub& rmsgstub = message_vec_[msgidx]; solid_dbg(logger, Verbose, "msgidx = " << msgidx << " isHeadState = " << rmsgstub.isHeadState() << " isSynchronous = " << rmsgstub.isSynchronous() << " isRelay = " << rmsgstub.isRelay()); if (rmsgstub.isHeadState()) { return true; //prevent splitting the header } if (rmsgstub.isSynchronous()) { if (write_queue_sync_index_ == InvalidIndex()) { write_queue_sync_index_ = msgidx; } else if (write_queue_sync_index_ == msgidx) { } else { write_inner_list_.pushBack(write_inner_list_.popFront()); continue; } } if (rmsgstub.isStartOrHeadState()) { return true; } if (rmsgstub.isRelay()) { if (_can_send_relay) { } else { write_inner_list_.pushBack(write_inner_list_.popFront()); continue; } } if (rmsgstub.packet_count_ < _rsender.configuration().max_message_continuous_packet_count) { } else { rmsgstub.packet_count_ = 0; if (rmsgstub.isSynchronous() && write_queue_async_count_ == 0) { //no async message in queue - continue with the current synchronous message } else if (write_queue_async_count_ > (async_postponed + 1)) { //we do not want to postpone all async messages write_inner_list_.pushBack(write_inner_list_.popFront()); ++async_postponed; continue; } } solid_dbg(logger, Verbose, "FOUND eligible message - " << msgidx); return true; } solid_dbg(logger, Info, this << " NO eligible message in a queue of " << write_inner_list_.size() << " wq_back_index_ = " << write_queue_back_index_ << " wq_sync_index_ = " << write_queue_sync_index_ << " wq_async_count_ = " << write_queue_async_count_ << " wq_direct_count_ = " << write_queue_direct_count_ << " wq.size = " << write_inner_list_.size() << " _can_send_relay = " << _can_send_relay); return false; } //----------------------------------------------------------------------------- // we have three types of messages: // - direct: serialized onto buffer // - relay: serialized onto a relay buffer (one that needs confirmation) // - relayed: copyed onto the output buffer (no serialization) size_t MessageWriter::doWritePacketData( char* _pbufbeg, char* _pbufend, PacketOptions& _rpacket_options, uint8_t& _rackd_buf_count, RequestIdVectorT& _cancel_remote_msg_vec, uint8_t _relay_free_count, Sender& _rsender, ErrorConditionT& _rerror) { char* pbufpos = _pbufbeg; if (_rackd_buf_count != 0u) { solid_dbg(logger, Verbose, this << " stored ackd_buf_count = " << (int)_rackd_buf_count); uint8_t cmd = static_cast<uint8_t>(PacketHeader::CommandE::AckdCount); pbufpos = _rsender.protocol().storeValue(pbufpos, cmd); pbufpos = _rsender.protocol().storeValue(pbufpos, _rackd_buf_count); _rackd_buf_count = 0; } while (!_cancel_remote_msg_vec.empty() && static_cast<size_t>(_pbufend - pbufpos) >= _rsender.protocol().minimumFreePacketDataSize()) { solid_dbg(logger, Verbose, this << " send CancelRequest " << _cancel_remote_msg_vec.back()); uint8_t cmd = static_cast<uint8_t>(PacketHeader::CommandE::CancelRequest); pbufpos = _rsender.protocol().storeValue(pbufpos, cmd); pbufpos = _rsender.protocol().storeCrossValue(pbufpos, _pbufend - pbufpos, _cancel_remote_msg_vec.back().index); solid_check_log(pbufpos != nullptr, logger, "fail store cross value"); pbufpos = _rsender.protocol().storeCrossValue(pbufpos, _pbufend - pbufpos, _cancel_remote_msg_vec.back().unique); solid_check_log(pbufpos != nullptr, logger, "fail store cross value"); _cancel_remote_msg_vec.pop_back(); } while ( !_rerror && static_cast<size_t>(_pbufend - pbufpos) >= _rsender.protocol().minimumFreePacketDataSize() && doFindEligibleMessage(_rsender, _relay_free_count != 0, _pbufend - pbufpos)) { const size_t msgidx = write_inner_list_.frontIndex(); PacketHeader::CommandE cmd = PacketHeader::CommandE::Message; solid_dbg(logger, Verbose, this << " msgidx = " << msgidx << " state " << (int)message_vec_[msgidx].state_); switch (message_vec_[msgidx].state_) { case MessageStub::StateE::WriteStart: { MessageStub& rmsgstub = message_vec_[msgidx]; rmsgstub.serializer_ptr_ = createSerializer(_rsender); rmsgstub.msgbundle_.message_flags.set(MessageFlagsE::StartedSend); rmsgstub.state_ = MessageStub::StateE::WriteHeadStart; solid_dbg(logger, Info, this << " message header url: " << rmsgstub.msgbundle_.message_url << " isRelay = " << rmsgstub.isRelay()); cmd = PacketHeader::CommandE::NewMessage; } case MessageStub::StateE::WriteHeadStart: case MessageStub::StateE::WriteHeadContinue: pbufpos = doWriteMessageHead(pbufpos, _pbufend, msgidx, _rpacket_options, _rsender, cmd, _rerror); break; case MessageStub::StateE::WriteBodyStart: case MessageStub::StateE::WriteBodyContinue: pbufpos = doWriteMessageBody(pbufpos, _pbufend, msgidx, _rpacket_options, _rsender, _rerror); break; case MessageStub::StateE::WriteWait: solid_throw_log(logger, "Invalid state for write queue - WriteWait"); break; case MessageStub::StateE::WriteCanceled: pbufpos = doWriteMessageCancel(pbufpos, _pbufend, msgidx, _rpacket_options, _rsender, _rerror); break; case MessageStub::StateE::RelayedStart: { MessageStub& rmsgstub = message_vec_[msgidx]; rmsgstub.serializer_ptr_ = createSerializer(_rsender); rmsgstub.state_ = MessageStub::StateE::RelayedHeadStart; solid_dbg(logger, Verbose, this << " message header url: " << rmsgstub.prelay_data_->pmessage_header_->url_); cmd = PacketHeader::CommandE::NewMessage; } case MessageStub::StateE::RelayedHeadStart: case MessageStub::StateE::RelayedHeadContinue: pbufpos = doWriteRelayedHead(pbufpos, _pbufend, msgidx, _rpacket_options, _rsender, cmd, _rerror); break; case MessageStub::StateE::RelayedBody: pbufpos = doWriteRelayedBody(pbufpos, _pbufend, msgidx, _rpacket_options, _rsender, _rerror); break; case MessageStub::StateE::RelayedWait: solid_throw_log(logger, "Invalid state for write queue - RelayedWait"); break; case MessageStub::StateE::RelayedCancelRequest: pbufpos = doWriteRelayedCancelRequest(pbufpos, _pbufend, msgidx, _rpacket_options, _rsender, _rerror); break; case MessageStub::StateE::RelayedCancel: pbufpos = doWriteRelayedCancel(pbufpos, _pbufend, msgidx, _rpacket_options, _rsender, _rerror); break; default: //solid_check(false, "message state not handled: "<<(int)message_vec_[msgidx].state_<<" for message "<<msgidx); solid_assert_log(false, logger); break; } } //while solid_dbg(logger, Verbose, this << " write_q_size " << write_inner_list_.size() << " order_q_size " << order_inner_list_.size()); return pbufpos - _pbufbeg; } //----------------------------------------------------------------------------- char* MessageWriter::doWriteMessageHead( char* _pbufpos, char* _pbufend, const size_t _msgidx, PacketOptions& /*_rpacket_options*/, Sender& _rsender, const PacketHeader::CommandE _cmd, ErrorConditionT& _rerror) { uint8_t cmd = static_cast<uint8_t>(_cmd); _pbufpos = _rsender.protocol().storeValue(_pbufpos, cmd); _pbufpos = _rsender.protocol().storeCrossValue(_pbufpos, _pbufend - _pbufpos, static_cast<uint32_t>(_msgidx)); solid_check_log(_pbufpos != nullptr, logger, "fail store cross value"); char* psizepos = _pbufpos; _pbufpos = _rsender.protocol().storeValue(psizepos, static_cast<uint16_t>(0)); MessageStub& rmsgstub = message_vec_[_msgidx]; rmsgstub.msgbundle_.message_flags = Message::update_state_flags(Message::clear_state_flags(rmsgstub.msgbundle_.message_flags) | Message::state_flags(rmsgstub.msgbundle_.message_ptr->flags())); _rsender.context().request_id.index = static_cast<uint32_t>(_msgidx + 1); _rsender.context().request_id.unique = rmsgstub.unique_; _rsender.context().message_flags = rmsgstub.msgbundle_.message_flags; _rsender.context().pmessage_url = &rmsgstub.msgbundle_.message_url; const ptrdiff_t rv = rmsgstub.state_ == MessageStub::StateE::WriteHeadStart ? rmsgstub.serializer_ptr_->run(_rsender.context(), _pbufpos, _pbufend - _pbufpos, rmsgstub.msgbundle_.message_ptr->header_) : rmsgstub.serializer_ptr_->run(_rsender.context(), _pbufpos, _pbufend - _pbufpos); rmsgstub.state_ = MessageStub::StateE::WriteHeadContinue; if (rv >= 0) { _rsender.protocol().storeValue(psizepos, static_cast<uint16_t>(rv)); solid_dbg(logger, Info, this << " stored message header with index = " << _msgidx << " and size = " << rv); if (rmsgstub.serializer_ptr_->empty()) { //we've just finished serializing header rmsgstub.state_ = MessageStub::StateE::WriteBodyStart; } _pbufpos += rv; } else { _rerror = rmsgstub.serializer_ptr_->error(); } return _pbufpos; } //----------------------------------------------------------------------------- char* MessageWriter::doWriteMessageBody( char* _pbufpos, char* _pbufend, const size_t _msgidx, PacketOptions& _rpacket_options, Sender& _rsender, ErrorConditionT& _rerror) { char* pcmdpos = nullptr; pcmdpos = _pbufpos; _pbufpos += 1; _pbufpos = _rsender.protocol().storeCrossValue(_pbufpos, _pbufend - _pbufpos, static_cast<uint32_t>(_msgidx)); solid_check_log(_pbufpos != nullptr, logger, "fail store cross value"); char* psizepos = _pbufpos; _pbufpos = _rsender.protocol().storeValue(psizepos, static_cast<uint16_t>(0)); uint8_t cmd = static_cast<uint8_t>(PacketHeader::CommandE::Message); MessageStub& rmsgstub = message_vec_[_msgidx]; _rsender.context().request_id.index = static_cast<uint32_t>(_msgidx + 1); _rsender.context().request_id.unique = rmsgstub.unique_; _rsender.context().message_flags = rmsgstub.msgbundle_.message_flags; _rsender.context().pmessage_url = &rmsgstub.msgbundle_.message_url; const ptrdiff_t rv = rmsgstub.state_ == MessageStub::StateE::WriteBodyStart ? rmsgstub.serializer_ptr_->run(_rsender.context(), _pbufpos, _pbufend - _pbufpos, rmsgstub.msgbundle_.message_ptr, rmsgstub.msgbundle_.message_type_id) : rmsgstub.serializer_ptr_->run(_rsender.context(), _pbufpos, _pbufend - _pbufpos); rmsgstub.state_ = MessageStub::StateE::WriteBodyContinue; if (rv >= 0) { if (rmsgstub.isRelay()) { _rpacket_options.request_accept = true; } if (rmsgstub.serializer_ptr_->empty()) { //we've just finished serializing body cmd |= static_cast<uint8_t>(PacketHeader::CommandE::EndMessageFlag); solid_dbg(logger, Info, this << " stored message body with index = " << _msgidx << " and size = " << rv << " cmd = " << (int)cmd << " is_relayed = " << rmsgstub.isRelay()); doTryCompleteMessageAfterSerialization(_msgidx, _rsender, _rerror); } else { ++rmsgstub.packet_count_; } _rsender.protocol().storeValue(pcmdpos, cmd); //store the data size _rsender.protocol().storeValue(psizepos, static_cast<uint16_t>(rv)); _pbufpos += rv; } else { _rerror = rmsgstub.serializer_ptr_->error(); } return _pbufpos; } //----------------------------------------------------------------------------- char* MessageWriter::doWriteRelayedHead( char* _pbufpos, char* _pbufend, const size_t _msgidx, PacketOptions& /*_rpacket_options*/, Sender& _rsender, const PacketHeader::CommandE _cmd, ErrorConditionT& _rerror) { uint8_t cmd = static_cast<uint8_t>(_cmd); _pbufpos = _rsender.protocol().storeValue(_pbufpos, cmd); _pbufpos = _rsender.protocol().storeCrossValue(_pbufpos, _pbufend - _pbufpos, static_cast<uint32_t>(_msgidx)); solid_check_log(_pbufpos != nullptr, logger, "fail store cross value"); char* psizepos = _pbufpos; _pbufpos = _rsender.protocol().storeValue(psizepos, static_cast<uint16_t>(0)); MessageStub& rmsgstub = message_vec_[_msgidx]; _rsender.context().request_id.index = static_cast<uint32_t>(_msgidx + 1); _rsender.context().request_id.unique = rmsgstub.unique_; _rsender.context().message_flags = rmsgstub.prelay_data_->pmessage_header_->flags_; _rsender.context().message_flags.set(MessageFlagsE::Relayed); _rsender.context().pmessage_url = &rmsgstub.prelay_data_->pmessage_header_->url_; const ptrdiff_t rv = rmsgstub.state_ == MessageStub::StateE::RelayedHeadStart ? rmsgstub.serializer_ptr_->run(_rsender.context(), _pbufpos, _pbufend - _pbufpos, *rmsgstub.prelay_data_->pmessage_header_) : rmsgstub.serializer_ptr_->run(_rsender.context(), _pbufpos, _pbufend - _pbufpos); rmsgstub.state_ = MessageStub::StateE::RelayedHeadContinue; if (rv >= 0) { _rsender.protocol().storeValue(psizepos, static_cast<uint16_t>(rv)); solid_dbg(logger, Verbose, "stored message header with index = " << _msgidx << " and size = " << rv); if (rmsgstub.serializer_ptr_->empty()) { //we've just finished serializing header cache(rmsgstub.serializer_ptr_); rmsgstub.state_ = MessageStub::StateE::RelayedBody; } _pbufpos += rv; } else { cache(rmsgstub.serializer_ptr_); _rerror = rmsgstub.serializer_ptr_->error(); } return _pbufpos; } //----------------------------------------------------------------------------- char* MessageWriter::doWriteRelayedBody( char* _pbufpos, char* _pbufend, const size_t _msgidx, PacketOptions& /*_rpacket_options*/, Sender& _rsender, ErrorConditionT& /*_rerror*/) { char* pcmdpos = nullptr; pcmdpos = _pbufpos; _pbufpos += 1; _pbufpos = _rsender.protocol().storeCrossValue(_pbufpos, _pbufend - _pbufpos, static_cast<uint32_t>(_msgidx)); solid_check_log(_pbufpos != nullptr, logger, "fail store cross value"); char* psizepos = _pbufpos; _pbufpos = _rsender.protocol().storeValue(psizepos, static_cast<uint16_t>(0)); uint8_t cmd = static_cast<uint8_t>(PacketHeader::CommandE::Message); MessageStub& rmsgstub = message_vec_[_msgidx]; solid_assert_log(rmsgstub.prelay_data_, logger); size_t towrite = _pbufend - _pbufpos; if (towrite > rmsgstub.relay_size_) { towrite = rmsgstub.relay_size_; } memcpy(_pbufpos, rmsgstub.prelay_pos_, towrite); _pbufpos += towrite; rmsgstub.prelay_pos_ += towrite; rmsgstub.relay_size_ -= towrite; solid_dbg(logger, Verbose, "storing " << towrite << " bytes" << " for msg " << _msgidx << " cmd = " << (int)cmd << " flags = " << rmsgstub.prelay_data_->flags_ << " relaydata = " << rmsgstub.prelay_data_); if (rmsgstub.relay_size_ == 0) { solid_assert_log(write_inner_list_.size(), logger); doWriteQueueErase(_msgidx, __LINE__); const bool is_message_end = rmsgstub.prelay_data_->isMessageEnd(); const bool is_message_last = rmsgstub.prelay_data_->isMessageLast(); const bool is_request = rmsgstub.prelay_data_->isRequest(); //Message::is_waiting_response(rmsgstub.prelay_data_->pmessage_header_->flags_); _rsender.completeRelayed(rmsgstub.prelay_data_, rmsgstub.pool_msg_id_); rmsgstub.prelay_data_ = nullptr; //when prelay_data_ is null we consider the message not in write_inner_list_ if (is_message_end) { cmd |= static_cast<uint8_t>(PacketHeader::CommandE::EndMessageFlag); } if (is_message_last) { if (is_request) { rmsgstub.state_ = MessageStub::StateE::RelayedWait; } else { order_inner_list_.erase(_msgidx); rmsgstub.clear(); } } } _rsender.protocol().storeValue(pcmdpos, cmd); //store the data size _rsender.protocol().storeValue(psizepos, static_cast<uint16_t>(towrite)); return _pbufpos; } //----------------------------------------------------------------------------- char* MessageWriter::doWriteMessageCancel( char* _pbufpos, char* _pbufend, const size_t _msgidx, PacketOptions& /*_rpacket_options*/, Sender& _rsender, ErrorConditionT& /*_rerror*/) { solid_dbg(logger, Verbose, "" << _msgidx); uint8_t cmd = static_cast<uint8_t>(PacketHeader::CommandE::CancelMessage); _pbufpos = _rsender.protocol().storeValue(_pbufpos, cmd); _pbufpos = _rsender.protocol().storeCrossValue(_pbufpos, _pbufend - _pbufpos, static_cast<uint32_t>(_msgidx)); solid_check_log(_pbufpos != nullptr, logger, "fail store cross value"); solid_assert_log(write_inner_list_.size(), logger); doWriteQueueErase(_msgidx, __LINE__); order_inner_list_.erase(_msgidx); doUnprepareMessageStub(_msgidx); if (write_queue_sync_index_ == _msgidx) { write_queue_sync_index_ = InvalidIndex(); } return _pbufpos; } //----------------------------------------------------------------------------- char* MessageWriter::doWriteRelayedCancel( char* _pbufpos, char* _pbufend, const size_t _msgidx, PacketOptions& /*_rpacket_options*/, Sender& _rsender, ErrorConditionT& /*_rerror*/) { MessageStub& rmsgstub = message_vec_[_msgidx]; solid_dbg(logger, Error, "" << _msgidx << " uid = " << rmsgstub.unique_ << " state = " << (int)rmsgstub.state_); uint8_t cmd = static_cast<uint8_t>(PacketHeader::CommandE::CancelMessage); _pbufpos = _rsender.protocol().storeValue(_pbufpos, cmd); _pbufpos = _rsender.protocol().storeCrossValue(_pbufpos, _pbufend - _pbufpos, static_cast<uint32_t>(_msgidx)); solid_check_log(_pbufpos != nullptr, logger, "fail store cross value"); solid_assert_log(rmsgstub.prelay_data_ == nullptr, logger); //_rsender.completeRelayed(rmsgstub.prelay_data_, rmsgstub.pool_msg_id_); //rmsgstub.prelay_data_ = nullptr; solid_assert_log(write_inner_list_.size(), logger); doWriteQueueErase(_msgidx, __LINE__); order_inner_list_.erase(_msgidx); doUnprepareMessageStub(_msgidx); if (write_queue_sync_index_ == _msgidx) { write_queue_sync_index_ = InvalidIndex(); } return _pbufpos; } //----------------------------------------------------------------------------- char* MessageWriter::doWriteRelayedCancelRequest( char* _pbufpos, char* _pbufend, const size_t _msgidx, PacketOptions& /*_rpacket_options*/, Sender& _rsender, ErrorConditionT& /*_rerror*/) { solid_dbg(logger, Verbose, "" << _msgidx); uint8_t cmd = static_cast<uint8_t>(PacketHeader::CommandE::CancelMessage); _pbufpos = _rsender.protocol().storeValue(_pbufpos, cmd); _pbufpos = _rsender.protocol().storeCrossValue(_pbufpos, _pbufend - _pbufpos, static_cast<uint32_t>(_msgidx)); solid_check_log(_pbufpos != nullptr, logger, "fail store cross value"); solid_assert_log(write_inner_list_.size(), logger); doWriteQueueErase(_msgidx, __LINE__); order_inner_list_.erase(_msgidx); doUnprepareMessageStub(_msgidx); if (write_queue_sync_index_ == _msgidx) { write_queue_sync_index_ = InvalidIndex(); } return _pbufpos; } //----------------------------------------------------------------------------- void MessageWriter::doTryCompleteMessageAfterSerialization( const size_t _msgidx, Sender& _rsender, ErrorConditionT& _rerror) { MessageStub& rmsgstub(message_vec_[_msgidx]); RequestId requid(static_cast<uint32_t>(_msgidx), rmsgstub.unique_); solid_dbg(logger, Info, this << " done serializing message " << requid << ". Message id sent to client " << _rsender.context().request_id); cache(rmsgstub.serializer_ptr_); solid_assert_log(write_inner_list_.size(), logger); doWriteQueueErase(_msgidx, __LINE__); rmsgstub.msgbundle_.message_flags.reset(MessageFlagsE::StartedSend); rmsgstub.msgbundle_.message_flags.set(MessageFlagsE::DoneSend); rmsgstub.serializer_ptr_ = nullptr; rmsgstub.state_ = MessageStub::StateE::WriteStart; solid_dbg(logger, Verbose, MessageWriterPrintPairT(*this, PrintInnerListsE)); if (!Message::is_awaiting_response(rmsgstub.msgbundle_.message_flags)) { //no wait response for the message - complete MessageBundle tmp_msg_bundle(std::move(rmsgstub.msgbundle_)); MessageId tmp_pool_msg_id(rmsgstub.pool_msg_id_); order_inner_list_.erase(_msgidx); doUnprepareMessageStub(_msgidx); _rerror = _rsender.completeMessage(tmp_msg_bundle, tmp_pool_msg_id); solid_dbg(logger, Verbose, MessageWriterPrintPairT(*this, PrintInnerListsE)); } else { rmsgstub.state_ = MessageStub::StateE::WriteWait; } solid_dbg(logger, Verbose, MessageWriterPrintPairT(*this, PrintInnerListsE)); } //----------------------------------------------------------------------------- void MessageWriter::forEveryMessagesNewerToOlder(VisitFunctionT const& _rvisit_fnc) { solid_dbg(logger, Verbose, ""); size_t msgidx = order_inner_list_.backIndex(); while (msgidx != InvalidIndex()) { MessageStub& rmsgstub = message_vec_[msgidx]; const bool message_in_write_queue = !rmsgstub.isWaitResponseState(); if (rmsgstub.msgbundle_.message_ptr) { //skip relayed messages _rvisit_fnc( rmsgstub.msgbundle_, rmsgstub.pool_msg_id_); if (!rmsgstub.msgbundle_.message_ptr) { //message fetched if (message_in_write_queue) { solid_assert_log(write_inner_list_.size(), logger); doWriteQueueErase(msgidx, __LINE__); } const size_t oldidx = msgidx; msgidx = order_inner_list_.previousIndex(oldidx); order_inner_list_.erase(oldidx); doUnprepareMessageStub(oldidx); } else { msgidx = order_inner_list_.previousIndex(msgidx); } } } //while } //----------------------------------------------------------------------------- void MessageWriter::print(std::ostream& _ros, const PrintWhat _what) const { if (_what == PrintInnerListsE) { _ros << "InnerLists: "; auto print_fnc = [&_ros](const size_t _idx, MessageStub const&) { _ros << _idx << ' '; }; _ros << "OrderList: "; order_inner_list_.forEach(print_fnc); _ros << '\t'; _ros << "WriteList: "; write_inner_list_.forEach(print_fnc); _ros << '\t'; _ros << "CacheList size: " << cache_inner_list_.size(); //cache_inner_list_.forEach(print_fnc); _ros << '\t'; } } //----------------------------------------------------------------------------- void MessageWriter::cache(Serializer::PointerT& _ser) { if (_ser) { _ser->clear(); _ser->link(serializer_stack_top_); serializer_stack_top_ = std::move(_ser); } } //----------------------------------------------------------------------------- Serializer::PointerT MessageWriter::createSerializer(Sender& _sender) { if (serializer_stack_top_) { Serializer::PointerT ser{std::move(serializer_stack_top_)}; serializer_stack_top_ = std::move(ser->link()); _sender.protocol().reconfigure(*ser, _sender.configuration()); return ser; } return _sender.protocol().createSerializer(_sender.configuration()); } //----------------------------------------------------------------------------- /*virtual*/ MessageWriter::Sender::~Sender() { } /*virtual*/ ErrorConditionT MessageWriter::Sender::completeMessage(MessageBundle& /*_rmsgbundle*/, MessageId const& /*_rmsgid*/) { return ErrorConditionT{}; } /*virtual*/ void MessageWriter::Sender::completeRelayed(RelayData* /*_relay_data*/, MessageId const& /*_rmsgid*/) { } /*virtual*/ bool MessageWriter::Sender::cancelMessage(MessageBundle& /*_rmsgbundle*/, MessageId const& /*_rmsgid*/) { return true; } /*virtual*/ void MessageWriter::Sender::cancelRelayed(RelayData* /*_relay_data*/, MessageId const& /*_rmsgid*/) { } //----------------------------------------------------------------------------- std::ostream& operator<<(std::ostream& _ros, std::pair<MessageWriter const&, MessageWriter::PrintWhat> const& _msgwriterpair) { _msgwriterpair.first.print(_ros, _msgwriterpair.second); return _ros; } //----------------------------------------------------------------------------- } //namespace mprpc } //namespace frame } //namespace solid
41.616352
402
0.61912
[ "solid" ]
363dc6c7975cd19976ac7318cec454110b31fd6d
1,248
cpp
C++
codeforces/C - Classroom Watch/Time limit exceeded on pretest 1.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
codeforces/C - Classroom Watch/Time limit exceeded on pretest 1.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
codeforces/C - Classroom Watch/Time limit exceeded on pretest 1.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: kzvd4729 created: Oct/16/2017 17:56 * solution_verdict: Time limit exceeded on pretest 1 language: GNU C++14 * run_time: 1000 ms memory_used: 79800 KB * problem: https://codeforces.com/contest/876/problem/C ****************************************************************************************/ #include<bits/stdc++.h> #define long long long using namespace std; long n; vector<long>ans; bool ok(long z) { long zz=z; while(zz) { long r=(zz+10)%10; z+=r; zz/=10; } if(z==n)return true; return false; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin>>n; for(long x=n;x>=max(n-100000,0LL);x--) { if(ok(x))ans.push_back(x); } sort(ans.begin(),ans.end()); cout<<ans.size()<<endl; for(long i=0;i<ans.size();i++) { cout<<ans[i]; if(i==ans.size()-1)cout<<endl; else cout<<" "; } ans.clear(); main(); return 0; }
27.733333
111
0.39984
[ "vector" ]
3640943250a3e451eb9dadfe3f0653667aaec806
13,773
cpp
C++
example/inverse_chi_squared_bayes_eg.cpp
oleg-alexandrov/math
2137c31eb8e52129d997a76b893f71c1da0ccc5f
[ "BSL-1.0" ]
233
2015-01-12T19:26:01.000Z
2022-03-11T09:21:47.000Z
3rdparty/boost_1_73_0/libs/math/example/inverse_chi_squared_bayes_eg.cpp
qingkouwei/mediaones
cec475e1bfd5807b5351cc7e38d244ac5298ca16
[ "MIT" ]
626
2015-02-05T18:12:27.000Z
2022-03-20T13:19:18.000Z
3rdparty/boost_1_73_0/libs/math/example/inverse_chi_squared_bayes_eg.cpp
qingkouwei/mediaones
cec475e1bfd5807b5351cc7e38d244ac5298ca16
[ "MIT" ]
243
2015-01-17T17:46:32.000Z
2022-03-07T12:56:26.000Z
// inverse_chi_squared_bayes_eg.cpp // Copyright Thomas Mang 2011. // Copyright Paul A. Bristow 2011. // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt // or copy at http://www.boost.org/LICENSE_1_0.txt) // This file is written to be included from a Quickbook .qbk document. // It can still be compiled by the C++ compiler, and run. // Any output can also be added here as comment or included or pasted in elsewhere. // Caution: this file contains Quickbook markup as well as code // and comments: don't change any of the special comment markups! #include <iostream> // using std::cout; using std::endl; //#define define possible error-handling macros here? #include "boost/math/distributions.hpp" // using ::boost::math::inverse_chi_squared; int main() { using std::cout; using std::endl; using ::boost::math::inverse_chi_squared; using ::boost::math::inverse_gamma; using ::boost::math::quantile; using ::boost::math::cdf; cout << "Inverse_chi_squared_distribution Bayes example: " << endl <<endl; cout.precision(3); // Examples of using the inverse_chi_squared distribution. //[inverse_chi_squared_bayes_eg_1 /*` The scaled-inversed-chi-squared distribution is the conjugate prior distribution for the variance ([sigma][super 2]) parameter of a normal distribution with known expectation ([mu]). As such it has widespread application in Bayesian statistics: In [@http://en.wikipedia.org/wiki/Bayesian_inference Bayesian inference], the strength of belief into certain parameter values is itself described through a distribution. Parameters hence become themselves modelled and interpreted as random variables. In this worked example, we perform such a Bayesian analysis by using the scaled-inverse-chi-squared distribution as prior and posterior distribution for the variance parameter of a normal distribution. For more general information on Bayesian type of analyses, see: * Andrew Gelman, John B. Carlin, Hal E. Stern, Donald B. Rubin, Bayesian Data Analysis, 2003, ISBN 978-1439840955. * Jim Albert, Bayesian Computation with R, Springer, 2009, ISBN 978-0387922973. (As the scaled-inversed-chi-squared is another parameterization of the inverse-gamma distribution, this example could also have used the inverse-gamma distribution). Consider precision machines which produce balls for a high-quality ball bearing. Ideally each ball should have a diameter of precisely 3000 [mu]m (3 mm). Assume that machines generally produce balls of that size on average (mean), but individual balls can vary slightly in either direction following (approximately) a normal distribution. Depending on various production conditions (e.g. raw material used for balls, workplace temperature and humidity, maintenance frequency and quality) some machines produce balls tighter distributed around the target of 3000 [mu]m, while others produce balls with a wider distribution. Therefore the variance parameter of the normal distribution of the ball sizes varies from machine to machine. An extensive survey by the precision machinery manufacturer, however, has shown that most machines operate with a variance between 15 and 50, and near 25 [mu]m[super 2] on average. Using this information, we want to model the variance of the machines. The variance is strictly positive, and therefore we look for a statistical distribution with support in the positive domain of the real numbers. Given the expectation of the normal distribution of the balls is known (3000 [mu]m), for reasons of conjugacy, it is customary practice in Bayesian statistics to model the variance to be scaled-inverse-chi-squared distributed. In a first step, we will try to use the survey information to model the general knowledge about the variance parameter of machines measured by the manufacturer. This will provide us with a generic prior distribution that is applicable if nothing more specific is known about a particular machine. In a second step, we will then combine the prior-distribution information in a Bayesian analysis with data on a specific single machine to derive a posterior distribution for that machine. [h5 Step one: Using the survey information.] Using the survey results, we try to find the parameter set of a scaled-inverse-chi-squared distribution so that the properties of this distribution match the results. Using the mathematical properties of the scaled-inverse-chi-squared distribution as guideline, we see that that both the mean and mode of the scaled-inverse-chi-squared distribution are approximately given by the scale parameter (s) of the distribution. As the survey machines operated at a variance of 25 [mu]m[super 2] on average, we hence set the scale parameter (s[sub prior]) of our prior distribution equal to this value. Using some trial-and-error and calls to the global quantile function, we also find that a value of 20 for the degrees-of-freedom ([nu][sub prior]) parameter is adequate so that most of the prior distribution mass is located between 15 and 50 (see figure below). We first construct our prior distribution using these values, and then list out a few quantiles: */ double priorDF = 20.0; double priorScale = 25.0; inverse_chi_squared prior(priorDF, priorScale); // Using an inverse_gamma distribution instead, we could equivalently write // inverse_gamma prior(priorDF / 2.0, priorScale * priorDF / 2.0); cout << "Prior distribution:" << endl << endl; cout << " 2.5% quantile: " << quantile(prior, 0.025) << endl; cout << " 50% quantile: " << quantile(prior, 0.5) << endl; cout << " 97.5% quantile: " << quantile(prior, 0.975) << endl << endl; //] [/inverse_chi_squared_bayes_eg_1] //[inverse_chi_squared_bayes_eg_output_1 /*`This produces this output: Prior distribution: 2.5% quantile: 14.6 50% quantile: 25.9 97.5% quantile: 52.1 */ //] [/inverse_chi_squared_bayes_eg_output_1] //[inverse_chi_squared_bayes_eg_2 /*` Based on this distribution, we can now calculate the probability of having a machine working with an unusual work precision (variance) at <= 15 or > 50. For this task, we use calls to the `boost::math::` functions `cdf` and `complement`, respectively, and find a probability of about 0.031 (3.1%) for each case. */ cout << " probability variance <= 15: " << boost::math::cdf(prior, 15.0) << endl; cout << " probability variance <= 25: " << boost::math::cdf(prior, 25.0) << endl; cout << " probability variance > 50: " << boost::math::cdf(boost::math::complement(prior, 50.0)) << endl << endl; //] [/inverse_chi_squared_bayes_eg_2] //[inverse_chi_squared_bayes_eg_output_2 /*`This produces this output: probability variance <= 15: 0.031 probability variance <= 25: 0.458 probability variance > 50: 0.0318 */ //] [/inverse_chi_squared_bayes_eg_output_2] //[inverse_chi_squared_bayes_eg_3 /*`Therefore, only 3.1% of all precision machines produce balls with a variance of 15 or less (particularly precise machines), but also only 3.2% of all machines produce balls with a variance of as high as 50 or more (particularly imprecise machines). Moreover, slightly more than one-half (1 - 0.458 = 54.2%) of the machines work at a variance greater than 25. Notice here the distinction between a [@http://en.wikipedia.org/wiki/Bayesian_inference Bayesian] analysis and a [@http://en.wikipedia.org/wiki/Frequentist_inference frequentist] analysis: because we model the variance as random variable itself, we can calculate and straightforwardly interpret probabilities for given parameter values directly, while such an approach is not possible (and interpretationally a strict ['must-not]) in the frequentist world. [h5 Step 2: Investigate a single machine] In the second step, we investigate a single machine, which is suspected to suffer from a major fault as the produced balls show fairly high size variability. Based on the prior distribution of generic machinery performance (derived above) and data on balls produced by the suspect machine, we calculate the posterior distribution for that machine and use its properties for guidance regarding continued machine operation or suspension. It can be shown that if the prior distribution was chosen to be scaled-inverse-chi-square distributed, then the posterior distribution is also scaled-inverse-chi-squared-distributed (prior and posterior distributions are hence conjugate). For more details regarding conjugacy and formula to derive the parameters set for the posterior distribution see [@http://en.wikipedia.org/wiki/Conjugate_prior Conjugate prior]. Given the prior distribution parameters and sample data (of size n), the posterior distribution parameters are given by the two expressions: __spaces [nu][sub posterior] = [nu][sub prior] + n which gives the posteriorDF below, and __spaces s[sub posterior] = ([nu][sub prior]s[sub prior] + [Sigma][super n][sub i=1](x[sub i] - [mu])[super 2]) / ([nu][sub prior] + n) which after some rearrangement gives the formula for the posteriorScale below. Machine-specific data consist of 100 balls which were accurately measured and show the expected mean of 3000 [mu]m and a sample variance of 55 (calculated for a sample mean defined to be 3000 exactly). From these data, the prior parameterization, and noting that the term [Sigma][super n][sub i=1](x[sub i] - [mu])[super 2] equals the sample variance multiplied by n - 1, it follows that the posterior distribution of the variance parameter is scaled-inverse-chi-squared distribution with degrees-of-freedom ([nu][sub posterior]) = 120 and scale (s[sub posterior]) = 49.54. */ int ballsSampleSize = 100; cout <<"balls sample size: " << ballsSampleSize << endl; double ballsSampleVariance = 55.0; cout <<"balls sample variance: " << ballsSampleVariance << endl; double posteriorDF = priorDF + ballsSampleSize; cout << "prior degrees-of-freedom: " << priorDF << endl; cout << "posterior degrees-of-freedom: " << posteriorDF << endl; double posteriorScale = (priorDF * priorScale + (ballsSampleVariance * (ballsSampleSize - 1))) / posteriorDF; cout << "prior scale: " << priorScale << endl; cout << "posterior scale: " << posteriorScale << endl; /*`An interesting feature here is that one needs only to know a summary statistics of the sample to parameterize the posterior distribution: the 100 individual ball measurements are irrelevant, just knowledge of the sample variance and number of measurements is sufficient. */ //] [/inverse_chi_squared_bayes_eg_3] //[inverse_chi_squared_bayes_eg_output_3 /*`That produces this output: balls sample size: 100 balls sample variance: 55 prior degrees-of-freedom: 20 posterior degrees-of-freedom: 120 prior scale: 25 posterior scale: 49.5 */ //] [/inverse_chi_squared_bayes_eg_output_3] //[inverse_chi_squared_bayes_eg_4 /*`To compare the generic machinery performance with our suspect machine, we calculate again the same quantiles and probabilities as above, and find a distribution clearly shifted to greater values (see figure). [graph prior_posterior_plot] */ inverse_chi_squared posterior(posteriorDF, posteriorScale); cout << "Posterior distribution:" << endl << endl; cout << " 2.5% quantile: " << boost::math::quantile(posterior, 0.025) << endl; cout << " 50% quantile: " << boost::math::quantile(posterior, 0.5) << endl; cout << " 97.5% quantile: " << boost::math::quantile(posterior, 0.975) << endl << endl; cout << " probability variance <= 15: " << boost::math::cdf(posterior, 15.0) << endl; cout << " probability variance <= 25: " << boost::math::cdf(posterior, 25.0) << endl; cout << " probability variance > 50: " << boost::math::cdf(boost::math::complement(posterior, 50.0)) << endl; //] [/inverse_chi_squared_bayes_eg_4] //[inverse_chi_squared_bayes_eg_output_4 /*`This produces this output: Posterior distribution: 2.5% quantile: 39.1 50% quantile: 49.8 97.5% quantile: 64.9 probability variance <= 15: 2.97e-031 probability variance <= 25: 8.85e-010 probability variance > 50: 0.489 */ //] [/inverse_chi_squared_bayes_eg_output_4] //[inverse_chi_squared_bayes_eg_5 /*`Indeed, the probability that the machine works at a low variance (<= 15) is almost zero, and even the probability of working at average or better performance is negligibly small (less than one-millionth of a permille). On the other hand, with an almost near-half probability (49%), the machine operates in the extreme high variance range of > 50 characteristic for poorly performing machines. Based on this information the operation of the machine is taken out of use and serviced. In summary, the Bayesian analysis allowed us to make exact probabilistic statements about a parameter of interest, and hence provided us results with straightforward interpretation. */ //] [/inverse_chi_squared_bayes_eg_5] } // int main() //[inverse_chi_squared_bayes_eg_output /*` [pre Inverse_chi_squared_distribution Bayes example: Prior distribution: 2.5% quantile: 14.6 50% quantile: 25.9 97.5% quantile: 52.1 probability variance <= 15: 0.031 probability variance <= 25: 0.458 probability variance > 50: 0.0318 balls sample size: 100 balls sample variance: 55 prior degrees-of-freedom: 20 posterior degrees-of-freedom: 120 prior scale: 25 posterior scale: 49.5 Posterior distribution: 2.5% quantile: 39.1 50% quantile: 49.8 97.5% quantile: 64.9 probability variance <= 15: 2.97e-031 probability variance <= 25: 8.85e-010 probability variance > 50: 0.489 ] [/pre] */ //] [/inverse_chi_squared_bayes_eg_output]
40.628319
135
0.752487
[ "model" ]
364101396cc26175a1280e35d5ecab0563bc384c
6,240
cpp
C++
AgeEstimation.cpp
wuxuef2/face
377f5d17e0d3500720f4f609c0a4d70fa02fc11b
[ "MIT" ]
18
2015-05-07T13:54:53.000Z
2020-02-29T05:21:34.000Z
AgeEstimation.cpp
wuxuef2/face
377f5d17e0d3500720f4f609c0a4d70fa02fc11b
[ "MIT" ]
null
null
null
AgeEstimation.cpp
wuxuef2/face
377f5d17e0d3500720f4f609c0a4d70fa02fc11b
[ "MIT" ]
16
2015-12-22T05:43:53.000Z
2019-12-26T02:37:09.000Z
/* * AgeEstimation.cpp * * Created on: Mar 22, 2015 * Author: wuxuef */ #include "AgeEstimation.h" //#include <direct.h> #define free2dvector(vec) \ { \ for(int i = 0; i < vec.size(); i++) vec[i].clear(); \ vec.clear(); \ } /* get reference to pixel at (col,row), for multi-channel images (col) should be multiplied by number of channels */ #define CV_IMAGE_ELEM( image, elemtype, row, col ) \ (((elemtype*)((image)->imageData + (image)->widthStep*(row)))[(col)]) AgeEstimation::AgeEstimation() { __MeanS = 0; __MeanT = 0; __ShapeParamGroups = 0; __TextureParamGroups = 0; SVMParam = std::string("SVM_AAM.xml"); } AgeEstimation::~AgeEstimation() { cvReleaseMat(&__MeanS); cvReleaseMat(&__MeanT); cvReleaseMat(&__ShapeParamGroups); cvReleaseMat(&__TextureParamGroups); } void printMat(CvMat mat) { for (int i = 0; i < mat.rows; i++) { for (int j = 0; j < mat.cols; j++) { printf("%lf,", cvmGet(&mat, i, j)); } printf("\n___________________________________________________________\n"); } } void AgeEstimation::train(const std::vector<AAM_Shape> &AllShapes, const std::vector<IplImage*> &AllImages, const int ng_samples[], //CvMat* AllTextures, double shape_percentage, /* = 0.95 */ double texture_percentage /* = 0.95 */) { if(AllShapes.size() != AllImages.size()) { //fprintf(stderr, "ERROE(%s, %d): #Shapes != #Images\n", __FILE__, __LINE__); //exit(0); AgingException ex(3); throw ex; } CvMat* Points; CvMemStorage* Storage; //construct the pivot space of shape and texutre seperately std::vector<AAM_Shape> AllAlignedShapes; __shape.Train(AllShapes, AllAlignedShapes, 0.95); Points = cvCreateMat (1, __shape.nPoints(), CV_32FC2); Storage = cvCreateMemStorage(0); __paw.Train(__shape.GetAAMReferenceShape(), Points, Storage); int nSamples = AllShapes.size(); int nPointsby2 = __shape.nPoints() * 2; __nShapeModes = __shape.nModes(); int nPixelsby3 = __paw.nPix() * 3; CvMat* AllTextures = cvCreateMat(nSamples, nPixelsby3, CV_64FC1); __texture.Train(AllShapes, __paw, AllImages, AllTextures, 0.95, false); //if true, save the images __nTextureModes = __texture.nModes(); __MeanS = cvCreateMat(1, nPointsby2, CV_64FC1); __MeanT = cvCreateMat(1, nPixelsby3, CV_64FC1); cvCopy(__shape.GetMean(), __MeanS); cvCopy(__texture.GetMean(), __MeanT); __AAMRefShape.Mat2Point(__MeanS); //center at (0, 0) //calculate the mean parameters of all shapes and textures in each age group for (int i = 0; i < AGE_AREA; i++) { __nGSamples[i] = ng_samples[i]; } int sampleNumbers = 0; for (int i = 0; i < AGE_AREA; i++) { sampleNumbers += ng_samples[i]; } AAM_Shape oneShape; int pointsNumber = 68; float* points = new float[sampleNumbers * 2 * pointsNumber]; float* labs = new float[sampleNumbers]; float* begin = points; int counter = 0; for (int i = 0; i < AGE_AREA; i++) { for (int j = 0; j < ng_samples[i]; j++) { AAM_Shape oneShape = AllAlignedShapes[counter]; oneShape.shap2Array(begin); begin += 2 * pointsNumber; labs[counter] = i; counter++; } } CvMat trainingDataMat = cvMat(sampleNumbers, 2 * pointsNumber, CV_32FC1, points); CvMat labelsMat = cvMat(sampleNumbers, 1, CV_32FC1, labs); printMat(trainingDataMat); //printMat(labelsMat); //训练参数设定 CvSVMParams params; params.svm_type = CvSVM::C_SVC; //SVM类型 params.kernel_type = CvSVM::LINEAR; //核函数的类型 //SVM训练过程的终止条件, max_iter:最大迭代次数 epsilon:结果的精确性 params.term_crit = cvTermCriteria(CV_TERMCRIT_ITER, 10000, FLT_EPSILON); SVM.train(&trainingDataMat, &labelsMat, NULL, NULL, params); SVM.save(SVMParam.c_str()); delete[] points; delete[] labs; } float AgeEstimation::predict(const AAM_Shape& shape, const IplImage& curImage) { //get the current shape parameters AAM_Shape curShape = shape; curShape.Centralize(); double thisfacewidth = curShape.GetWidth(); if(stdwidth < thisfacewidth) curShape.Scale(stdwidth / thisfacewidth); curShape.AlignTo(__AAMRefShape); CvMat* p = cvCreateMat(1, __nShapeModes, CV_64FC1); CvMat* pq = cvCreateMat(1, 4+__nShapeModes, CV_64FC1); __shape.CalcParams(curShape, pq); cvGetCols(pq, p, 4, 4+__nShapeModes); //get the current texture parameters CvMat* curTexture = cvCreateMat(1, __paw.nPix() * 3, CV_64FC1); __paw.FasterGetWarpTextureFromShape(shape, &curImage, curTexture, false); /*IplImage *meanImg = cvCreateImage(cvGetSize(&curImage), curImage.depth, curImage.nChannels); __paw.GetWarpImageFromVector(meanImg,curTexture); cvShowImage("org Texture", meanImg);*/ __texture.AlignTextureToRef(__MeanT, curTexture); CvMat* lamda = cvCreateMat(1, __nTextureModes, CV_64FC1); __texture.CalcParams(curTexture, lamda); int pointsNumber = curShape.NPoints(); float* points = new float[2 * pointsNumber]; curShape.shap2Array(points); CvMat sample = cvMat(1, 2 * pointsNumber, CV_32FC1, points); if (SVM.get_support_vector_count() <= 0) { SVM.load(SVMParam.c_str()); } float ans = SVM.predict(&sample); printMat(sample); cvReleaseMat(&p); cvReleaseMat(&pq); cvReleaseMat(&curTexture); cvReleaseMat(&lamda); delete[] points; return ans; } void AgeEstimation::Read(std::ifstream& is) { __shape.Read(is); __ShapeParamGroups = cvCreateMat(NGROUPS, __shape.nModes(), CV_64FC1); is >> __ShapeParamGroups; __texture.Read(is); __TextureParamGroups = cvCreateMat(NGROUPS, __texture.nModes(), CV_64FC1); is >> __TextureParamGroups; __paw.Read(is); __nShapeModes = __shape.nModes(); __nTextureModes = __texture.nModes(); __MeanS = cvCreateMat(1, __shape.nPoints() * 2, CV_64FC1); __MeanT = cvCreateMat(1, __paw.nPix() * 3, CV_64FC1); cvCopy(__shape.GetMean(), __MeanS); cvCopy(__texture.GetMean(), __MeanT); __AAMRefShape.Mat2Point(__MeanS); }
29.714286
103
0.651282
[ "shape", "vector" ]
364214bc72fce4810f680dbc305ec4e19ace2e16
13,788
cc
C++
components/payments/content/payment_request_spec.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
components/payments/content/payment_request_spec.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
components/payments/content/payment_request_spec.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/payments/content/payment_request_spec.h" #include <utility> #include "base/feature_list.h" #include "base/logging.h" #include "base/strings/utf_string_conversions.h" #include "components/payments/core/features.h" #include "components/payments/core/payment_instrument.h" #include "components/payments/core/payment_method_data.h" #include "components/payments/core/payment_request_data_util.h" #include "components/strings/grit/components_strings.h" #include "ui/base/l10n/l10n_util.h" namespace payments { namespace { // Returns the card network name associated with a given BasicCardNetwork. Names // are inspired by https://www.w3.org/Payments/card-network-ids. std::string GetBasicCardNetworkName(const mojom::BasicCardNetwork& network) { switch (network) { case mojom::BasicCardNetwork::AMEX: return "amex"; case mojom::BasicCardNetwork::DINERS: return "diners"; case mojom::BasicCardNetwork::DISCOVER: return "discover"; case mojom::BasicCardNetwork::JCB: return "jcb"; case mojom::BasicCardNetwork::MASTERCARD: return "mastercard"; case mojom::BasicCardNetwork::MIR: return "mir"; case mojom::BasicCardNetwork::UNIONPAY: return "unionpay"; case mojom::BasicCardNetwork::VISA: return "visa"; } NOTREACHED(); return std::string(); } // Returns the card type associated with the given BasicCardType. autofill::CreditCard::CardType GetBasicCardType( const mojom::BasicCardType& type) { switch (type) { case mojom::BasicCardType::CREDIT: return autofill::CreditCard::CARD_TYPE_CREDIT; case mojom::BasicCardType::DEBIT: return autofill::CreditCard::CARD_TYPE_DEBIT; case mojom::BasicCardType::PREPAID: return autofill::CreditCard::CARD_TYPE_PREPAID; } NOTREACHED(); return autofill::CreditCard::CARD_TYPE_UNKNOWN; } PaymentMethodData CreatePaymentMethodData( const mojom::PaymentMethodDataPtr& method_data_entry) { PaymentMethodData method_data; method_data.supported_methods = method_data_entry->supported_methods; // Transfer the supported basic card networks (visa, amex) and types // (credit, debit). for (const mojom::BasicCardNetwork& network : method_data_entry->supported_networks) { method_data.supported_networks.push_back(GetBasicCardNetworkName(network)); } for (const mojom::BasicCardType& type : method_data_entry->supported_types) { autofill::CreditCard::CardType card_type = GetBasicCardType(type); method_data.supported_types.insert(card_type); } return method_data; } // Validates the |method_data| and fills |supported_card_networks_|, // |supported_card_networks_set_|, |basic_card_specified_networks_|, // and |url_payment_method_identifiers_|. void PopulateValidatedMethodData( const std::vector<PaymentMethodData>& method_data_vector, std::vector<std::string>* supported_card_networks, std::set<std::string>* basic_card_specified_networks, std::set<std::string>* supported_card_networks_set, std::set<autofill::CreditCard::CardType>* supported_card_types_set, std::vector<std::string>* url_payment_method_identifiers, std::map<std::string, std::set<std::string>>* stringified_method_data) { data_util::ParseSupportedMethods(method_data_vector, supported_card_networks, basic_card_specified_networks, url_payment_method_identifiers); supported_card_networks_set->insert(supported_card_networks->begin(), supported_card_networks->end()); data_util::ParseSupportedCardTypes(method_data_vector, supported_card_types_set); } void PopulateValidatedMethodData( const std::vector<mojom::PaymentMethodDataPtr>& method_data_mojom, std::vector<std::string>* supported_card_networks, std::set<std::string>* basic_card_specified_networks, std::set<std::string>* supported_card_networks_set, std::set<autofill::CreditCard::CardType>* supported_card_types_set, std::vector<std::string>* url_payment_method_identifiers, std::map<std::string, std::set<std::string>>* stringified_method_data) { std::vector<PaymentMethodData> method_data_vector; method_data_vector.reserve(method_data_mojom.size()); for (const mojom::PaymentMethodDataPtr& method_data_entry : method_data_mojom) { for (const std::string& method : method_data_entry->supported_methods) { (*stringified_method_data)[method].insert( method_data_entry->stringified_data); } method_data_vector.push_back(CreatePaymentMethodData(method_data_entry)); } PopulateValidatedMethodData( method_data_vector, supported_card_networks, basic_card_specified_networks, supported_card_networks_set, supported_card_types_set, url_payment_method_identifiers, stringified_method_data); } } // namespace const char kBasicCardMethodName[] = "basic-card"; PaymentRequestSpec::PaymentRequestSpec( mojom::PaymentOptionsPtr options, mojom::PaymentDetailsPtr details, std::vector<mojom::PaymentMethodDataPtr> method_data, Observer* observer, const std::string& app_locale) : options_(std::move(options)), details_(std::move(details)), app_locale_(app_locale), selected_shipping_option_(nullptr) { if (observer) AddObserver(observer); UpdateSelectedShippingOption(/*after_update=*/false); PopulateValidatedMethodData( method_data, &supported_card_networks_, &basic_card_specified_networks_, &supported_card_networks_set_, &supported_card_types_set_, &url_payment_method_identifiers_, &stringified_method_data_); } PaymentRequestSpec::~PaymentRequestSpec() {} void PaymentRequestSpec::UpdateWith(mojom::PaymentDetailsPtr details) { details_ = std::move(details); // We reparse the |details_| and update the observers. UpdateSelectedShippingOption(/*after_update=*/true); NotifyOnSpecUpdated(); current_update_reason_ = UpdateReason::NONE; } void PaymentRequestSpec::AddObserver(Observer* observer) { CHECK(observer); observers_.AddObserver(observer); } void PaymentRequestSpec::RemoveObserver(Observer* observer) { observers_.RemoveObserver(observer); } bool PaymentRequestSpec::request_shipping() const { return options_->request_shipping; } bool PaymentRequestSpec::request_payer_name() const { return options_->request_payer_name; } bool PaymentRequestSpec::request_payer_phone() const { return options_->request_payer_phone; } bool PaymentRequestSpec::request_payer_email() const { return options_->request_payer_email; } PaymentShippingType PaymentRequestSpec::shipping_type() const { // Transform Mojo-specific enum into platform-agnostic equivalent. switch (options_->shipping_type) { case mojom::PaymentShippingType::DELIVERY: return PaymentShippingType::DELIVERY; case payments::mojom::PaymentShippingType::PICKUP: return PaymentShippingType::PICKUP; case payments::mojom::PaymentShippingType::SHIPPING: return PaymentShippingType::SHIPPING; default: NOTREACHED(); } // Needed for compilation on some platforms. return PaymentShippingType::SHIPPING; } bool PaymentRequestSpec::IsMethodSupportedThroughBasicCard( const std::string& method_name) { return basic_card_specified_networks_.count(method_name) > 0; } base::string16 PaymentRequestSpec::GetFormattedCurrencyAmount( const mojom::PaymentCurrencyAmountPtr& currency_amount) { CurrencyFormatter* formatter = GetOrCreateCurrencyFormatter( currency_amount->currency, currency_amount->currency_system, app_locale_); return formatter->Format(currency_amount->value); } std::string PaymentRequestSpec::GetFormattedCurrencyCode( const mojom::PaymentCurrencyAmountPtr& currency_amount) { CurrencyFormatter* formatter = GetOrCreateCurrencyFormatter( currency_amount->currency, currency_amount->currency_system, app_locale_); return formatter->formatted_currency_code(); } void PaymentRequestSpec::StartWaitingForUpdateWith( PaymentRequestSpec::UpdateReason reason) { current_update_reason_ = reason; for (auto& observer : observers_) { observer.OnStartUpdating(reason); } } bool PaymentRequestSpec::IsMixedCurrency() const { const std::string& total_currency = details_->total->amount->currency; return std::any_of(details_->display_items.begin(), details_->display_items.end(), [&total_currency](const mojom::PaymentItemPtr& item) { return item->amount->currency != total_currency; }); } const mojom::PaymentItemPtr& PaymentRequestSpec::GetTotal( PaymentInstrument* selected_instrument) const { const mojom::PaymentDetailsModifierPtr* modifier = GetApplicableModifier(selected_instrument); return modifier ? (*modifier)->total : details().total; } std::vector<const mojom::PaymentItemPtr*> PaymentRequestSpec::GetDisplayItems( PaymentInstrument* selected_instrument) const { std::vector<const mojom::PaymentItemPtr*> display_items; const mojom::PaymentDetailsModifierPtr* modifier = GetApplicableModifier(selected_instrument); for (const auto& item : details().display_items) { display_items.push_back(&item); } if (modifier) { for (const auto& additional_item : (*modifier)->additional_display_items) { display_items.push_back(&additional_item); } } return display_items; } const std::vector<mojom::PaymentShippingOptionPtr>& PaymentRequestSpec::GetShippingOptions() const { return details().shipping_options; } const mojom::PaymentDetailsModifierPtr* PaymentRequestSpec::GetApplicableModifier( PaymentInstrument* selected_instrument) const { if (!selected_instrument || !base::FeatureList::IsEnabled(features::kWebPaymentsModifiers)) return nullptr; for (const auto& modifier : details().modifiers) { std::vector<std::string> supported_networks; std::set<autofill::CreditCard::CardType> supported_types; // The following 4 are unused but required by PopulateValidatedMethodData. std::set<std::string> basic_card_specified_networks; std::set<std::string> supported_card_networks_set; std::vector<std::string> url_payment_method_identifiers; std::map<std::string, std::set<std::string>> stringified_method_data; PopulateValidatedMethodData( {CreatePaymentMethodData(modifier->method_data)}, &supported_networks, &basic_card_specified_networks, &supported_card_networks_set, &supported_types, &url_payment_method_identifiers, &stringified_method_data); if (selected_instrument->IsValidForModifier( modifier->method_data->supported_methods, supported_types, supported_networks)) { return &modifier; } } return nullptr; } void PaymentRequestSpec::UpdateSelectedShippingOption(bool after_update) { if (!request_shipping()) return; selected_shipping_option_ = nullptr; selected_shipping_option_error_.clear(); if (details().shipping_options.empty()) { // No options are provided by the merchant. if (after_update) { // This is after an update, which means that the selected address is not // supported. The merchant may have customized the error string, or a // generic one is used. if (!details().error.empty()) { selected_shipping_option_error_ = base::UTF8ToUTF16(details().error); } else { // The generic error string depends on the shipping type. switch (shipping_type()) { case PaymentShippingType::DELIVERY: selected_shipping_option_error_ = l10n_util::GetStringUTF16( IDS_PAYMENTS_UNSUPPORTED_DELIVERY_ADDRESS); break; case PaymentShippingType::PICKUP: selected_shipping_option_error_ = l10n_util::GetStringUTF16( IDS_PAYMENTS_UNSUPPORTED_PICKUP_ADDRESS); break; case PaymentShippingType::SHIPPING: selected_shipping_option_error_ = l10n_util::GetStringUTF16( IDS_PAYMENTS_UNSUPPORTED_SHIPPING_ADDRESS); break; } } } return; } // As per the spec, the selected shipping option should initially be the last // one in the array that has its selected field set to true. If none are // selected by the merchant, |selected_shipping_option_| stays nullptr. auto selected_shipping_option_it = std::find_if( details().shipping_options.rbegin(), details().shipping_options.rend(), [](const payments::mojom::PaymentShippingOptionPtr& element) { return element->selected; }); if (selected_shipping_option_it != details().shipping_options.rend()) { selected_shipping_option_ = selected_shipping_option_it->get(); } } void PaymentRequestSpec::NotifyOnSpecUpdated() { for (auto& observer : observers_) observer.OnSpecUpdated(); } CurrencyFormatter* PaymentRequestSpec::GetOrCreateCurrencyFormatter( const std::string& currency_code, const std::string& currency_system, const std::string& locale_name) { // Create a currency formatter for |currency_code|, or if already created // return the cached version. std::pair<std::map<std::string, CurrencyFormatter>::iterator, bool> emplace_result = currency_formatters_.emplace( std::piecewise_construct, std::forward_as_tuple(currency_code), std::forward_as_tuple(currency_code, currency_system, locale_name)); return &(emplace_result.first->second); } } // namespace payments
37.983471
80
0.740499
[ "vector", "transform" ]
3644fcfed9e0c116af878b33eb197b8c817ffe19
7,919
cpp
C++
ModelViewer/QtSceneFromModel_T2D_CHM_mt.cpp
COFS-UWA/MPM3D
1a0c5dc4e92dff3855367846002336ca5a18d124
[ "MIT" ]
null
null
null
ModelViewer/QtSceneFromModel_T2D_CHM_mt.cpp
COFS-UWA/MPM3D
1a0c5dc4e92dff3855367846002336ca5a18d124
[ "MIT" ]
2
2020-10-19T02:03:11.000Z
2021-03-19T16:34:39.000Z
ModelViewer/QtSceneFromModel_T2D_CHM_mt.cpp
COFS-UWA/MPM3D
1a0c5dc4e92dff3855367846002336ca5a18d124
[ "MIT" ]
1
2020-04-28T00:33:14.000Z
2020-04-28T00:33:14.000Z
#include "ModelViewer_pcp.h" #include "QtSceneFromModel_T2D_CHM_mt.h" QtSceneFromModel_T2D_CHM_mt::QtSceneFromModel_T2D_CHM_mt( QOpenGLFunctions_3_3_Core &_gl) : QtSceneFromModel(_gl), model(nullptr), pt_num(0), pts(nullptr), display_bg_mesh(true), bg_mesh_obj(_gl), display_pcls(true), pcls_obj(_gl), display_pts(true), pts_obj(_gl), display_rigid_circle(true), rc_obj(_gl), display_whole_model(true), padding_ratio(0.05f), bg_color(0.2f, 0.3f, 0.3f), pcl_color(1.0f, 0.8941f, 0.7098f) {} QtSceneFromModel_T2D_CHM_mt::~QtSceneFromModel_T2D_CHM_mt() {} void QtSceneFromModel_T2D_CHM_mt::set_viewport( int wd, int ht, GLfloat xlen, GLfloat ylen) { int wd2, ht2, padding; ht2 = wd * (ylen / xlen); if (ht2 <= ht) { padding = (ht - ht2) / 2; vp_x_pos = 0; vp_y_pos = padding; vp_x_size = wd; vp_y_size = ht2; } else { wd2 = ht * (xlen / ylen); padding = (wd - wd2) / 2; vp_x_pos = padding; vp_y_pos = 0; vp_x_size = wd2; vp_y_size = ht; } } int QtSceneFromModel_T2D_CHM_mt::initialize(int wd, int ht) { // init shaders // shader_plain2D shader_plain2D.addShaderFromSourceFile( QOpenGLShader::Vertex, "../../Asset/shader_plain2D.vert" ); shader_plain2D.addShaderFromSourceFile( QOpenGLShader::Fragment, "../../Asset/shader_plain2D.frag" ); shader_plain2D.link(); // shader_circles shader_circles.addShaderFromSourceFile( QOpenGLShader::Vertex, "../../Asset/shader_circles.vert" ); shader_circles.addShaderFromSourceFile( QOpenGLShader::Fragment, "../../Asset/shader_circles.frag" ); shader_circles.link(); // get bounding box if (display_whole_model) { Rect bbox = model->get_mesh_bbox(); if (model->has_rigid_circle()) { Rect rc_bbox; model->get_rigid_circle().get_bbox(rc_bbox); bbox.envelop(rc_bbox); } GLfloat xlen = GLfloat(bbox.xu - bbox.xl); GLfloat ylen = GLfloat(bbox.yu - bbox.yl); GLfloat padding = (xlen > ylen ? xlen : ylen) * padding_ratio; display_bbox.xl = GLfloat(bbox.xl) - padding; display_bbox.xu = GLfloat(bbox.xu) + padding; display_bbox.yl = GLfloat(bbox.yl) - padding; display_bbox.yu = GLfloat(bbox.yu) + padding; } // viewport set_viewport(wd, ht, display_bbox.xu - display_bbox.xl, display_bbox.yu - display_bbox.yl); // view matrix view_mat.setToIdentity(); view_mat.ortho( display_bbox.xl, display_bbox.xu, display_bbox.yl, display_bbox.yu, -1.0f, 1.0f); shader_plain2D.bind(); shader_plain2D.setUniformValue("view_mat", view_mat); shader_circles.bind(); shader_circles.setUniformValue("view_mat", view_mat); // init bg_mesh QVector3D gray(0.5f, 0.5f, 0.5f); bg_mesh_obj.init_from_elements( model->get_node_pos(), model->get_node_num(), model->get_elem_node_index(), model->get_elem_num(), gray); // init pcls auto *pcl_index = model->get_pcl_index0(); auto* pcl_pos = model->get_pcl_pos(); const size_t pcl_num = model->get_pcl_num(); Model_T2D_CHM_mt::Position *pcl_pos1 = (Model_T2D_CHM_mt::Position *)::operator new(sizeof(Model_T2D_CHM_mt::Position) * pcl_num); for (size_t p_id = 0; p_id < pcl_num; ++p_id) { const size_t ori_p_id = pcl_index[p_id]; pcl_pos1[p_id].x = pcl_pos[ori_p_id].x; pcl_pos1[p_id].y = pcl_pos[ori_p_id].y; } pcls_obj.init( pcl_pos1, model->get_pcl_vol(), model->get_pcl_num(), pcl_color, 0.5f); ::operator delete ((void *)pcl_pos1); // init rigid circle QVector3D light_slate_blue(0.5176f, 0.4392, 1.0f); if (model->has_rigid_circle()) { auto &rc = model->get_rigid_circle(); rc_obj.init( rc.get_x(), rc.get_y(), rc.get_radius(), light_slate_blue, 3.0f); } // init pts QVector3D red(1.0f, 0.0f, 0.0f); if (pts && pt_num) pts_obj.init(pts, pt_num, pt_radius, red); return 0; } void QtSceneFromModel_T2D_CHM_mt::draw() { gl.glViewport(vp_x_pos, vp_y_pos, vp_x_size, vp_y_size); gl.glClearColor(bg_color.x(), bg_color.y(), bg_color.z(), 1.0f); gl.glClear(GL_COLOR_BUFFER_BIT); shader_plain2D.bind(); if (display_bg_mesh) bg_mesh_obj.draw(shader_plain2D); if (model->has_rigid_circle() && display_rigid_circle) rc_obj.draw(shader_plain2D); shader_circles.bind(); if (display_pcls) pcls_obj.draw(shader_circles); if (display_pts && pts && pt_num) pts_obj.draw(shader_circles); } void QtSceneFromModel_T2D_CHM_mt::resize(int wd, int ht) { set_viewport(wd, ht, display_bbox.xu - display_bbox.xl, display_bbox.yu - display_bbox.yl ); } int QtSceneFromModel_T2D_CHM_mt::set_pts_from_pcl_id( size_t* ids, size_t id_num, float radius) { if (!model || !ids || !id_num || radius <= 0.0f) return -1; pt_num = id_num; pt_radius = radius; pts_mem.reserve(id_num); pts = pts_mem.get_mem(); const Model_T2D_CHM_mt::Position *pcl_pos = model->get_pcl_pos(); for (size_t p_id = 0; p_id < id_num; ++p_id) { const Model_T2D_CHM_mt::Position &pp = pcl_pos[ids[p_id]]; PointData& pd = pts[p_id]; pd.x = GLfloat(pp.x); pd.y = GLfloat(pp.y); } return 0; } int QtSceneFromModel_T2D_CHM_mt::set_pts_from_node_id( size_t* ids, size_t id_num, float radius) { if (!model || !ids || !id_num || radius <= 0.0f) return -1; pt_num = id_num; pt_radius = radius; pts_mem.reserve(id_num); pts = pts_mem.get_mem(); const Model_T2D_CHM_mt::Position *node_pos = model->get_node_pos(); for (size_t p_id = 0; p_id < id_num; ++p_id) { const Model_T2D_CHM_mt::Position &np = node_pos[ids[p_id]]; PointData& pd = pts[p_id]; pd.x = GLfloat(np.x); pd.y = GLfloat(np.y); } return 0; } int QtSceneFromModel_T2D_CHM_mt::set_pts_from_vx_s_bc(float radius) { Model_T2D_CHM_mt& md = *model; size_t node_num = md.get_node_num(); const Model_T2D_CHM_mt::NodeHasVBC* nhv = md.get_has_vbc_s(); const Model_T2D_CHM_mt::Position* node_pos = md.get_node_pos(); pt_radius = radius; pt_num = 0; pts_mem.reserve(100); PointData pd_tmp; for (size_t n_id = 0; n_id < node_num; ++n_id) { if (nhv[n_id].has_vx_bc) { const Model_T2D_CHM_mt::Position& n = node_pos[n_id]; pd_tmp.x = n.x; pd_tmp.y = n.y; pts_mem.add(pd_tmp); ++pt_num; } } pts = pts_mem.get_mem(); return 0; } int QtSceneFromModel_T2D_CHM_mt::set_pts_from_vy_s_bc(float radius) { Model_T2D_CHM_mt &md = *model; size_t node_num = md.get_node_num(); const Model_T2D_CHM_mt::NodeHasVBC* nhv = md.get_has_vbc_s(); const Model_T2D_CHM_mt::Position* node_pos = md.get_node_pos(); pt_radius = radius; pt_num = 0; pts_mem.reserve(100); PointData pd_tmp; for (size_t n_id = 0; n_id < node_num; ++n_id) { if (nhv[n_id].has_vy_bc) { const Model_T2D_CHM_mt::Position& n = node_pos[n_id]; pd_tmp.x = n.x; pd_tmp.y = n.y; pts_mem.add(pd_tmp); ++pt_num; } } pts = pts_mem.get_mem(); return 0; } int QtSceneFromModel_T2D_CHM_mt::set_pts_from_vx_f_bc(float radius) { Model_T2D_CHM_mt& md = *model; const size_t node_num = md.get_node_num(); const Model_T2D_CHM_mt::NodeHasVBC* nhv = md.get_has_vbc_f(); const Model_T2D_CHM_mt::Position* node_pos = md.get_node_pos(); pt_radius = radius; pt_num = 0; pts_mem.reserve(100); PointData pd_tmp; for (size_t n_id = 0; n_id < node_num; ++n_id) { if (nhv[n_id].has_vx_bc) { const Model_T2D_CHM_mt::Position& n = node_pos[n_id]; pd_tmp.x = n.x; pd_tmp.y = n.y; pts_mem.add(pd_tmp); ++pt_num; } } pts = pts_mem.get_mem(); return 0; } int QtSceneFromModel_T2D_CHM_mt::set_pts_from_vy_f_bc(float radius) { Model_T2D_CHM_mt& md = *model; const size_t node_num = md.get_node_num(); const Model_T2D_CHM_mt::NodeHasVBC* nhv = md.get_has_vbc_f(); const Model_T2D_CHM_mt::Position* node_pos = md.get_node_pos(); pt_radius = radius; pt_num = 0; pts_mem.reserve(100); PointData pd_tmp; for (size_t n_id = 0; n_id < node_num; ++n_id) { if (nhv[n_id].has_vy_bc) { const Model_T2D_CHM_mt::Position& n = node_pos[n_id]; pd_tmp.x = n.x; pd_tmp.y = n.y; pts_mem.add(pd_tmp); ++pt_num; } } pts = pts_mem.get_mem(); return 0; }
24.143293
95
0.698826
[ "model" ]
3653eafbb2c449a5468dfbc4dccdd30bf8406803
29,973
hpp
C++
include/fluid/oclsph.hpp
tom91136/libfluid
a0d54d06b1fe754db14ddc7d511fb7b57a5cce45
[ "Apache-2.0" ]
4
2019-03-11T18:12:22.000Z
2019-07-11T12:39:35.000Z
include/fluid/oclsph.hpp
tom91136/libfluid
a0d54d06b1fe754db14ddc7d511fb7b57a5cce45
[ "Apache-2.0" ]
null
null
null
include/fluid/oclsph.hpp
tom91136/libfluid
a0d54d06b1fe754db14ddc7d511fb7b57a5cce45
[ "Apache-2.0" ]
null
null
null
#ifndef LIBFLUID_CLSPH_HPP #define LIBFLUID_CLSPH_HPP #define CL_HPP_TARGET_OPENCL_VERSION 120 #define CL_HPP_MINIMUM_OPENCL_VERSION 120 #define CL_HPP_CL_1_2_DEFAULT_BUILD #define CL_HPP_ENABLE_EXCEPTIONS #define GLM_ENABLE_EXPERIMENTAL #define CURVE_UINT3_TYPE glm::tvec3<size_t> #define CURVE_UINT3_CTOR(x, y, z) (glm::tvec3<size_t>((x), (y), (z))) #include <iostream> #include <iomanip> #include <fstream> #include <sstream> #include <chrono> #include <vector> #include <memory> #include <algorithm> #include <sys/types.h> #include <sys/stat.h> #include "cl2.hpp" #include "clutils.hpp" #include "fluid.hpp" #include "oclsph_type.h" #include "curves.h" #include "mc.h" #include "ska_sort.hpp" //#define DEBUG namespace ocl { using glm::tvec3; using glm::tvec4; using clutil::TypedBuffer; using clutil::RW; using clutil::RO; using clutil::WO; typedef cl::Buffer ClSphConfigStruct; typedef cl::Buffer ClMcConfigStruct; typedef cl::KernelFunctor< ClSphConfigStruct &, cl::Buffer &, cl::Buffer &, uint, // zIdx, grid, gridN cl::Buffer &, // type cl::Buffer &, // pstar cl::Buffer &, // original colour cl::Buffer & // colour > SphDiffuseKernel; typedef cl::KernelFunctor< ClSphConfigStruct &, cl::Buffer &, cl::Buffer &, uint, // zIdx, grid, gridN cl::Buffer &, // type cl::Buffer &, // pstar cl::Buffer &, // mass cl::Buffer & // lambda > SphLambdaKernel; typedef cl::KernelFunctor< ClSphConfigStruct &, cl::Buffer &, cl::Buffer &, uint, // zIdx, grid, gridN cl::Buffer &, // type cl::Buffer &, uint, // mesh + N cl::Buffer &, // pstar cl::Buffer &, // lambda cl::Buffer &, // pos cl::Buffer &, // vel cl::Buffer & // deltap > SphDeltaKernel; typedef cl::KernelFunctor< ClSphConfigStruct &, cl::Buffer &, // type cl::Buffer &, // pstar cl::Buffer &, // pos cl::Buffer & // vel > SphFinaliseKernel; typedef cl::KernelFunctor< ClSphConfigStruct &, ClMcConfigStruct &, cl::Buffer &, uint, cl::Buffer &, // type float3, uint3, uint3, cl::Buffer &, cl::Buffer &, cl::Buffer &, cl::Buffer & > McLatticeKernel; typedef cl::KernelFunctor< ClMcConfigStruct &, uint3, cl::Buffer &, cl::LocalSpaceArg, cl::Buffer & > McSizeKernel; typedef cl::KernelFunctor< ClSphConfigStruct &, ClMcConfigStruct &, float3, uint3, cl::Buffer &, cl::Buffer &, cl::Buffer &, uint, cl::Buffer &, cl::Buffer &, cl::Buffer &, cl::Buffer &, cl::Buffer &, cl::Buffer &, cl::Buffer &, cl::Buffer &, cl::Buffer & > McEvalKernel; struct ClSphAtoms { const size_t size; std::vector<uint> zIndex; std::vector<ClSphType> type; std::vector<float> mass; std::vector<uchar4> colour; std::vector<float3> pStar; std::vector<float3> position; std::vector<float3> velocity; explicit ClSphAtoms(size_t size) : size(size), zIndex(size), type(size), mass(size), colour(size), pStar(size), position(size), velocity(size) {} }; struct PartiallyAdvected { uint zIndex{}; float3 pStar{}; fluid::Particle<size_t, float> particle; PartiallyAdvected() = default; explicit PartiallyAdvected(uint zIndex, float3 pStar, const fluid::Particle<size_t, float> &particle) : zIndex(zIndex), pStar(pStar), particle(particle) {} }; class SphSolver : public fluid::SphSolver<size_t, float> { private: const float h; const cl::Device device; const cl::Context ctx; const cl::Program clsph; cl::CommandQueue queue; SphDiffuseKernel sphDiffuseKernel; SphLambdaKernel sphLambdaKernel; SphDeltaKernel sphDeltaKernel; SphFinaliseKernel sphFinaliseKernel; McLatticeKernel mcLatticeKernel; McSizeKernel mcSizeKernel; McEvalKernel mcEvalKernel; public: explicit SphSolver(float h, const std::string &kernelPath, const cl::Device &device) : h(h), device(device), ctx(cl::Context(device)), clsph(clutil::loadProgramFromFile( ctx, kernelPath + "oclsph_kernel.h", kernelPath, "-DSPH_H=((float)" + std::to_string(h) + ")")), //TODO check capability queue(cl::CommandQueue(ctx, device, cl::QueueProperties::None)), sphDiffuseKernel(clsph, "sph_diffuse"), sphLambdaKernel(clsph, "sph_lambda"), sphDeltaKernel(clsph, "sph_delta"), sphFinaliseKernel(clsph, "sph_finalise"), mcLatticeKernel(clsph, "mc_lattice"), mcSizeKernel(clsph, "mc_size"), mcEvalKernel(clsph, "mc_eval") { checkSize(); } private: static inline ClSphType resolveType(fluid::Type t) { switch (t) { case fluid::Type::Fluid: return ClSphType::Fluid; case fluid::Type::Obstacle: return ClSphType::Obstacle; default: throw std::logic_error("unhandled branch (fluid::Type->ClSphType)"); } } static inline fluid::Type resolveType(ClSphType t) { switch (t) { case ClSphType::Fluid: return fluid::Type::Fluid; case ClSphType::Obstacle: return fluid::Type::Obstacle; default: throw std::logic_error("unhandled branch (fluid::Type<-ClSphType)"); } } static inline std::string to_string(tvec3<size_t> v) { return "(" + std::to_string(v.x) + "," + std::to_string(v.y) + "," + std::to_string(v.z) + ")"; } void checkSize() { std::vector<size_t> expected(_SIZES, _SIZES + _SIZES_LENGTH); std::vector<size_t> actual(_SIZES_LENGTH, 0); try { TypedBuffer<size_t, WO> buffer(ctx, _SIZES_LENGTH); cl::KernelFunctor<cl::Buffer &>(clsph, "check_size") (cl::EnqueueArgs(queue, cl::NDRange(_SIZES_LENGTH)), buffer.actual); buffer.drainTo(queue, actual); queue.finish(); } catch (cl::Error &exc) { std::cerr << "Kernel failed to execute: " << exc.what() << " -> " << clResolveError(exc.err()) << "(" << exc.err() << ")" << std::endl; throw; } #ifdef DEBUG std::cout << "Expected(" << _SIZES_LENGTH << ")=" << clutil::mkString<size_t>(expected, [](auto x) { return std::to_string(x); }) << std::endl; std::cout << "Actual(" << _SIZES_LENGTH << ") =" << clutil::mkString<size_t>(actual, [](auto x) { return std::to_string(x); }) << std::endl; #endif assert(expected == actual); } std::vector<surface::MeshTriangle<float>> sampleLattice( float isolevel, float scale, const tvec3<float> min, float step, const surface::Lattice<float4> &lattice) { std::vector<surface::MeshTriangle<float>> triangles; // XXX ICC needs perfectly nested loops like this for omp collapse const size_t latticeX = lattice.xSize() - 1; const size_t latticeY = lattice.ySize() - 1; const size_t latticeZ = lattice.zSize() - 1; #ifndef _MSC_VER #pragma omp declare reduction (merge : std::vector<geometry::MeshTriangle<float>> : omp_out.insert(omp_out.end(), omp_in.begin(), omp_in.end())) #pragma omp parallel for collapse(3) reduction(merge: triangles) #endif for (size_t x = 0; x < latticeX; ++x) { for (size_t y = 0; y < latticeY; ++y) { for (size_t z = 0; z < latticeZ; ++z) { std::array<float, 8> vertices{}; std::array<tvec3<float>, 8> normals{}; std::array<tvec3<float>, 8> pos{}; for (size_t j = 0; j < 8; ++j) { tvec3<size_t> offset = tvec3<size_t>(x, y, z) + surface::CUBE_OFFSETS[j]; float4 v = lattice(offset.x, offset.y, offset.z); vertices[j] = v.s0; normals[j] = tvec3<float>(v.s1, v.s2, v.s3); pos[j] = (tvec3<float>(offset) * step + min) * scale; } surface::marchSingle(isolevel, vertices, normals, pos, triangles); } } } std::cout << "Acc2=" << 0 << "Lattice:" << lattice.size() << std::endl; return triangles; } std::vector<PartiallyAdvected> advectAndCopy(const fluid::Config<float> &config, std::vector<fluid::Particle<size_t, float>> &xs) { std::vector<PartiallyAdvected> advected(xs.size()); const float threshold = 200.f; const float thresholdSquared = threshold * threshold; #pragma omp parallel for for (int i = 0; i < static_cast<int>(xs.size()); ++i) { fluid::Particle<size_t, float> &p = xs[i]; advected[i].particle = p; advected[i].pStar = clutil::vec3ToCl(p.position / config.scale); if (p.type == fluid::Type::Obstacle) continue; tvec3<float> combinedForce = p.mass * config.constantForce; for (const fluid::Well<float> &well : config.wells) { const float dist = glm::distance( p.position, well.centre); if (dist < 75.f) { const tvec3<float> rHat = glm::normalize(well.centre - p.position); const tvec3<float> forceWell = glm::clamp( (rHat * well.force * p.mass) / (dist * dist), -10.f, 10.f); combinedForce += forceWell; } } p.velocity = combinedForce * config.dt + p.velocity; advected[i].pStar = clutil::vec3ToCl( (p.velocity * config.dt) + (p.position / config.scale)); } return advected; } size_t zCurveGridIndexAtCoordAt(float x, float y, float z) const { return zCurveGridIndexAtCoord( static_cast<size_t>( x / h), static_cast<size_t>( y / h), static_cast<size_t>( z / h)); } const std::tuple<ClSphConfig, tvec3<float>, tvec3<size_t> > computeBoundAndZindex( const fluid::Config<float> &config, std::vector<PartiallyAdvected> &advection) const { tvec3<float> minExtent(std::numeric_limits<float>::max()); tvec3<float> maxExtent(std::numeric_limits<float>::min()); const float padding = h * 2; //#if _OPENMP > 201307 //#pragma omp declare reduction(glmMin: tvec3<float>: omp_out = glm::min(omp_in, omp_out)) //#pragma omp declare reduction(glmMax: tvec3<float>: omp_out = glm::max(omp_in, omp_out)) //#pragma omp parallel for reduction(glmMin:minExtent) reduction(glmMax:maxExtent) //#endif // for (int i = 0; i < static_cast<int>(advection.size()); ++i) { //// if(advection[i].particle.type != fluid::Fluid) continue; // const float3 pStar = advection[i].pStar; // minExtent = glm::min(clutil::clToVec3<float>(pStar), minExtent); // maxExtent = glm::max(clutil::clToVec3<float>(pStar), maxExtent); // } // // minExtent -= padding; // maxExtent += padding; minExtent = (config.minBound / config.scale) - padding; maxExtent = (config.maxBound / config.scale) + padding; #pragma omp parallel for for (int i = 0; i < static_cast<int>(advection.size()); ++i) { const float3 pStar = advection[i].pStar; advection[i].zIndex = zCurveGridIndexAtCoordAt( pStar.x - minExtent.x, pStar.y - minExtent.y, pStar.z - minExtent.z ); // advection[i].zIndex = zCurveGridIndexAtCoord( // static_cast<size_t>((pStar.x - minExtent.x) / h), // static_cast<size_t>((pStar.y - minExtent.y) / h), // static_cast<size_t>((pStar.z - minExtent.z) / h)); } ClSphConfig clConfig; clConfig.dt = config.dt; clConfig.scale = config.scale; clConfig.iteration = static_cast<size_t>(config.iteration); clConfig.minBound = clutil::vec3ToCl(config.minBound); clConfig.maxBound = clutil::vec3ToCl(config.maxBound); return std::make_tuple(clConfig, minExtent, glm::tvec3<size_t>((maxExtent - minExtent) / h)); } inline void finishQueue() { #ifdef DEBUG queue.finish(); #endif } std::vector<geometry::MeshTriangle<float>> runMcKernels( clutil::Stopwatch &watch, const tvec3<size_t> sampleSize, TypedBuffer<ClSphConfig, RO> &sphConfig, TypedBuffer<ClMcConfig, RO> &mcConfig, TypedBuffer<uint, RO> &gridTable, TypedBuffer<ClSphType, RO> type, TypedBuffer<float3, RW> &particlePositions, TypedBuffer<uchar4, RW> &particleColours, const tvec3<float> minExtent, const tvec3<size_t> extent ) { const uint gridTableN = static_cast<uint>(gridTable.length); const size_t latticeN = sampleSize.x * sampleSize.y * sampleSize.z; TypedBuffer<float4, RW> latticePNs(ctx, latticeN); TypedBuffer<uchar4, RW> latticeCs(ctx, latticeN); const size_t kernelWorkGroupSize = mcSizeKernel .getKernel() .getWorkGroupInfo<CL_KERNEL_WORK_GROUP_SIZE>(device); const tvec3<size_t> marchRange = sampleSize - tvec3<size_t>(1); const size_t marchVolume = marchRange.x * marchRange.y * marchRange.z; size_t workGroupSize = kernelWorkGroupSize; size_t numWorkGroup = std::ceil(static_cast<float>(marchVolume) / workGroupSize); #ifdef DEBUG std::cout << "[<>]Samples:" << glm::to_string(marchRange) << " MarchVol=" << marchVolume << " WG:" << kernelWorkGroupSize << " nWG:" << numWorkGroup << "\n"; #endif auto create_field = watch.start("\t[GPU] mc-field"); mcLatticeKernel( cl::EnqueueArgs(queue, cl::NDRange(sampleSize.x, sampleSize.y, sampleSize.z)), sphConfig.actual, mcConfig.actual, gridTable.actual, gridTableN, type.actual, clutil::vec3ToCl(minExtent), clutil::uvec3ToCl(sampleSize), clutil::uvec3ToCl(extent), particlePositions.actual, particleColours.actual, latticePNs.actual, latticeCs.actual ); finishQueue(); create_field(); auto partial_trig_sum = watch.start("\t[GPU] mc_psum"); TypedBuffer<uint, WO> partialTrigSum(ctx, numWorkGroup); mcSizeKernel( cl::EnqueueArgs(queue, cl::NDRange(numWorkGroup * workGroupSize), cl::NDRange(workGroupSize)), mcConfig.actual, clutil::uvec3ToCl(sampleSize), latticePNs.actual, cl::Local(sizeof(uint) * workGroupSize), partialTrigSum.actual ); std::vector<uint> hostPartialTrigSum(numWorkGroup, 0); partialTrigSum.drainTo(queue, hostPartialTrigSum); uint numTrigs = 0; for (uint j = 0; j < numWorkGroup; ++j) numTrigs += hostPartialTrigSum[j]; finishQueue(); partial_trig_sum(); #ifdef DEBUG std::cout << "[<>]Acc=" << numTrigs << std::endl; #endif auto gpu_mc = watch.start("\t[GPU] gpu_mc"); std::vector<surface::MeshTriangle<float>> triangles(numTrigs); if (numTrigs != 0) { std::vector<uint> zero{0}; TypedBuffer<uint, RW> trigCounter(queue, zero); TypedBuffer<float3, WO> outVxs(ctx, numTrigs); TypedBuffer<float3, WO> outVys(ctx, numTrigs); TypedBuffer<float3, WO> outVzs(ctx, numTrigs); TypedBuffer<float3, WO> outNxs(ctx, numTrigs); TypedBuffer<float3, WO> outNys(ctx, numTrigs); TypedBuffer<float3, WO> outNzs(ctx, numTrigs); TypedBuffer<uchar4, WO> outCxs(ctx, numTrigs); TypedBuffer<uchar4, WO> outCys(ctx, numTrigs); TypedBuffer<uchar4, WO> outCzs(ctx, numTrigs); mcEvalKernel( cl::EnqueueArgs(queue, cl::NDRange(marchVolume)), sphConfig.actual, mcConfig.actual, clutil::vec3ToCl(minExtent), clutil::uvec3ToCl(sampleSize), latticePNs.actual, latticeCs.actual, trigCounter.actual, numTrigs, outVxs.actual, outVys.actual, outVzs.actual, outNxs.actual, outNys.actual, outNzs.actual, outCxs.actual, outCys.actual, outCzs.actual ); finishQueue(); gpu_mc(); auto gpu_mc_drain = watch.start("\t[GPU] gpu_mc drain"); std::vector<float3> hostOutVxs(numTrigs); std::vector<float3> hostOutVys(numTrigs); std::vector<float3> hostOutVzs(numTrigs); std::vector<float3> hostOutNxs(numTrigs); std::vector<float3> hostOutNys(numTrigs); std::vector<float3> hostOutNzs(numTrigs); std::vector<uchar4> hostOutCxs(numTrigs); std::vector<uchar4> hostOutCys(numTrigs); std::vector<uchar4> hostOutCzs(numTrigs); outVxs.drainTo(queue, hostOutVxs); outVys.drainTo(queue, hostOutVys); outVzs.drainTo(queue, hostOutVzs); outNxs.drainTo(queue, hostOutNxs); outNys.drainTo(queue, hostOutNys); outNzs.drainTo(queue, hostOutNzs); outCxs.drainTo(queue, hostOutCxs); outCys.drainTo(queue, hostOutCys); outCzs.drainTo(queue, hostOutCzs); finishQueue(); gpu_mc_drain(); auto gpu_mc_assem = watch.start("\t[GPU] gpu_mc assem"); #pragma omp parallel for for (int i = 0; i < static_cast<int>(numTrigs); ++i) { triangles[i].v0 = clutil::clToVec3<float>(hostOutVxs[i]); triangles[i].v1 = clutil::clToVec3<float>(hostOutVys[i]); triangles[i].v2 = clutil::clToVec3<float>(hostOutVzs[i]); triangles[i].n0 = clutil::clToVec3<float>(hostOutNxs[i]); triangles[i].n1 = clutil::clToVec3<float>(hostOutNys[i]); triangles[i].n2 = clutil::clToVec3<float>(hostOutNzs[i]); triangles[i].c.x = clutil::packARGB(hostOutCxs[i]); triangles[i].c.y = clutil::packARGB(hostOutCys[i]); triangles[i].c.z = clutil::packARGB(hostOutCzs[i]); } gpu_mc_assem(); #ifdef DEBUG std::cout << "[<>] LatticeDataN:" << (float) (sizeof(float4) * marchVolume) / 1000000.0 << "MB" << " MCGPuN:" << (float) (sizeof(float3) * numTrigs * 6) / 1000000.0 << "MB \n"; #endif } return triangles; } void runSphKernel(clutil::Stopwatch &watch, size_t iterations, TypedBuffer<ClSphConfig, RO> &sphConfig, TypedBuffer<uint, RO> &gridTable, TypedBuffer<uint, RO> &zIndex, TypedBuffer<ClSphType, RO> type, TypedBuffer<float, RO> &mass, TypedBuffer<uchar4, RO> &colour, TypedBuffer<float3, RW> &pStar, TypedBuffer<float3, RW> &deltaP, TypedBuffer<float, RW> &lambda, TypedBuffer<uchar4, RW> &diffused, TypedBuffer<float3, RW> &position, TypedBuffer<float3, RW> &velocity, std::vector<ClSphTraiangle> &hostColliderMesh ) { auto kernel_copy = watch.start("\t[GPU] kernel_copy"); const uint colliderMeshN = static_cast<uint>(hostColliderMesh.size()); cl::Buffer colliderMesh = colliderMeshN == 0 ? cl::Buffer(ctx, CL_MEM_READ_WRITE, 1) : cl::Buffer(queue, hostColliderMesh.begin(), hostColliderMesh.end(), true); const uint gridTableN = static_cast<uint>(gridTable.length); finishQueue(); kernel_copy(); const auto localRange = cl::NDRange(); const auto globalRange = cl::NDRange(position.length); auto diffuse = watch.start("\t[GPU] sph-diffuse"); sphDiffuseKernel(cl::EnqueueArgs(queue, globalRange, localRange), sphConfig.actual, zIndex.actual, gridTable.actual, gridTableN, type.actual, pStar.actual, colour.actual, diffused.actual ); finishQueue(); diffuse(); auto lambda_delta = watch.start("\t[GPU] sph-lambda/delta*" + std::to_string(iterations)); for (size_t itr = 0; itr < iterations; ++itr) { sphLambdaKernel(cl::EnqueueArgs(queue, globalRange, localRange), sphConfig.actual, zIndex.actual, gridTable.actual, gridTableN, type.actual, pStar.actual, mass.actual, lambda.actual ); sphDeltaKernel(cl::EnqueueArgs(queue, globalRange, localRange), sphConfig.actual, zIndex.actual, gridTable.actual, gridTableN, type.actual, colliderMesh, colliderMeshN, pStar.actual, lambda.actual, position.actual, velocity.actual, deltaP.actual ); } finishQueue(); lambda_delta(); auto finalise = watch.start("\t[GPU] sph-finalise"); sphFinaliseKernel(cl::EnqueueArgs(queue, globalRange, localRange), sphConfig.actual, type.actual, pStar.actual, position.actual, velocity.actual ); finishQueue(); finalise(); } // const std::array<tvec3<float>, 27> NEIGHBOUR_OFFSETS = { // tvec3<float>(-h, -h, -h), tvec3<float>(+0, -h, -h), tvec3<float>(+h, -h, -h), // tvec3<float>(-h, +0, -h), tvec3<float>(+0, +0, -h), tvec3<float>(+h, +0, -h), // tvec3<float>(-h, +h, -h), tvec3<float>(+0, +h, -h), tvec3<float>(+h, +h, -h), // tvec3<float>(-h, -h, +0), tvec3<float>(+0, -h, +0), tvec3<float>(+h, -h, +0), // tvec3<float>(-h, +0, +0), tvec3<float>(+0, +0, +0), tvec3<float>(+h, +0, +0), // tvec3<float>(-h, +h, +0), tvec3<float>(+0, +h, +0), tvec3<float>(+h, +h, +0), // tvec3<float>(-h, -h, +h), tvec3<float>(+0, -h, +h), tvec3<float>(+h, -h, +h), // tvec3<float>(-h, +0, +h), tvec3<float>(+0, +0, +h), tvec3<float>(+h, +0, +h), // tvec3<float>(-h, +h, +h), tvec3<float>(+0, +h, +h), tvec3<float>(+h, +h, +h) // }; const std::array<tvec3<float>, 1> NEIGHBOUR_OFFSETS = { tvec3<float>(0, 0, 0) }; public: fluid::Result<float> advance(const fluid::Config<float> &config, std::vector<fluid::Particle<size_t, float>> &xs, const std::vector<fluid::MeshCollider<float>> &colliders) override { clutil::Stopwatch watch = clutil::Stopwatch("CPU advance"); auto total = watch.start("Advance ===total==="); ClMcConfig mcConfig; mcConfig.isolevel = config.isolevel; mcConfig.sampleResolution = config.resolution; mcConfig.particleSize = 25.f; mcConfig.particleInfluence = 0.5; auto sourceDrain = watch.start("CPU source+drain"); const float spacing = (h * config.scale / 2); for (const fluid::Source<float> &source : config.sources) { const float size = std::sqrt(source.rate); const int width = std::floor(size); const int depth = std::ceil(size); const auto offset = source.centre - (tvec3<float>(width, 0, depth) / 2 * spacing); for (int x = 0; x < width; ++x) { for (int z = 0; z < depth; ++z) { auto pos = offset + tvec3<float>(x, 0, z) * spacing; xs.emplace_back(source.tag, fluid::Type::Fluid, 1, source.colour, pos, source.velocity); } } } xs.erase(std::remove_if(xs.begin(), xs.end(), [&config](const fluid::Particle<size_t, float> &x) { if (x.type == fluid::Type::Obstacle) return false; for (const fluid::Drain<float> &drain: config.drains) { // FIXME needs to actually erase at surface, not shperically if (glm::distance(drain.centre, x.position) < drain.width) { return true; } } return false; }), xs.end()); sourceDrain(); if (xs.empty()) { std::cout << "Particles depleted" << std::endl; std::this_thread::sleep_for(std::chrono::milliseconds(5)); return fluid::Result<float>({}, {}); } auto advect = watch.start("CPU advect+copy"); std::vector<PartiallyAdvected> advected = advectAndCopy(config, xs); const size_t atomsN = advected.size(); advect(); auto bound = watch.start("CPU bound+zindex"); ClSphConfig sphConfig; tvec3<float> minExtent; tvec3<size_t> extent; std::tie(sphConfig, minExtent, extent) = computeBoundAndZindex(config, advected); bound(); auto sortz = watch.start("CPU sortz"); std::sort(advected.begin(), advected.end(), [](const PartiallyAdvected &l, const PartiallyAdvected &r) { return l.zIndex < r.zIndex; }); // ska_sort(hostAtoms.begin(), hostAtoms.end(), // [](const ClSphAtom &a) { return a.zIndex; }); sortz(); auto gridtable = watch.start("CPU gridtable"); const size_t gridTableN = zCurveGridIndexAtCoord(extent.x, extent.y, extent.z); #ifdef DEBUG std::cout << "Atoms = " << atomsN << " Extent = " << glm::to_string(minExtent) << " -> " << to_string(extent) << " GridTable = " << gridTableN << std::endl; #endif std::vector<uint> hostGridTable(gridTableN); uint gridIndex = 0; for (size_t i = 0; i < gridTableN; ++i) { hostGridTable[i] = gridIndex; while (gridIndex != atomsN && advected[gridIndex].zIndex == i) { gridIndex++; } } gridtable(); auto query = watch.start("CPU query(" + std::to_string(config.queries.size()) + ")"); std::vector<fluid::QueryResult<float>> queries; for (const fluid::Query<float> &q : config.queries) { auto scaled = (q.point / config.scale) - minExtent; int N = 0; auto avg = tvec4<float>(0.f); for (tvec3<float> offset : NEIGHBOUR_OFFSETS) { auto r = offset + scaled; size_t zIdx = zCurveGridIndexAtCoordAt(r.x, r.y, r.z); if (zIdx < gridTableN && zIdx + 1 < gridTableN) { for (size_t a = hostGridTable[zIdx]; a < hostGridTable[zIdx + 1]; a++) { if (advected[a].particle.type != fluid::Fluid) continue; N++; avg += clutil::unpackARGB<float>(advected[a].particle.colour); } } } if (N != 0) queries.emplace_back(q.id, q.point, N, clutil::packARGB(avg / N)); } query(); auto collider_concat = watch.start("CPU collider++"); std::vector<ClSphTraiangle> hostColliderMesh; for (int i = 0; i < static_cast<int>(colliders.size()); ++i) { auto xs = colliders[i].triangles; for (int j = 0; j < static_cast<int>(xs.size()); ++j) { ClSphTraiangle trig; trig.a = clutil::vec3ToCl(xs[j].v0); trig.b = clutil::vec3ToCl(xs[j].v1); trig.c = clutil::vec3ToCl(xs[j].v2); hostColliderMesh.push_back(trig); } } #ifdef DEBUG std::cout << "Collider trig: " << hostColliderMesh.size() << "\n"; #endif collider_concat(); auto kernel_alloc = watch.start("CPU host alloc+copy"); const tvec3<size_t> sampleSize = tvec3<size_t>( glm::floor(tvec3<float>(extent) * mcConfig.sampleResolution)) + tvec3<size_t>(1); ClSphAtoms atoms(advected.size()); #pragma omp parallel for for (int i = 0; i < static_cast<int>(advected.size()); ++i) { atoms.zIndex[i] = advected[i].zIndex; atoms.pStar[i] = advected[i].pStar; atoms.type[i] = resolveType(advected[i].particle.type); atoms.mass[i] = advected[i].particle.mass; atoms.colour[i] = clutil::unpackARGB(advected[i].particle.colour); atoms.position[i] = clutil::vec3ToCl(advected[i].particle.position); atoms.velocity[i] = clutil::vec3ToCl(advected[i].particle.velocity); } std::vector<surface::MeshTriangle<float>> triangles; auto kernel_exec = watch.start("\t[GPU] ===total==="); try { auto sphConfig_ = TypedBuffer<ClSphConfig, RO>::ofStruct(ctx, sphConfig); auto mcConfig_ = TypedBuffer<ClMcConfig, RO>::ofStruct(ctx, mcConfig); TypedBuffer<uint, RO> gridTable(queue, hostGridTable); TypedBuffer<uint, RO> zIndex(queue, atoms.zIndex); TypedBuffer<ClSphType, RO> type(queue, atoms.type); TypedBuffer<float, RO> mass(queue, atoms.mass); TypedBuffer<uchar4, RO> colour(queue, atoms.colour); TypedBuffer<float3, RW> pStar(queue, atoms.pStar); TypedBuffer<float3, RW> deltaP(ctx, atoms.size); TypedBuffer<float, RW> lambda(ctx, atoms.size); TypedBuffer<uchar4, RW> diffused(ctx, atoms.size); TypedBuffer<float3, RW> position(queue, atoms.position); TypedBuffer<float3, RW> velocity(queue, atoms.velocity); kernel_alloc(); runSphKernel(watch, sphConfig.iteration, sphConfig_, gridTable, zIndex, type, mass, colour, pStar, deltaP, lambda, diffused, position, velocity, hostColliderMesh); triangles = runMcKernels(watch, sampleSize, sphConfig_, mcConfig_, gridTable, type, position, diffused, minExtent, extent); std::vector<float3> hostPosition(advected.size()); std::vector<float3> hostVelocity(advected.size()); std::vector<uchar4> hostDiffused(advected.size()); position.drainTo(queue, hostPosition); velocity.drainTo(queue, hostVelocity); diffused.drainTo(queue, hostDiffused); auto write_back = watch.start("write_back"); #pragma omp parallel for for (int i = 0; i < static_cast<int>(xs.size()); ++i) { xs[i].id = advected[i].particle.id; xs[i].type = advected[i].particle.type; xs[i].mass = advected[i].particle.mass; if (advected[i].particle.type == fluid::Fluid) { xs[i].colour = clutil::packARGB(hostDiffused[i]); xs[i].position = clutil::clToVec3<float>(hostPosition[i]); xs[i].velocity = clutil::clToVec3<float>(hostVelocity[i]); } else { xs[i].colour = advected[i].particle.colour; xs[i].position = advected[i].particle.position; xs[i].velocity = advected[i].particle.velocity; } } write_back(); } catch (const cl::Error &exc) { std::cerr << "Kernel failed to execute: " << exc.what() << " -> " << clResolveError(exc.err()) << "(" << exc.err() << ")" << std::endl; throw exc; } kernel_exec(); // // auto march = watch.start("CPU mc"); // // std::vector<surface::MeshTriangle<float>> triangles = // sampleLattice(100, config.scale, // minExtent, h / mcConfig.sampleResolution, hostLattice); // // march(); total(); // std::vector<unsigned short> outIdx; // std::vector<tvec3<float>> outVert; // hrc::time_point vbiStart = hrc::now(); // surface::indexVBO2<float>(triangles, outIdx, outVert); // hrc::time_point vbiEnd = hrc::now(); // auto vbi = duration_cast<nanoseconds>(vbiEnd - vbiStart).count(); // // std::cout // << "\n\tTrigs = " << triangles.size() // << "\n\tIdx = " << outIdx.size() // << "\n\tVert = " << outVert.size() // << "\n\tVBI = " << (vbi / 1000000.0) << "ms\n" // << std::endl; total(); #ifdef DEBUG std::cout << watch << std::endl; #endif return fluid::Result<float>(triangles, queries); } }; } #endif //LIBFLUID_CLSPH_HPP
31.751059
144
0.618924
[ "mesh", "geometry", "vector" ]
3659a371d2e8fe5b5144f4b6ecec02a21f79baf2
5,435
cpp
C++
fundamentals/operator-overload/member.cpp
kaanguney/c_plus_plus
cc7c4d26184ea9dd86aec588aa8a07dbcd65b33a
[ "MIT" ]
null
null
null
fundamentals/operator-overload/member.cpp
kaanguney/c_plus_plus
cc7c4d26184ea9dd86aec588aa8a07dbcd65b33a
[ "MIT" ]
null
null
null
fundamentals/operator-overload/member.cpp
kaanguney/c_plus_plus
cc7c4d26184ea9dd86aec588aa8a07dbcd65b33a
[ "MIT" ]
null
null
null
#include <iostream> #include "matrix.h" using namespace std; Matrix::Matrix() { // default constructor rowNumber = 0; columnNumber = 0; elements = NULL; } int Matrix::getRowNumber() const { return rowNumber; } int Matrix::getColumnNumber() const { return columnNumber; } Matrix::~Matrix() { if(elements != NULL) { // destruct in that case... for(int i=0; i<rowNumber; i++) { delete [] elements[i]; } delete [] elements; } } Matrix::Matrix(int Rownum, int ColumnNum, int init) { // user-defined constructor, for deep-copy... if(Rownum <= 0 || ColumnNum <= 0) { // then, use default constructor... rowNumber = 0; columnNumber = 0; elements = NULL; } else { rowNumber = Rownum; columnNumber = ColumnNum; elements = new int*[rowNumber]; for(int i=0; i<rowNumber; i++) { elements[i] = new int[columnNumber]; } for(int i=0; i<rowNumber; i++) { for(int j=0; j<columnNumber; j++) { elements[i][j] = init; } } } } int Matrix::getElementAt(int row, int column) const { int dummy = 0; // to prevent compiler errors... for(int k=0; k<rowNumber; k++) { for(int j=0; j<columnNumber; j++) { if(k == row && j == column) { return elements[k][j]; } } } return dummy; } void Matrix::setElementAt(int row, int column, int elt) const { for(int k=0; k<rowNumber; k++) { for(int j=0; j<columnNumber; j++) { if(k == row && j == column) { this->elements[k][j] = elt; } } } } int ** Matrix::mat_create() const { // get the clone, use for deep-copy... int ** data = NULL; if(elements == NULL) { return data; } else { data = new int*[rowNumber]; for(int i=0; i<rowNumber; i++) { data[i] = new int[columnNumber]; } for(int i=0; i<rowNumber; i++) { for(int j=0; j<columnNumber; j++) { data[i][j] = elements[i][j]; } } } return data; } Matrix::Matrix(const Matrix & matrix) { // deep-copy for matrix... elements = matrix.mat_create(); // returns pointer to pointer rowNumber = matrix.getRowNumber(); columnNumber = matrix.getColumnNumber(); } void Matrix::print() { // display the matrix for(int i=0; i<rowNumber; i++) { for(int j=0; j<columnNumber; j++) { cout << elements[i][j] << " "; } cout << "\n"; } } void Matrix::del_matrix() { // useful during assignments... for(int i=0; i<rowNumber; i++) { delete [] elements[i]; } delete [] elements; } const Matrix & Matrix::operator= (const Matrix & matrix) { // assignment... if(this != &matrix) { // if not already equal... del_matrix(); // delete previous data... rowNumber = matrix.getRowNumber(); // deal with the privates... columnNumber = matrix.getColumnNumber(); elements = matrix.mat_create(); } return *this; } Matrix Matrix::operator+ (const Matrix & matrix) const { Matrix res(*this); // this keyword is used to work specifically on that object... for(int i=0; i<rowNumber; i++) { for(int j=0; j<columnNumber; j++) { res.setElementAt(i, j, (matrix.getElementAt(i, j) + this->getElementAt(i, j))); } } return res; } Matrix Matrix::operator- (const Matrix & matrix) const { Matrix res(*this); for(int i=0; i<rowNumber; i++) { for(int j=0; j<columnNumber; j++) { res.setElementAt(i, j, (this->getElementAt(i, j) - matrix.getElementAt(i, j))); } } return res; } bool Matrix::operator== (const Matrix &matrix) const { if(!(this->columnNumber == matrix.columnNumber && this->rowNumber == matrix.rowNumber)) { return false; } // if dimensions not same... else { // dimensions same, now check if every elements is same... for(int i=0; i<rowNumber; i++) { for(int j=0; j<columnNumber; j++) { if(this->elements[i][j] != matrix.elements[i][j]) { // not all elements are the same in this case... return false; } } } return true; } } Matrix Matrix::operator!() const { Matrix res(columnNumber, rowNumber, 1); // initial value is 1, inverse of the matrix... // now, fill it in... for(int i=0; i<this->getRowNumber(); i++) { for(int j=0; j<this->getColumnNumber(); j++) { res.elements[j][i] = this->elements[i][j]; } } return res; }
20.984556
116
0.463661
[ "object" ]
3664749bac80bf6a4102c0b44e2a9c25e0311d9e
1,596
cc
C++
test/geometry_test.cc
RuiwenTang/Skity
2f98d8bda9946a9055d955fae878fef43c4eee57
[ "MIT" ]
65
2021-08-05T09:52:49.000Z
2022-03-29T14:45:20.000Z
test/geometry_test.cc
RuiwenTang/Skity
2f98d8bda9946a9055d955fae878fef43c4eee57
[ "MIT" ]
1
2022-03-24T09:35:06.000Z
2022-03-25T06:38:20.000Z
test/geometry_test.cc
RuiwenTang/Skity
2f98d8bda9946a9055d955fae878fef43c4eee57
[ "MIT" ]
9
2021-08-08T07:30:13.000Z
2022-03-29T14:45:25.000Z
#include "src/geometry/geometry.hpp" #include <gtest/gtest.h> #include <iostream> #include <vector> #include "src/geometry/math.hpp" TEST(QUAD, tangents) { std::vector<std::array<skity::Point, 3>> pts = { {skity::Point{10, 20, 0, 1}, skity::Point{10, 20, 0, 1}, skity::Point{20, 30, 0, 1}}, {skity::Point{10, 20, 0, 1}, skity::Point{15, 25, 0, 1}, skity::Point{20, 30, 0, 1}}, {skity::Point{10, 20, 0, 1}, skity::Point{20, 30, 0, 1}, skity::Point{20, 30, 0, 1}}, }; size_t count = pts.size(); for (size_t i = 0; i < count; i++) { skity::Vector start = skity::QuadCoeff::EvalQuadTangentAt(pts[i], 0); skity::Vector mid = skity::QuadCoeff::EvalQuadTangentAt(pts[i], .5f); skity::Vector end = skity::QuadCoeff::EvalQuadTangentAt(pts[i], 1.f); EXPECT_TRUE(start.x && start.y); EXPECT_TRUE(mid.x && mid.y); EXPECT_TRUE(end.x && end.y); EXPECT_TRUE(skity::FloatNearlyZero(skity::CrossProduct(start, mid))); EXPECT_TRUE(skity::FloatNearlyZero(skity::CrossProduct(mid, end))); } } TEST(Geometry, line_intersect) { skity::Point p1 = skity::Point(0, 1, 0, 0); skity::Point p2 = skity::Point(1, 1.9, 0, 0); skity::Point p3 = skity::Point(0, 0, 0, 0); skity::Point p4 = skity::Point(1, 1, 0, 0); skity::Point result; int32_t ret = skity::IntersectLineLine(p1, p2, p3, p4, result); std::cout << "ret = " << ret << std::endl; std::cout << "result = {" << result.x << ", " << result.y << "}" << std::endl; } int main(int argc, const char **argv) { testing::InitGoogleTest(); return RUN_ALL_TESTS(); }
31.92
80
0.605263
[ "geometry", "vector" ]
366b4424e4eec1855c559e6e93edc6146a3a177a
13,718
cpp
C++
cpp/CF++/source/CFPP-String.cpp
vzaccaria/teasy-2.0
a0ec0e020fb0b0517e4a250e2c3cae4494cef40a
[ "MIT" ]
24
2016-04-13T10:40:16.000Z
2016-12-20T04:19:10.000Z
cpp/CF++/source/CFPP-String.cpp
vzaccaria/teasy-2.0
a0ec0e020fb0b0517e4a250e2c3cae4494cef40a
[ "MIT" ]
null
null
null
cpp/CF++/source/CFPP-String.cpp
vzaccaria/teasy-2.0
a0ec0e020fb0b0517e4a250e2c3cae4494cef40a
[ "MIT" ]
null
null
null
/******************************************************************************* * Copyright (c) 2014, Jean-David Gadina - www.xs-labs.com / www.digidna.net * Distributed under the Boost Software License, Version 1.0. * * Boost Software License - Version 1.0 - August 17th, 2003 * * Permission is hereby granted, free of charge, to any person or organization * obtaining a copy of the software and accompanying documentation covered by * this license (the "Software") to use, reproduce, display, distribute, * execute, and transmit the Software, and to prepare derivative works of the * Software, and to permit third-parties to whom the Software is furnished to * do so, all subject to the following: * * The copyright notices in the Software and this entire statement, including * the above license grant, this restriction and the following disclaimer, * must be included in all copies of the Software, in whole or in part, and * all derivative works of the Software, unless such copies or derivative * works are solely in the form of machine-executable object code generated by * a source language processor. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ******************************************************************************/ /*! * @file CFPP-String.cpp * @copyright (c) 2014 - Jean-David Gadina - www.xs-labs.com / www.digidna.net * @abstract CoreFoundation++ CFStringRef wrapper */ #include <CF++.h> namespace CF { String::String( void ) { this->_cfObject = NULL; this->SetValue( "" ); } String::String( CFTypeRef cfObject ) { if( cfObject != NULL && CFGetTypeID( cfObject ) == this->GetTypeID() ) { this->_cfObject = static_cast< CFStringRef >( CFRetain( cfObject ) ); } else { this->_cfObject = NULL; } } String::String( CFStringRef cfObject ) { if( cfObject != NULL && CFGetTypeID( cfObject ) == this->GetTypeID() ) { this->_cfObject = static_cast< CFStringRef >( CFRetain( cfObject ) ); } else { this->_cfObject = NULL; } } String::String( CFTypeRef cfObject, std::string defaultValueIfNULL, CFStringEncoding encoding ) { if( cfObject != NULL && CFGetTypeID( cfObject ) == this->GetTypeID() ) { this->_cfObject = static_cast< CFStringRef >( CFRetain( cfObject ) ); } else { this->_cfObject = NULL; this->SetValue( defaultValueIfNULL, encoding ); } } String::String( CFStringRef cfObject, std::string defaultValueIfNULL, CFStringEncoding encoding ) { if( cfObject != NULL && CFGetTypeID( cfObject ) == this->GetTypeID() ) { this->_cfObject = static_cast< CFStringRef >( CFRetain( cfObject ) ); } else { this->_cfObject = NULL; this->SetValue( defaultValueIfNULL, encoding ); } } String::String( std::string value, CFStringEncoding encoding ) { this->_cfObject = NULL; this->SetValue( value, encoding ); } String::String( char * value, CFStringEncoding encoding ) { this->_cfObject = NULL; if( value == NULL ) { value = const_cast< char * >( "" ); } this->SetValue( value, encoding ); } String::String( const char * value, CFStringEncoding encoding ) { this->_cfObject = NULL; this->SetValue( value, encoding ); } String::String( const String & value ) { if( value._cfObject != NULL ) { this->_cfObject = static_cast< CFStringRef >( CFRetain( ( value._cfObject ) ) ); } else { this->_cfObject = NULL; } } #ifdef CFPP_HAS_CPP11 String::String( String && value ) { this->_cfObject = value._cfObject; value._cfObject = NULL; } #endif String::~String( void ) { if( this->_cfObject != NULL ) { CFRelease( this->_cfObject ); this->_cfObject = NULL; } } String & String::operator = ( String value ) { swap( *( this ), value ); return *( this ); } String & String::operator = ( CFTypeRef value ) { if( this->_cfObject != NULL ) { CFRelease( this->_cfObject ); } if( value != NULL && CFGetTypeID( value ) == this->GetTypeID() ) { this->_cfObject = static_cast< CFStringRef >( CFRetain( value ) ); } else { this->_cfObject = NULL; } return *( this ); } String & String::operator = ( CFStringRef value ) { if( this->_cfObject != NULL ) { CFRelease( this->_cfObject ); } if( value != NULL && CFGetTypeID( value ) == this->GetTypeID() ) { this->_cfObject = static_cast< CFStringRef >( CFRetain( value ) ); } else { this->_cfObject = NULL; } return *( this ); } String & String::operator = ( std::string value ) { this->SetValue( value ); return *( this ); } String & String::operator = ( char * value ) { this->SetValue( value ); return *( this ); } String & String::operator = ( const char * value ) { this->SetValue( value ); return *( this ); } bool String::operator == ( const String & value ) const { if( this->_cfObject == NULL || value._cfObject == NULL ) { return false; } return ( CFStringCompare( this->_cfObject, value._cfObject, 0 ) == kCFCompareEqualTo ) ? true : false; } bool String::operator == ( CFTypeRef value ) const { String s; s = value; return *( this ) == s; } bool String::operator == ( CFStringRef value ) const { String s; s = value; return *( this ) == s; } bool String::operator == ( std::string value ) const { String s; s = value; return *( this ) == s; } bool String::operator == ( char * value ) const { String s; s = value; return *( this ) == s; } bool String::operator == ( const char * value ) const { String s; s = value; return *( this ) == s; } bool String::operator != ( const String & value ) const { return !( *( this ) == value ); } bool String::operator != ( CFTypeRef value ) const { return !( *( this ) == value ); } bool String::operator != ( CFStringRef value ) const { return !( *( this ) == value ); } bool String::operator != ( std::string value ) const { return !( *( this ) == value ); } bool String::operator != ( char * value ) const { return !( *( this ) == value ); } bool String::operator != ( const char * value ) const { return !( *( this ) == value ); } String & String::operator += ( const String & value ) { AutoPointer array; CFStringRef newString; CFStringRef strings[ 2 ]; if( value._cfObject == NULL ) { return *( this ); } if( this->_cfObject == NULL ) { return const_cast< String & >( value ); } strings[ 0 ] = this->_cfObject; strings[ 1 ] = value._cfObject; array = CFArrayCreate( static_cast< CFAllocatorRef >( NULL ), reinterpret_cast< const void ** >( strings ), 2, NULL ); newString = CFStringCreateByCombiningStrings( static_cast< CFAllocatorRef >( NULL ), array.As< CFArrayRef >(), CFSTR( "" ) ); CFRelease( this->_cfObject ); this->_cfObject = newString; return *( this ); } String & String::operator += ( CFStringRef value ) { String s; s = value; *( this ) += s; return *( this ); } String & String::operator += ( std::string value ) { String s; s = value; *( this ) += s; return *( this ); } String & String::operator += ( char * value ) { String s; s = value; *( this ) += s; return *( this ); } String & String::operator += ( const char * value ) { String s; s = value; *( this ) += s; return *( this ); } char String::operator [] ( int index ) const { const char * s; CFIndex cfIndex; cfIndex = static_cast< CFIndex >( index ); if( this->_cfObject == NULL ) { return 0; } if( cfIndex >= 0 ) { if( cfIndex >= this->GetLength() ) { return 0; } } else { cfIndex = this->GetLength() + cfIndex; if( cfIndex < 0 || cfIndex >= this->GetLength() ) { return 0; } } s = CFStringGetCStringPtr( this->_cfObject, kCFStringEncodingUTF8 ); return s[ static_cast< unsigned >( cfIndex ) ]; } String::operator std::string () const { return this->GetValue(); } CFTypeID String::GetTypeID( void ) const { return CFStringGetTypeID(); } CFTypeRef String::GetCFObject( void ) const { return static_cast< CFTypeRef >( this->_cfObject ); } bool String::HasPrefix( String value ) const { if( this->_cfObject == NULL || value._cfObject == NULL ) { return false; } return ( CFStringHasPrefix( this->_cfObject, value._cfObject ) ) ? true : false; } bool String::HasPrefix( CFStringRef value ) const { String s; s = value; return this->HasPrefix( s ); } bool String::HasPrefix( std::string value ) const { String s; s = value; return this->HasPrefix( s ); } bool String::HasSuffix( String value ) const { if( this->_cfObject == NULL || value._cfObject == NULL ) { return false; } return ( CFStringHasSuffix( this->_cfObject, value._cfObject ) ) ? true : false; } bool String::HasSuffix( CFStringRef value ) const { String s; s = value; return this->HasSuffix( s ); } bool String::HasSuffix( std::string value ) const { String s; s = value; return this->HasSuffix( s ); } CFIndex String::GetLength( void ) const { if( this->_cfObject == NULL ) { return 0; } return CFStringGetLength( this->_cfObject ); } std::string String::GetValue( CFStringEncoding encoding ) const { const char * s; char * buf; size_t length; std::string str; if( this->_cfObject == NULL ) { return ""; } s = this->GetCStringValue( encoding ); if( s == NULL ) { length = static_cast< size_t >( CFStringGetMaximumSizeForEncoding( CFStringGetLength( this->_cfObject ), encoding ) ); buf = static_cast< char * >( calloc( length + 1, 1 ) ); CFStringGetCString( this->_cfObject, buf, static_cast< CFIndex >( length + 1 ), encoding ); str = ( buf == NULL ) ? "" : buf; free( buf ); } else { str = s; } return str; } const char * String::GetCStringValue( CFStringEncoding encoding ) const { if( this->_cfObject != NULL ) { return CFStringGetCStringPtr( this->_cfObject, encoding ); } return NULL; } void String::SetValue( std::string value, CFStringEncoding encoding ) { if( this->_cfObject != NULL ) { CFRelease( this->_cfObject ); } this->_cfObject = CFStringCreateWithCString( static_cast< CFAllocatorRef >( NULL ), value.c_str(), encoding ); } void swap( String & v1, String & v2 ) { using std::swap; swap( v1._cfObject, v2._cfObject ); } }
24.98725
136
0.489503
[ "object" ]
366fc2668c6e8d4dae6a8d2df2cc1f9175f13933
3,837
hpp
C++
include/Serialization/ISerializedObject.hpp
rhymu8354/Serialization
42b8bc5cde56225dea0a6a28d8fd80f401999a2a
[ "MIT" ]
null
null
null
include/Serialization/ISerializedObject.hpp
rhymu8354/Serialization
42b8bc5cde56225dea0a6a28d8fd80f401999a2a
[ "MIT" ]
null
null
null
include/Serialization/ISerializedObject.hpp
rhymu8354/Serialization
42b8bc5cde56225dea0a6a28d8fd80f401999a2a
[ "MIT" ]
1
2021-06-27T19:22:20.000Z
2021-06-27T19:22:20.000Z
#ifndef SERIALIZATION_I_SERIALIZED_OBJECT_HPP #define SERIALIZATION_I_SERIALIZED_OBJECT_HPP /** * @file ISerializedObject.hpp * * This module declares the Serialization::ISerializedObject * interface. * * Copyright (c) 2013-2018 by Richard Walters */ #include <string> #include <SystemAbstractions/IFile.hpp> namespace Serialization { /** * This is the interface to something which is going to be serialized * into a string of bytes, or has been deserialized from a * string of bytes. */ class ISerializedObject { // Lifecycle Management public: virtual ~ISerializedObject() = default; ISerializedObject(const ISerializedObject& other) = default; ISerializedObject(ISerializedObject&& other) = default; ISerializedObject& operator=(const ISerializedObject& other) = default; ISerializedObject& operator=(ISerializedObject&& other) = default; // Methods public: /** * This is the default constructor. */ ISerializedObject() = default; /** * This method serializes the object into a string of bytes, * which are written to the given file. * * @param[in] file * This is the file to which, starting at the current * position in the file, the serialized representation of the * state of the object will be written. * * @param[in] serializationVersion * This is the version of the serialization in which to * encode the object. If zero (the default), the newest * version is used. * * @return * An indicator of whether or not the method was * successful is returned. */ virtual bool Serialize( SystemAbstractions::IFile* file, unsigned int serializationVersion = 0 ) const = 0; /** * This method deserializes the object from a string of bytes, * which are read from the given file. * * @param[in] file * This is the file containing, starting at the current * position in the file, the serialized representation of the * state to assign to the object. * * @return * An indicator of whether or not the method was * successful is returned. */ virtual bool Deserialize(SystemAbstractions::IFile* file) = 0; /** * This method renders the object into a human-readable * string that makes the type and value evident. * * @return * A human-readable string revealing the type and * value of the object is returned. */ virtual std::string Render() const = 0; /** * This method parses the given human-readable string to * obtain the object's value. * * @param[in] rendering * This is the string from which to parse the object. * * @return * An indicator of whether or not the method was * successful is returned. */ virtual bool Parse(std::string rendering) = 0; /** * This method compares the object to another object provided * by base interface to determine whether or not they have * equivalent states. * * @param[in] other * This is the other object with which to compare. * * @return * An indication of whether or not the two objects are * equivalent is returned. */ virtual bool IsEqualTo(const ISerializedObject* other) const = 0; }; } #endif /* SERIALIZATION_I_SERIALIZED_OBJECT_HPP */
32.516949
79
0.587438
[ "render", "object" ]
3674759bc46bd3140f4a541e239f1b4620830993
1,942
cpp
C++
docs/snippets/gpu/preprocessing.cpp
ryanloney/openvino-1
4e0a740eb3ee31062ba0df88fcf438564f67edb7
[ "Apache-2.0" ]
1,127
2018-10-15T14:36:58.000Z
2020-04-20T09:29:44.000Z
docs/snippets/gpu/preprocessing.cpp
ryanloney/openvino-1
4e0a740eb3ee31062ba0df88fcf438564f67edb7
[ "Apache-2.0" ]
439
2018-10-20T04:40:35.000Z
2020-04-19T05:56:25.000Z
docs/snippets/gpu/preprocessing.cpp
ryanloney/openvino-1
4e0a740eb3ee31062ba0df88fcf438564f67edb7
[ "Apache-2.0" ]
414
2018-10-17T05:53:46.000Z
2020-04-16T17:29:53.000Z
#include <openvino/runtime/core.hpp> #include <openvino/runtime/intel_gpu/ocl/ocl.hpp> #include <openvino/runtime/intel_gpu/properties.hpp> #include <openvino/core/preprocess/pre_post_process.hpp> ov::intel_gpu::ocl::ClImage2DTensor get_y_tensor(); ov::intel_gpu::ocl::ClImage2DTensor get_uv_tensor(); int main() { ov::Core core; auto model = core.read_model("model.xml"); //! [init_preproc] using namespace ov::preprocess; auto p = PrePostProcessor(model); p.input().tensor().set_element_type(ov::element::u8) .set_color_format(ov::preprocess::ColorFormat::NV12_TWO_PLANES, {"y", "uv"}) .set_memory_type(ov::intel_gpu::memory_type::surface); p.input().preprocess().convert_color(ov::preprocess::ColorFormat::BGR); p.input().model().set_layout("NCHW"); auto model_with_preproc = p.build(); //! [init_preproc] auto compiled_model = core.compile_model(model, "GPU"); auto context = compiled_model.get_context().as<ov::intel_gpu::ocl::ClContext>(); auto input = model->get_parameters().at(0); auto infer_request = compiled_model.create_infer_request(); { //! [single_batch] ov::intel_gpu::ocl::ClImage2DTensor y_tensor = get_y_tensor(); ov::intel_gpu::ocl::ClImage2DTensor uv_tensor = get_uv_tensor(); infer_request.set_tensor("y", y_tensor); infer_request.set_tensor("uv", uv_tensor); infer_request.infer(); //! [single_batch] } { auto y_tensor_0 = get_y_tensor(); auto y_tensor_1 = get_y_tensor(); auto uv_tensor_0 = get_uv_tensor(); auto uv_tensor_1 = get_uv_tensor(); //! [batched_case] std::vector<ov::Tensor> y_tensors = {y_tensor_0, y_tensor_1}; std::vector<ov::Tensor> uv_tensors = {uv_tensor_0, uv_tensor_1}; infer_request.set_tensors("y", y_tensors); infer_request.set_tensors("uv", uv_tensors); infer_request.infer(); //! [batched_case] } return 0; }
35.309091
98
0.685891
[ "vector", "model" ]
367478d9760c2acccbfc50795f8869b2f9e17b6b
31,812
cpp
C++
testing_source_hdf5/testing_harness_write_hdf5.cpp
mlawsonca/empress
aa3eb8544f2e01fcbd77749f7dce1b95fbfa11e9
[ "MIT" ]
5
2018-11-28T19:38:23.000Z
2021-03-15T20:44:07.000Z
testing_source_hdf5/testing_harness_write_hdf5.cpp
mlawsonca/empress
aa3eb8544f2e01fcbd77749f7dce1b95fbfa11e9
[ "MIT" ]
null
null
null
testing_source_hdf5/testing_harness_write_hdf5.cpp
mlawsonca/empress
aa3eb8544f2e01fcbd77749f7dce1b95fbfa11e9
[ "MIT" ]
1
2018-07-18T15:22:36.000Z
2018-07-18T15:22:36.000Z
/* * Copyright 2018 National Technology & Engineering Solutions of * Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, * the U.S. Government retains certain rights in this software. * * The MIT License (MIT) * * Copyright (c) 2018 Sandia Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <stdlib.h> //needed for atoi/atol/malloc/free/rand #include <stdint.h> //needed for uint #include <vector> #include <stdio.h> //needed for printf #include <assert.h> //needed for assert #include <string.h> //needed for strcmp // #include <chrono> //needed for high_resolution_clock #include <math.h> //needed for pow() #include <sys/time.h> //needed for timeval #include <float.h> //needed for DBL_MAX #include <numeric> //needed for accumulate #include <mpi.h> #include <hdf5_hl.h> #include <hdf5.h> // #include <testing_harness_debug_helper_functions.hh> #include <my_metadata_client_hdf5.hh> #include <client_timing_constants_write_hdf5.hh> #include <testing_harness_helper_functions_hdf5.hh> // #include <testing_harness_hdf5.hh> using namespace std; bool extreme_debug_logging = false; bool debug_logging = false; bool error_logging = true; bool testing_logging = false; bool zero_rank_logging = false; // static debugLog error_log = debugLog(error_logging, zero_rank_logging); // static debugLog debug_log = debugLog(debug_logging, zero_rank_logging); // static debugLog extreme_debug_log = debugLog(extreme_debug_logging, false); // static debugLog testing_log = debugLog(testing_logging, zero_rank_logging); debugLog error_log = debugLog(error_logging, zero_rank_logging); debugLog debug_log = debugLog(debug_logging, zero_rank_logging); debugLog extreme_debug_log = debugLog(extreme_debug_logging, false); debugLog testing_log = debugLog(testing_logging, zero_rank_logging); static bool output_timing = true; bool do_debug_testing = false; static bool write_data = true; bool read_data = false; //ignore, just since using one helper function file for both reading and writing std::vector<long double> time_pts; std::vector<int> catg_of_time_pts; int zero_time_sec; void add_timing_point(int catg) { if (output_timing) { struct timeval now; gettimeofday(&now, NULL); // cout << "time_pts.push_back: " << ((now.tv_sec - zero_time_sec) + now.tv_usec / 1000000.0) << endl; time_pts.push_back( (now.tv_sec - zero_time_sec) + now.tv_usec / 1000000.0); catg_of_time_pts.push_back(catg); } } // static void create_file(const string &run_name, string job_id, uint64_t timestep_id, hid_t &file_id); // static void open_file_indv(const string &run_name, string job_id, uint64_t timestep_id, hid_t &file_id); static void write_chunk_data(hid_t var_id, uint32_t num_dims, hsize_t *offset, hsize_t *chunk_dims, uint32_t total_y_length, uint32_t total_z_length, int rank, vector<double> &data_vct ); void create_var_attrs(int rank, md_dim_bounds proc_dims, int timestep_num, int var_indx, string VARNAME, uint32_t num_types, bool write_data, vector<var_attribute_str> &attrs, double &timestep_temp_max, double &timestep_temp_min); void create_timestep_attrs(hid_t timestep_file_id, int rank, int timestep_num, uint32_t num_client_procs, double timestep_temp_max, double timestep_temp_min, char *max_type_name, char *min_type_name, double *all_timestep_temp_maxes_for_all_procs, double *all_timestep_temp_mins_for_all_procs); void create_run_attrs(string run_name, string job_id, uint32_t num_timesteps, double *all_timestep_temp_maxes_for_all_procs, double *all_timestep_temp_mins_for_all_procs, char *max_type_name, char *min_type_name); void do_cleanup(int rank, uint32_t num_client_procs); // static void create_attr_text(int rank, hid_t var_id, const string &attr_data); // static herr_t attr_info(hid_t var_id, const char *name, const H5A_info_t *ainfo, void *opdata); /* argv[1] = dirman hexid argv[2] = number of subdivision of the x dimension (number of processes) argv[3] = number of subdivisions of the y dimension (number of processes) argv[4] = number of subdivisions of the z dimension (number of processes) argv[5] = total length in the x dimension argv[6] = total length in the y dimension argv[7] = total length in the z dimension argv[8] = number of datasets to be stored in the database argv[9] = number of types stored in each dataset argv[10] = estimate of the number of testing time points we will have */ int main(int argc, char **argv) { int rc; // char name[100]; // gethostname(name, sizeof(name)); // extreme_debug_log << name << endl; if (argc != 10) { error_log << "Error. Program should be given 9 arguments. npx, npy, npz, nx, ny, nz, number of timesteps, estm num time_pts, job_id" << endl; cout << (int)ERR_ARGC << " " << 0 << endl; return RC_ERR; } debug_log << "starting" << endl; uint32_t num_x_procs = stoul(argv[1],nullptr,0); uint32_t num_y_procs = stoul(argv[2],nullptr,0); uint32_t num_z_procs = stoul(argv[3],nullptr,0); uint64_t total_x_length = stoull(argv[4],nullptr,0); uint64_t total_y_length = stoull(argv[5],nullptr,0); uint64_t total_z_length = stoull(argv[6],nullptr,0); uint32_t num_timesteps = stoul(argv[7],nullptr,0); uint32_t estm_num_time_pts = stoul(argv[8],nullptr,0); string job_id = argv[9]; // uint64_t job_id = stoull(argv[11],nullptr,0); //all 10 char plus null character uint32_t num_vars = 10; uint32_t num_types = 10; // char var_names[10][11] = {"temperat_1", "temperat_2", "pressure_1", "pressure_2", "velocity_1", "location_1", "magn_field", "energy_var", "density_vr", "conductivi"}; // char var_names[10][11] = {"temperat", "temperat", "pressure", "pressure", "velocity_x", "velocity_y", "velocity_z", "magn_field", "energy_var", "density_vr"}; vector<string> var_names = {"temperat", "temperat", "pressure", "pressure", "velocity_x", "velocity_y", "velocity_z", "magn_field", "energy_var", "density_vr"}; catg_of_time_pts.reserve(estm_num_time_pts); time_pts.reserve(estm_num_time_pts); struct timeval now; gettimeofday(&now, NULL); zero_time_sec = 86400 * (now.tv_sec / 86400); add_timing_point(PROGRAM_START); MPI_Init(&argc, &argv); int rank; int num_client_procs; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size( MPI_COMM_WORLD, &num_client_procs); add_timing_point(MPI_INIT_DONE); extreme_debug_log.set_rank(rank); debug_log.set_rank(rank); error_log.set_rank(rank); testing_log.set_rank(rank); if(rank == 0) { extreme_debug_log << "starting" << endl; } uint32_t version1 = 1; uint32_t version2 = 2; //add the '0' for the type version char run_timestep_type_names[2][10] = {"max_temp0", "min_temp0"}; int num_run_timestep_types = 2; uint32_t x_length_per_proc = total_x_length / num_x_procs; //todo - deal with edge case? uint32_t y_length_per_proc = total_y_length / num_y_procs; uint32_t z_length_per_proc = total_z_length / num_z_procs; uint64_t my_var_id; uint32_t num_dims; uint32_t var_num; uint32_t var_version; uint32_t x_pos; uint32_t y_pos; uint32_t z_pos; uint32_t x_offset; uint32_t y_offset; uint32_t z_offset; double all_timestep_temp_maxes_for_all_procs[num_timesteps]; double all_timestep_temp_mins_for_all_procs[num_timesteps]; //reminder - if you don't do this, rank 0 and 1 have the same outputs srand(rank+1); extreme_debug_log << "rank: " << rank << " first rgn: " << rand() << endl; //-------------------------------------------------------------- x_pos = rank % num_x_procs; y_pos = (rank / num_x_procs) % num_y_procs; z_pos = ((rank / (num_x_procs * num_y_procs)) % num_z_procs); x_offset = x_pos * x_length_per_proc; y_offset = y_pos * y_length_per_proc; z_offset = z_pos * z_length_per_proc; extreme_debug_log << "zoffset: " << to_string(z_offset) << endl; extreme_debug_log << "x pos is " << to_string(x_pos) << " and x_offset is " << to_string(x_offset) << endl; extreme_debug_log << "y pos is " << to_string(y_pos) << " and y_offset is " << to_string(y_offset) << endl; extreme_debug_log << "z pos is " << to_string(z_pos) << " and z_offset is " << to_string(z_offset) << endl; extreme_debug_log << "num x procs " << to_string(num_x_procs) << " num y procs " << to_string(num_y_procs) << " num z procs " << to_string(num_z_procs) << endl; num_dims = 3; /* * HDF5 APIs definitions */ hid_t run_attr_table_id; hid_t run_file_id, var_id; hid_t var_data_space, chunk_data_space; herr_t status; // hsize_t var_dims[num_dims]; /* dataset dimensions */ hsize_t chunk_dims[num_dims] = {x_length_per_proc, y_length_per_proc, z_length_per_proc}; /* chunk selection parameters */ hsize_t offset[num_dims] = {x_offset, y_offset, z_offset}; md_dim_bounds proc_dims; proc_dims.num_dims = num_dims; proc_dims.d0_min = x_offset; proc_dims.d0_max = x_offset + x_length_per_proc - 1; proc_dims.d1_min = y_offset; proc_dims.d1_max = y_offset + y_length_per_proc - 1; proc_dims.d2_min = z_offset; proc_dims.d2_max = z_offset + z_length_per_proc - 1; // add_timing_point(DIMS_INIT_DONE); add_timing_point(INIT_VARS_DONE); MPI_Barrier(MPI_COMM_WORLD); add_timing_point(WRITING_START); string run_name = "XGC"; if (rank == 0) { add_timing_point(CREATE_NEW_RUN_START); metadata_create_run (run_name, job_id, run_file_id, run_attr_table_id); //can't close the file since each new timestep needs to link to the run attr table // //close so as to prevent memory leaks since we wont be adding run attributes until later status = H5Fclose(run_file_id); assert(status >= 0); status = H5PTclose(run_attr_table_id); assert(status >= 0); add_timing_point(CREATE_NEW_RUN_DONE); } add_timing_point(CREATE_TIMESTEPS_START); for(int timestep_id = 0; timestep_id < num_timesteps; timestep_id++) { MPI_Barrier(MPI_COMM_WORLD); //want to measure last-first for writing each timestep_id add_timing_point(CREATE_NEW_TIMESTEP_START); double timestep_temp_max; double timestep_temp_min; md_timestep_entry timestep_entry; vector<var_attribute_str> attrs; //create all of the md/data layout for the file before opening to avoid the collectives if (rank == 0) { //create the file and associated metadata tables individually add_timing_point(CREATE_TIMESTEP_MD_TABLES_START); open_run_for_write (run_name, job_id, run_file_id); metadata_create_timestep(run_name, job_id, timestep_id, run_file_id, timestep_entry); H5Fclose (run_file_id); for (int var_indx = 0; var_indx < num_vars; var_indx++) { uint32_t var_version; if(var_indx == 1 || var_indx == 3) { //these have been designated ver2 var_version = version2; } else { var_version = version1; } string VARNAME = var_names.at(var_indx) + to_string(var_version); extreme_debug_log << "VARNAME: " << VARNAME << endl; hsize_t var_dims[num_dims] = {total_x_length, total_y_length, total_z_length}; metadata_create_and_close_chunked_var(num_dims, var_dims, chunk_dims, timestep_entry.file_id, VARNAME); } close_timestep(timestep_entry); add_timing_point(CREATE_TIMESTEP_MD_TABLES_DONE); } debug_log << "rank: " << rank << " about to open file " << endl; add_timing_point(OPEN_TIMESTEP_START); open_timestep_file_collectively_for_write(run_name, job_id, timestep_id, timestep_entry.file_id); // add_timing_point(OPEN_TIMESTEP_DONE); add_timing_point(CREATE_VARS_AND_ATTRS_FOR_NEW_TIMESTEP_START); for (int var_indx = 0; var_indx < num_vars; var_indx++) { add_timing_point(CREATE_VAR_AND_ATTRS_FOR_NEW_VAR_START); uint32_t var_version; if(var_indx == 1 || var_indx == 3) { //these have been designated ver2 var_version = version2; } else { var_version = version1; } string VARNAME = var_names[var_indx] + to_string(var_version); if (write_data) { hid_t var_id; vector<double> data_vctr; add_timing_point(CREATE_AND_WRITE_CHUNK_DATA_START); open_var(timestep_entry.file_id, var_names[var_indx], var_version, var_id); write_chunk_data(var_id, num_dims, offset, chunk_dims, total_y_length, total_z_length, rank, data_vctr); add_timing_point(CREATE_AND_WRITE_CHUNK_DATA_DONE); status = H5Dclose(var_id); assert(status >= 0); // add_timing_point(VAR_CLOSE_DONE); if(var_indx == 0 ) { add_timing_point(CHUNK_MAX_MIN_FIND_START); timestep_temp_max = -1 *RAND_MAX; timestep_temp_min = RAND_MAX; for (double val : data_vctr) { if (val < timestep_temp_min) { timestep_temp_min = val; } if (val > timestep_temp_max) { timestep_temp_max = val; } } timestep_temp_min -= 100*timestep_id; timestep_temp_max += 100*timestep_id; add_timing_point(CHUNK_MAX_MIN_FIND_DONE); } //end if(var_indx == 0) } //end if write data create_var_attrs(rank, proc_dims, timestep_id, var_indx, VARNAME, num_types, write_data, attrs, timestep_temp_max, timestep_temp_min); } //var loop done // add_timing_point(CLOSE_TIMESTEP_DONE); //close since the attr writing can't be done with a collectively opened file H5Fclose(timestep_entry.file_id); add_timing_point(CREATE_VARS_AND_ATTRS_FOR_NEW_TIMESTEP_DONE); vector<var_attribute_str> all_attrs; add_timing_point(GATHER_ATTRS_START); ser_gatherv_and_deser(attrs, num_client_procs, rank, all_attrs); add_timing_point(GATHER_ATTRS_DONE); if(rank == 0) { //first need to open the table add_timing_point(INSERT_VAR_ATTRS_START); open_timestep_file_and_var_attr_table_for_write(run_name, job_id, timestep_id, timestep_entry.file_id, timestep_entry.var_attr_table_id ); metadata_insert_var_attribute_batch(timestep_entry.var_attr_table_id, all_attrs ); status = H5PTclose(timestep_entry.var_attr_table_id); assert(status >= 0); add_timing_point(INSERT_VAR_ATTRS_DONE); } create_timestep_attrs(timestep_entry.file_id, rank, timestep_id, num_client_procs, timestep_temp_max, timestep_temp_min, run_timestep_type_names[0], run_timestep_type_names[1], all_timestep_temp_maxes_for_all_procs, all_timestep_temp_mins_for_all_procs); if(rank == 0) { H5Fclose(timestep_entry.file_id); } add_timing_point(CREATE_TIMESTEP_DONE); } add_timing_point(CREATE_ALL_TIMESTEPS_DONE); if (rank == 0) { create_run_attrs(run_name, job_id, num_timesteps, all_timestep_temp_maxes_for_all_procs, all_timestep_temp_mins_for_all_procs, run_timestep_type_names[0], run_timestep_type_names[1]); } //------------------------------------------------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------------------------------------------------- if(do_debug_testing && rank == 0) { // rc = debug_testing(server); hsize_t var_dims[num_dims] = {total_x_length, total_y_length, total_z_length}; testing_log << "about to start debug testing " << endl; rc = debug_testing(rank, chunk_dims, num_client_procs, run_name, num_timesteps, num_vars, num_dims, var_dims, job_id, var_names, version1, version2, write_data); if (rc != RC_OK) { error_log << "Error with debug testing \n"; } } //------------------------------------------------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------------------------------------------------- cleanup: do_cleanup(rank, num_client_procs); return rc; } // static void create_file(const string &run_name, string job_id, uint64_t timestep_id, hid_t &file_id) // { // string FILENAME = run_name + "/" + job_id + "/" + to_string(timestep_id); // extreme_debug_log << "FILENAME: " << FILENAME << endl; // /* // * Set up file access property list with parallel I/O access // */ // //create a property list for file access // hid_t property_list_id = H5Pcreate(H5P_FILE_ACCESS); assert(property_list_id >= 0); // herr_t status = H5Pset_fapl_mpio(property_list_id, MPI_COMM_WORLD, MPI_INFO_NULL); assert(status >= 0); // // add_timing_point(PARALLEL_FILE_ACCESS_INIT_DONE); // /* // * Create a new file collectively and release property list identifier. // */ // //note: New files are always created in read-write mode, // file_id = H5Fcreate(FILENAME.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT, property_list_id); assert(file_id >= 0); // status = H5Pclose(property_list_id); assert(status >= 0); // } // static void open_file_indv(const string &run_name, string job_id, uint64_t timestep_id, hid_t &file_id) // { // string FILENAME = run_name + "/" + job_id + "/" + to_string(timestep_id); // extreme_debug_log << "FILENAME: " << FILENAME << endl; // /* // * open the file for writing and reading // */ // //note: New files are always created in read-write mode, // file_id = H5Fopen(FILENAME.c_str(), H5F_ACC_RDWR, H5P_DEFAULT); assert(file_id >= 0); // } static void write_chunk_data(hid_t var_id, uint32_t num_dims, hsize_t *offset, hsize_t *chunk_dims, uint32_t total_y_length, uint32_t total_z_length, int rank, std::vector<double> &data_vct ) { hsize_t *count = chunk_dims; hsize_t stride[num_dims] = {1, 1, 1}; //todo - what if 2D? hsize_t block[num_dims] = {1, 1, 1}; //todo - what if 2D? hsize_t chunk_vol = chunk_dims[0] * chunk_dims[1] * chunk_dims[2]; //todo - what if 2D? data_vct.reserve(chunk_vol); hid_t var_data_space = H5Dget_space( var_id ); assert(var_data_space >= 0); hid_t chunk_data_space = H5Screate_simple(num_dims, chunk_dims, NULL); assert(chunk_data_space >= 0); /* * Select hyperslab in the file. */ // var_data_space = H5Dget_space(var_id); assert(var_data_space >= 0); herr_t status = H5Sselect_hyperslab(var_data_space, H5S_SELECT_SET, offset, stride, count, block); assert(status >= 0); /* * Initialize data buffer */ add_timing_point(CREATE_DATA_START); generate_data_for_proc(total_y_length, total_z_length, offset, rank, data_vct, chunk_dims[0], chunk_dims[1], chunk_dims[2], chunk_vol); add_timing_point(CREATE_DATA_DONE); // extreme_debug_log << "data_vct.size(): " << data_vct.size() << endl; // if(data_vct.size() > 0) { // extreme_debug_log << "data_vct[0]: " << data_vct[0] << endl; // } /* * Create property list for collective dataset write. */ //create a property list for dataset creation hid_t property_list_id = H5Pcreate(H5P_DATASET_XFER); assert(property_list_id >= 0); status = H5Pset_dxpl_mpio(property_list_id, H5FD_MPIO_COLLECTIVE); assert(status >= 0); /* * Write a subset of data to the dataset */ status = H5Dwrite(var_id, H5T_NATIVE_DOUBLE, chunk_data_space, var_data_space, property_list_id, &data_vct[0]); assert(status >= 0); extreme_debug_log << "H5Dwrite status: " << status << endl; status = H5Pclose(property_list_id); assert(status >= 0); status = H5Sclose(chunk_data_space); assert(status >= 0); status = H5Sclose(var_data_space); assert(status >= 0); } void create_var_attrs(int rank, md_dim_bounds proc_dims, int timestep_num, int var_indx, string VARNAME, uint32_t num_types, bool write_data, vector<var_attribute_str> &attrs, double &timestep_temp_max, double &timestep_temp_min) { float type_freqs[] = {25, 5, .1, 100, 100, 20, 2.5, .5, 1, 10}; // char type_types[10][3] = {"b", "b", "b", "d", "d", "2p","2p","2p","2d","2d"}; char type_types[10][3] = {"b", "b", "b", "d", "d", "s","s","s","2d","2d"}; //all 12 char plus null character char type_names[10][13] = {"blob_freq", "blob_ifreq", "blob_rare", "max_val_type", "min_val_type", "note_freq", "note_ifreq", "note_rare", "ranges_type1", "ranges_type2"}; uint32_t type_version = 0; add_timing_point(CREATE_VAR_ATTRS_FOR_NEW_VAR_START); for(uint32_t type_indx=0; type_indx<num_types; type_indx++) { float freq = type_freqs[type_indx]; uint32_t odds = 100 / freq; uint32_t val = rand() % odds; extreme_debug_log << "rank: " << to_string(rank) << " and val: " << to_string(val) << " and odds: " << to_string(odds) << endl; if(val == 0) { //makes sure we have the desired frequency for each type add_timing_point(CREATE_NEW_VAR_ATTR_START); string attr_data; if(strcmp(type_types[type_indx], "b") == 0) { bool flag = rank % 2; make_single_val_data(flag, attr_data); } else if(strcmp(type_types[type_indx], "d") == 0) { // int sign = pow(-1, rand() % 2); int sign = pow(-1,(type_indx+1)%2); //max will be positive, min will be neg double val = (double)rand() / RAND_MAX; // val = sign * (DBL_MIN + val * (DBL_MAX - DBL_MIN) ); //note - can use DBL MAX/MIN but the numbers end up being E305 to E308 // val = sign * (FLT_MIN + val * (FLT_MAX - FLT_MIN) ); //note - can use DBL MAX/MIN but the numbers end up being E35 to E38 val = sign * val * ( pow(10,10) ) ; //produces a number in the range [0,10^10] make_single_val_data(val, attr_data); //if write data the chunk min and max for var 0 will be based on the actual data values (this is done above) if(!write_data && var_indx == 0 ) { if ( type_indx == 3 ) { timestep_temp_max = val; extreme_debug_log << "for rank: " << rank << " timestep: " << timestep_num << " just added " << val << " as the max value \n"; } else if (type_indx == 4 ) { timestep_temp_min = val; extreme_debug_log << "for rank: " << rank << " timestep: " << timestep_num << " just added " << val << " as the min value \n"; } } } else if(strcmp(type_types[type_indx], "s") == 0) { attr_data = "attr data for var" + to_string(var_indx) + "timestep"+to_string(timestep_num); } else if(strcmp(type_types[type_indx], "2d") == 0) { vector<int> vals(2); vals[0] = (int) (rand() % RAND_MAX); vals[1] = vals[0] + 10000; make_single_val_data(vals, attr_data); } else { error_log << "error. type didn't match list of possibilities" << endl; add_timing_point(ERR_TYPE_COMPARE); } add_timing_point(VAR_ATTR_INIT_DONE); string type_name = type_names[type_indx] + to_string(type_version); attrs.push_back ( var_attribute_str (type_name.c_str(), VARNAME.c_str(), proc_dims, attr_data) ); // if(attrs.size() < 5) { // extreme_debug_log << "for rank: " << rank << " the " << attrs.size() << "th attr has val: " << attr_data << endl; // } add_timing_point(CREATE_NEW_VAR_ATTR_DONE); }//val = 0 done } //type loop done add_timing_point(CREATE_VAR_ATTRS_FOR_NEW_VAR_DONE); } void create_timestep_attrs(hid_t timestep_file_id, int rank, int timestep_num, uint32_t num_client_procs, double timestep_temp_max, double timestep_temp_min, char *max_type_name, char *min_type_name, double *all_timestep_temp_maxes_for_all_procs, double *all_timestep_temp_mins_for_all_procs) { add_timing_point(CREATE_TIMESTEP_ATTRS_START); if(rank == 0) { double all_temp_maxes[num_client_procs]; double all_temp_mins[num_client_procs]; MPI_Gather(&timestep_temp_max, 1, MPI_DOUBLE, all_temp_maxes, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD); MPI_Gather(&timestep_temp_min, 1, MPI_DOUBLE, all_temp_mins, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD); double timestep_var_max = -1 * RAND_MAX; double timestep_var_min = RAND_MAX; add_timing_point(GATHER_DONE_PROC_MAX_MIN_FIND_START); for (int proc_rank = 0; proc_rank<num_client_procs; proc_rank++) { if( all_temp_maxes[proc_rank] > timestep_var_max) { timestep_var_max = all_temp_maxes[proc_rank]; } if( all_temp_mins[proc_rank] < timestep_var_min) { timestep_var_min = all_temp_mins[proc_rank]; } } add_timing_point(PROC_MAX_MIN_FIND_DONE); all_timestep_temp_maxes_for_all_procs[timestep_num] = timestep_var_max; all_timestep_temp_mins_for_all_procs[timestep_num] = timestep_var_min; testing_log << "timestep " << timestep_num << " temperature max: " << timestep_var_max << endl; testing_log << "timestep " << timestep_num << " temperature min: " << timestep_var_min << endl; vector<non_var_attribute_str> attrs; string temp_max_data, temp_min_data; make_single_val_data(timestep_var_max, temp_max_data); make_single_val_data(timestep_var_min, temp_min_data); attrs.push_back ( non_var_attribute_str (max_type_name, temp_max_data) ); attrs.push_back ( non_var_attribute_str (min_type_name, temp_min_data) ); hid_t timestep_attr_table_id; open_timestep_attr_table (timestep_file_id, timestep_attr_table_id); metadata_insert_timestep_attribute_batch(timestep_attr_table_id, attrs ); H5PTclose(timestep_attr_table_id); } else { MPI_Gather(&timestep_temp_max, 1, MPI_DOUBLE, NULL, NULL, MPI_DOUBLE, 0, MPI_COMM_WORLD); MPI_Gather(&timestep_temp_min, 1, MPI_DOUBLE, NULL, NULL, MPI_DOUBLE, 0, MPI_COMM_WORLD); } add_timing_point(CREATE_TIMESTEP_ATTRS_DONE); } void create_run_attrs(string run_name, string job_id, uint32_t num_timesteps, double *all_timestep_temp_maxes_for_all_procs, double *all_timestep_temp_mins_for_all_procs, char *max_type_name, char *min_type_name ) { add_timing_point(CREATE_RUN_ATTRS_START); double run_temp_max = -1 * RAND_MAX; double run_temp_min = RAND_MAX; add_timing_point(RUN_MAX_MIN_FIND_START); for(int timestep = 0; timestep < num_timesteps; timestep++) { if( all_timestep_temp_maxes_for_all_procs[timestep] > run_temp_max) { run_temp_max = all_timestep_temp_maxes_for_all_procs[timestep]; } if( all_timestep_temp_mins_for_all_procs[timestep] < run_temp_min) { run_temp_min = all_timestep_temp_mins_for_all_procs[timestep]; } } add_timing_point(RUN_MAX_MIN_FIND_DONE); vector<non_var_attribute_str> attrs; string temp_max_data; string temp_min_data; make_single_val_data(run_temp_max, temp_max_data); make_single_val_data(run_temp_min, temp_min_data); attrs.push_back ( non_var_attribute_str (max_type_name, temp_max_data) ); attrs.push_back ( non_var_attribute_str (min_type_name, temp_min_data) ); hid_t run_file_id; hid_t run_attr_table_id; open_run_and_attr_table_for_write (run_name, job_id, run_file_id, run_attr_table_id); metadata_insert_run_attribute_batch(run_attr_table_id, attrs ); H5PTclose(run_attr_table_id); H5Fclose(run_file_id); add_timing_point(CREATE_RUN_ATTRS_DONE); } void do_cleanup(int rank, uint32_t num_client_procs) { long double *all_time_pts_buf; int *all_catg_time_pts_buf; add_timing_point(WRITING_DONE); MPI_Barrier (MPI_COMM_WORLD); testing_log << "about to start cleanup" << endl; add_timing_point(WRITING_DONE_FOR_ALL_PROCS_START_CLEANUP); if(output_timing) { int each_proc_num_time_pts[num_client_procs]; int displacement_for_each_proc[num_client_procs]; int *all_catg_time_pts_buf; gatherv_int(catg_of_time_pts, num_client_procs, rank, each_proc_num_time_pts, displacement_for_each_proc, &all_catg_time_pts_buf); int sum = 0; if(rank == 0) { sum = accumulate(each_proc_num_time_pts, each_proc_num_time_pts+num_client_procs, sum); extreme_debug_log << "sum: " << sum << endl; all_time_pts_buf = (long double *) malloc(sum * sizeof(long double)); } int num_time_pts = time_pts.size(); debug_log << "num_time pts: " << to_string(num_time_pts) << "time_pts.size(): " << time_pts.size()<< endl; MPI_Gatherv(&time_pts[0], num_time_pts, MPI_LONG_DOUBLE, all_time_pts_buf, each_proc_num_time_pts, displacement_for_each_proc, MPI_LONG_DOUBLE, 0, MPI_COMM_WORLD); if (rank == 0) { //prevent it from buffering the printf statements setbuf(stdout, NULL); std::cout << "begin timing output" << endl; for(int i=0; i<sum; i++) { // cout << "all_time_pts_buf[i]: " << all_time_pts_buf[i] << endl; printf("%d %Lf ", all_catg_time_pts_buf[i], all_time_pts_buf[i]); // std::cout << all_catg_time_pts_buf[i] << " " << all_time_pts_buf[i] << " "; if (i%20 == 0 && i!=0) { std::cout << std::endl; } } std::cout << std::endl; free(all_time_pts_buf); free(all_catg_time_pts_buf); } } MPI_Barrier (MPI_COMM_WORLD); MPI_Finalize(); debug_log << "got to cleanup7" << endl; debug_log << "finished \n"; }
38.235577
186
0.655224
[ "vector" ]
3676cbc71848e02fb041d0a7e9521591c8ecdd66
2,213
cpp
C++
EntityComponentSystem/PbrRenderer/Model.cpp
Spheya/Slamanander-Engine
d0708399eacab26b243045b33b51ff30d614b7bd
[ "MIT" ]
null
null
null
EntityComponentSystem/PbrRenderer/Model.cpp
Spheya/Slamanander-Engine
d0708399eacab26b243045b33b51ff30d614b7bd
[ "MIT" ]
null
null
null
EntityComponentSystem/PbrRenderer/Model.cpp
Spheya/Slamanander-Engine
d0708399eacab26b243045b33b51ff30d614b7bd
[ "MIT" ]
null
null
null
#include "Model.hpp" #include <iostream> #pragma warning(push, 0) #pragma warning(disable : 4701) #include <tiny_obj_loader.h> #pragma warning(pop) renderer::Model::Model(const std::string file) : _vao(GL_TRIANGLES, 0) { objl::Loader loader; std::vector<glm::vec3> positions; std::vector<glm::vec2> uvCoords; std::vector<glm::vec3> normals; if (!loader.LoadFile(file)) std::terminate(); for (const auto& vertex : loader.LoadedVertices) { positions.emplace_back(vertex.Position.X, vertex.Position.Y, vertex.Position.Z); uvCoords.emplace_back(vertex.TextureCoordinate.X, vertex.TextureCoordinate.Y); normals.emplace_back(vertex.Normal.X, vertex.Normal.Y, vertex.Normal.Z); } storeVboData(positions, uvCoords, normals); _vao.setIndexBuffer(loader.LoadedIndices); } renderer::Model::Model(const std::vector<glm::vec3>& positions, const std::vector<glm::vec2>& uvCoords, const std::vector<glm::vec3>& normals) : _vao(GL_TRIANGLES, positions.size()) { storeVboData(positions, uvCoords, normals); } renderer::Model::Model(const std::vector<GLuint>& indices, const std::vector<glm::vec3>& positions, const std::vector<glm::vec2>& uvCoords, const std::vector<glm::vec3>& normals) : Model(positions, uvCoords, normals) { _vao.setIndexBuffer(indices); } void renderer::Model::storeVboData(const std::vector<glm::vec3>& positions, const std::vector<glm::vec2>& uvCoords, const std::vector<glm::vec3>& normals) { if (!positions.empty()) { auto positionsVbo = _vao.createVbo(); _vao.getVbo(positionsVbo).write(positions.size() * sizeof(glm::vec3), &positions[0]); _vao.getVbo(positionsVbo).bindAttribPointer(0, 3, GL_FLOAT); } if (!uvCoords.empty()) { auto uvCoordsVbo = _vao.createVbo(); _vao.getVbo(uvCoordsVbo).write(uvCoords.size() * sizeof(glm::vec2), &uvCoords[0]); _vao.getVbo(uvCoordsVbo).bindAttribPointer(1, 2, GL_FLOAT); } if (!normals.empty()) { auto normalsVbo = _vao.createVbo(); _vao.getVbo(normalsVbo).write(normals.size() * sizeof(glm::vec3), &normals[0]); _vao.getVbo(normalsVbo).bindAttribPointer(2, 3, GL_FLOAT); } } renderer::Vao& renderer::Model::getVao() { return _vao; } const renderer::Vao& renderer::Model::getVao() const { return _vao; }
31.169014
180
0.723904
[ "vector", "model" ]
367a5af1c4e5060a9f95bb4771a60026416311b8
8,321
cc
C++
src/main/dtw_merge.cc
takenori-y/SPTK
573df2dd032c39db2aa24de012d2fe9a44f96280
[ "Apache-2.0" ]
null
null
null
src/main/dtw_merge.cc
takenori-y/SPTK
573df2dd032c39db2aa24de012d2fe9a44f96280
[ "Apache-2.0" ]
null
null
null
src/main/dtw_merge.cc
takenori-y/SPTK
573df2dd032c39db2aa24de012d2fe9a44f96280
[ "Apache-2.0" ]
null
null
null
// ------------------------------------------------------------------------ // // Copyright 2021 SPTK Working Group // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // ------------------------------------------------------------------------ // #include <fstream> // std::ifstream #include <iomanip> // std::setw #include <iostream> // std::cerr, std::cin, std::cout, std::endl, etc. #include <sstream> // std::ostringstream #include <vector> // std::vector #include "Getopt/getoptwin.h" #include "SPTK/utils/sptk_utils.h" namespace { const int kDefaultNumOrder(25); void PrintUsage(std::ostream* stream) { // clang-format off *stream << std::endl; *stream << " dtw_merge - merge two vector sequences" << std::endl; *stream << std::endl; *stream << " usage:" << std::endl; *stream << " dtw_merge [ options ] vfile file1 [ infile ] > stdout" << std::endl; // NOLINT *stream << " options:" << std::endl; *stream << " -l l : length of vector ( int)[" << std::setw(5) << std::right << kDefaultNumOrder + 1 << "][ 1 <= l <= ]" << std::endl; // NOLINT *stream << " -m m : order of vector ( int)[" << std::setw(5) << std::right << "l-1" << "][ 0 <= m <= ]" << std::endl; // NOLINT *stream << " -h : print this message" << std::endl; *stream << " vfile:" << std::endl; *stream << " Viterbi path ( int)" << std::endl; *stream << " file1:" << std::endl; *stream << " reference vector sequence (double)" << std::endl; *stream << " infile:" << std::endl; *stream << " query vector sequence (double)[stdin]" << std::endl; *stream << " stdout:" << std::endl; *stream << " warped vector sequence (double)" << std::endl; *stream << std::endl; *stream << " SPTK: version " << sptk::kVersion << std::endl; *stream << std::endl; // clang-format on } } // namespace /** * @a dtw_merge [ @e option ] @e vfile @e file1 [ @e infile ] * * - @b -l @e int * - length of vector @f$(1 \le M+1)@f$ * - @b -m @e int * - order of vector @f$(0 \le M)@f$ * - @b vfile @e str * - int-type Viterbi path * - @b file1 @e str * - double-type reference vector sequence * - @b infile @e str * - double-type query vector sequence * - @b stdout * - double-type concatenated vector sequence * * @param[in] argc Number of arguments. * @param[in] argv Argument vector. * @return 0 on success, 1 on failure. */ int main(int argc, char* argv[]) { int num_order(kDefaultNumOrder); for (;;) { const int option_char(getopt_long(argc, argv, "l:m:h", NULL, NULL)); if (-1 == option_char) break; switch (option_char) { case 'l': { if (!sptk::ConvertStringToInteger(optarg, &num_order) || num_order <= 0) { std::ostringstream error_message; error_message << "The argument for the -l option must be a positive integer"; sptk::PrintErrorMessage("dtw_merge", error_message); return 1; } --num_order; break; } case 'm': { if (!sptk::ConvertStringToInteger(optarg, &num_order) || num_order < 0) { std::ostringstream error_message; error_message << "The argument for the -m option must be a " << "non-negative integer"; sptk::PrintErrorMessage("dtw_merge", error_message); return 1; } break; } case 'h': { PrintUsage(&std::cout); return 0; } default: { PrintUsage(&std::cerr); return 1; } } } const char* viterbi_path_file; const char* reference_file; const char* query_file; const int num_input_files(argc - optind); if (3 == num_input_files) { viterbi_path_file = argv[argc - 3]; reference_file = argv[argc - 2]; query_file = argv[argc - 1]; } else if (2 == num_input_files) { viterbi_path_file = argv[argc - 2]; reference_file = argv[argc - 1]; query_file = NULL; } else { std::ostringstream error_message; error_message << "Three input files are required"; sptk::PrintErrorMessage("dtw_merge", error_message); return 1; } std::ifstream ifs1; ifs1.open(viterbi_path_file, std::ios::in | std::ios::binary); if (ifs1.fail()) { std::ostringstream error_message; error_message << "Cannot open file " << viterbi_path_file; sptk::PrintErrorMessage("dtw_merge", error_message); return 1; } std::istream& input_stream_for_path(ifs1); std::ifstream ifs2; ifs2.open(reference_file, std::ios::in | std::ios::binary); if (ifs2.fail()) { std::ostringstream error_message; error_message << "Cannot open file " << reference_file; sptk::PrintErrorMessage("dtw_merge", error_message); return 1; } std::istream& input_stream_for_reference(ifs2); std::ifstream ifs3; ifs3.open(query_file, std::ios::in | std::ios::binary); if (ifs3.fail() && NULL != query_file) { std::ostringstream error_message; error_message << "Cannot open file " << query_file; sptk::PrintErrorMessage("dtw_merge", error_message); return 1; } std::istream& input_stream_for_query(ifs3.fail() ? std::cin : ifs3); const int length(num_order + 1); std::vector<double> query_vector(length); std::vector<double> reference_vector(length); if (!sptk::ReadStream(false, 0, 0, length, &query_vector, &input_stream_for_query, NULL) || !sptk::ReadStream(false, 0, 0, length, &reference_vector, &input_stream_for_reference, NULL)) { return 0; } int prev_query_vector_index(0), prev_reference_vector_index(0); int curr_query_vector_index, curr_reference_vector_index; while ( sptk::ReadStream(&curr_query_vector_index, &input_stream_for_path) && sptk::ReadStream(&curr_reference_vector_index, &input_stream_for_path)) { if (curr_query_vector_index < 0 || curr_reference_vector_index < 0 || curr_query_vector_index < prev_query_vector_index || curr_reference_vector_index < prev_reference_vector_index) { std::ostringstream error_message; error_message << "Invalid Viterbi path"; sptk::PrintErrorMessage("dtw_merge", error_message); return 1; } { const int diff(curr_query_vector_index - prev_query_vector_index); for (int i(0); i < diff; ++i) { if (!sptk::ReadStream(false, 0, 0, length, &query_vector, &input_stream_for_query, NULL)) { return 0; } } prev_query_vector_index = curr_query_vector_index; } { const int diff(curr_reference_vector_index - prev_reference_vector_index); for (int i(0); i < diff; ++i) { if (!sptk::ReadStream(false, 0, 0, length, &reference_vector, &input_stream_for_reference, NULL)) { return 0; } } prev_reference_vector_index = curr_reference_vector_index; } if (!sptk::WriteStream(0, length, query_vector, &std::cout, NULL) || !sptk::WriteStream(0, length, reference_vector, &std::cout, NULL)) { std::ostringstream error_message; error_message << "Failed to write merged vector"; sptk::PrintErrorMessage("dtw_merge", error_message); return 1; } } return 0; }
36.982222
159
0.570004
[ "vector" ]
367e11bfc304bd58afe19973fe12b89c4fe0f5ad
1,596
cpp
C++
simplefvm/src/FVMSolver/CoeffsPartsVelocity/Flux/VFluxPort.cpp
artvns/SimpleFvm
5a8eca332d6780e738c0bc6c8c2b787b47b5b20d
[ "MIT" ]
4
2022-01-03T08:45:55.000Z
2022-01-06T19:57:11.000Z
simplefvm/src/FVMSolver/CoeffsPartsVelocity/Flux/VFluxPort.cpp
artvns/SimpleFvm
5a8eca332d6780e738c0bc6c8c2b787b47b5b20d
[ "MIT" ]
null
null
null
simplefvm/src/FVMSolver/CoeffsPartsVelocity/Flux/VFluxPort.cpp
artvns/SimpleFvm
5a8eca332d6780e738c0bc6c8c2b787b47b5b20d
[ "MIT" ]
null
null
null
#include "VFluxPort.h" namespace fvmsolver { VFluxPort::VFluxPort( const SolverFluidPropsMask& fluid, const SolverFieldsMask& fields, const SolverMeshParamsMask& mesh, const SolverCellNumsGlobalMask& nums, const SolverAdjCellGlobalNumsVMask& adjCellNums) : fluid_(fluid), fields_(fields), mesh_(mesh), nums_(nums), adjCellNums_(adjCellNums) { } double VFluxPort::getRHO() const { return fluid_.getRHO(); } double VFluxPort::get_u(size_t num) const { return fields_.getU(num); } double VFluxPort::get_v(size_t num) const { return fields_.getV(num); } double VFluxPort::get_dX(size_t step) const { return mesh_.get_dX(step); } double VFluxPort::get_dY(size_t step) const { return mesh_.get_dY(step); } size_t VFluxPort::getNumVp(size_t step) const { return nums_.get_pCellNum(step); } size_t VFluxPort::getNumVn(size_t step) const { return adjCellNums_.getNumVn(step); } size_t VFluxPort::getNumVs(size_t step) const { return adjCellNums_.getNumVs(step); } size_t VFluxPort::getNumUwn(size_t step) const { return adjCellNums_.getNumUwn(step); } size_t VFluxPort::getNumUws(size_t step) const { return adjCellNums_.getNumUws(step); } size_t VFluxPort::getNumUen(size_t step) const { return adjCellNums_.getNumUen(step); } size_t VFluxPort::getNumUes(size_t step) const { return adjCellNums_.getNumUes(step); } }
23.470588
63
0.64411
[ "mesh" ]
3682429dabcc680c06e24a24df6162c8b36ce561
4,103
cpp
C++
osprey/testsuite/cases/cern/root/TRandom3/TRandom3.cpp
sharugupta/OpenUH
daddd76858a53035f5d713f648d13373c22506e8
[ "BSD-2-Clause" ]
null
null
null
osprey/testsuite/cases/cern/root/TRandom3/TRandom3.cpp
sharugupta/OpenUH
daddd76858a53035f5d713f648d13373c22506e8
[ "BSD-2-Clause" ]
null
null
null
osprey/testsuite/cases/cern/root/TRandom3/TRandom3.cpp
sharugupta/OpenUH
daddd76858a53035f5d713f648d13373c22506e8
[ "BSD-2-Clause" ]
null
null
null
// J.M. Dana // dana@ace.ual.es #include <stdio.h> // Compatibility with #include <errno.h> // gcc 2.96 #include <iostream> #include <sys/time.h> #include <unistd.h> #include <vector> #include <string> #include "timing.h" #include "Rtypes.h" #include "TRandom.h" #include "TRandom3.h" using namespace std; #define N 500000000 // ------------------------------------------------------------------ TRandom3::TRandom3(UInt_t seed) { //*-*-*-*-*-*-*-*-*-*-*default constructor*-*-*-*-*-*-*-*-*-*-*-*-*-*-* // If seed is 0, the seed is automatically computed via a TUUID object. // In this case the seed is guaranteed to be unique in space and time. //SetName("Random3"); //SetTitle("Random number generator: Mersenne Twistor"); SetSeed(seed); } TRandom3::~TRandom3(){} void TRandom3::SetSeed(UInt_t seed) { // Set the random generator sequence // if seed is 0 (default value) a TUUID is generated and used to fill // the first 8 integers of the seed array. // In this case the seed is guaranteed to be unique in space and time. TRandom::SetSeed(seed); fCount624 = 624; Int_t i,j; if (seed > 0) { fMt[0] = fSeed; j = 1; } else { exit(99); /* TUUID uid; UChar_t uuid[16]; uid.GetUUID(uuid); for (i=0;i<8;i++) { fMt[i] = uuid[2*i]*256 +uuid[2*i+1]; } j = 9; */ } for(i=j; i<624; i++) { fMt[i] = (69069 * fMt[i-1]) & 0xffffffff; } } Double_t TRandom3::Rndm(Int_t i) { // Machine independent random number generator. // Produces uniformly-distributed floating points in [0,1] // Method: Mersenne Twistor UInt_t y; const Int_t kM = 397; const Int_t kN = 624; const UInt_t kTemperingMaskB = 0x9d2c5680; const UInt_t kTemperingMaskC = 0xefc60000; const UInt_t kUpperMask = 0x80000000; const UInt_t kLowerMask = 0x7fffffff; const UInt_t kMatrixA = 0x9908b0df; if (fCount624 >= kN) { register Int_t i; for (i=0; i < kN-kM; i++) { y = (fMt[i] & kUpperMask) | (fMt[i+1] & kLowerMask); fMt[i] = fMt[i+kM] ^ (y >> 1) ^ ((y & 0x1) ? kMatrixA : 0x0); } for ( ; i < kN-1 ; i++) { y = (fMt[i] & kUpperMask) | (fMt[i+1] & kLowerMask); fMt[i] = fMt[i+kM-kN] ^ (y >> 1) ^ ((y & 0x1) ? kMatrixA : 0x0); } y = (fMt[kN-1] & kUpperMask) | (fMt[0] & kLowerMask); fMt[kN-1] = fMt[kM-1] ^ (y >> 1) ^ ((y & 0x1) ? kMatrixA : 0x0); fCount624 = 0; } y = fMt[fCount624++]; y ^= (y >> 11); y ^= ((y << 7 ) & kTemperingMaskB ); y ^= ((y << 15) & kTemperingMaskC ); y ^= (y >> 18); if (y) return ( (Double_t) y * 2.3283064365386963e-10); // * Power(2,-32) return Rndm(); } //______________________________________________________________________________ void TRandom3::RndmArray(Int_t n, Double_t *array) { // Return an array of n random numbers uniformly distributed in ]0,1] Int_t k = 0; UInt_t y; const Int_t kM = 397; const Int_t kN = 624; const UInt_t kTemperingMaskB = 0x9d2c5680; const UInt_t kTemperingMaskC = 0xefc60000; const UInt_t kUpperMask = 0x80000000; const UInt_t kLowerMask = 0x7fffffff; const UInt_t kMatrixA = 0x9908b0df; while (k < n) { if (fCount624 >= kN) { register Int_t i; for (i=0; i < kN-kM; i++) { y = (fMt[i] & kUpperMask) | (fMt[i+1] & kLowerMask); fMt[i] = fMt[i+kM] ^ (y >> 1) ^ ((y & 0x1) ? kMatrixA : 0x0); } for ( ; i < kN-1 ; i++) { y = (fMt[i] & kUpperMask) | (fMt[i+1] & kLowerMask); fMt[i] = fMt[i+kM-kN] ^ (y >> 1) ^ ((y & 0x1) ? kMatrixA : 0x0); } y = (fMt[kN-1] & kUpperMask) | (fMt[0] & kLowerMask); fMt[kN-1] = fMt[kM-1] ^ (y >> 1) ^ ((y & 0x1) ? kMatrixA : 0x0); fCount624 = 0; } y = fMt[fCount624++]; y ^= (y >> 11); y ^= ((y << 7 ) & kTemperingMaskB ); y ^= ((y << 15) & kTemperingMaskC ); y ^= (y >> 18); if (y) { array[k] = Double_t( y * 2.3283064365386963e-10); // * Power(2,-32) k++; } } }
26.301282
80
0.541555
[ "object", "vector" ]
3682b9b508188d681d60325cfe891c49a7f4532b
15,477
cc
C++
src/visualisers/TephiGrid.cc
b8raoult/magics
eb2c86ec6e392e89c90044128dc671f22283d6ad
[ "ECL-2.0", "Apache-2.0" ]
41
2018-12-07T23:10:50.000Z
2022-02-19T03:01:49.000Z
src/visualisers/TephiGrid.cc
b8raoult/magics
eb2c86ec6e392e89c90044128dc671f22283d6ad
[ "ECL-2.0", "Apache-2.0" ]
59
2019-01-04T15:43:30.000Z
2022-03-31T09:48:15.000Z
src/visualisers/TephiGrid.cc
b8raoult/magics
eb2c86ec6e392e89c90044128dc671f22283d6ad
[ "ECL-2.0", "Apache-2.0" ]
13
2019-01-07T14:36:33.000Z
2021-09-06T14:48:36.000Z
/* * (C) Copyright 1996-2016 ECMWF. * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. * In applying this licence, ECMWF does not waive the privileges and immunities * granted to it by virtue of its status as an intergovernmental organisation nor * does it submit to any jurisdiction. */ /*! \file TephiGrid.cc \brief Implementation of the Template class TephiGrid. Magics Team - ECMWF 2006 Started: Tue 3-Oct-2006 Changes: */ #include "TephiGrid.h" #include "Layer.h" #include "Layout.h" #include "PaperPoint.h" #include "Polyline.h" #include "SciMethods.h" #include "Text.h" #include "Transformation.h" using namespace magics; TephiGrid::TephiGrid() {} TephiGrid::~TephiGrid() {} void tempe(double x) {} void step(set<double>& values, set<double>& labels, double from, double to, double ref, double step, int freq) { if (ref > to) return; int l = 0; for (double v = ref; v < to; v += step) { values.insert(v); if (l % freq == 0) { labels.insert(v); } l++; } if (ref < from) return; l = 0; for (double v = ref; v > from; v -= step) { values.insert(v); if (l % freq == 0) { labels.insert(v); } l++; } } void TephiGrid::visit(DrawingVisitor& out) { const Transformation& tephi = out.transformation(); vector<double> tempe; double maxpcx = (tephi.getMaxPCX() + (tephi.getMinPCX() * .25)) / 1.25; double minpcx = tephi.getMinPCX(); PaperPoint lr(maxpcx, tephi.getMinPCY()); UserPoint xy; tephi.revert(lr, xy); double tmin; double tmax; double pmin; double pmax; tephi.boundingBox(tmin, pmin, tmax, pmax); double tfactor = 10; tmax = int(tmax / tfactor) * tfactor + tfactor; tmin = int(tmin / tfactor) * tfactor - tfactor; double pfactor = 100; pmax = int(pmax / pfactor) * pfactor + pfactor; pmin = int(pmin / pfactor) * pfactor; double thmin = magics::theta(tmin + 273.15, pmin * 100.) - 237.15; thmin = -100; double thmax = magics::theta(tmin + 273.15, pmax * 100.) - 237.15; thmax = +450; // Isotherm; if (isotherm_) { std::set<double> isotherms; std::set<double> labels; MagFont font(isotherm_label_font_, isotherm_label_style_, isotherm_label_size_); font.colour(*isotherm_label_colour_); double theta = magics::theta(xy.x() + 273.15, (xy.y()) * 100.); step(isotherms, labels, tmin, tmax, isotherm_reference_, isotherm_interval_, isotherm_label_frequency_); for (std::set<double>::iterator t = isotherms.begin(); t != isotherms.end(); ++t) { Polyline poly; Colour colour = (*t != isotherm_reference_) ? *isotherm_colour_ : *isotherm_reference_colour_; poly.setColour(colour); poly.setThickness(isotherm_thickness_); poly.setLineStyle(isotherm_style_); poly.push_back(tephi(UserPoint(*t, pressureFromTheta(thmin + 273.15, *t + 273.15) / 100.))); poly.push_back(tephi(UserPoint(*t, pressureFromTheta(thmax + 273.15, *t + 273.15) / 100.))); tephi(poly, out.layout()); std::set<double>::iterator label = labels.find(*t); if (label == labels.end()) continue; UserPoint point(*t, pressureFromTheta(theta, *t + 273.15) / 100.); PaperPoint xy = tephi(point); if (tephi.in(xy)) { Text* text = new Text(); text->addText("T=" + tostring(*t), font); text->setAngle(-3.14 / 4); text->setBlanking(true); text->push_back(xy); out.push_back(text); } } } if (dry_adiabatic_) { PaperPoint ll(tephi.getMinPCX(), tephi.getMinPCY()); UserPoint tp_ll; tephi.revert(ll, tp_ll); std::set<double> dry; std::set<double> labels; MagFont font(dry_adiabatic_label_font_, dry_adiabatic_label_style_, dry_adiabatic_label_size_); font.colour(*dry_adiabatic_label_colour_); step(dry, labels, thmin, thmax, dry_adiabatic_reference_, dry_adiabatic_interval_, dry_adiabatic_label_frequency_); for (std::set<double>::iterator t = dry.begin(); t != dry.end(); ++t) { Polyline poly; poly.setLineStyle(dry_adiabatic_style_); poly.setColour(*dry_adiabatic_colour_); poly.setThickness(dry_adiabatic_thickness_); poly.push_back(tephi(UserPoint(tmin, magics::pressureFromTheta(*t + 273.15, tmin + 273.15) / 100))); poly.push_back(tephi(UserPoint(tmax, magics::pressureFromTheta(*t + 273.15, tmax + 273.15) / 100))); tephi(poly, out.layout()); std::set<double>::iterator label = labels.find(*t); if (label == labels.end()) continue; UserPoint point(tp_ll.x(), pressureFromTheta(*t + 273.15, tp_ll.x() + 273.15) / 100.); if (tephi.in(point)) { Text* text = new Text(); text->setAngle(3.14 / 4); text->addText("th=" + tostring(*t), font); text->setBlanking(true); text->push_back(tephi(point)); out.push_back(text); } } } if (isobar_) { std::set<double> isobars; std::set<double> labels; step(isobars, labels, pmin, pmax, isobar_reference_, isobar_interval_, isobar_label_frequency_); for (std::set<double>::iterator p = isobars.begin(); p != isobars.end(); ++p) { Polyline poly; poly.setColour(*isobar_colour_); poly.setLineStyle(isobar_style_); poly.setThickness(isobar_thickness_); for (double t = tmin; t < tmax; t += 1) { PaperPoint xy = tephi(UserPoint(t, *p)); poly.push_back(xy); std::set<double>::iterator label = labels.find(*p); if (label == labels.end()) continue; if (xy.x() >= maxpcx) { map<double, PaperPoint>::iterator label = pressureRightLabels_.find(*p); if (label == pressureRightLabels_.end()) { xy.x(tephi.getMinPCX() * 0.75); pressureRightLabels_.insert(make_pair(*p, xy)); } } if (xy.x() <= minpcx) { xy.x(tephi.getMaxPCX() * 0.85); map<double, PaperPoint>::iterator label = pressureLeftLabels_.find(*p); if (label == pressureLeftLabels_.end()) { pressureLeftLabels_.insert(make_pair(*p, xy)); } else pressureLeftLabels_[*p] = xy; } } tephi(poly, out.layout()); Polyline* axe = new Polyline(); axe->setColour(Colour("black")); axe->setLineStyle(LineStyle::DASH); axe->setThickness(1); axe->push_back(PaperPoint(maxpcx, tephi.getMinPCY())); axe->push_back(PaperPoint(maxpcx, tephi.getMaxPCY())); out.push_back(axe); } } if (mixing_ratio_) { vector<float> ratios; ratios.push_back(0.1); ratios.push_back(0.2); ratios.push_back(0.5); ratios.push_back(0.7); ratios.push_back(1.); ratios.push_back(1.5); ratios.push_back(2.); ratios.push_back(3.); ratios.push_back(5.); ratios.push_back(7.); ratios.push_back(10.); ratios.push_back(15.); ratios.push_back(20.); ratios.push_back(30.); ratios.push_back(50.); // ratios.push_back(100.); // Humidity Mixing ratio Lines int grid = 0; int label = 0; for (vector<float>::iterator r = ratios.begin(); r != ratios.end(); ++r) { if (grid % mixing_ratio_frequency_) continue; grid++; Polyline poly; poly.setColour(*mixing_ratio_colour_); poly.setLineStyle(mixing_ratio_style_); poly.setThickness(mixing_ratio_thickness_); for (double p = pmin - 10; p < pmax + 15; p += 10) { double t = temperatureFromMixingRatio(*r, p * 100); PaperPoint xy = tephi(UserPoint(t - 273.15, p)); if (std::isnan(xy.x_) || std::isnan(xy.y_)) { // The point is outside the area continue; // WE perhaps need to continue } poly.push_back(xy); if (label % mixing_ratio_label_frequency_) continue; label++; if (xy.y() < tephi.getMinPCY()) { xy.y(tephi.getMaxPCY() * 0.5); if (tephi.in(xy)) { map<double, PaperPoint>::iterator label = mixingLabels_.find(*r); if (label == mixingLabels_.end()) { mixingLabels_.insert(make_pair(*r, xy)); } } } } tephi(poly, out.layout()); } } if (saturated_adiabatic_) { MagFont font(saturated_adiabatic_label_font_, saturated_adiabatic_label_style_, saturated_adiabatic_label_size_); font.colour(*saturated_adiabatic_label_colour_); // saturated adiabatic std::set<double> sat; std::set<double> labels; step(sat, labels, thmin, thmax, saturated_adiabatic_reference_, saturated_adiabatic_interval_, saturated_adiabatic_label_frequency_); for (std::set<double>::iterator thetaw = sat.begin(); thetaw != sat.end(); ++thetaw) { if (*thetaw > 40.) continue; Polyline poly; poly.setColour(*saturated_adiabatic_colour_); poly.setLineStyle(saturated_adiabatic_style_); poly.setThickness(saturated_adiabatic_thickness_); double s = thetaEq(*thetaw + 273.15, *thetaw + 273.15, 1000 * 100); double pl = -1; for (double p = 200; p < pmax; p += 1) { double t = temperatureFromThetaEq(s, p * 100) - 273.15; if (t >= -40) poly.push_back(tephi(UserPoint(t, p))); else pl = p; } tephi(poly, out.layout()); std::set<double>::iterator label = labels.find(*thetaw); if (label == labels.end()) continue; UserPoint point(-40.5, pl - 1); if (tephi.in(point)) { Text* text = new Text(); text->addText(tostring(*thetaw), font); text->setAngle(-3.14 / 4); text->push_back(tephi(point)); out.push_back(text); } } } if (true) { MagFont font(isotherm_label_font_, isotherm_label_style_, isotherm_label_size_); font.colour(*isotherm_label_colour_); for (int i = 10; i < 25; i += 10) { Polyline poly; Colour colour = *isotherm_colour_; poly.setColour(colour); poly.setThickness(isotherm_thickness_); poly.setLineStyle(LineStyle::DASH); for (double p = pmin; p <= pmax; p += 10) { poly.push_back(tephi(UserPoint(1000. + i, p))); } tephi(poly, out.layout()); UserPoint pt(1000 + i, tephi.getMaxPCY()); PaperPoint xy = tephi(pt); xy.y(tephi.getMaxPCY() * .5); infoLabels_.insert(make_pair(i, xy)); } std::set<double> isobars; std::set<double> labels; step(isobars, labels, pmin, pmax, isobar_reference_, isobar_interval_, isobar_label_frequency_); for (std::set<double>::iterator p = isobars.begin(); p != isobars.end(); ++p) { Polyline poly; poly.setColour(*isobar_colour_); poly.setLineStyle(LineStyle::DASH); poly.setThickness(isobar_thickness_); poly.push_back(tephi(UserPoint(1000, *p))); poly.push_back(tephi(UserPoint(1100, *p))); tephi(poly, out.layout()); } } } /*! Class information are given to the output-stream. */ void TephiGrid::print(ostream& out) const { out << "TephiGrid["; TephiGridAttributes::print(out); out << "]"; } void TephiGrid::visit(LeftAxisVisitor& out) { MagFont font(isobar_label_font_, isobar_label_style_, isobar_label_size_); font.colour(*isobar_label_colour_); for (map<double, PaperPoint>::iterator label = pressureLeftLabels_.begin(); label != pressureLeftLabels_.end(); ++label) { Text* text = new Text(); text->setText(tostring(label->first)); text->setFont(font); text->setBlanking(true); text->setJustification(Justification::RIGHT); text->push_back(label->second); out.push_back(text); } } void TephiGrid::visit(RightAxisVisitor& out) { MagFont font(isobar_label_font_, isobar_label_style_, isobar_label_size_); font.colour(*isobar_label_colour_); for (map<double, PaperPoint>::iterator label = pressureRightLabels_.begin(); label != pressureRightLabels_.end(); ++label) { Text* text = new Text(); text->setText(tostring(label->first)); text->setFont(font); text->setBlanking(true); text->setJustification(Justification::LEFT); text->push_back(label->second); out.push_back(text); } } void TephiGrid::visit(BottomAxisVisitor& out) { MagFont font(mixing_ratio_label_font_, mixing_ratio_label_style_, mixing_ratio_label_size_); font.colour(*mixing_ratio_label_colour_); for (map<double, PaperPoint>::iterator label = mixingLabels_.begin(); label != mixingLabels_.end(); ++label) { Text* text = new Text(); text->setText(tostring(label->first)); text->setFont(font); text->setBlanking(true); text->push_back(label->second); out.push_back(text); } font = MagFont(isotherm_label_font_, isotherm_label_style_, isotherm_label_size_); font.colour(*isotherm_label_colour_); for (map<double, PaperPoint>::iterator label = infoLabels_.begin(); label != infoLabels_.end(); ++label) { Text* text = new Text(); text->setText(tostring(label->first)); text->setFont(font); text->setBlanking(true); text->push_back(label->second); out.push_back(text); } } void TephiGrid::visit(TopAxisVisitor& out) {} void TephiGrid::visit(SceneLayer& layer, vector<LayoutVisitor*>& visitors) { // First we create the layer! // and push It to the parent layer! StaticLayer* tephi = new NoDataLayer(this); // taylor->id(iconName_); // taylor>name(iconName_); layer.add(tephi); for (vector<LayoutVisitor*>::iterator visitor = visitors.begin(); visitor != visitors.end(); ++visitor) { tephi->set(*visitor); (*visitor)->visit(*this); } }
34.546875
117
0.558442
[ "vector" ]
3682ba8f9b54e75d3288a39352c2c4270861ca4a
21,839
cpp
C++
src/CQChartsColorEdit.cpp
SammyEnigma/CQCharts
56433e32c943272b6faaf6771d0652c0507f943e
[ "MIT" ]
14
2018-05-22T15:06:08.000Z
2022-01-20T12:18:28.000Z
src/CQChartsColorEdit.cpp
SammyEnigma/CQCharts
56433e32c943272b6faaf6771d0652c0507f943e
[ "MIT" ]
6
2020-09-04T15:49:24.000Z
2022-01-12T19:06:45.000Z
src/CQChartsColorEdit.cpp
SammyEnigma/CQCharts
56433e32c943272b6faaf6771d0652c0507f943e
[ "MIT" ]
9
2019-04-01T13:10:11.000Z
2022-01-22T01:46:27.000Z
#include <CQChartsColorEdit.h> #include <CQColors.h> #include <CQChartsObj.h> #include <CQChartsWidgetUtil.h> #include <CQChartsUtil.h> #include <CQChartsVariant.h> #include <CQCharts.h> #include <CQColorsEditModel.h> #include <CQPropertyView.h> #include <CQWidgetMenu.h> #include <CQRealSpin.h> #include <CQIntegerSpin.h> #include <CQColorEdit.h> #include <CQCheckBox.h> #include <QComboBox> #include <QLabel> #include <QStackedWidget> #include <QHBoxLayout> #include <QVBoxLayout> #include <QPainter> CQChartsColorLineEdit:: CQChartsColorLineEdit(QWidget *parent) : CQChartsLineEditBase(parent) { setObjectName("colorLineEdit"); setToolTip("Color"); //--- menuEdit_ = dataEdit_ = new CQChartsColorEdit; dataEdit_->setNoFocus(); menu_->setWidget(dataEdit_); //--- connectSlots(true); colorToWidgets(); } const CQChartsColor & CQChartsColorLineEdit:: color() const { return dataEdit_->color(); } void CQChartsColorLineEdit:: setColor(const CQChartsColor &color) { updateColor(color, /*updateText*/ true); } void CQChartsColorLineEdit:: setNoFocus() { dataEdit_->setNoFocus(); } void CQChartsColorLineEdit:: updateColor(const CQChartsColor &color, bool updateText) { connectSlots(false); dataEdit_->setColor(color); connectSlots(true); if (updateText) colorToWidgets(); emit colorChanged(); } void CQChartsColorLineEdit:: textChanged() { CQChartsColor color; if (edit_->text().trimmed() != "") { color = CQChartsColor(edit_->text()); if (! color.isValid()) { colorToWidgets(); return; } } updateColor(color, /*updateText*/false); } void CQChartsColorLineEdit:: colorToWidgets() { connectSlots(false); if (color().isValid()) edit_->setText(color().colorStr()); else edit_->setText(""); auto tip = QString("%1 (%2)").arg(toolTip()).arg(color().colorStr()); edit_->setToolTip(tip); connectSlots(true); } void CQChartsColorLineEdit:: menuEditChanged() { colorToWidgets(); emit colorChanged(); } void CQChartsColorLineEdit:: connectSlots(bool b) { connectBaseSlots(b); CQChartsWidgetUtil::connectDisconnect(b, dataEdit_, SIGNAL(colorChanged()), this, SLOT(menuEditChanged())); } void CQChartsColorLineEdit:: drawPreview(QPainter *painter, const QRect &rect) { auto c = (color().isValid() ? interpColor(color()) : palette().color(QPalette::Window)); painter->fillRect(rect, QBrush(c)); //--- auto str = (color().isValid() ? color().colorStr() : "<none>"); drawCenteredText(painter, str); } //------ #include <CQPropertyViewItem.h> #include <CQPropertyViewDelegate.h> CQChartsColorPropertyViewType:: CQChartsColorPropertyViewType() { } CQPropertyViewEditorFactory * CQChartsColorPropertyViewType:: getEditor() const { return new CQChartsColorPropertyViewEditor; } bool CQChartsColorPropertyViewType:: setEditorData(CQPropertyViewItem *item, const QVariant &value) { return item->setData(value); } void CQChartsColorPropertyViewType:: draw(CQPropertyViewItem *item, const CQPropertyViewDelegate *delegate, QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &ind, const QVariant &value, const ItemState &itemState) { delegate->drawBackground(painter, option, ind, itemState); bool ok; auto color = CQChartsVariant::toColor(value, ok); if (! ok) return; int x = option.rect.left(); //--- // draw color if can be directly determined if (color.isDirect()) { auto *obj = qobject_cast<CQChartsObj *>(item->object()); if (obj) { auto rect = option.rect; rect.setWidth(option.rect.height()); rect.adjust(0, 1, -3, -2); auto c = obj->charts()->interpColor(color, CQChartsUtil::ColorInd()); painter->fillRect(rect, QBrush(c)); painter->setPen(CQChartsUtil::bwColor(c)); painter->drawRect(rect); x = rect.right() + 2; } } //--- auto str = color.colorStr(); QFontMetrics fm(option.font); int w = fm.width(str); auto option1 = option; option1.rect = QRect(x, option1.rect.top(), w + 2*margin(), option1.rect.height()); delegate->drawString(painter, option1, str, ind, itemState); } QString CQChartsColorPropertyViewType:: tip(const QVariant &value) const { bool ok; auto color = CQChartsVariant::toColor(value, ok); if (! ok) return ""; return color.colorStr(); } //------ CQChartsColorPropertyViewEditor:: CQChartsColorPropertyViewEditor() { } QWidget * CQChartsColorPropertyViewEditor:: createEdit(QWidget *parent) { auto *edit = new CQChartsColorLineEdit(parent); return edit; } void CQChartsColorPropertyViewEditor:: connect(QWidget *w, QObject *obj, const char *method) { auto *edit = qobject_cast<CQChartsColorLineEdit *>(w); assert(edit); // TODO: why do we need direct connection for plot object to work ? QObject::connect(edit, SIGNAL(colorChanged()), obj, method, Qt::DirectConnection); } QVariant CQChartsColorPropertyViewEditor:: getValue(QWidget *w) { auto *edit = qobject_cast<CQChartsColorLineEdit *>(w); assert(edit); return CQChartsVariant::fromColor(edit->color()); } void CQChartsColorPropertyViewEditor:: setValue(QWidget *w, const QVariant &var) { auto *edit = qobject_cast<CQChartsColorLineEdit *>(w); assert(edit); bool ok; auto color = CQChartsVariant::toColor(var, ok); if (! ok) return; edit->setColor(color); } //------ CQChartsColorEdit:: CQChartsColorEdit(QWidget *parent) : CQChartsEditBase(parent) { setObjectName("colorEdit"); //--- auto *layout = CQUtil::makeLayout<QGridLayout>(this, 2, 2); //--- int row = 0; auto addLabelWidget = [&](const QString &label, QWidget *edit) { auto *labelW = CQUtil::makeLabelWidget<QLabel>(label, "label"); layout->addWidget(labelW, row, 0); layout->addWidget(edit , row, 1); widgetLabels_[edit] = labelW; ++row; }; auto addCheckWidget = [&](const QString &label, QWidget *edit) { auto *check = CQUtil::makeLabelWidget<QCheckBox>(label, "label"); layout->addWidget(check, row, 0); layout->addWidget(edit , row, 1); widgetLabels_[edit] = check; ++row; }; //--- typeCombo_ = CQUtil::makeWidget<QComboBox>("typeCombo"); typeCombo_->addItems(QStringList() << "None" << "Palette" << "Indexed Palette" << "Interface" << "Contrast" << "Model" << "Lighter" << "Darker" << "Color"); typeCombo_->setToolTip("Color value type"); addLabelWidget("Type", typeCombo_); //--- indPalCombo_ = CQUtil::makeWidget<QComboBox>(this, "indPaletteCombo"); indPalCombo_->addItems(QStringList() << "Index" << "Palette"); indPalStack_ = CQUtil::makeWidget<QStackedWidget>(this, "indPaletteStack"); //- indEdit_ = CQUtil::makeWidget<CQIntegerSpin>("indEdit"); indEdit_->setRange(-1, 99); indEdit_->setToolTip("Palette index in theme (-1 is unset)"); //- paletteEdit_ = CQUtil::makeWidget<QComboBox>("paletteCombo"); QStringList paletteNames; CQColorsMgrInst->getPaletteNames(paletteNames); paletteEdit_->addItems(paletteNames); //- indPalStack_->addWidget(indEdit_); indPalStack_->addWidget(paletteEdit_); layout->addWidget(indPalCombo_, row, 0); layout->addWidget(indPalStack_, row, 1); widgetLabels_[indPalStack_] = indPalCombo_; ++row; //--- rFrame_ = CQUtil::makeWidget<QFrame>("rFrame"); auto *rLayout = CQUtil::makeLayout<QHBoxLayout>(rFrame_, 0, 2); rEdit_ = CQUtil::makeWidget<CQColorsEditModel>("rEdit"); rNeg_ = CQUtil::makeLabelWidget<QCheckBox>("Negate", "negate"); rEdit_->setToolTip("Red model number"); rNeg_ ->setToolTip("Invert red model value"); rLayout->addWidget(rEdit_); rLayout->addWidget(rNeg_); addLabelWidget("R", rFrame_); //--- gFrame_ = CQUtil::makeWidget<QFrame>("gFrame"); auto *gLayout = CQUtil::makeLayout<QHBoxLayout>(gFrame_, 0, 2); gEdit_ = CQUtil::makeWidget<CQColorsEditModel>("gEdit"); gNeg_ = CQUtil::makeLabelWidget<QCheckBox>("Negate", "negate"); gEdit_->setToolTip("Green model number"); gNeg_ ->setToolTip("Invert green model value"); gLayout->addWidget(gEdit_); gLayout->addWidget(gNeg_); addLabelWidget("G", gFrame_); //--- bFrame_ = CQUtil::makeWidget<QFrame>("bFrame"); auto *bLayout = CQUtil::makeLayout<QHBoxLayout>(bFrame_, 0, 2); bEdit_ = CQUtil::makeWidget<CQColorsEditModel>("bEdit"); bNeg_ = CQUtil::makeLabelWidget<QCheckBox>("Negate", "negate"); bEdit_->setToolTip("Blue model number"); bNeg_ ->setToolTip("Invert blue model value"); bLayout->addWidget(bEdit_); bLayout->addWidget(bNeg_); addLabelWidget("B", bFrame_); //--- valueEdit_ = CQUtil::makeWidget<CQRealSpin>("valueEdit"); valueEdit_->setToolTip("Palette, interface or contrast value (0-1 if not scaled)"); addCheckWidget("Value", valueEdit_); valueCheck_ = qobject_cast<QCheckBox *>(widgetLabels_[valueEdit_]); //--- colorEdit_ = CQUtil::makeWidget<CQColorEdit>("colorEdit"); colorEdit_->setToolTip("Explicit color name"); addLabelWidget("Color", colorEdit_); //--- scaleCheck_ = CQUtil::makeWidget<CQCheckBox>("scaleCheck"); scaleCheck_->setToolTip("Rescale value from palette x range"); addLabelWidget("Scale", scaleCheck_); //--- invertCheck_ = CQUtil::makeWidget<CQCheckBox>("invertCheck"); invertCheck_->setToolTip("Invert palette color value"); addLabelWidget("Invert", invertCheck_); //--- layout->setRowStretch(row, 1); layout->setColumnStretch(2, 1); //--- connectSlots(true); setFixedHeight(CQChartsColorEdit::minimumSizeHint().height()); updateState(); } void CQChartsColorEdit:: setColor(const CQChartsColor &color) { color_ = color; colorToWidgets(); updateState(); emit colorChanged(); } void CQChartsColorEdit:: setNoFocus() { //colorEdit_->setNoFocus(); typeCombo_ ->setFocusPolicy(Qt::NoFocus); //indEdit_ ->setFocusPolicy(Qt::NoFocus); //valueEdit_ ->setFocusPolicy(Qt::NoFocus); valueCheck_ ->setFocusPolicy(Qt::NoFocus); scaleCheck_ ->setFocusPolicy(Qt::NoFocus); invertCheck_->setFocusPolicy(Qt::NoFocus); } void CQChartsColorEdit:: connectSlots(bool b) { assert(b != connected_); connected_ = b; //--- auto connectDisconnect = [&](QWidget *w, const char *from, const char *to) { CQChartsWidgetUtil::connectDisconnect(connected_, w, from, this, to); }; connectDisconnect(typeCombo_ , SIGNAL(currentIndexChanged(int)), SLOT(widgetsToColor())); connectDisconnect(indPalCombo_, SIGNAL(currentIndexChanged(int)), SLOT(indPalSlot(int))); connectDisconnect(indEdit_ , SIGNAL(valueChanged(int)), SLOT(widgetsToColor())); connectDisconnect(paletteEdit_, SIGNAL(currentIndexChanged(int)), SLOT(widgetsToColor())); connectDisconnect(rEdit_ , SIGNAL(currentIndexChanged(int)), SLOT(widgetsToColor())); connectDisconnect(rNeg_ , SIGNAL(stateChanged(int)), SLOT(widgetsToColor())); connectDisconnect(gEdit_ , SIGNAL(currentIndexChanged(int)), SLOT(widgetsToColor())); connectDisconnect(gNeg_ , SIGNAL(stateChanged(int)), SLOT(widgetsToColor())); connectDisconnect(bEdit_ , SIGNAL(currentIndexChanged(int)), SLOT(widgetsToColor())); connectDisconnect(bNeg_ , SIGNAL(stateChanged(int)), SLOT(widgetsToColor())); connectDisconnect(valueEdit_ , SIGNAL(valueChanged(double)), SLOT(widgetsToColor())); connectDisconnect(valueCheck_ , SIGNAL(stateChanged(int)), SLOT(widgetsToColor())); connectDisconnect(colorEdit_ , SIGNAL(colorChanged(const QColor &)), SLOT(widgetsToColor())); connectDisconnect(scaleCheck_ , SIGNAL(stateChanged(int)), SLOT(widgetsToColor())); connectDisconnect(invertCheck_, SIGNAL(stateChanged(int)), SLOT(widgetsToColor())); } void CQChartsColorEdit:: colorToWidgets() { connectSlots(false); if (color_.isValid()) { bool hasValue = false; if (color_.type() == CQChartsColor::Type::PALETTE || color_.type() == CQChartsColor::Type::PALETTE_VALUE) { typeCombo_->setCurrentIndex(1); if (color_.hasPaletteIndex()) { indPalStack_->setCurrentIndex(0); indPalCombo_->setCurrentIndex(0); indEdit_ ->setValue(color_.ind()); } else if (color_.hasPaletteName()) { indPalStack_->setCurrentIndex(1); indPalCombo_->setCurrentIndex(1); QString name; if (color_.getPaletteName(name)) paletteEdit_->setCurrentIndex(paletteEdit_->findText(name)); else paletteEdit_->setCurrentIndex(0); } else { indPalStack_->setCurrentIndex(0); indPalCombo_->setCurrentIndex(0); indEdit_ ->setValue(-1); } hasValue = (color_.type() == CQChartsColor::Type::PALETTE_VALUE); if (hasValue) scaleCheck_->setChecked(color_.isScale()); else scaleCheck_->setChecked(false); invertCheck_->setChecked(color_.isInvert()); } else if (color_.type() == CQChartsColor::Type::INDEXED || color_.type() == CQChartsColor::Type::INDEXED_VALUE) { typeCombo_->setCurrentIndex(2); if (color_.hasPaletteIndex()) { indPalStack_->setCurrentIndex(0); indPalCombo_->setCurrentIndex(0); indEdit_ ->setValue(color_.ind()); } else if (color_.hasPaletteName()) { indPalStack_->setCurrentIndex(1); indPalCombo_->setCurrentIndex(1); QString name; if (color_.getPaletteName(name)) paletteEdit_->setCurrentIndex(paletteEdit_->findText(name)); else paletteEdit_->setCurrentIndex(0); } else { indPalStack_->setCurrentIndex(0); indPalCombo_->setCurrentIndex(0); indEdit_ ->setValue(-1); } hasValue = (color_.type() == CQChartsColor::Type::INDEXED_VALUE); invertCheck_->setChecked(color_.isInvert()); } else if (color_.type() == CQChartsColor::Type::INTERFACE || color_.type() == CQChartsColor::Type::INTERFACE_VALUE) { typeCombo_->setCurrentIndex(3); hasValue = (color_.type() == CQChartsColor::Type::INTERFACE_VALUE); } else if (color_.type() == CQChartsColor::Type::CONTRAST || color_.type() == CQChartsColor::Type::CONTRAST_VALUE) { typeCombo_->setCurrentIndex(4); hasValue = (color_.type() == CQChartsColor::Type::INTERFACE_VALUE); } else if (color_.type() == CQChartsColor::Type::MODEL || color_.type() == CQChartsColor::Type::MODEL_VALUE) { typeCombo_->setCurrentIndex(5); int r, g, b; color_.getModelRGB(r, g, b); rEdit_->setCurrentIndex(std::abs(r)); gEdit_->setCurrentIndex(std::abs(g)); bEdit_->setCurrentIndex(std::abs(b)); rNeg_->setChecked(r < 0); gNeg_->setChecked(g < 0); bNeg_->setChecked(b < 0); hasValue = (color_.type() == CQChartsColor::Type::MODEL_VALUE); } else if (color_.type() == CQChartsColor::Type::LIGHTER || color_.type() == CQChartsColor::Type::LIGHTER_VALUE) { typeCombo_->setCurrentIndex(6); hasValue = (color_.type() == CQChartsColor::Type::LIGHTER_VALUE); } else if (color_.type() == CQChartsColor::Type::DARKER || color_.type() == CQChartsColor::Type::DARKER_VALUE) { typeCombo_->setCurrentIndex(7); hasValue = (color_.type() == CQChartsColor::Type::DARKER_VALUE); } else if (color_.type() == CQChartsColor::Type::COLOR) { typeCombo_->setCurrentIndex(8); colorEdit_->setColor(color_.color()); } //--- valueCheck_->setChecked(hasValue); if (hasValue) valueEdit_->setValue(color_.value()); else valueEdit_->setValue(0.0); valueEdit_->setEnabled(valueCheck_->isChecked()); } else { typeCombo_->setCurrentIndex(0); } connectSlots(true); } void CQChartsColorEdit:: widgetsToColor() { int typeInd = typeCombo_->currentIndex(); CQChartsColor color; if (typeInd == 1) { if (valueCheck_->isChecked()) color = CQChartsColor(CQChartsColor::Type::PALETTE_VALUE); else color = CQChartsColor(CQChartsColor::Type::PALETTE); if (indPalStack_->currentIndex() == 0) color.setInd(indEdit_->value()); else color.setPaletteName(paletteEdit_->currentText()); if (valueCheck_->isChecked()) { if (scaleCheck_->isChecked()) color.setScaleValue(CQChartsColor::Type::PALETTE_VALUE, valueEdit_->value(), true); else color.setValue(CQChartsColor::Type::PALETTE_VALUE, valueEdit_->value()); } if (invertCheck_->isChecked()) color.setInvert(true); } else if (typeInd == 2) { if (valueCheck_->isChecked()) color = CQChartsColor(CQChartsColor::Type::INDEXED_VALUE); else color = CQChartsColor(CQChartsColor::Type::INDEXED); if (indPalStack_->currentIndex() == 0) color.setInd(indEdit_->value()); else color.setPaletteName(paletteEdit_->currentText()); if (valueCheck_->isChecked()) color.setValue(CQChartsColor::Type::INDEXED_VALUE, valueEdit_->value()); if (invertCheck_->isChecked()) color.setInvert(true); } else if (typeInd == 3) { if (valueCheck_->isChecked()) color = CQChartsColor(CQChartsColor::Type::INTERFACE_VALUE); else color = CQChartsColor(CQChartsColor::Type::INTERFACE); if (valueCheck_->isChecked()) color.setValue(CQChartsColor::Type::INTERFACE_VALUE, valueEdit_->value()); } else if (typeInd == 4) { if (valueCheck_->isChecked()) color = CQChartsColor(CQChartsColor::Type::CONTRAST_VALUE); else color = CQChartsColor(CQChartsColor::Type::CONTRAST); if (valueCheck_->isChecked()) color.setValue(CQChartsColor::Type::CONTRAST_VALUE, valueEdit_->value()); } else if (typeInd == 5) { if (valueCheck_->isChecked()) color = CQChartsColor(CQChartsColor::Type::MODEL_VALUE); else color = CQChartsColor(CQChartsColor::Type::MODEL); int r = rEdit_->currentIndex(); if (rNeg_->isChecked()) r = -r; int g = gEdit_->currentIndex(); if (gNeg_->isChecked()) g = -g; int b = bEdit_->currentIndex(); if (bNeg_->isChecked()) b = -b; color.setModelRGB(r, g, b); if (valueCheck_->isChecked()) color.setValue(CQChartsColor::Type::MODEL_VALUE, valueEdit_->value()); } else if (typeInd == 6) { if (valueCheck_->isChecked()) color = CQChartsColor(CQChartsColor::Type::LIGHTER_VALUE); else color = CQChartsColor(CQChartsColor::Type::LIGHTER); if (valueCheck_->isChecked()) color.setValue(CQChartsColor::Type::LIGHTER_VALUE, valueEdit_->value()); } else if (typeInd == 7) { if (valueCheck_->isChecked()) color = CQChartsColor(CQChartsColor::Type::DARKER_VALUE); else color = CQChartsColor(CQChartsColor::Type::DARKER); if (valueCheck_->isChecked()) color.setValue(CQChartsColor::Type::DARKER_VALUE, valueEdit_->value()); } else if (typeInd == 8) { color = CQChartsColor(CQChartsColor::Type::COLOR); auto c = colorEdit_->color(); if (c.isValid()) color.setColor(c); } color_ = color; //--- updateState(); emit colorChanged(); } void CQChartsColorEdit:: indPalSlot(int ind) { indPalStack_->setCurrentIndex(ind); } void CQChartsColorEdit:: updateState() { auto setEditVisible = [&](QWidget *w, bool visible) { w->setVisible(visible); w->setEnabled(visible); widgetLabels_[w]->setVisible(visible); }; setEditVisible(indPalStack_, false); setEditVisible(rFrame_ , false); setEditVisible(gFrame_ , false); setEditVisible(bFrame_ , false); setEditVisible(valueEdit_ , false); setEditVisible(colorEdit_ , false); setEditVisible(scaleCheck_ , false); setEditVisible(invertCheck_, false); if (color_.isValid()) { if (color_.type() == CQChartsColor::Type::PALETTE || color_.type() == CQChartsColor::Type::PALETTE_VALUE) { setEditVisible(indPalStack_, true); setEditVisible(valueEdit_ , true); setEditVisible(invertCheck_, true); if (color_.type() == CQChartsColor::Type::PALETTE_VALUE) setEditVisible(scaleCheck_, true); } else if (color_.type() == CQChartsColor::Type::INDEXED || color_.type() == CQChartsColor::Type::INDEXED_VALUE) { setEditVisible(indPalStack_, true); setEditVisible(valueEdit_ , true); setEditVisible(invertCheck_, true); } else if (color_.type() == CQChartsColor::Type::INTERFACE || color_.type() == CQChartsColor::Type::INTERFACE_VALUE) { setEditVisible(valueEdit_, true); } else if (color_.type() == CQChartsColor::Type::CONTRAST || color_.type() == CQChartsColor::Type::CONTRAST_VALUE) { setEditVisible(valueEdit_, true); } else if (color_.type() == CQChartsColor::Type::MODEL || color_.type() == CQChartsColor::Type::MODEL_VALUE) { setEditVisible(rFrame_ , true); setEditVisible(gFrame_ , true); setEditVisible(bFrame_ , true); setEditVisible(valueEdit_, true); } else if (color_.type() == CQChartsColor::Type::LIGHTER || color_.type() == CQChartsColor::Type::LIGHTER_VALUE) { setEditVisible(valueEdit_, true); } else if (color_.type() == CQChartsColor::Type::DARKER || color_.type() == CQChartsColor::Type::DARKER_VALUE) { setEditVisible(valueEdit_, true); } else if (color_.type() == CQChartsColor::Type::COLOR) { setEditVisible(colorEdit_, true); } } valueEdit_->setEnabled(valueCheck_->isChecked()); } QSize CQChartsColorEdit:: sizeHint() const { auto s1 = CQChartsEditBase::sizeHint(); auto s2 = minimumSizeHint(); return QSize(s1.width(), s2.height()); } QSize CQChartsColorEdit:: minimumSizeHint() const { QFontMetrics fm(font()); int eh = fm.height() + 4; return QSize(0, eh*8); }
24.483184
96
0.670772
[ "object", "model" ]