blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a3917f30c4eaa36b77795b919dd0ad1a1bd43d13 | ec76c1297252070d72fd194baebca3146bafac59 | /damBreak_laminar/damBreak/3.7/uniform/time | e0cadc4b0d41a09015bb8f22f440f794b207787c | [] | no_license | Shivam-IITKGP/CFD_InterFoam_BottleFill | 413cdb5536cf71d95da882821fa36c7bd138e17e | be711e0f19a5331bb1094b8e54982c9ad101da5c | refs/heads/main | 2023-04-13T12:58:09.332312 | 2021-04-15T16:24:42 | 2021-04-15T16:24:42 | 358,315,309 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 836 | /*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Version: 8
\\/ M anipulation |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class dictionary;
location "3.7/uniform";
object time;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
value 3.70000000000000018;
name "3.7";
index 9921;
deltaT 0.000396226;
deltaT0 0.000396226;
// ************************************************************************* //
| [
"shivamshahi12@gmail.com"
] | shivamshahi12@gmail.com | |
448fe5b8fa78c7644f2aed5c1146fe6704b14455 | 02d76740ebcde2b25967585b84d8ccaef3c96834 | /NetworkingProject/Tutorial 7/Tutorial 7/Tut 7 - Server/Tut 7 - Server/Circle.h | 3b6bb2110193de14c5f4509753bba765a5b83c44 | [] | no_license | sybek96/OnlineGameTech | 7a8417d8be321dad9f4f685f4d7d8b5694fc3202 | f66f7d6a50befb30667cff7cf6ce973e7db80739 | refs/heads/master | 2020-04-07T20:56:29.753055 | 2018-12-06T19:30:23 | 2018-12-06T19:30:23 | 158,708,626 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 447 | h | #pragma once
#include <SDL.h>
#undef main //some weird vodoo magic with sdl sdl_main is included automatically so have to do this define
enum class Color { RED, BLUE, GREEN };
class Circle
{
public:
Circle();
Circle(int rad, int x, int y, Color _col);
~Circle();
void draw(SDL_Renderer* renderer);
void setTexture(SDL_Texture* _tex);
int m_radius;
int m_xPos;
int m_yPos;
Color m_color;
SDL_Texture* texture;
SDL_Rect playerRect;
};
| [
"sybek96@interia.pl"
] | sybek96@interia.pl |
024584580390540860d4e5475c9de6e06de1c5c2 | ff5439a3960f58588db0743155f4783691a7e684 | /memfnwithpar.cpp | d22e7f4dca5a93714a80a1d3c353514a164701cb | [] | no_license | rahul2412/C_plus_plus | e693c8b4bd8e9bd489b864c79107f7215e0c2306 | f9c61139f3af0564aa4c05de3eaf469558530197 | refs/heads/master | 2021-04-28T08:13:33.811134 | 2018-02-20T19:36:57 | 2018-02-20T19:36:57 | 122,244,448 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 358 | cpp | #include <iostream>
using namespace std;
class part{
int model_no;
int part_no;
float cost;
public:
void setpart(int mn,int pn,float c)
{ model_no=mn;
part_no=pn;
cost=c;}
void display() {
cout<<"modelno="<<model_no<<"\n"<<"part-no="<<part_no<<"\n"<<"cost="<<cost<<"\n";
}};
main()
{
part o1;
o1.setpart(245,373,215.5);
o1.display();}
| [
"noreply@github.com"
] | noreply@github.com |
fdd3d446db678b00615829aea3b2abf270925fa8 | 9997cb296b19a9ae3149484caa2290c26c1f030a | /boj/17611/17611.cpp14.cpp | b9a4b62a32c305f77a0cfa9281a34cff286a47d7 | [] | no_license | pukuba/Algorithm | 0eca36297a5a278e666cb2d851bd0a4c99e11357 | ea71d0e21534a2a54626fc89da58e58ea8eb1791 | refs/heads/master | 2023-06-03T05:54:43.564074 | 2021-06-23T02:26:06 | 2021-06-23T02:26:06 | 317,562,256 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,073 | cpp | #include <bits/stdc++.h>
using namespace std;
int n,inf=500002;
typedef long long ll;
ll ans;
vector<pair<int,int> > v;
void update_lazy(vector<ll> &tree,vector<ll> &lazy,int node,int start,int end){
if(lazy[node]){
tree[node] += (end-start+1) * lazy[node];
if(start != end){
lazy[node*2] += lazy[node];
lazy[node*2+1] += lazy[node];
}
lazy[node] = 0;
}
}
ll update_range(vector<ll> &tree,vector<ll> &lazy,int node,int start,int end,int left,int right){
update_lazy(tree,lazy,node,start,end);
if(start > right || end < left) return tree[node];
if(left <= start && end <= right){
lazy[node]++;
return tree[node];
}
return tree[node] = update_range(tree,lazy,node*2,start,start+end>>1,left,right) + update_range(tree,lazy,node*2+1,(start+end>>1)+1,end,left,right);
}
ll query(vector<ll> &tree,vector<ll> &lazy,int node,int start,int end,int left,int right){
update_lazy(tree,lazy,node,start,end);
if(start > right || end < left) return 0;
if(left <= start && end <= right) return tree[node];
return query(tree,lazy,node*2,start,start+end>>1,left,right) + query(tree,lazy,node*2+1,(start+end>>1)+1,end,left,right);
}
int main(){
ios_base::sync_with_stdio(0);cin.tie(nullptr);
vector<ll> tree_x(4444444),tree_y(4444444),lazy_x(4444444),lazy_y(4444444);
cin>>n;
for(int i=1; i<=n; i++){
int x,y;
cin>>x>>y;
v.push_back({x,y});
}
v.push_back(v[0]);
for(int i=1; i<=n; i++){
if(v[i].first != v[i-1].first) update_range(tree_x,lazy_x,1,0,inf*2-1,min(v[i].first,v[i-1].first)+1+inf,max(v[i].first,v[i-1].first)+inf);
if(v[i].second !=v[i-1].second)
update_range(tree_y,lazy_y,1,0,inf*2-1,min(v[i].second,v[i-1].second)+1+inf,max(v[i].second,v[i-1].second)+inf);
}
for(int i=-inf; i<inf; i++) ans = max({ans,query(tree_x,lazy_x,1,0,inf*2-1,i+inf,i+inf),query(tree_y,lazy_y,1,0,inf*2-1,i+inf,i+inf)});
cout<<ans;
}
| [
"20sunrin041@sunrint.hs.kr"
] | 20sunrin041@sunrint.hs.kr |
71b60201b2d1ade6ca23d22e4a1a749aaf7fa126 | 693811a42e45213701193b8a0d53e700d3763ca4 | /account.cpp | f01d71a267f61c99f15d888eb86a6797688a6451 | [] | no_license | mjaber39/object-oriented-programming-exercises | 998d21b59c61ebe28526042edeee4c67548317e1 | 680955948719ea07bf4e914bdb3150b965dcd3e8 | refs/heads/master | 2021-04-07T07:27:43.750948 | 2020-03-20T03:12:56 | 2020-03-20T03:12:56 | 248,657,356 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 738 | cpp | #include <iostream> //adding io file
#include "account.hpp" //adding header file
using namespace std;
account::account (double initialBalance)
{
if (initialBalance >= 0.00)
balance = initialBalance;
else
{
cout <<"Negative Balance" << endl;
balance = 0.0;
}
}
void account::credit (double amount)
{
balance = balance + amount;
}
bool account::debit (double amount)
{
if (amount > balance)
{
cout << "Balance amount exceeded account balance." <<endl;
return false;
}
else
{
balance = balance - amount;
return true;
}
}
void account::setBalance(double newBalance)
{
balance = newBalance;
}
double account::getBalance()
{
return balance;
}
| [
"noreply@github.com"
] | noreply@github.com |
d36e092feb90bc736093a61b0982d1dad89f1742 | c1bd3126cbc16011b8e91d6d227de83494cffdae | /DualModeEEELink.cpp | bf40d7c6bf537b64748e7072565b960b88a837c5 | [] | no_license | mehrganm/DualModeEEESim | 259cc71cdb08d59bfd75e814b90c89cf10b1d87d | 7fec7d4cc26ff19e774bb926665eb982c5a5ca3b | refs/heads/master | 2021-01-21T11:56:29.648493 | 2017-05-23T01:57:50 | 2017-05-23T01:57:50 | 91,763,290 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,011 | cpp | #include "DualModeEEELink.h"
DualModeEEELink::DualModeEEELink (std::string name, double cap) : SleepLink(name, cap)
{
P_Active = 100.00;
P_FastWake = 70.00;
P_DeepSleep = 10.00;
P_AtoF = P_FtoD = P_DtoA = P_FtoA = P_AtoD = 100.00;
T_AtoF = 0.18e-6;
T_FtoD = 0.72e-6;
T_DtoA = 5.50e-6;
T_FtoA = 0.34e-6;
T_AtoD = 0.90e-6;
curMode = Active;
DFlag = true;
evtLinkActive = new event ("The link is ACTIVE");
B_event = new event ("A burst is complete");
tblDelay = new table ("Packet delay table");
tblQWait = new table ("Packet waiting time in the queue table");
tblActive = new table("Time in Active");
tblFastWake = new table ("Time in Fast Wake");
tblDeepSleep = new table ("Time in Deep Sleep");
tblAtoF = new table ("Time in AtoF");
tblFtoD = new table ("Time in FtoD");
tblDtoA = new table ("Time in DtoA");
tblFtoA = new table ("Time in FtoA");
tblAtoD = new table ("Time in AtoD");
evtLinkActive->clear();
B_event->clear();
}
DualModeEEELink::~DualModeEEELink ()
{
delete Server;
delete evtLinkActive;
}
void DualModeEEELink::connectLink (DualModeEEELink * conLink)
{
nextlink = conLink;
}
void DualModeEEELink::setCoalParams (double t_idle, double t_coal, unsigned int s_coal, unsigned int s_lim)
{
T_Idle = t_idle;
T_Coal = t_coal;
S_Coal = s_coal;
S_Lim = s_lim;
}
bool DualModeEEELink::chkCondDSFirstArrival(Packet * pkt)
{
int ret;
if (B_event->event_qlen() == 0) // If the first packet in the burst, set a burst timer
{
printf ("%.3f: First Packet (seq %d) in the burst, timer set to %f us, expires at %.3f\n", clock*1.0e+6, pkt->getSeqNum(), T_Coal*1.0e+6, (clock + T_Coal)*1.0e+6);
B_event->clear(); // If you don't clear it the event will be in the OCCURED state and the next wait will resume immediately
ret = B_event->timed_wait(T_Coal); // Set the timer
if (ret == TIMED_OUT) // If triggered due to timer expiration
{
if (B_event->event_qlen()+1 <= S_Lim)
DFlag = true;
else
DFlag = false;
printf ("%.3f: Burst timer expired, # of pkts in burst: %d, DFlag set to %s\n", clock*1.0e+6, B_event->event_qlen()+1, DFlag==true?"TRUE":"FALSE");
B_event->set(); // Burst to queue
wakeupFromDS(pkt);
}
return true;
}
else
return false;
}
bool DualModeEEELink::chkCondDSBurstFull(Packet * pkt)
{
//assert(curMode == DeepSleep);
if (B_event->event_qlen() >= (S_Coal-1)) // If reached burst size
{
if (B_event->event_qlen()+1 <= S_Lim)
DFlag = true;
else
DFlag = false;
printf ("%.3f: Burst buffer full, # of pkts in burst: %d, DFlag set to %s \n", clock*1.0e+6, B_event->event_qlen()+1, DFlag==true?"TRUE":"FALSE");
B_event->set(); // Burst to queue
wakeupFromDS(pkt);
return true;
}
else
return false;
}
bool DualModeEEELink::chkCondBufferEmpty(Packet * pkt)
{
assert(curMode == Active);
if ( (Server->qlength() == 0) && (DFlag == true) )
{
printf ("%.3f: Link buffer empty. Link is going to Deep Sleep...\n", clock*1.0e+6);
putToDSFromA();
return true;
}
else if ( (Server->qlength() == 0) && (DFlag == false) )
{
printf ("%.3f: Link buffer empty. Link is going to Fast Wake...\n", clock*1.0e+6);
putToFWFromA();
stayInFW(T_Idle);
if (B_event->event_qlen() == 0) // Still no packets in the buffer, go to DS directly
{
printf ("%.3f: Fast Wake Timeout, no pkts in the buffer, link is going to deep sleep... Spent %.3f us in FAST WAKE.\n", clock*1.0e+6, (clock - stateChange)*1.0e+6);
putToDSFromFW();
}
else // Some pkts in the buffer while in FW, go to Active
{
if (B_event->event_qlen()+1 <= S_Lim)
DFlag = true;
else
DFlag = false;
printf ("%.3f: Fast Wake Timeout, # of pkts in burst: %d, DFlag set to %s \n", clock*1.0e+6, B_event->event_qlen(), DFlag==true?"TRUE":"FALSE");
B_event->set();
wakeupFromFW();
}
return true;
}
else
return false;
}
void DualModeEEELink::putToDSFromFW()
{
assert(curMode == FastWake);
curMode = TransFtoD; stateChange = clock;
hold(T_FtoD);
tblFtoD->record(clock - stateChange);
curMode = DeepSleep; stateChange = clock;
printf ("%.3f: Link is in DEEP SLEEP state. %d packet(s) arrived while transitioning to DEEP SLEEP. \n", clock*1.0e+6, B_event->event_qlen());
}
void DualModeEEELink::putToDSFromA()
{
assert(curMode == Active);
create("putToDSFromA");
tblActive->record(clock - stateChange);
curMode = TransAtoD; stateChange = clock;
hold(T_AtoD);
tblAtoD->record(clock - stateChange);
curMode = DeepSleep; stateChange = clock;
printf ("%.3f: Link is in DEEP SLEEP state. %d packet(s) arrived while transitioning to DEEP SLEEP. \n", clock*1.0e+6, B_event->event_qlen());
}
void DualModeEEELink::putToFWFromA()
{
tblActive->record(clock - stateChange);
curMode = TransAtoF; stateChange = clock;
hold(T_AtoF);
tblAtoF->record(clock - stateChange);
curMode = FastWake; stateChange = clock;
printf ("%.3f: Link is in FAST WAKE. Will go to DEEP SLEEP at %.3f us if buffer empty by then. %d pkt(s) arrived while transitioning to FAST WAKE.\n", clock*1.0e+6, (clock + T_Idle)*1.0e+6, B_event->event_qlen());
}
void DualModeEEELink::stayInFW(double tm)
{
assert(curMode == FastWake);
hold (tm);
tblFastWake->record(clock - stateChange);
}
void DualModeEEELink::wakeupFromFW()
{
assert(curMode == FastWake);
create("wakeupFromFW");
printf ("%.3f: Link is waking up from Fast Wake...\n", clock*1.0e+6);
curMode = TransFtoA; stateChange = clock;
hold(T_FtoA);
tblFtoA->record(clock - stateChange);
curMode = Active; stateChange = clock;
printf ("%.3f: Link is in the ACTIVE state. \n", clock*1.0e+6);
//printf ("%.3f: About to start serving packets starting at seq #%ld in this busy period\n", clock*1.0e+6, pkt->getSeqNum());
evtLinkActive->set();
}
void DualModeEEELink::wakeupFromDS(Packet * pkt)
{
assert((curMode == TransAtoD) || (curMode == TransFtoD) || (curMode == DeepSleep) || (curMode == TransDtoA));
if (curMode == TransDtoA)
{
printf ("%.3f: Link in transition DtoA. Waiting until it becomes active again.\n", clock*1.0e+6);
return;
}
create("wakeupFromDS");
tblDeepSleep->record(clock - stateChange);
printf ("%.3f: Link is waking up from Deep Sleep, triggered by pkt %ld...\n", clock*1.0e+6, pkt->getSeqNum());
curMode = TransDtoA; stateChange = clock;
hold(T_DtoA);
tblDtoA->record(clock - stateChange);
curMode = Active; stateChange = clock;
printf ("%.3f: Link is in the ACTIVE state. \n", clock*1.0e+6);
evtLinkActive->set();
}
void DualModeEEELink::processPacket(Packet * pkt)
{
char * temp_str = new char[pkt->getName().length()+1];
pkt->getName().copy(temp_str,pkt->getName().length());
temp_str[pkt->getName().length()] = '\0';
create(temp_str);
printf ("%.3f: %s: Pkt %ld entered the link \n", clock*1.0e+6, my_name.c_str(), pkt->getSeqNum());
set_priority (ULONG_MAX - pkt->getSeqNum());
if ( curMode == Active )
{
}
else if ( (curMode == TransFtoA) || (curMode == TransDtoA) )
{
printf ("%.3f: Packet %ld arrived to a link in transition to ACTIVE, waiting... \n", clock*1.0e+6, pkt->getSeqNum());
evtLinkActive->wait();
}
else if ( (curMode == FastWake) || (curMode == TransAtoF) )
{
printf ("%.3f: (seq %d) Waiting in the buffer with %d other pkts\n", clock*1.0e+6, pkt->getSeqNum(), B_event->wait_cnt());
B_event->wait(); // Add the pkt to burst buffer
evtLinkActive->wait();
}
else if ( (curMode == DeepSleep) || (curMode == TransAtoD) || (curMode == TransFtoD))
{
if (!chkCondDSFirstArrival(pkt) && !chkCondDSBurstFull(pkt))
{
printf ("%.3f: Link not Active, (seq %ld) Waiting in the buffer with %d other pkts\n", clock*1.0e+6, pkt->getSeqNum(), B_event->wait_cnt());
B_event->wait(); // Add the pkt to burst buffer
}
evtLinkActive->wait();
}
Server->reserve();
tblQWait->record(clock - pkt->getOrgTime());
hold ((double)pkt->getLength()/capacity);
printf ("%.3f: Packet %ld served, arrived at %.3f, Delay = %.3f us\n", clock*1.0e+6, pkt->getSeqNum(), 0, pkt->getOrgTime()*1.0e+6, (clock - pkt->getOrgTime())*1.0e+6);
tblDelay->record(clock - pkt->getOrgTime());
if (nextlink)
{
printf ("%.3f: %s: Packet %ld will enter %s now\n", clock*1.0e+6, my_name.c_str(), pkt->getSeqNum(), nextlink->getName().c_str());
//newPacket = new packet(clock, curr_sq, 12000, 0, my_name + std::string(":") + std::to_string(curr_sq));
nextlink->processPacket(pkt);
}
chkCondBufferEmpty(pkt);
Server->release();
}
void DualModeEEELink::report()
{
printf("============================================================= \n");
printf("== Simulation of EEE link with two sleep modes == \n");
printf("============================================================= \n");
printf("= T_DtoA = %.3f us \n", T_DtoA*1.0e+6);
printf("= T_FtoA = %.3f us \n", T_FtoA*1.0e+6);
printf("= T_FtoD = %.3f us \n", T_FtoD*1.0e+6);
printf("= T_AtoF = %.3f us \n", T_AtoF*1.0e+6);
printf("= T_AtoD = %.3f us \n", T_AtoD*1.0e+6);
printf("=------------------------------------------------------------ \n");
printf("= Link Capacity = %.1f Gb/s \n", capacity/1.0e+9);
printf("= S_Coal = %d \n", S_Coal);
printf("= S_Lim = %d \n", S_Lim);
printf("= T_Idle = %.3f us \n", T_Idle*1.0e+6);
printf("= T_Coal = %.3f us \n", T_Coal*1.0e+6);
printf("============================================================= \n");
printf("= Time in Active = %2.6f \n", tblActive->sum()/clock);
printf("= Time in Deep Sleep = %2.6f \n", tblDeepSleep->sum()/clock);
printf("= Time in Fast Wake = %2.6f \n", tblFastWake->sum()/clock);
printf("= Time in AtoF = %2.6f \n", tblAtoF->sum()/clock);
printf("= Time in FtoD = %2.6f \n", tblFtoD->sum()/clock);
printf("= Time in DtoA = %2.6f \n", tblDtoA->sum()/clock);
printf("= Time in FtoA = %2.6f \n", tblFtoA->sum()/clock);
printf("= Time in AtoD = %2.6f \n", tblAtoD->sum()/clock);
printf("=------------------------------------------------------------ \n");
printf("= Total Completions = %d frames\n", Server->completions());
printf("= Mean num in system = %.3f pkts\n", Server->qlen());
printf("= Mean response time = %.3f us \n", Server->resp()*1.0e+6);
printf("= Mean service time = %.3f us \n", Server->serv()*1.0e+6);
printf("= Mean throughput = %.3f pkts/s\n",Server->tput());
printf("= Mean packet delay = %.3f us \n", tblDelay->mean()*1.0e+6);
printf("= Mean waiting time = %.3f us \n", tblQWait->mean()*1.0e+6);
//printf("= Power Consumption = %.3f % \n", pConsump);
printf("=------------------------------------------------------------ \n");
}
| [
"noreply@github.com"
] | noreply@github.com |
fc0acee9e7dc18a4c5b0e1da333478212e223fdd | 53580eaac1154e5389029a8a53a75aa4d9ee7dab | /basket-of-names/search-based/list/main.cpp | e33da693ad96464e80e906ada49430c17c8a282a | [
"MIT"
] | permissive | tommygod3/basket-of-names | bca41ec270f9e4df4a8c7b14a836f712f1a914af | 58bbdb58a79a073e762d7bb757780cc44dd2c700 | refs/heads/master | 2022-05-31T18:35:55.357461 | 2020-05-03T22:22:23 | 2020-05-03T22:22:23 | 241,130,257 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 250 | cpp | #include "search-based-list.h"
int main(int argc, char *argv[]) {
if (argc == 2)
{
SearchBasedList searchBasedList = SearchBasedList(argv[1]);
searchBasedList.createResults();
searchBasedList.printResults();
}
}
| [
"tommygod1@live.com"
] | tommygod1@live.com |
562fef1e176959c52dec78cfa4b234f343ad1cd9 | a3daa7f52385bc001683f87de6cc173ea8e2ac19 | /src/ProceduralEnvironment.h | db8cb52c40fdda8617084bedd2cd1e649167a244 | [] | no_license | teerzo/OpenGLProject | d1b68752b341b906fb116c55f4c371b8611ba040 | 8833520ccdef80be8b1fe3e5e88db3f214458031 | refs/heads/master | 2021-01-19T10:59:36.033185 | 2015-04-24T07:01:32 | 2015-04-24T07:01:32 | 30,327,181 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,233 | h | #ifndef _PROCEDURAL_ENVIRONMENT_H_
#define _PROCEDURAL_ENVIRONMENT_H_
#include "Application.h"
#include "RenderTarget.h"
#include "tiny_obj_loader.h"
#include "Emitter.h"
#include "../deps/FBXLoader/FBXFile.h"
class Building;
struct TestObject {
std::vector<OpenGLData> meshes;
FBXSkeleton* skeleton;
FBXAnimation* animation;
};
class ProceduralEnvironment : public Application
{
public:
Emitter emitter;
std::vector<glm::vec3>DEBUGNORMALS;
std::vector<glm::vec3>DEBUGPOSITIONS;
OpenGLData gridMesh;
unsigned int active_buffer;
unsigned int vao[2];
unsigned int vbo[2];
unsigned int grid_size;
float last_draw_time;
void CreateUpdateShader();
void DrawPerlin();
float *perlin_data;
unsigned int perlin_1_texture;
std::vector<Building*> buildings;
std::vector<MeshGroup*> soulspears;
MeshGroup* buildingBase;
MeshGroup* bunnyObject;
unsigned int dirt_texture;
unsigned int grass_texture;
unsigned int lava_texture;
unsigned int rock_texture;
unsigned int soulspear_texture;
glm::vec4 highest_position;
glm::vec4 lowest_position;
TwBar* tweakBarLighting;
// light tweak
glm::vec3 tweak_light_direction;
glm::vec3 tweak_light_color;
float tweak_light_intensity;
TwBar* tweakBarTerrain;
// Perlin tweak
glm::vec3 tweak_perlin_position;
float tweak_perlin_texture_size;
float tweak_perlin_mesh_size;
float tweak_perlin_height;
float tweak_perlin_octaves;
float tweak_perlin_persistance;
// Lava tweak
glm::vec3 tweak_lava_direction;
float tweak_lava_speed;
float tweak_rock_height;
float tweak_grass_height;
float tweak_lava_height;
float tweak_dirt_height;
RenderTarget gBuffer;
OpenGLData pointLight;
unsigned int gBufferProgramID;
unsigned int compositeProgramID;
unsigned int particleProgramID;
unsigned int perlinUpdateProgramID;
unsigned int perlinDrawProgramID;
unsigned int directionalLightProgramID;
unsigned int pointLightProgramID;
unsigned int spotLightProgramID;
// Animation
FBXFile* m_file;
TestObject m_pyro;
void GenerateGLMeshes( FBXFile* fbx, TestObject& object );
void EvaluateSkeleton( FBXAnimation* anim, FBXSkeleton* skeleton, float timer );
void UpdateBones( FBXSkeleton* skeleton );
void DrawParticles();
void DrawAnimation();
OpenGLData BuildGrid(glm::vec2 real_dims, glm::ivec2 dims);
OpenGLData BuildGridWithNormals(glm::vec2 real_dims, glm::ivec2 dims);
void BuildVertexGrid( glm::vec2 real_dims, glm::ivec2 dims );
bool BuildPerlinTexture( unsigned int* a_texture, const glm::ivec2 dims, const int octaves, const float persistance, const float offset );
double Perlin(double x, double y, double z);
virtual ~ProceduralEnvironment();
virtual void SetApplicationDefaults();
virtual bool ApplicationStartup();
virtual void ApplicationShutdown();
virtual void CheckInput();
virtual bool Update();
virtual void Draw();
virtual void DebugDraw();
void Reload();
void ReloadShaders();
void LoadShaders();
// Render Code
void RenderGeometry();
void RenderLights();
void DrawDirectionLight(const glm::vec3& a_direction, const glm::vec3& a_color);
void DrawPointLight(glm::vec3 a_position, float a_radius, glm::vec3 a_color);
void RenderComposite();
};
#endif // _PROCEDURAL_ENVIRONMENT_H_ | [
"teerzo@live.com.au"
] | teerzo@live.com.au |
55f1f69c26ce4d00b4274f3280e62800ea866613 | baab07b796f78d722991ef8ab941b989d92936fc | /p4/practica2.cpp | 3d78143ed5ca51197df8964e60eced3e20ebc065 | [] | no_license | cristinazuhe/InformaticaGrafica | ddf6d71dbe20fbb41a3ef8993d33c2e8de0f4c94 | 8b5d4b25dfdff8972356ac6bc6427629cc0b77cd | refs/heads/master | 2021-01-10T12:41:41.817369 | 2016-01-24T12:21:56 | 2016-01-24T12:21:56 | 44,780,229 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,224 | cpp | // *********************************************************************
// **
// ** Informática Gráfica, curso 2014-15
// **
// ** Práctica 2 (implementación)
// **
// *********************************************************************
#include <GL/glut.h>
#include "error-ogl.hpp"
#include "tuplas.hpp" // Tupla3f, Tupla4f, Tupla3i
#include "practica2.hpp"
#include "operacionesmalla.hpp"
#include <vector>
#include "file_ply_stl.hpp"
#include <iostream>
#include <math.h>
#define PI (3.141592653589793)
// ---------------------------------------------------------------------
// Se llama una vez al inicio, cuando ya se ha creado la ventana e
// incializado OpenGL. El PLY se debe cargar aquí.
MallaTVT mimallav;
void P2_Inicializar( int argc,char *argv[] )
{
if( argc!=4){
exit(-1);
}
//leemos el ply e introducimos los vertices en la malla.
ply::read_vertices( argv[2], mimallav.vertices_ply ); //leemos el archivo ply
double n_perfiles=strtod(argv[3],NULL); //leer el numero de perfiles a realizar
CrearObjetoRevolucion( &mimallav , n_perfiles);
CrearNormalesCaras( &mimallav);
CrearNormalesVertices( &mimallav);
}
bool activonormalcaras=false; //para representar las normales de las caras
bool activonormalvertices=false; //para represnetar las normales de los vertices
int orden2=9; //para indicar el modo de dibujo
void P2_ModificarOrdenAAlambre( ) { orden2=0;} //0-->alambre
void P2_ModificarOrdenAAjedrez( ) { orden2=1;} //1-->ajedrez
void P2_ModificarOrdenASolido( ) { orden2=2;} //2-->solido
void P2_ModificarOrdenAPuntos( ) { orden2=3;} //3-->puntos
void P2_ModificarPintarNormalesVertices() {orden2=4;} //4-->normalesvertices
void P2_ModificarPintarNormalesCaras() {orden2=5;} //5-->normalescaras
void P2_ActivoNormalCaras() { //para representar las normales de las caras
if(activonormalcaras)
activonormalcaras=false;
else
activonormalcaras=true;
}
void P2_ActivoNormalVertices() { //para represnetar las normales de los vertices
if(activonormalvertices)
activonormalvertices=false;
else
activonormalvertices=true;
}
void P2_DibujarObjetos( )
{
glEnableClientState( GL_VERTEX_ARRAY );
if(orden2==0)
VerMallaEnAlambre( &mimallav );
else if(orden2==2)
VerMallaEnSolido( &mimallav );
else if(orden2==1)
VerMallaEnAjedrez( &mimallav );
else if(orden2==3)
VerMallaEnPuntos( &mimallav );
else if(orden2==4)
PintarNormalesVertices( &mimallav ) ;
else if(orden2==5)
PintarNormalesCaras( &mimallav ) ;
if(activonormalcaras){
//pintamos las normales de las caras
glColor3f(1.0,0.0,0.0);
glVertexPointer( 3, GL_FLOAT, 0, mimallav.normales_car[0].coo);
glDrawArrays( GL_LINES , 0, (mimallav.num_caras/3)*2); //por cada cara tenemos dos vértices que nos dan la normal (el vertice baricentro y el vertice normal)
}
if(activonormalvertices){
//normales de los vertices;
glPointSize(5.0);
glColor3f(0.0,1.0,0.0);
glVertexPointer( 3, GL_FLOAT, 0, mimallav.normales_ver[0].coo);
glDrawArrays( GL_LINES , 0, ((mimallav.num_vertices)/3)*2);
}
}
| [
"zuhe18@gmail.com"
] | zuhe18@gmail.com |
fad40bd56599d7e574335b2e3a0eba01eb0f98ca | 90122236ae8101333bc036015bbb651fe624fca3 | /HeartBeatServer/main.cpp | 1ebdc1ae5e22892ed8cc52717dd4d046371c0325 | [] | no_license | mehome/HeartBeat | da1548542b39a29a2f451ebf33d8019bf8ca3e17 | 1f5bc298db8f7a12d803c050397c23c244cf3772 | refs/heads/master | 2021-09-11T01:27:39.343921 | 2018-04-05T17:02:29 | 2018-04-05T17:02:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 263 | cpp | // HeartBeatServer.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "IOCPHeartBeatServer.h"
int main()
{
IOCPHeartBeatServer server;
server.LoadSockLib();
server.Start();
getchar();
server.Stop();
return 0;
}
| [
"oatrx@aliyun.com"
] | oatrx@aliyun.com |
588b4341bbc87f9f9f07e8349e93a76f931dead6 | 9ee4c46df9c887801f4a498d9a08f4cd58825360 | /main.cpp | 8e92bb46f1e507649f87ee796f57914ef26a8418 | [] | no_license | lieuwex/editor | 76710ceb525f86977d4bda2e648fa49db0647f07 | 1ff40064765f6a5ed3b3cbfdee8238d54bae3abd | refs/heads/master | 2020-12-30T22:12:08.948773 | 2016-01-03T20:41:39 | 2016-01-03T20:41:39 | 49,026,758 | 0 | 0 | null | 2016-01-04T22:20:56 | 2016-01-04T22:20:56 | null | UTF-8 | C++ | false | false | 684 | cpp | #include <iostream>
#include <fstream>
#include <cstdlib>
#include <signal.h>
#include "io.h"
#include "screen.h"
#include "interface.h"
using namespace std;
bool screeninited=false;
string closemessage;
void siginthandler(int){
closemessage="Killed by ^C";
exit(130);
}
void atexitfunc(void){
if(screeninited)IO::endscreen();
if(closemessage.size())cout<<closemessage<<endl;
}
int main(int argc,char **argv){
signal(SIGINT,siginthandler);
atexit(atexitfunc);
ofstream logfile("editor.log");
cerr.rdbuf(logfile.rdbuf());
cerr<<string(5,'\n');
IO::initscreen();
screeninited=true;
int i;
for(i=1;i<argc;i++)Inter::addfilebufferfile(argv[i]);
return IO::runloop();
}
| [
"hallo@tomsmeding.nl"
] | hallo@tomsmeding.nl |
8386af1c5ca812669df4254a9f55f022084a9db5 | 27e3176cd523711212f371845151a5da9cd547dc | /Larduino_HSP_v3.6c/sketches/lgtdemo/dac1_ramp/dac1_ramp.ino | 0a4e40e712c30a6030626b2b8c05458423ef50c4 | [
"CC0-1.0"
] | permissive | andrewintw/automatic-sprayer | b839bdc8f507383119ec4a3b1a9cd5a673913465 | 1784059751cc839d316eb720809963adc00ca5ab | refs/heads/master | 2022-12-03T00:04:53.556155 | 2020-08-19T20:16:57 | 2020-08-19T20:16:57 | 277,870,842 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 437 | ino | //============================================
// Larduino w/ 328D
// DAC1 output demo
// DAC1 output ==> PE5 on board
//============================================
unsigned char value = 0;
void setup() {
// put your setup code here, to run once:
analogReference(INTERNAL2V56);
pinMode(DAC1, ANALOG);
}
void loop() {
// put your main code here, to run repeatedly:
analogWrite(DAC1, value);
delay(10);
value += 10;
}
| [
"andrew.lin@browan.com"
] | andrew.lin@browan.com |
b6ce604621778b01e93997b46d05fd2fef7f45ca | d6267a448e056b47d79cc716d18edec6dd91154c | /modules/platforms/cpp/core/include/ignite/cache/query/continuous/continuous_query.h | 781ce2ee47b31304b9b048c14ec0e4df1a1b5854 | [
"Apache-2.0",
"LicenseRef-scancode-gutenberg-2020",
"CC0-1.0",
"BSD-3-Clause"
] | permissive | sk8tz/ignite | 1635163cc2309aa0f9fd65734317af861679679f | 2774d879a72b0eeced862cc9a3fbd5d9c5ff2d72 | refs/heads/master | 2023-04-19T03:07:50.202953 | 2017-01-04T21:01:13 | 2017-01-04T21:01:13 | 78,094,618 | 0 | 0 | Apache-2.0 | 2023-04-17T19:45:36 | 2017-01-05T08:30:14 | Java | UTF-8 | C++ | false | false | 9,445 | h | /*
* 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.
*/
/**
* @file
* Declares ignite::cache::query::continuous::ContinuousQuery class.
*/
#ifndef _IGNITE_CACHE_QUERY_CONTINUOUS_CONTINUOUS_QUERY
#define _IGNITE_CACHE_QUERY_CONTINUOUS_CONTINUOUS_QUERY
#include <ignite/impl/cache/query/continuous/continuous_query_impl.h>
#include <ignite/cache/event/cache_entry_event_listener.h>
namespace ignite
{
namespace cache
{
// Forward-declaration.
template<typename K, typename V>
class IGNITE_IMPORT_EXPORT Cache;
namespace query
{
namespace continuous
{
/**
* Continuous query.
*
* Continuous queries allow to register a remote and a listener
* for cache update events. On any update to the related cache
* an event is sent to the node that has executed the query and
* listener is notified on that node.
*
* Continuous query can either be executed on the whole topology
* or only on local node.
*
* To execute the query over the cache use method
* ignite::cache::Cache::QueryContinuous().
*/
template<typename K, typename V>
class ContinuousQuery
{
friend class Cache<K, V>;
public:
/**
* Default value for the buffer size.
*/
enum { DEFAULT_BUFFER_SIZE = 1 };
/**
* Default value for the time interval.
*/
enum { DEFAULT_TIME_INTERVAL = 0 };
/**
* Destructor.
*/
~ContinuousQuery()
{
// No-op.
}
/**
* Constructor.
*
* @param lsnr Event listener. Invoked on the node where
* continuous query execution has been started.
*/
ContinuousQuery(Reference<event::CacheEntryEventListener<K, V> > lsnr) :
impl(new impl::cache::query::continuous::ContinuousQueryImpl<K, V>(lsnr))
{
// No-op.
}
/**
* Constructor.
*
* @param lsnr Event listener Invoked on the node where
* continuous query execution has been started.
* @param loc Whether query should be executed locally.
*/
ContinuousQuery(Reference<event::CacheEntryEventListener<K, V> > lsnr, bool loc) :
impl(new impl::cache::query::continuous::ContinuousQueryImpl<K, V>(lsnr, loc))
{
// No-op.
}
/**
* Set local flag.
*
* @param val Value of the flag. If true, query will be
* executed only on local node, so only local entries
* will be returned as query result.
*/
void SetLocal(bool val)
{
impl.Get()->SetLocal(val);
}
/**
* Get local flag.
*
* @return Value of the flag. If true, query will be
* executed only on local node, so only local entries
* will be returned as query result.
*/
bool GetLocal() const
{
return impl.Get()->GetLocal();
}
/**
* Set buffer size.
*
* When a cache update happens, entry is first
* put into a buffer. Entries from buffer will be sent to
* the master node only if the buffer is full or time
* provided via timeInterval is exceeded.
*
* @param val Buffer size.
*/
void SetBufferSize(int32_t val)
{
impl.Get()->SetBufferSize(val);
}
/**
* Get buffer size.
*
* When a cache update happens, entry is first
* put into a buffer. Entries from buffer will be sent to
* the master node only if the buffer is full or time
* provided via timeInterval is exceeded.
*
* @return Buffer size.
*/
int32_t GetBufferSize() const
{
return impl.Get()->GetBufferSize();
}
/**
* Set time interval.
*
* When a cache update happens, entry is first put into
* a buffer. Entries from buffer are sent to the master node
* only if the buffer is full (its size can be changed via
* SetBufferSize) or time provided via this method is
* exceeded.
*
* Default value is DEFAULT_TIME_INTERVAL, i.e. 0, which
* means that time check is disabled and entries will be
* sent only when buffer is full.
*
* @param val Time interval in miliseconds.
*/
void SetTimeInterval(int64_t val)
{
impl.Get()->SetTimeInterval(val);
}
/**
* Get time interval.
*
* When a cache update happens, entry is first put into
* a buffer. Entries from buffer are sent to the master node
* only if the buffer is full (its size can be changed via
* SetBufferSize) or time provided via SetTimeInterval
* method is exceeded.
*
* Default value is DEFAULT_TIME_INTERVAL, i.e. 0, which
* means that time check is disabled and entries will be
* sent only when buffer is full.
*
* @return Time interval.
*/
int64_t GetTimeInterval() const
{
return impl.Get()->GetTimeInterval();
}
/**
* Set cache entry event listener.
*
* @param val Cache entry event listener. Invoked on the
* node where continuous query execution has been
* started.
*/
void SetListener(Reference<event::CacheEntryEventListener<K, V> > lsnr)
{
impl.Get()->SetListener(lsnr);
}
/**
* Get cache entry event listener.
*
* @return Cache entry event listener.
*/
const event::CacheEntryEventListener<K, V>& GetListener() const
{
return impl.Get()->GetListener();
}
/**
* Get cache entry event listener.
*
* @return Cache entry event listener.
*/
event::CacheEntryEventListener<K, V>& GetListener()
{
return impl.Get()->GetListener();
}
private:
/** Implementation. */
common::concurrent::SharedPointer<impl::cache::query::continuous::ContinuousQueryImpl<K, V> > impl;
};
}
}
}
}
#endif //_IGNITE_CACHE_QUERY_CONTINUOUS_CONTINUOUS_QUERY | [
"ptupitsyn@apache.org"
] | ptupitsyn@apache.org |
6d375d6604e8423b1c1bbdb7fed7f421b5895694 | e75a08da68411448403ae4475f579168f5ca22f0 | /KDtree.cpp | 09bddf169e93f4da5e4297d9f030335f1b6a71f5 | [] | no_license | Isacarthuso/KDtree | 740152b6cf4899b52bc332143c637960bf862159 | 74202536394125b5f80cf0d7bb55657f0d49b6ac | refs/heads/master | 2022-12-24T17:18:02.096342 | 2020-09-27T20:00:55 | 2020-09-27T20:00:55 | 273,228,244 | 1 | 0 | null | 2020-09-27T18:46:55 | 2020-06-18T12:09:31 | C++ | UTF-8 | C++ | false | false | 17,131 | cpp | #include"KDtree.hpp"
No* ROOT;
//dimension = 0 -> 2D and dimension = 1 -> 3D
bool dimension;
void createKDtree(vector<vector<float>> points, bool dim)
{
vector<float> balancedPoint;
if(dim)
dimension = 1;
else
dimension = 0;
int i;
i = 0;
do{
balancedPoint = choosetheponintToBalanceKDtree(points);
insertPointAtTree(balancedPoint, 0);
if(dimension)
points.erase(points.begin() + balancedPoint[3]);
else
points.erase(points.begin() + balancedPoint[2]);
i++;
} while (!points.empty());
}
void insertNo(No* previousNo, No* currentyNo, vector<float> point)
{
//For layer = 0
if (previousNo->layer == 0 && point[0] >= previousNo->noPoint[0])
{
if (previousNo->nextNoRigth == NULL)
{
previousNo->nextNoRigth = currentyNo;
currentyNo->noPoint = point;
currentyNo->layer = 1;
cout << "-------------------- New No -------------------------:" << endl;
cout << "No Address: " << currentyNo << endl;
cout << "point x: " << currentyNo->noPoint[0] << endl;
cout << "point y: " << currentyNo->noPoint[1] << endl;
if (dimension)
cout << "point z: " << currentyNo->noPoint[2] << endl;
cout << "Point Level: " << currentyNo->layer << endl;
cout << "Previous No: " << previousNo << endl;
cout << "Previous Rigth No: " << previousNo->nextNoRigth << endl;
cout << "Previous Left No: " << previousNo->nextNoLeft << endl;
cout << "-----------------------------------------------------: " << endl;
}
else
{
insertNo(previousNo->nextNoRigth, currentyNo, point);
}
}
if (previousNo->layer == 0 && point[0] < previousNo->noPoint[0])
{
if (previousNo->nextNoLeft == NULL)
{
previousNo->nextNoLeft = currentyNo;
currentyNo->noPoint = point;
currentyNo->layer = 1;
cout << "-------------------- New No -------------------------:" << endl;
cout << "No Address: " << currentyNo << endl;
cout << "point x: " << currentyNo->noPoint[0] << endl;
cout << "point y: " << currentyNo->noPoint[1] << endl;
if (dimension)
cout << "point z: " << currentyNo->noPoint[2] << endl;
cout << "Point Level: " << currentyNo->layer << endl;
cout << "Previous No: " << previousNo << endl;
cout << "Previous Rigth No: " << previousNo->nextNoRigth << endl;
cout << "Previous Left No: " << previousNo->nextNoLeft << endl;
cout << "-----------------------------------------------------: " << endl;
}
else
{
insertNo(previousNo->nextNoLeft, currentyNo, point);
}
}
//For layer = 1
if (previousNo->layer == 1 && point[1] >= previousNo->noPoint[1])
{
if (previousNo->nextNoRigth == NULL)
{
previousNo->nextNoRigth = currentyNo;
currentyNo->noPoint = point;
if(dimension)
currentyNo->layer = 2;
else
currentyNo->layer = 0;
cout << "-------------------- New No -------------------------:" << endl;
cout << "No Address: " << currentyNo << endl;
cout << "point x: " << currentyNo->noPoint[0] << endl;
cout << "point y: " << currentyNo->noPoint[1] << endl;
if(dimension)
cout << "point z: " << currentyNo->noPoint[2] << endl;
cout << "Point Level: " << currentyNo->layer << endl;
cout << "Previous No: " << previousNo << endl;
cout << "Previous Rigth No: " << previousNo->nextNoRigth << endl;
cout << "Previous Left No: " << previousNo->nextNoLeft << endl;
cout << "-----------------------------------------------------: " << endl;
}
else
{
insertNo(previousNo->nextNoRigth, currentyNo, point);
}
}
if (previousNo->layer == 1 && point[1] < previousNo->noPoint[1])
{
if (previousNo->nextNoLeft == NULL)
{
previousNo->nextNoLeft = currentyNo;
currentyNo->noPoint = point;
if (dimension)
currentyNo->layer = 2;
else
currentyNo->layer = 0;
cout << "-------------------- New No -------------------------:" << endl;
cout << "No Address: " << currentyNo << endl;
cout << "point x: " << currentyNo->noPoint[0] << endl;
cout << "point y: " << currentyNo->noPoint[1] << endl;
if (dimension)
cout << "point z: " << currentyNo->noPoint[2] << endl;
cout << "Point Level: " << currentyNo->layer << endl;
cout << "Previous No: " << previousNo << endl;
cout << "Previous Rigth No: " << previousNo->nextNoRigth << endl;
cout << "Previous Left No: " << previousNo->nextNoLeft << endl;
cout << "-----------------------------------------------------: " << endl;
}
else
{
insertNo(previousNo->nextNoLeft, currentyNo, point);
}
}
//For layer = 2
if (dimension)
{
if (previousNo->layer == 2 && point[2] >= previousNo->noPoint[2])
{
if (previousNo->nextNoRigth == NULL)
{
previousNo->nextNoRigth = currentyNo;
currentyNo->noPoint = point;
currentyNo->layer = 0;
cout << "-------------------- New No -------------------------:" << endl;
cout << "No Address: " << currentyNo << endl;
cout << "point x: " << currentyNo->noPoint[0] << endl;
cout << "point y: " << currentyNo->noPoint[1] << endl;
cout << "point z: " << currentyNo->noPoint[2] << endl;
cout << "Point Level: " << currentyNo->layer << endl;
cout << "Previous No: " << previousNo << endl;
cout << "Previous Rigth No: " << previousNo->nextNoRigth << endl;
cout << "Previous Left No: " << previousNo->nextNoLeft << endl;
cout << "-----------------------------------------------------: " << endl;
}
else
{
insertNo(previousNo->nextNoRigth, currentyNo, point);
}
}
if (previousNo->layer == 2 && point[2] < previousNo->noPoint[2])
{
if (previousNo->nextNoLeft == NULL)
{
previousNo->nextNoLeft = currentyNo;
currentyNo->noPoint = point;
currentyNo->layer = 0;
cout << "-------------------- New No -------------------------:" << endl;
cout << "No Address: " << currentyNo << endl;
cout << "point x: " << currentyNo->noPoint[0] << endl;
cout << "point y: " << currentyNo->noPoint[1] << endl;
cout << "point z: " << currentyNo->noPoint[2] << endl;
cout << "Point Level: " << currentyNo->layer << endl;
cout << "Previous No: " << previousNo << endl;
cout << "Previous Rigth No: " << previousNo->nextNoRigth << endl;
cout << "Previous Left No: " << previousNo->nextNoLeft << endl;
cout << "-----------------------------------------------------: " << endl;
}
else
{
insertNo(previousNo->nextNoLeft, currentyNo, point);
}
}
}
}
void deleteNos(void)
{
insertPointAtTree({ 0,0,0 }, 1);
}
void insertPointAtTree(vector<float> point, bool deleteNo)
{
static No *root = NULL;
No* no = new No;
if(deleteNo == 0)
{
if (root == NULL)
{
no->noPoint = point;
no->layer = 0;
root = no;
ROOT = root;
cout << "----------------------- ROOT --------------------------: " << endl;
cout << "ROOT ADDRESS: " << root << endl;
cout << "point x: " << root->noPoint[0] << endl;
cout << "point y: " << root->noPoint[1] << endl;
if( dimension )
cout << "point z: " << root->noPoint[2] << endl;
cout << "Root Layer: " << root->layer << endl;
cout << "-----------------------------------------------------: " << endl;
}
else
{
insertNo(root, no, point);
}
}
if (deleteNo == 1)
delete no;
}
vector<float> choosetheponintToBalanceKDtree(vector<vector<float>> cloud)
{
float large, menor, range, median, deltaP;
int region = 0;
vector<float> bestpoint;
//initialization
large = cloud[0][region];
menor = cloud[0][region];
for (int index = 0; index < cloud.size(); index++)
{
if (cloud[index][region] < menor)
menor = cloud[index][region];
if (cloud[index][region] > large)
large = cloud[index][region];
}
range = large - menor;
median = menor + range / 2;
//init
deltaP = fabs(median - cloud[0][region]);
if(dimension)
bestpoint = { { cloud[0][0], cloud[0][1],cloud[0][2], 0 } };
else
bestpoint = {{ cloud[0][0], cloud[0][1], 0 }};
for (int index = 0; index < cloud.size(); index++)
{
if (fabs(median - cloud[index][region]) < deltaP)
{
deltaP = fabs(median - cloud[index][region]);
if(dimension)
bestpoint = { { cloud[index][0],cloud[index][1], cloud[index][2],float(index) } };
else
bestpoint = { { cloud[index][0],cloud[index][1], float(index) } };
}
}
return bestpoint;
}
vector<vector<float>> searchNearestNeighbors(vector<float> target, float tolerance)
{
vector<vector<float>> nearestNeighbors;
goThrougthTheTree(ROOT, target, tolerance, nearestNeighbors);
return nearestNeighbors;
}
void goThrougthTheTree(No* no, vector<float> target, float tolerance, vector<vector<float>>& NearestNeighbor)
{
vector<float> addNN;
float distance;
if (no != NULL)
{
if (dimension)
{
if ((no->noPoint[0] >= (target[0] - tolerance) && no->noPoint[0] <= (target[0] + tolerance)) &&
(no->noPoint[1] >= (target[1] - tolerance) && no->noPoint[1] <= (target[1] + tolerance)) &&
(no->noPoint[2] >= (target[2] - tolerance) && no->noPoint[2] <= (target[2] + tolerance)))
{
distance = sqrt((no->noPoint[0] - target[0]) * (no->noPoint[0] - target[0]) +
(no->noPoint[1] - target[1]) * (no->noPoint[1] - target[1]) +
(no->noPoint[2] - target[2]) * (no->noPoint[2] - target[2]));
if (distance <= tolerance)
{
addNN.push_back(no->noPoint[0]);
addNN.push_back(no->noPoint[1]);
addNN.push_back(no->noPoint[2]);
NearestNeighbor.push_back(addNN);
}
}
}
else
{
if ((no->noPoint[0] >= (target[0] - tolerance) && no->noPoint[0] <= (target[0] + tolerance)) &&
no->noPoint[1] >= (target[1] - tolerance) && no->noPoint[1] <= (target[1] + tolerance))
{
distance = sqrt((no->noPoint[0] - target[0]) * (no->noPoint[0] - target[0]) +
(no->noPoint[1] - target[1]) * (no->noPoint[1] - target[1]));
if (distance <= tolerance)
{
addNN.push_back(no->noPoint[0]);
addNN.push_back(no->noPoint[1]);
NearestNeighbor.push_back(addNN);
}
}
}
if (no->layer == 0)
{
if(( target[0] + tolerance) > (no->noPoint[0] ))
goThrougthTheTree(no->nextNoRigth, target, tolerance, NearestNeighbor);
if(( target[0] - tolerance) <= (no->noPoint[0] ))
goThrougthTheTree(no->nextNoLeft, target, tolerance, NearestNeighbor);
}
if (no->layer == 1)
{
if ((target[1] + tolerance) > (no->noPoint[1]))
goThrougthTheTree(no->nextNoRigth, target, tolerance, NearestNeighbor);
if ((target[1] - tolerance) <= (no->noPoint[1]))
goThrougthTheTree(no->nextNoLeft, target, tolerance, NearestNeighbor);
}
if (no->layer == 2)
{
if ((target[2] + tolerance) > (no->noPoint[2]))
goThrougthTheTree(no->nextNoRigth, target, tolerance, NearestNeighbor);
if ((target[2] - tolerance) <= (no->noPoint[2]))
goThrougthTheTree(no->nextNoLeft, target, tolerance, NearestNeighbor);
}
}
}
void deleteClusters(void)
{
vector<bool> proc;
int min;
vector<vector<float>>* back = clusteringTree({ 0,0,0 }, { { 0,0,0 } }, proc, 0.0, min, 1);
}
vector<vector<float>>* clusteringTree(vector<float> point, vector<vector<float>> points, vector<bool>& processed, float distanceTol, int& minpoints, bool deleteClusters)
{
vector<vector<float>> nearest;
vector<vector<float>> nearestOfnearest;
vector<vector<float>>* cluster = new vector<vector<float>>;
if (deleteClusters == 0)
{
nearestOfnearest.clear();
nearest = searchNearestNeighbors(point, distanceTol);
nearestOfnearest.insert(nearestOfnearest.end(), nearest.begin(), nearest.end());
for (int i = 0; i < nearestOfnearest.size(); i++)
{
for (int j = 0; j < points.size(); j++)
{
if (nearestOfnearest[i][0] == points[j][0] && nearestOfnearest[i][1] == points[j][1] &&
nearestOfnearest[i][2] == points[j][2] && processed[j] == false)
processed[j] = true;
}
}
cout << "Points in clustering: " << points.size() << endl;
cout << "NearestOfnearest size before: " << nearestOfnearest.size() << endl;
vector<vector<float>>::iterator itnext = nearestOfnearest.begin() + 1;
vector<vector<float>>::iterator itend = nearestOfnearest.end();
int indexnextPoint = 0;
do
{
vector<vector<float>> newPoits;
vector<vector<float>> NN = searchNearestNeighbors(*itnext, distanceTol);
for (int id = 0; id < NN.size(); id++)
{
bool pointPresent = false;
for (int i = 0; i < nearestOfnearest.size(); i++)
{
if (nearestOfnearest[i][0] == NN[id][0] && nearestOfnearest[i][1] == NN[id][1] &&
nearestOfnearest[i][2] == NN[id][2])
{
pointPresent = true;
break;
}
}
if (pointPresent == false)
{
for (int j = 0; j < points.size(); j++)
{
if (NN[id][0] == points[j][0] && NN[id][1] == points[j][1] &&
NN[id][2] == points[j][2] && processed[j] == false)
{
processed[j] = true;
newPoits.push_back(NN[id]);
}
}
}
}
nearestOfnearest.reserve(newPoits.size());
nearestOfnearest.insert(nearestOfnearest.end(), newPoits.begin(), newPoits.end());
newPoits.clear();
itend = nearestOfnearest.end();
itnext = nearestOfnearest.begin();
++indexnextPoint;
itnext += indexnextPoint;
} while (itnext != itend);
cout << "nearestOfnearest size after: " << nearestOfnearest.size() << endl;
for (int i = 0; i < nearestOfnearest.size(); i++)
{
cluster->push_back(nearestOfnearest[i]);
}
if (cluster->size() >= minpoints)
return cluster;
else
return NULL;
}
if (deleteClusters == 1)
{
delete cluster;
return NULL;
}
}
vector<vector<vector<float>>*> clustersTree(vector<vector<float>> points, float distanceTol, int minpoints)
{
vector<vector<vector<float>>*> ptrClusters;
vector<vector<float>>* ptrCluster;
vector<bool> processed(points.size(), false);
ptrClusters.clear();
int i = 0;
while (i < points.size())
{
if (processed[i])
{
i++;
continue;
}
ptrCluster = clusteringTree(points[i], points, processed, distanceTol, minpoints,0);
if(ptrCluster != NULL)
ptrClusters.push_back(ptrCluster);
i++;
}
return ptrClusters;
}
| [
"isacarthuso@gmail.com"
] | isacarthuso@gmail.com |
cbfbda90b00a63bbe336d743a0d5d5b1e16b7b20 | 52f579cb029589b71f2e787e297c6e4e6f11ec43 | /src/consensus/merkle.h | 670c5bdc6f341b2c1eb4ba1ed9d4399d47779e29 | [
"MIT"
] | permissive | RossClelland/uscbuild | fa093e53bdf3ca68d1db4d73e3e9276ff10a46a9 | db77df86e94ba4362040d5bedf1c71e5b4f01654 | refs/heads/master | 2021-01-24T13:19:00.570675 | 2018-02-27T18:14:59 | 2018-02-27T18:14:59 | 123,169,482 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,324 | h | // Copyright (c) 2015 The Uscoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef USCOIN_MERKLE
#define USCOIN_MERKLE
#include <stdint.h>
#include <vector>
#include "primitives/transaction.h"
#include "primitives/block.h"
#include "uint256.h"
uint256 ComputeMerkleRoot(const std::vector<uint256>& leaves, bool* mutated = nullptr);
std::vector<uint256> ComputeMerkleBranch(const std::vector<uint256>& leaves, uint32_t position);
uint256 ComputeMerkleRootFromBranch(const uint256& leaf, const std::vector<uint256>& branch, uint32_t position);
/*
* Compute the Merkle root of the transactions in a block.
* *mutated is set to true if a duplicated subtree was found.
*/
uint256 BlockMerkleRoot(const CBlock& block, bool* mutated = nullptr);
/*
* Compute the Merkle root of the witness transactions in a block.
* *mutated is set to true if a duplicated subtree was found.
*/
uint256 BlockWitnessMerkleRoot(const CBlock& block, bool* mutated = nullptr);
/*
* Compute the Merkle branch for the tree of transactions in a block, for a
* given position.
* This can be verified using ComputeMerkleRootFromBranch.
*/
std::vector<uint256> BlockMerkleBranch(const CBlock& block, uint32_t position);
#endif
| [
"34719071+RossClelland@users.noreply.github.com"
] | 34719071+RossClelland@users.noreply.github.com |
ede9a429f0daca32f79c41ca2c669e460c34b50e | c7979f4f6435fe8d0d07fff7a430da55e3592aed | /ABC040/D.cpp | bf174257f36a19c4d248ebdacb1686f277535897 | [] | no_license | banboooo044/AtCoder | cee87d40bb98abafde19017f4f4e2f984544b9f8 | 7541d521cf0da848ecb5eb10ffea7d75a44cbbb6 | refs/heads/master | 2020-04-14T11:35:24.977457 | 2019-09-17T03:20:27 | 2019-09-17T03:20:27 | 163,818,272 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,491 | cpp | #include <bits/stdc++.h>
#define REP(i,n) for (long i=0;i<(n);i++)
#define FOR(i,a,b) for (long i=(a);i<(b);i++)
#define RREP(i,n) for(long i=n;i>=0;i--)
#define RFOR(i,a,b) for(long i=(a);i>(b);i--)
#define dump1d_arr(array) REP(i,array.size()) cerr << #array << "[" << (i) << "] ==> " << (array[i]) << endl;
#define dump2d_arr(array) REP(i,array.size()) REP(j,array[i].size()) cerr << #array << "[" << (i) << "]" << "[" << (j) << "] ==> " << (array[i][j]) << endl;
#define dump(x) cerr << #x << " => " << (x) << endl;
#define CLR(vec) { REP(i,vec.size()) vec[i] = 0; }
#define llINF (long long) 9223372036854775807
#define loINF (long) 2147483647
#define shINF (short) 32767
#define SORT(c,func) sort((c).begin(),(c).end(),func())
#define MIN(vec) *min_element(vec.begin(), vec.end());
#define MAX(vec) *max_element(vec.begin(), vec.end());
#define UNIQ(vec) vec.erase(unique(vec.begin(), vec.end()),vec.end());
#define IN(n,m) (!(m.find(n) == m.end()))
#define TO_INT(vec,s) REP(i,s.length()){vec.push_back(s[i] - ‘0’);}
#define ENUM_v(vec) for (auto e : vec)
#define dump_MAP(m) for(auto itr = m.begin(); itr != m.end(); ++itr) { cerr << itr->first << " --> " << itr->second << endl; }
#define FINDL(vec,x) (lower_bound(vec.begin(),vec.end(),x) - vec.begin())
#define FINDU(vec,x) (upper_bound(vec.begin(),vec.end(),x) - vec.begin())
#define COMP(type,el) struct Order_r {bool operator() (road const& A,road const& B) const{return A.y > B.y;}}
using namespace std;
typedef vector<long> VI;
typedef vector<VI> VVI;
typedef struct {
long a,b,y;
}road;
typedef struct {
long q,v,w;
}query;
struct Order_r {
bool operator() (road const& A,road const& B) const {
return A.y > B.y;
}
};
struct Order_q {
bool operator() (query const& A,query const& B) const {
return A.w > B.w;
}
};
class Union_Find {
private:
vector<unsigned> par; // par[x] : x の親ノード
vector<unsigned> rank; // rank[x] : 木の高さ
vector<long> group;
size_t sz; // 集合の個数
public:
// コンストラクタ : 空
Union_Find() : sz(0) { }
// コンストラクタ : 1 要素の集合 n 個
Union_Find(size_t n) :
par(n, -1), rank(n, 0), sz(n) ,group(n,1) {
for (size_t i = 0; i < n; i++) par[i] = i;
}
size_t size() { return sz; }
// 集合の追加 : 1 個
void add_node() {
par.push_back(par.size());
rank.push_back(0);
sz++;
}
// 集合の追加 : n 個
void add_node(size_t n) {
for (size_t i = 0; i < n; i++) add_node();
}
// x が属する集合の代表元を返す
size_t find(size_t x) {
if (par[x] == x)
return x;
else
return par[x] = find(par[x]);
}
// x が属する集合と y が属する集合をマージする
void unite(size_t x, size_t y) {
x = find(x);
y = find(y);
if (x == y) return;
if (rank[x] < rank[y]) {
par[x] = y;
group[y] += group[x];
group[x] = (-1);
}
else {
par[y] = x;
if (rank[x] == rank[y]) rank[x]++;
group[x] += group[y];
group[y] = (-1);
}
sz--;
}
unsigned long getGroupSize(long key){
return group[find(key)];
}
// x と y が同じ集合に属しているか?
bool same(size_t x, size_t y) {
return find(x) == find(y);
}
void dump_par(void){
dump1d_arr(par);
}
void dump_rank(void){
dump1d_arr(rank);
}
};
void dump_road(road A){
dump(A.a)
dump(A.b)
dump(A.y)
}
void dump_query(query A){
dump(A.q)
dump(A.v)
dump(A.w)
}
int main(void){
long N,M,Q;
long a,b,y,v,w;
cin >> N >> M;
vector<road> R(M);
Union_Find uf(N);
REP(i,M) {
cin >> a >> b >> y;
R[i] = {a,b,y};
}
cin >> Q;
vector<query> men(Q);
vector<long> ans(Q,0);
REP(i,Q) {
cin >> v >> w;
men[i] = {i,v,w};
}
SORT(R,Order_r);
SORT(men,Order_q);
//REP(i,R.size()) dump_road(R[i]);
//REP(i,men.size()) dump_query(men[i]);
long itr = 0;
long j;
REP(i,Q) {
for (j = itr;R[j].y > men[i].w && j < M;j++){
uf.unite((R[j].a)-1,(R[j].b)-1);
}
itr = j;
ans[men[i].q] = uf.getGroupSize((men[i].v)-1);
}
REP(i,Q) cout << ans[i] << endl;
return 0;
} | [
"touhoucrisis7@gmail.com"
] | touhoucrisis7@gmail.com |
d8ee5af009ccfac817c2c2fa3c4c07793b62be3f | ba9322f7db02d797f6984298d892f74768193dcf | /cms/src/model/DisableAlarmResult.cc | 9bc285a75171127f4bcb3fc4103c01ff442da7c5 | [
"Apache-2.0"
] | permissive | sdk-team/aliyun-openapi-cpp-sdk | e27f91996b3bad9226c86f74475b5a1a91806861 | a27fc0000a2b061cd10df09cbe4fff9db4a7c707 | refs/heads/master | 2022-08-21T18:25:53.080066 | 2022-07-25T10:01:05 | 2022-07-25T10:01:05 | 183,356,893 | 3 | 0 | null | 2019-04-25T04:34:29 | 2019-04-25T04:34:28 | null | UTF-8 | C++ | false | false | 1,617 | cc | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* 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 <alibabacloud/cms/model/DisableAlarmResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Cms;
using namespace AlibabaCloud::Cms::Model;
DisableAlarmResult::DisableAlarmResult() :
ServiceResult()
{}
DisableAlarmResult::DisableAlarmResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
DisableAlarmResult::~DisableAlarmResult()
{}
void DisableAlarmResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
if(!value["Success"].isNull())
success_ = value["Success"].asString() == "true";
if(!value["Code"].isNull())
code_ = value["Code"].asString();
if(!value["Message"].isNull())
message_ = value["Message"].asString();
}
std::string DisableAlarmResult::getMessage()const
{
return message_;
}
std::string DisableAlarmResult::getCode()const
{
return code_;
}
bool DisableAlarmResult::getSuccess()const
{
return success_;
}
| [
"haowei.yao@alibaba-inc.com"
] | haowei.yao@alibaba-inc.com |
9b7a73db6b020b9d2d610185c69b64e2e35b4d65 | 0944757f8ef83b362fbc012260fb707c3c7d1213 | /Builtin.h | d7dd45c13f9150b5a1a3b9b19c1e0aac44aabe09 | [] | no_license | filipkofron/TinyTalk-old | 246e1877d61d99e0d47dfcecfcf8b76f0c650258 | 4f049ecaad3bfd35c755aafccd87cba34387d677 | refs/heads/master | 2021-01-20T11:05:38.195087 | 2015-02-25T16:17:18 | 2015-02-25T16:17:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,351 | h | #ifndef BUILTIN_H
#define BUILTIN_H
class Builtin;
#include <vector>
#include <string>
#include "TTObject.h"
#define BUILTIN_CHECK_ARGS_COUNT(x, y) \
if (argNames.size() != x || values.size() != y)\
{\
std::cerr << "[Builtin]: Error: " << __PRETTY_FUNCTION__ << " function accepts " << x << " arguments and " << y << "values" << std::endl; \
KILL; \
}\
do {} while(false)
#define BUILTIN_CHECK_LITERAL(x) \
if (values[x]->type != TT_LITERAL) \
{ \
std::cerr << "[Builtin]: Error: " << __PRETTY_FUNCTION__ << " builtin function cannot use anything else than TT_LITERAL." << std::endl; \
KILL; \
} \
do {} while(false)
#define BUILTIN_CHECK_EXPRESSION(x) \
if (values[x]->type != TT_EXPR) \
{ \
std::cerr << "[Builtin]: Error: " << __PRETTY_FUNCTION__ << " builtin function cannot use anything else than TT_EXPR." << std::endl; \
KILL; \
} \
do {} while(false)
#define BUILTIN_CHECK_INTEGER(x) \
if (values[x]->getLiteral()->type != LITERAL_TYPE_INTEGER) \
{ \
std::cerr << "[Builtin]: Error: " << __PRETTY_FUNCTION__ << " function can only use integers now." << std::endl; \
KILL; \
} \
do {} while(false)
#define BUILTIN_CHECK_STRING(x) \
if (values[x]->getLiteral()->type != LITERAL_TYPE_STRING) \
{ \
std::cerr << "[Builtin]: Error: " << __PRETTY_FUNCTION__ << " function can only use strings now." << std::endl; \
KILL; \
} \
do {} while(false)
#define BUILTIN_CHECK_BYTE_ARRAY(x) \
if (values[x]->getLiteral()->type != LITERAL_TYPE_BYTE_ARRAY) \
{ \
std::cerr << "[Builtin]: Error: " << __PRETTY_FUNCTION__ << " function can only use byte array now." << std::endl; \
KILL; \
} \
do {} while(false)
#define BUILTIN_CHECK_LITERAL_SIZE(x, size) \
if (values[x]->getLiteral()->length != size) \
{ \
std::cerr << "[Builtin]: Error: " << __PRETTY_FUNCTION__ << " invalid literal size. expected: " << size << " got: " << values[x]->getLiteral()->length << std::endl; \
KILL; \
} \
do {} while(false)
class Builtin
{
public:
virtual RefPtr<TTObject> invoke(RefPtr<TTObject> dest, std::vector<std::string> &argNames, std::vector<RefPtr<TTObject> > values, RefPtr<TTObject> env, RefPtr<TTObject> thiz) = 0;
};
#endif
| [
"filip.kofron.cz@gmail.com"
] | filip.kofron.cz@gmail.com |
9e631864310eb9964bd6e3b275e0014dc882672c | 49e5f6f4bd36dcef3bab25ae099b50a010857fed | /作业17.C线性表.cpp | 8a8251afd8a4acb5eb6155f17c9ee25e46c26823 | [] | no_license | Wqxleo/C_plus | 5248f5f59d8a93b0e8ad0d1f2d1459f658253b67 | d59036aac66371d0f032927f7a6ff4c302a791d1 | refs/heads/master | 2023-08-18T03:22:37.070622 | 2019-04-05T09:55:13 | 2019-04-05T09:55:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,992 | cpp | #include <iostream>
using namespace std;
class MyList
{
public:
MyList(int _Len)
{
len = _Len;
elements = new int[len];
curLen = 0;
}
void append(int d)
{
elements[curLen] = d;
curLen++;
}
void insert(int p, int d)
{
int *tmp = new int[len];
int i;
for(i = 0;i < p;i++)
{
tmp[i] = elements[i];
}
tmp[p] = d;
curLen++;
for(i = p +1; i < curLen; i++)
{
tmp[i] = elements[i-1];
}
delete [] elements;
elements = tmp;
}
void erase(int p)
{
int *tmp = new int[len];
int i;
for(i = 0;i < p;i++)
{
tmp[i] = elements[i];
}
for(i = p +1; i < curLen; i++)
{
tmp[i-1] = elements[i];
}
curLen--;
delete [] elements;
elements = tmp;
}
void set(int p, int d)
{
elements[p] = d;
}
void show()
{
int i;
for(i = 0; i < curLen; i++)
{
if(i != 0)
cout<<" ";
cout<<elements[i];
}
cout<<endl;
}
private:
int *elements;
int len;
int curLen;
};
int main()
{
int cases, len, data, pos;
char op;
cin>>len;
MyList myList(len);
cin>>cases;
for (int i = 0; i < cases; i++)
{
cin>>op;
switch (op)
{
case 'A':
cin>>data;
myList.append(data);
break;
case 'I':
cin>>pos>>data;
myList.insert(pos, data);
break;
case 'E':
cin>>pos;
myList.erase(pos);
break;
case 'S':
cin>>pos>>data;
myList.set(pos, data);
}
myList.show();
}
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
07f5363c1c3baec63b126e26e569a0a22362e6ac | 7b90100360582e37f558bfe068a3ebbc56849213 | /src/bindings/c++/iccp-c++.cpp | 3b688f86d31b5265ede28b6932780d9f50ca4059 | [
"MIT",
"BSD-3-Clause"
] | permissive | tomay3000/sail | a80421a9fc91e26816e3e7039c74f52f17f89ba3 | 9d68484c8a8735edeb492a629bc6b34e2162d250 | refs/heads/master | 2023-06-10T22:31:17.522475 | 2021-06-30T12:33:21 | 2021-06-30T12:33:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,045 | cpp | /* This file is part of SAIL (https://github.com/smoked-herring/sail)
Copyright (c) 2020 Dmitry Baryshev
The MIT License
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 <cstdlib>
#include <cstring>
#include "sail-common.h"
#include "sail.h"
#include "sail-c++.h"
namespace sail
{
class SAIL_HIDDEN iccp::pimpl
{
public:
pimpl()
{
}
arbitrary_data data;
};
iccp::iccp()
: d(new pimpl)
{
}
iccp::iccp(const void *data, unsigned data_length)
: iccp()
{
with_data(data, data_length);
}
iccp::iccp(const arbitrary_data &data)
: iccp()
{
with_data(data);
}
iccp::iccp(const iccp &ic)
: iccp()
{
*this = ic;
}
iccp& iccp::operator=(const iccp &ic)
{
with_data(ic.data());
return *this;
}
iccp::iccp(iccp &&ic) noexcept
{
d = ic.d;
ic.d = nullptr;
}
iccp& iccp::operator=(iccp &&ic)
{
delete d;
d = ic.d;
ic.d = nullptr;
return *this;
}
iccp::~iccp()
{
delete d;
}
bool iccp::is_valid() const
{
return !d->data.empty();
}
const arbitrary_data& iccp::data() const
{
return d->data;
}
iccp& iccp::with_data(const void *data, unsigned data_length)
{
d->data.clear();
if (data == nullptr || data_length == 0) {
return *this;
}
d->data.resize(data_length);
memcpy(d->data.data(), data, data_length);
return *this;
}
iccp& iccp::with_data(const arbitrary_data &data)
{
return with_data(data.data(), static_cast<unsigned>(data.size()));
}
iccp::iccp(const sail_iccp *ic)
: iccp()
{
if (ic == nullptr) {
SAIL_LOG_DEBUG("NULL pointer has been passed to sail::iccp(). The object is untouched");
return;
}
with_data(ic->data, ic->data_length);
}
sail_status_t iccp::to_sail_iccp(sail_iccp **iccp) const
{
SAIL_CHECK_ICCP_PTR(iccp);
sail_iccp *iccp_local;
SAIL_TRY(sail_alloc_iccp_from_data(d->data.data(), static_cast<unsigned>(d->data.size()), &iccp_local));
*iccp = iccp_local;
return SAIL_OK;
}
}
| [
"dmitrymq@gmail.com"
] | dmitrymq@gmail.com |
984b4c762d1a0024ae38c087081df4e223c5c86f | af168681c24ed4f20a8902de694e5d2c7f18c89d | /practice/mcutie.cpp | 68c46e8473540f8e12bb59d26fe355a1b81c44a3 | [] | no_license | Captain272/cpp_code_base | 1dc552094940c301790e9313509412c782e97597 | 38f6d7aaca9cf6cabfc705a111fd99f10971d6ee | refs/heads/master | 2023-08-28T12:34:58.637415 | 2021-10-01T07:51:30 | 2021-10-01T07:51:30 | 412,550,375 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,410 | cpp | #include<iostream>
using namespace std;
void merge(int arr[],int l,int m,int r){
int n1,n2;
n1=m-l+1;
n2=r-m;
// cout<<n1<<ends<<n2<<endl;
int L[n1],R[n2];
// L[n1]=999999999;
// R[n2]=999999999;
int i,j,k;
for(int i=0;i<n1;i++){
L[i]=arr[l+i];
}
for(int j=0;j<n2;j++){
R[j]=arr[m+1+j];
}
for(int i=0;i<n1;i++){
cout<<L[i]<<ends;
}
cout<<endl;
for(int j=0;j<n2;j++){
cout<<R[j]<<ends;
}
i=0;
j=0;
k=l;
// while(L[i]!=999999999 && R[j]!=999999999){
while(i<n1 && j<n2){
// cout<<L[i]<<ends<<L[j]<<endl;
if(L[i]<=R[j]){
arr[k]=L[i];
// k++;
i++;
}
else if(L[i]>R[j]){
arr[k]=R[j];
// k++;
j++;
}
k++;
}
while(i<n1){
arr[k]=L[i];
i++;
k++;
}
while(j<n2){
arr[k]=R[j];
j++;
k++;
}
}
void mergesort(int arr[],int l,int r){
if(l<r){
int m=l+(r-l)/2;
cout<<l<<ends<<m<<ends<<r<<endl;
mergesort(arr,l,m);
mergesort(arr,m+1,r);
merge(arr,l,m,r);
}
}
int main(){
int arr[6]={12, 11, 13, 5, 6, 7};
int n=sizeof(arr)/sizeof(arr[0]);
cout<<n;
mergesort(arr,0,n);
// mergeSort(arr,0,n);
cout<<endl<<n<<endl;
for(int i=0;i<6;i++){
cout<<arr[i]<<ends;
}
}
//merge(int arr[],int l,int m,int r){
// int i,j,k;
// int n1,n2;
// n1=m-l+1;
// n2=r-m;
//// cout<<n1<<ends<<n2<<endl;
// int L[n1],R[n2];
// for(int i=0;i<n1;i++){
// L[i]=arr[l+i];
//// cout<<endl<<L[i]<<ends;
// }
// cout<<ends;
// for(int j=0;j<n2;j++){
// R[j]=arr[m+1+j];
//// cout<<ends<<R[j]<<ends;
// }
//// L[n1-1]=999999999;
//// R[n2-1]=999999999;
// i=0;
// j=0;
// k=l;
//// while(L[i]!=999999999 && R[j]!=999999999 ){
// while(i<n1 && j<n2){
// if(L[i]<=R[j]){
//// cout<<L[i]<<ends<<R[j]<<"Left is less"<<endl;
// arr[k]=L[i];
// i++;
// k++;
// }
// else{
//// cout<<L[i]<<ends<<R[j]<<"Right is less"<<endl;
// arr[k]=R[j];
// j++;
// k++;
// }
// }
//
// while(i<n1){
// arr[k]=L[i];
// k++;
// i++;
// }
// while(j<n2){
// arr[k]=R[j];
// k++;
// j++;
// }
//// cout<<endl;
//// for(int i=0;i<n1+n2-2;i++){
//// cout<<arr[i]<<ends;
//// }
//}
//
//mergesort(int arr[],int l,int r){
// if(l<r){
// int m=l+(r-l)/2;
//
//// cout<<l<<ends<<m<<ends<<r<<endl;
// mergesort(arr,l,m);
// mergesort(arr,m+1,r);
// merge(arr,l,m,r);
// }
//}
//
//int main(){
// int arr[6]={6,5,4,3,2,1};
// int n=sizeof(arr)/sizeof(arr[0]);
// mergesort(arr,0,n);
// for(int i=0;i<n;i++){
// cout<<arr[i]<<ends;
// }
//}
| [
"www.abhijeeeth@gmail.com"
] | www.abhijeeeth@gmail.com |
19c11738ca345b1952dacda1d99562d0da05cdd9 | 59add4edff34e6cf966d0012db2ef929882d5958 | /Eleusis_sln/Eleusis_SampleApp/Views/TextView.cpp | 1edfedd88e1482a6c49da40dd2b4306294bc9def | [
"MIT"
] | permissive | Qazwar/Eleusis | bab1f82be433db36c74c8f57ecac5759734ae3e8 | 806fc2e488afac4d74556cbe2fffe0b8d5758f38 | refs/heads/master | 2020-05-18T01:14:24.926228 | 2018-05-19T19:30:17 | 2018-05-19T19:30:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,755 | cpp | #include "TextView.h"
#include <memory>
using namespace Eleusis;
using namespace Eleusis::SampleApp;
using namespace std;
TextView::TextView() :
SectionViewBase()
{
fillColor_set(Colors::White);
SelectEdit* l_editTextBlock = new SelectEdit();
l_editTextBlock->LayoutGuest.Classic.topLeft(50, 50);
l_editTextBlock->setText("Edit me :-)");
l_editTextBlock->textSize_set(35);
l_editTextBlock->fillColor_set(Colors::Gray);
l_editTextBlock->fontFamily_set("Segoe UI Light");
l_editTextBlock->width_set(600);
l_editTextBlock->height_set(100._FPs);
l_editTextBlock->caretColor_set(Colors::Gray);
insertChild(l_editTextBlock);
Paragraph* l_paragraph1 = new Paragraph();
l_paragraph1->setText("Eleusis tries to offer rich-text editing functionality. Eleusis uses Pango, "
"text rendering library from GTK family, and adds editing capabilities to it.");
l_paragraph1->textSize_set(13);
l_paragraph1->fontFamily_set("Segoe UI");
l_paragraph1->fontWeight_set(FontWeight::w900_Ultraheavy);
l_editTextBlock->insertParagraph(l_paragraph1);
Paragraph* l_paragraph2 = new Paragraph();
l_paragraph2->setText("TextBlock is basic text object in Eleusis. "
"TextBlock is made of Paragraphs, and paragraphs consist of ");
l_paragraph2->textSize_set(20);
l_paragraph2->fontFamily_set("Palatino Linotype");
l_paragraph2->fontStyle_set(FontStyle::Italic);
l_paragraph2->leftIndent_set(100);
l_editTextBlock->insertParagraph(l_paragraph2);
Span* l_span1 = new Span("spans.");
l_span1->backgroundColor_set(Colors::Gold);
l_span1->fontWeight_set(FontWeight::w700_Ultrabold);
l_span1->fontStyle_set(FontStyle::Italic);
l_span1->fontFamily_set("Arial Black");
l_span1->foregroundColor_set(Colors::White);
l_paragraph2->insertSpan(l_span1);
Paragraph* l_paragraph3 = new Paragraph();
l_paragraph3->setText("Span is an array of characters that have same rendering parameters.");
l_paragraph3->textSize_set(20);
l_paragraph3->fontFamily_set("Palatino Linotype");
l_paragraph3->fontWeight_set(FontWeight::w900_Ultraheavy);
l_paragraph3->leftIndent_set(20);
shared_ptr<LinearGradientBrush> l_gradient2 = shared_ptr<LinearGradientBrush>(new LinearGradientBrush());
l_gradient2->addGradientStop(Colors::GreenYellow, 0.0);
l_gradient2->addGradientStop(Colors::Magenta, 0.33);
l_gradient2->addGradientStop(Colors::SkyBlue, 0.67);
l_gradient2->addGradientStop(Colors::OrangeRed, 1.0);
l_gradient2->setGradientStrech(0, 300, 600, 400);
l_paragraph3->fillBrush_set(l_gradient2);
l_editTextBlock->insertParagraph(l_paragraph3);
TextualShape* _textualShape = new TextualShape("Hoower");
_textualShape->fontFamily_set("Times New Roman");
_textualShape->fillColor_set(Colors::Gray);
_textualShape->LayoutGuest.Classic.topLeft(300, 800);
_textualShape->textSize_set(200);
_textualShape->fontStyle_set(FontStyle::Italic);
insertChild(_textualShape);
_textualShape->mouseEnter +=
[_textualShape](Node* sender, EventArgs* e)
{
if (_textualShape->animate()->isRunning())
{
_textualShape->animate()->reverse();
return;
}
_textualShape->animate()->clear();
_textualShape->animate()->fillColor.startValue(Colors::Gray);
_textualShape->animate()->fillColor.endValue(Colors::Turquoise);
_textualShape->animate()->start();
};
_textualShape->mouseLeave +=
[_textualShape](Node* sender, EventArgs* e)
{
_textualShape->animate()->reverse();
if (!_textualShape->animate()->isRunning())
_textualShape->animate()->start();
};
} | [
"bogdan_nikolic@hotmail.com"
] | bogdan_nikolic@hotmail.com |
4340b5c2e203f2eacce438ad822cebced565e48e | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/git/gumtree/git_repos_function_1776_git-2.0.5.cpp | c4658d2457af0ae0b4989797da66590d5169f260 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 352 | cpp | static int fill_active_slot(struct walker *walker)
{
struct object_request *obj_req;
for (obj_req = object_queue_head; obj_req; obj_req = obj_req->next) {
if (obj_req->state == WAITING) {
if (has_sha1_file(obj_req->sha1))
obj_req->state = COMPLETE;
else {
start_object_request(walker, obj_req);
return 1;
}
}
}
return 0;
} | [
"993273596@qq.com"
] | 993273596@qq.com |
127c8a38761f249b090a2bfc5c01d220c98b801a | 481f3c6b713379912988084cf10810e7d9a74fd0 | /third_party/blink/renderer/core/layout/layout_box.cc | 29c0f7e5ea8c0db84d7b5e116171c06de89bae39 | [
"MPL-2.0-no-copyleft-exception",
"LicenseRef-scancode-unknown-license-reference",
"AGPL-3.0-only",
"LGPL-2.1-only",
"GPL-2.0-only",
"MPL-2.0",
"BSD-3-Clause",
"BSD-2-Clause",
"LGPL-2.0-only",
"LGPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-1.0-or-later",
"LicenseRef-scan... | permissive | huhisoft/huhi-android | bab71148730ff68b770f56b93b731302528045ec | 1c00f05a2ab19f0d6acf42331931de61555a93e8 | refs/heads/master | 2023-01-13T11:26:25.618267 | 2019-11-11T04:09:38 | 2019-11-11T04:09:38 | 219,455,870 | 0 | 4 | BSD-3-Clause | 2022-12-10T08:31:33 | 2019-11-04T08:48:00 | null | UTF-8 | C++ | false | false | 256,031 | cc | /*
* Copyright (C) 1999 Lars Knoll (knoll@kde.org)
* (C) 1999 Antti Koivisto (koivisto@kde.org)
* (C) 2005 Allan Sandfeld Jensen (kde@carewolf.com)
* (C) 2005, 2006 Samuel Weinig (sam.weinig@gmail.com)
* Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010 Apple Inc.
* All rights reserved.
* Copyright (C) 2013 Adobe Systems Incorporated. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#include "third_party/blink/renderer/core/layout/layout_box.h"
#include <math.h>
#include <algorithm>
#include "cc/input/scroll_snap_data.h"
#include "third_party/blink/public/platform/web_rect.h"
#include "third_party/blink/public/platform/web_scroll_into_view_params.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/editing/editing_utilities.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/local_frame_client.h"
#include "third_party/blink/renderer/core/frame/local_frame_view.h"
#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/frame/visual_viewport.h"
#include "third_party/blink/renderer/core/html/html_element.h"
#include "third_party/blink/renderer/core/html/html_frame_element_base.h"
#include "third_party/blink/renderer/core/html/html_frame_owner_element.h"
#include "third_party/blink/renderer/core/input/event_handler.h"
#include "third_party/blink/renderer/core/layout/api/line_layout_block_flow.h"
#include "third_party/blink/renderer/core/layout/api/line_layout_box.h"
#include "third_party/blink/renderer/core/layout/box_layout_extra_input.h"
#include "third_party/blink/renderer/core/layout/hit_test_result.h"
#include "third_party/blink/renderer/core/layout/layout_analyzer.h"
#include "third_party/blink/renderer/core/layout/layout_deprecated_flexible_box.h"
#include "third_party/blink/renderer/core/layout/layout_embedded_content.h"
#include "third_party/blink/renderer/core/layout/layout_fieldset.h"
#include "third_party/blink/renderer/core/layout/layout_flexible_box.h"
#include "third_party/blink/renderer/core/layout/layout_grid.h"
#include "third_party/blink/renderer/core/layout/layout_inline.h"
#include "third_party/blink/renderer/core/layout/layout_list_marker.h"
#include "third_party/blink/renderer/core/layout/layout_multi_column_flow_thread.h"
#include "third_party/blink/renderer/core/layout/layout_multi_column_spanner_placeholder.h"
#include "third_party/blink/renderer/core/layout/layout_table_cell.h"
#include "third_party/blink/renderer/core/layout/layout_view.h"
#include "third_party/blink/renderer/core/layout/ng/custom/custom_layout_child.h"
#include "third_party/blink/renderer/core/layout/ng/custom/layout_ng_custom.h"
#include "third_party/blink/renderer/core/layout/ng/custom/layout_worklet.h"
#include "third_party/blink/renderer/core/layout/ng/custom/layout_worklet_global_scope_proxy.h"
#include "third_party/blink/renderer/core/layout/ng/geometry/ng_box_strut.h"
#include "third_party/blink/renderer/core/layout/ng/ng_box_fragment.h"
#include "third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.h"
#include "third_party/blink/renderer/core/layout/ng/ng_constraint_space.h"
#include "third_party/blink/renderer/core/layout/ng/ng_fragmentation_utils.h"
#include "third_party/blink/renderer/core/layout/ng/ng_layout_result.h"
#include "third_party/blink/renderer/core/layout/ng/ng_layout_utils.h"
#include "third_party/blink/renderer/core/layout/ng/ng_length_utils.h"
#include "third_party/blink/renderer/core/layout/shapes/shape_outside_info.h"
#include "third_party/blink/renderer/core/page/autoscroll_controller.h"
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/core/page/scrolling/scrolling_coordinator.h"
#include "third_party/blink/renderer/core/page/scrolling/snap_coordinator.h"
#include "third_party/blink/renderer/core/paint/background_image_geometry.h"
#include "third_party/blink/renderer/core/paint/box_paint_invalidator.h"
#include "third_party/blink/renderer/core/paint/box_painter.h"
#include "third_party/blink/renderer/core/paint/compositing/paint_layer_compositor.h"
#include "third_party/blink/renderer/core/paint/ng/ng_paint_fragment.h"
#include "third_party/blink/renderer/core/paint/paint_layer.h"
#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
#include "third_party/blink/renderer/core/style/shadow_list.h"
#include "third_party/blink/renderer/platform/geometry/double_rect.h"
#include "third_party/blink/renderer/platform/geometry/float_quad.h"
#include "third_party/blink/renderer/platform/geometry/float_rounded_rect.h"
#include "third_party/blink/renderer/platform/geometry/length_functions.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
namespace blink {
// Used by flexible boxes when flexing this element and by table cells.
typedef WTF::HashMap<const LayoutBox*, LayoutUnit> OverrideSizeMap;
// Size of border belt for autoscroll. When mouse pointer in border belt,
// autoscroll is started.
static const int kAutoscrollBeltSize = 20;
static const unsigned kBackgroundObscurationTestMaxDepth = 4;
struct SameSizeAsLayoutBox : public LayoutBoxModelObject {
LayoutRect frame_rect;
LayoutSize previous_size;
LayoutUnit intrinsic_content_logical_height;
LayoutRectOutsets margin_box_outsets;
LayoutUnit preferred_logical_width[2];
void* pointers[5];
};
static_assert(sizeof(LayoutBox) == sizeof(SameSizeAsLayoutBox),
"LayoutBox should stay small");
BoxLayoutExtraInput::BoxLayoutExtraInput(LayoutBox& box) : box(box) {
box.SetBoxLayoutExtraInput(this);
}
BoxLayoutExtraInput::~BoxLayoutExtraInput() {
box.SetBoxLayoutExtraInput(nullptr);
}
LayoutBoxRareData::LayoutBoxRareData()
: spanner_placeholder_(nullptr),
override_logical_width_(-1),
override_logical_height_(-1),
// TODO(rego): We should store these based on physical direction.
has_override_containing_block_content_logical_width_(false),
has_override_containing_block_content_logical_height_(false),
has_override_percentage_resolution_block_size_(false),
has_previous_content_box_rect_and_layout_overflow_rect_(false),
percent_height_container_(nullptr),
snap_container_(nullptr),
snap_areas_(nullptr) {}
LayoutBox::LayoutBox(ContainerNode* node)
: LayoutBoxModelObject(node),
intrinsic_content_logical_height_(-1),
min_preferred_logical_width_(-1),
max_preferred_logical_width_(-1),
inline_box_wrapper_(nullptr) {
SetIsBox();
if (blink::IsA<HTMLLegendElement>(node))
SetIsHTMLLegendElement();
}
LayoutBox::~LayoutBox() = default;
PaintLayerType LayoutBox::LayerTypeRequired() const {
// hasAutoZIndex only returns true if the element is positioned or a flex-item
// since position:static elements that are not flex-items get their z-index
// coerced to auto.
if (IsPositioned() || CreatesGroup() || HasTransformRelatedProperty() ||
HasHiddenBackface() || HasReflection() || StyleRef().SpecifiesColumns() ||
StyleRef().IsStackingContext() ||
StyleRef().ShouldCompositeForCurrentAnimations() ||
IsEffectiveRootScroller())
return kNormalPaintLayer;
if (HasOverflowClip())
return kOverflowClipPaintLayer;
return kNoPaintLayer;
}
void LayoutBox::WillBeDestroyed() {
ClearOverrideSize();
ClearOverrideContainingBlockContentSize();
ClearOverridePercentageResolutionBlockSize();
if (IsOutOfFlowPositioned())
LayoutBlock::RemovePositionedObject(this);
RemoveFromPercentHeightContainer();
if (IsOrthogonalWritingModeRoot() && !DocumentBeingDestroyed())
UnmarkOrthogonalWritingModeRoot();
ShapeOutsideInfo::RemoveInfo(*this);
if (!DocumentBeingDestroyed()) {
if (NGPaintFragment* first_inline_fragment = FirstInlineFragment())
first_inline_fragment->LayoutObjectWillBeDestroyed();
}
LayoutBoxModelObject::WillBeDestroyed();
}
void LayoutBox::InsertedIntoTree() {
LayoutBoxModelObject::InsertedIntoTree();
AddScrollSnapMapping();
AddCustomLayoutChildIfNeeded();
if (IsOrthogonalWritingModeRoot())
MarkOrthogonalWritingModeRoot();
}
void LayoutBox::WillBeRemovedFromTree() {
if (!DocumentBeingDestroyed() && IsOrthogonalWritingModeRoot())
UnmarkOrthogonalWritingModeRoot();
ClearCustomLayoutChild();
ClearScrollSnapMapping();
LayoutBoxModelObject::WillBeRemovedFromTree();
}
void LayoutBox::RemoveFloatingOrPositionedChildFromBlockLists() {
DCHECK(IsFloatingOrOutOfFlowPositioned());
if (DocumentBeingDestroyed())
return;
if (IsFloating()) {
LayoutBlockFlow* parent_block_flow = nullptr;
for (LayoutObject* curr = Parent(); curr; curr = curr->Parent()) {
auto* curr_block_flow = DynamicTo<LayoutBlockFlow>(curr);
if (curr_block_flow) {
if (!parent_block_flow || curr_block_flow->ContainsFloat(this))
parent_block_flow = curr_block_flow;
}
}
if (parent_block_flow) {
parent_block_flow->MarkSiblingsWithFloatsForLayout(this);
parent_block_flow->MarkAllDescendantsWithFloatsForLayout(this, false);
}
}
if (IsOutOfFlowPositioned())
LayoutBlock::RemovePositionedObject(this);
}
void LayoutBox::StyleWillChange(StyleDifference diff,
const ComputedStyle& new_style) {
const ComputedStyle* old_style = Style();
if (old_style) {
LayoutFlowThread* flow_thread = FlowThreadContainingBlock();
if (flow_thread && flow_thread != this)
flow_thread->FlowThreadDescendantStyleWillChange(this, diff, new_style);
// The background of the root element or the body element could propagate up
// to the canvas. Just dirty the entire canvas when our style changes
// substantially.
if ((diff.NeedsFullPaintInvalidation() || diff.NeedsLayout()) &&
GetNode() &&
(IsDocumentElement() || IsA<HTMLBodyElement>(*GetNode()))) {
View()->SetShouldDoFullPaintInvalidation();
}
// When a layout hint happens and an object's position style changes, we
// have to do a layout to dirty the layout tree using the old position
// value now.
if (diff.NeedsFullLayout() && Parent() &&
old_style->GetPosition() != new_style.GetPosition()) {
if (!old_style->HasOutOfFlowPosition() &&
new_style.HasOutOfFlowPosition()) {
// We're about to go out of flow. Before that takes place, we need to
// mark the current containing block chain for preferred widths
// recalculation.
SetNeedsLayoutAndPrefWidthsRecalc(
layout_invalidation_reason::kStyleChange);
} else {
MarkContainerChainForLayout();
}
if (old_style->GetPosition() == EPosition::kStatic)
SetShouldDoFullPaintInvalidation();
else if (new_style.HasOutOfFlowPosition())
Parent()->SetChildNeedsLayout();
if (IsFloating() && !IsOutOfFlowPositioned() &&
new_style.HasOutOfFlowPosition())
RemoveFloatingOrPositionedChildFromBlockLists();
}
// FIXME: This branch runs when !oldStyle, which means that layout was never
// called so what's the point in invalidating the whole view that we never
// painted?
} else if (IsBody()) {
View()->SetShouldDoFullPaintInvalidation();
}
LayoutBoxModelObject::StyleWillChange(diff, new_style);
}
void LayoutBox::StyleDidChange(StyleDifference diff,
const ComputedStyle* old_style) {
// Horizontal writing mode definition is updated in LayoutBoxModelObject::
// updateFromStyle, (as part of the LayoutBoxModelObject::styleDidChange call
// below). So, we can safely cache the horizontal writing mode value before
// style change here.
bool old_horizontal_writing_mode = IsHorizontalWritingMode();
LayoutBoxModelObject::StyleDidChange(diff, old_style);
// Reflection works through PaintLayer. Some child classes e.g. LayoutSVGBlock
// don't create layers and ignore reflections.
if (HasReflection() && !HasLayer())
SetHasReflection(false);
auto* parent_flow_block = DynamicTo<LayoutBlockFlow>(Parent());
if (IsFloatingOrOutOfFlowPositioned() && old_style &&
!old_style->IsFloating() && !old_style->HasOutOfFlowPosition() &&
parent_flow_block)
parent_flow_block->ChildBecameFloatingOrOutOfFlow(this);
const ComputedStyle& new_style = StyleRef();
if (NeedsLayout() && old_style)
RemoveFromPercentHeightContainer();
if (old_horizontal_writing_mode != IsHorizontalWritingMode()) {
if (old_style) {
if (IsOrthogonalWritingModeRoot())
MarkOrthogonalWritingModeRoot();
else
UnmarkOrthogonalWritingModeRoot();
}
ClearPercentHeightDescendants();
}
SetShouldClipOverflow(ComputeShouldClipOverflow());
// If our zoom factor changes and we have a defined scrollLeft/Top, we need to
// adjust that value into the new zoomed coordinate space. Note that the new
// scroll offset may be outside the normal min/max range of the scrollable
// area, which is weird but OK, because the scrollable area will update its
// min/max in updateAfterLayout().
if (HasOverflowClip() && old_style &&
old_style->EffectiveZoom() != new_style.EffectiveZoom()) {
PaintLayerScrollableArea* scrollable_area = GetScrollableArea();
DCHECK(scrollable_area);
// We use getScrollOffset() rather than scrollPosition(), because scroll
// offset is the distance from the beginning of flow for the box, which is
// the dimension we want to preserve.
ScrollOffset old_offset = scrollable_area->GetScrollOffset();
if (old_offset.Width() || old_offset.Height()) {
ScrollOffset new_offset = old_offset.ScaledBy(new_style.EffectiveZoom() /
old_style->EffectiveZoom());
scrollable_area->SetScrollOffsetUnconditionally(new_offset);
}
}
UpdateShapeOutsideInfoAfterStyleChange(*Style(), old_style);
UpdateGridPositionAfterStyleChange(old_style);
// When we're no longer a flex item because we're now absolutely positioned,
// we need to clear the override size so we're not affected by it anymore.
// This technically covers too many cases (even when out-of-flow did not
// change) but that should be harmless.
if (IsOutOfFlowPositioned() && Parent() &&
Parent()->StyleRef().IsDisplayFlexibleOrGridBox())
ClearOverrideSize();
if (LayoutMultiColumnSpannerPlaceholder* placeholder = SpannerPlaceholder())
placeholder->LayoutObjectInFlowThreadStyleDidChange(old_style);
UpdateBackgroundAttachmentFixedStatusAfterStyleChange();
if (old_style) {
LayoutFlowThread* flow_thread = FlowThreadContainingBlock();
if (flow_thread && flow_thread != this)
flow_thread->FlowThreadDescendantStyleDidChange(this, diff, *old_style);
UpdateScrollSnapMappingAfterStyleChange(*old_style);
if (ShouldClipOverflow()) {
// The overflow clip paint property depends on border sizes through
// overflowClipRect(), and border radii, so we update properties on
// border size or radii change.
if (!old_style->BorderSizeEquals(new_style) ||
!old_style->RadiiEqual(new_style)) {
SetNeedsPaintPropertyUpdate();
if (Layer())
Layer()->SetNeedsCompositingInputsUpdate();
}
}
if (old_style->OverscrollBehaviorX() != new_style.OverscrollBehaviorX() ||
old_style->OverscrollBehaviorY() != new_style.OverscrollBehaviorY()) {
SetNeedsPaintPropertyUpdate();
}
if (IsInLayoutNGInlineFormattingContext() && IsAtomicInlineLevel() &&
old_style->Direction() != new_style.Direction()) {
SetNeedsCollectInlines();
}
}
if (diff.TransformChanged()) {
if (auto* coordinator = GetFrame()->GetPage()->GetScrollingCoordinator())
coordinator->NotifyGeometryChanged(GetFrameView());
}
// Update the script style map, from the new computed style.
if (IsCustomItem())
GetCustomLayoutChild()->styleMap()->UpdateStyle(GetDocument(), StyleRef());
// Non-atomic inlines should be LayoutInline or LayoutText, not LayoutBox.
DCHECK(!IsInline() || IsAtomicInlineLevel());
}
void LayoutBox::UpdateBackgroundAttachmentFixedStatusAfterStyleChange() {
if (!GetFrameView())
return;
// On low-powered/mobile devices, preventing blitting on a scroll can cause
// noticeable delays when scrolling a page with a fixed background image. As
// an optimization, assuming there are no fixed positoned elements on the
// page, we can acclerate scrolling (via blitting) if we ignore the CSS
// property "background-attachment: fixed".
bool ignore_fixed_background_attachment =
RuntimeEnabledFeatures::FastMobileScrollingEnabled();
if (ignore_fixed_background_attachment)
return;
SetIsBackgroundAttachmentFixedObject(
!BackgroundTransfersToView() &&
StyleRef().HasFixedAttachmentBackgroundImage());
}
void LayoutBox::UpdateShapeOutsideInfoAfterStyleChange(
const ComputedStyle& style,
const ComputedStyle* old_style) {
const ShapeValue* shape_outside = style.ShapeOutside();
const ShapeValue* old_shape_outside =
old_style ? old_style->ShapeOutside()
: ComputedStyleInitialValues::InitialShapeOutside();
const Length& shape_margin = style.ShapeMargin();
Length old_shape_margin =
old_style ? old_style->ShapeMargin()
: ComputedStyleInitialValues::InitialShapeMargin();
float shape_image_threshold = style.ShapeImageThreshold();
float old_shape_image_threshold =
old_style ? old_style->ShapeImageThreshold()
: ComputedStyleInitialValues::InitialShapeImageThreshold();
// FIXME: A future optimization would do a deep comparison for equality. (bug
// 100811)
if (shape_outside == old_shape_outside && shape_margin == old_shape_margin &&
shape_image_threshold == old_shape_image_threshold)
return;
if (!shape_outside)
ShapeOutsideInfo::RemoveInfo(*this);
else
ShapeOutsideInfo::EnsureInfo(*this).MarkShapeAsDirty();
if (shape_outside || shape_outside != old_shape_outside)
MarkShapeOutsideDependentsForLayout();
}
void LayoutBox::UpdateGridPositionAfterStyleChange(
const ComputedStyle* old_style) {
if (!old_style || !Parent() || !Parent()->IsLayoutGrid())
return;
if (old_style->GridColumnStart() == StyleRef().GridColumnStart() &&
old_style->GridColumnEnd() == StyleRef().GridColumnEnd() &&
old_style->GridRowStart() == StyleRef().GridRowStart() &&
old_style->GridRowEnd() == StyleRef().GridRowEnd() &&
old_style->Order() == StyleRef().Order() &&
old_style->HasOutOfFlowPosition() == StyleRef().HasOutOfFlowPosition())
return;
// Positioned items don't participate on the layout of the grid,
// so we don't need to mark the grid as dirty if they change positions.
if (old_style->HasOutOfFlowPosition() && StyleRef().HasOutOfFlowPosition())
return;
// It should be possible to not dirty the grid in some cases (like moving an
// explicitly placed grid item).
// For now, it's more simple to just always recompute the grid.
ToLayoutGrid(Parent())->DirtyGrid();
}
void LayoutBox::UpdateScrollSnapMappingAfterStyleChange(
const ComputedStyle& old_style) {
DCHECK(Style());
SnapCoordinator* snap_coordinator = GetDocument().GetSnapCoordinator();
if (!snap_coordinator)
return;
// scroll-snap-type and scroll-padding invalidate the snap container.
if (old_style.GetScrollSnapType() != StyleRef().GetScrollSnapType() ||
old_style.ScrollPaddingBottom() != StyleRef().ScrollPaddingBottom() ||
old_style.ScrollPaddingLeft() != StyleRef().ScrollPaddingLeft() ||
old_style.ScrollPaddingTop() != StyleRef().ScrollPaddingTop() ||
old_style.ScrollPaddingRight() != StyleRef().ScrollPaddingRight()) {
snap_coordinator->SnapContainerDidChange(*this, false /* is_removed */);
}
// scroll-snap-align, scroll-snap-stop and scroll-margin invalidate the snap
// area.
if (old_style.GetScrollSnapAlign() != StyleRef().GetScrollSnapAlign() ||
old_style.ScrollSnapStop() != StyleRef().ScrollSnapStop() ||
old_style.ScrollMarginBottom() != StyleRef().ScrollMarginBottom() ||
old_style.ScrollMarginLeft() != StyleRef().ScrollMarginLeft() ||
old_style.ScrollMarginTop() != StyleRef().ScrollMarginTop() ||
old_style.ScrollMarginRight() != StyleRef().ScrollMarginRight())
snap_coordinator->SnapAreaDidChange(*this, StyleRef().GetScrollSnapAlign());
}
void LayoutBox::AddScrollSnapMapping() {
SnapCoordinator* snap_coordinator = GetDocument().GetSnapCoordinator();
if (!snap_coordinator)
return;
snap_coordinator->SnapContainerDidChange(*this, false /* is_removed */);
snap_coordinator->SnapAreaDidChange(*this, Style()->GetScrollSnapAlign());
}
void LayoutBox::ClearScrollSnapMapping() {
SnapCoordinator* snap_coordinator = GetDocument().GetSnapCoordinator();
if (!snap_coordinator)
return;
snap_coordinator->SnapContainerDidChange(*this, true /* is_removed */);
snap_coordinator->SnapAreaDidChange(*this, cc::ScrollSnapAlign());
}
void LayoutBox::UpdateFromStyle() {
LayoutBoxModelObject::UpdateFromStyle();
const ComputedStyle& style_to_use = StyleRef();
SetFloating(!IsOutOfFlowPositioned() && style_to_use.IsFloating());
SetHasTransformRelatedProperty(style_to_use.HasTransformRelatedProperty());
SetHasReflection(style_to_use.BoxReflect());
// LayoutTable and LayoutTableCell will overwrite this flag if needed.
SetHasNonCollapsedBorderDecoration(style_to_use.HasBorderDecoration());
}
void LayoutBox::UpdateLayout() {
DCHECK(NeedsLayout());
LayoutAnalyzer::Scope analyzer(*this);
if (LayoutBlockedByDisplayLock(DisplayLockLifecycleTarget::kChildren))
return;
LayoutObject* child = SlowFirstChild();
if (!child) {
ClearNeedsLayout();
return;
}
LayoutState state(*this);
while (child) {
child->LayoutIfNeeded();
DCHECK(!child->NeedsLayout());
child = child->NextSibling();
}
UpdateAfterLayout();
ClearNeedsLayout();
NotifyDisplayLockDidLayout(DisplayLockLifecycleTarget::kChildren);
}
// ClientWidth and ClientHeight represent the interior of an object excluding
// border and scrollbar.
DISABLE_CFI_PERF
LayoutUnit LayoutBox::ClientWidth() const {
// We need to clamp negative values. This function may be called during layout
// before frame_rect_ gets the final proper value. Another reason: While
// border side values are currently limited to 2^20px (a recent change in the
// code), if this limit is raised again in the future, we'd have ill effects
// of saturated arithmetic otherwise.
return (frame_rect_.Width() - BorderLeft() - BorderRight() -
VerticalScrollbarWidthClampedToContentBox())
.ClampNegativeToZero();
}
DISABLE_CFI_PERF
LayoutUnit LayoutBox::ClientHeight() const {
// We need to clamp negative values. This function can be called during layout
// before frame_rect_ gets the final proper value. The scrollbar may be wider
// than the padding box. Another reason: While border side values are
// currently limited to 2^20px (a recent change in the code), if this limit is
// raised again in the future, we'd have ill effects of saturated arithmetic
// otherwise.
return (frame_rect_.Height() - BorderTop() - BorderBottom() -
HorizontalScrollbarHeight())
.ClampNegativeToZero();
}
int LayoutBox::PixelSnappedClientWidth() const {
return SnapSizeToPixel(ClientWidth(), Location().X() + ClientLeft());
}
DISABLE_CFI_PERF
int LayoutBox::PixelSnappedClientHeight() const {
return SnapSizeToPixel(ClientHeight(), Location().Y() + ClientTop());
}
int LayoutBox::PixelSnappedOffsetWidth(const Element*) const {
return SnapSizeToPixel(OffsetWidth(), Location().X() + ClientLeft());
}
int LayoutBox::PixelSnappedOffsetHeight(const Element*) const {
return SnapSizeToPixel(OffsetHeight(), Location().Y() + ClientTop());
}
LayoutUnit LayoutBox::ScrollWidth() const {
if (HasOverflowClip())
return GetScrollableArea()->ScrollWidth();
// For objects with visible overflow, this matches IE.
// FIXME: Need to work right with writing modes.
if (StyleRef().IsLeftToRightDirection())
return std::max(ClientWidth(), LayoutOverflowRect().MaxX() - BorderLeft());
return ClientWidth() -
std::min(LayoutUnit(), LayoutOverflowRect().X() - BorderLeft());
}
LayoutUnit LayoutBox::ScrollHeight() const {
if (HasOverflowClip())
return GetScrollableArea()->ScrollHeight();
// For objects with visible overflow, this matches IE.
// FIXME: Need to work right with writing modes.
return std::max(ClientHeight(), LayoutOverflowRect().MaxY() - BorderTop());
}
int LayoutBox::PixelSnappedScrollWidth() const {
return SnapSizeToPixel(ScrollWidth(), Location().X() + ClientLeft());
}
int LayoutBox::PixelSnappedScrollHeight() const {
if (HasOverflowClip())
return SnapSizeToPixel(GetScrollableArea()->ScrollHeight(),
Location().Y() + ClientTop());
// For objects with visible overflow, this matches IE.
// FIXME: Need to work right with writing modes.
return SnapSizeToPixel(ScrollHeight(), Location().Y() + ClientTop());
}
PhysicalRect LayoutBox::ScrollRectToVisibleRecursive(
const PhysicalRect& absolute_rect,
const WebScrollIntoViewParams& params) {
DCHECK(params.GetScrollType() == kProgrammaticScroll ||
params.GetScrollType() == kUserScroll);
if (!GetFrameView())
return absolute_rect;
// If we've reached the main frame's layout viewport (which is always set to
// the global root scroller, see ViewportScrollCallback::SetScroller), abort
// if the stop_at_main_frame_layout_viewport option is set. We do this so
// that we can allow a smooth "scroll and zoom" animation to do the final
// scroll in cases like scrolling a focused editable box into view.
if (params.stop_at_main_frame_layout_viewport && IsGlobalRootScroller())
return absolute_rect;
// Presumably the same issue as in setScrollTop. See crbug.com/343132.
DisableCompositingQueryAsserts disabler;
PhysicalRect absolute_rect_to_scroll = absolute_rect;
if (absolute_rect_to_scroll.Width() <= 0)
absolute_rect_to_scroll.SetWidth(LayoutUnit(1));
if (absolute_rect_to_scroll.Height() <= 0)
absolute_rect_to_scroll.SetHeight(LayoutUnit(1));
LayoutBox* parent_box = nullptr;
if (ContainingBlock())
parent_box = ContainingBlock();
PhysicalRect absolute_rect_for_parent;
if (!IsLayoutView() && HasOverflowClip()) {
absolute_rect_for_parent =
GetScrollableArea()->ScrollIntoView(absolute_rect_to_scroll, params);
} else if (!parent_box && CanBeProgramaticallyScrolled()) {
ScrollableArea* area_to_scroll = params.make_visible_in_visual_viewport
? GetFrameView()->GetScrollableArea()
: GetFrameView()->LayoutViewport();
absolute_rect_for_parent =
area_to_scroll->ScrollIntoView(absolute_rect_to_scroll, params);
// If the parent is a local iframe, convert to the absolute coordinate
// space of its document. For remote frames, this will happen on the other
// end of the IPC call.
HTMLFrameOwnerElement* owner_element = GetDocument().LocalOwner();
if (owner_element && owner_element->GetLayoutObject() &&
AllowedToPropagateRecursiveScrollToParentFrame(params)) {
parent_box = owner_element->GetLayoutObject()->EnclosingBox();
LayoutView* parent_view = owner_element->GetLayoutObject()->View();
absolute_rect_for_parent = View()->LocalToAncestorRect(
absolute_rect_for_parent, parent_view, kTraverseDocumentBoundaries);
}
} else {
absolute_rect_for_parent = absolute_rect_to_scroll;
}
// If we're in a position:fixed element, scrolling the layout viewport won't
// have any effect, so we avoid using the RootFrameViewport and explicitly
// scroll the visual viewport if we can. If not, we're done.
if (StyleRef().GetPosition() == EPosition::kFixed && Container() == View() &&
params.make_visible_in_visual_viewport) {
if (GetFrame()->IsMainFrame()) {
// TODO(donnd): We should continue the recursion if we're in a subframe.
return GetFrame()->GetPage()->GetVisualViewport().ScrollIntoView(
absolute_rect_for_parent, params);
} else {
return absolute_rect_for_parent;
}
}
if (parent_box) {
return parent_box->ScrollRectToVisibleRecursive(absolute_rect_for_parent,
params);
} else if (GetFrame()->IsLocalRoot() && !GetFrame()->IsMainFrame()) {
if (AllowedToPropagateRecursiveScrollToParentFrame(params)) {
GetFrameView()->ScrollRectToVisibleInRemoteParent(
absolute_rect_for_parent, params);
}
}
return absolute_rect_for_parent;
}
void LayoutBox::SetMargin(const NGPhysicalBoxStrut& box) {
margin_box_outsets_.SetTop(box.top);
margin_box_outsets_.SetRight(box.right);
margin_box_outsets_.SetBottom(box.bottom);
margin_box_outsets_.SetLeft(box.left);
}
void LayoutBox::AbsoluteQuads(Vector<FloatQuad>& quads,
MapCoordinatesFlags mode) const {
if (LayoutFlowThread* flow_thread = FlowThreadContainingBlock()) {
flow_thread->AbsoluteQuadsForDescendant(*this, quads, mode);
return;
}
quads.push_back(LocalRectToAbsoluteQuad(PhysicalBorderBoxRect(), mode));
}
FloatRect LayoutBox::LocalBoundingBoxRectForAccessibility() const {
return FloatRect(0, 0, frame_rect_.Width().ToFloat(),
frame_rect_.Height().ToFloat());
}
void LayoutBox::UpdateAfterLayout() {
// Transform-origin depends on box size, so we need to update the layer
// transform after layout.
if (HasLayer()) {
Layer()->UpdateTransformationMatrix();
Layer()->UpdateSizeAndScrollingAfterLayout();
}
// When we've finished layout, if we aren't a LayoutNG object, we need to
// reset our cached layout result. LayoutNG inside of
// |NGBlockNode::RunOldLayout| will call |LayoutBox::SetCachedLayoutResult|
// with a new synthesized layout result.
//
// We also want to make sure that if our entrance point into layout changes,
// e.g. an OOF-positioned object is laid out by an NG containing block, then
// Legacy, then NG again, NG won't use a stale layout result.
if (IsOutOfFlowPositioned() && !IsLayoutNGObject())
cached_layout_result_.reset();
}
LayoutUnit LayoutBox::LogicalHeightWithVisibleOverflow() const {
if (!LayoutOverflowIsSet() || HasOverflowClip())
return LogicalHeight();
LayoutRect overflow = LayoutOverflowRect();
if (StyleRef().IsHorizontalWritingMode())
return overflow.MaxY();
return overflow.MaxX();
}
LayoutUnit LayoutBox::ConstrainLogicalWidthByMinMax(
LayoutUnit logical_width,
LayoutUnit available_width,
const LayoutBlock* cb) const {
const ComputedStyle& style_to_use = StyleRef();
if (!style_to_use.LogicalMaxWidth().IsMaxSizeNone())
logical_width = std::min(
logical_width,
ComputeLogicalWidthUsing(kMaxSize, style_to_use.LogicalMaxWidth(),
available_width, cb));
return std::max(logical_width, ComputeLogicalWidthUsing(
kMinSize, style_to_use.LogicalMinWidth(),
available_width, cb));
}
LayoutUnit LayoutBox::ConstrainLogicalHeightByMinMax(
LayoutUnit logical_height,
LayoutUnit intrinsic_content_height) const {
// Note that the values 'min-content', 'max-content' and 'fit-content' should
// behave as the initial value if specified in the block direction.
const Length& logical_max_height = StyleRef().LogicalMaxHeight();
if (!logical_max_height.IsMaxSizeNone() &&
!logical_max_height.IsMinContent() &&
!logical_max_height.IsMaxContent() &&
!logical_max_height.IsFitContent()) {
LayoutUnit max_h = ComputeLogicalHeightUsing(kMaxSize, logical_max_height,
intrinsic_content_height);
if (max_h != -1)
logical_height = std::min(logical_height, max_h);
}
Length logical_min_height = StyleRef().LogicalMinHeight();
if (logical_min_height.IsMinContent() || logical_min_height.IsMaxContent() ||
logical_min_height.IsFitContent())
logical_min_height = Length::Auto();
return std::max(logical_height,
ComputeLogicalHeightUsing(kMinSize, logical_min_height,
intrinsic_content_height));
}
LayoutUnit LayoutBox::ConstrainContentBoxLogicalHeightByMinMax(
LayoutUnit logical_height,
LayoutUnit intrinsic_content_height) const {
// If the min/max height and logical height are both percentages we take
// advantage of already knowing the current resolved percentage height
// to avoid recursing up through our containing blocks again to determine it.
const ComputedStyle& style_to_use = StyleRef();
if (!style_to_use.LogicalMaxHeight().IsMaxSizeNone()) {
if (style_to_use.LogicalMaxHeight().IsPercent() &&
style_to_use.LogicalHeight().IsPercent()) {
LayoutUnit available_logical_height(
logical_height / style_to_use.LogicalHeight().Value() * 100);
logical_height = std::min(logical_height,
ValueForLength(style_to_use.LogicalMaxHeight(),
available_logical_height));
} else {
LayoutUnit max_height(ComputeContentLogicalHeight(
kMaxSize, style_to_use.LogicalMaxHeight(), intrinsic_content_height));
if (max_height != -1)
logical_height = std::min(logical_height, max_height);
}
}
if (style_to_use.LogicalMinHeight().IsPercent() &&
style_to_use.LogicalHeight().IsPercent()) {
LayoutUnit available_logical_height(
logical_height / style_to_use.LogicalHeight().Value() * 100);
logical_height =
std::max(logical_height, ValueForLength(style_to_use.LogicalMinHeight(),
available_logical_height));
} else {
logical_height = std::max(
logical_height,
ComputeContentLogicalHeight(kMinSize, style_to_use.LogicalMinHeight(),
intrinsic_content_height));
}
return logical_height;
}
void LayoutBox::SetLocationAndUpdateOverflowControlsIfNeeded(
const LayoutPoint& location) {
if (!HasLayer()) {
SetLocation(location);
return;
}
// The Layer does not yet have the up to date subpixel accumulation
// so we base the size strictly on the frame rect's location.
IntSize old_pixel_snapped_border_rect_size =
PixelSnappedBorderBoxRect().Size();
SetLocation(location);
if (PixelSnappedBorderBoxRect().Size() !=
old_pixel_snapped_border_rect_size) {
Layer()->UpdateSizeAndScrollingAfterLayout();
}
}
FloatQuad LayoutBox::AbsoluteContentQuad(MapCoordinatesFlags flags) const {
PhysicalRect rect = PhysicalContentBoxRect();
return LocalRectToAbsoluteQuad(rect, flags);
}
PhysicalRect LayoutBox::PhysicalBackgroundRect(
BackgroundRectType rect_type) const {
EFillBox background_box = EFillBox::kText;
// Find the largest background rect of the given opaqueness.
if (const FillLayer* current = &(StyleRef().BackgroundLayers())) {
do {
const FillLayer* cur = current;
current = current->Next();
if (rect_type == kBackgroundKnownOpaqueRect) {
if (cur->GetBlendMode() != BlendMode::kNormal ||
cur->Composite() != kCompositeSourceOver)
continue;
bool layer_known_opaque = false;
// Check if the image is opaque and fills the clip.
if (const StyleImage* image = cur->GetImage()) {
if ((cur->RepeatX() == EFillRepeat::kRepeatFill ||
cur->RepeatX() == EFillRepeat::kRoundFill) &&
(cur->RepeatY() == EFillRepeat::kRepeatFill ||
cur->RepeatY() == EFillRepeat::kRoundFill) &&
image->KnownToBeOpaque(GetDocument(), StyleRef())) {
layer_known_opaque = true;
}
}
// The background color is painted into the last layer.
if (!cur->Next()) {
Color background_color =
ResolveColor(GetCSSPropertyBackgroundColor());
if (!background_color.HasAlpha())
layer_known_opaque = true;
}
// If neither the image nor the color are opaque then skip this layer.
if (!layer_known_opaque)
continue;
}
EFillBox current_clip = cur->Clip();
// Restrict clip if attachment is local.
if (current_clip == EFillBox::kBorder &&
cur->Attachment() == EFillAttachment::kLocal)
current_clip = EFillBox::kPadding;
// If we're asking for the clip rect, a content-box clipped fill layer can
// be scrolled into the padding box of the overflow container.
if (rect_type == kBackgroundClipRect &&
current_clip == EFillBox::kContent &&
cur->Attachment() == EFillAttachment::kLocal) {
current_clip = EFillBox::kPadding;
}
background_box = EnclosingFillBox(background_box, current_clip);
} while (current);
}
switch (background_box) {
case EFillBox::kBorder:
return PhysicalBorderBoxRect();
break;
case EFillBox::kPadding:
return PhysicalPaddingBoxRect();
break;
case EFillBox::kContent:
return PhysicalContentBoxRect();
break;
default:
break;
}
return PhysicalRect();
}
void LayoutBox::AddOutlineRects(Vector<PhysicalRect>& rects,
const PhysicalOffset& additional_offset,
NGOutlineType) const {
rects.emplace_back(additional_offset, Size());
}
bool LayoutBox::CanResize() const {
// We need a special case for <iframe> because they never have
// hasOverflowClip(). However, they do "implicitly" clip their contents, so
// we want to allow resizing them also.
return (HasOverflowClip() || IsLayoutIFrame()) && StyleRef().HasResize();
}
int LayoutBox::VerticalScrollbarWidth() const {
if (!HasOverflowClip() || StyleRef().OverflowY() == EOverflow::kOverlay)
return 0;
return GetScrollableArea()->VerticalScrollbarWidth();
}
int LayoutBox::HorizontalScrollbarHeight() const {
if (!HasOverflowClip() || StyleRef().OverflowX() == EOverflow::kOverlay)
return 0;
return GetScrollableArea()->HorizontalScrollbarHeight();
}
LayoutUnit LayoutBox::VerticalScrollbarWidthClampedToContentBox() const {
LayoutUnit width(VerticalScrollbarWidth());
DCHECK_GE(width, LayoutUnit());
if (width) {
LayoutUnit maximum_width = LogicalWidth() - BorderAndPaddingLogicalWidth();
width = std::min(width, maximum_width.ClampNegativeToZero());
}
return width;
}
bool LayoutBox::CanBeScrolledAndHasScrollableArea() const {
return CanBeProgramaticallyScrolled() &&
(PixelSnappedScrollHeight() != PixelSnappedClientHeight() ||
PixelSnappedScrollWidth() != PixelSnappedClientWidth());
}
bool LayoutBox::CanBeProgramaticallyScrolled() const {
Node* node = GetNode();
if (node && node->IsDocumentNode())
return true;
if (!HasOverflowClip())
return false;
bool has_scrollable_overflow =
HasScrollableOverflowX() || HasScrollableOverflowY();
if (ScrollsOverflow() && has_scrollable_overflow)
return true;
return node && HasEditableStyle(*node);
}
void LayoutBox::Autoscroll(const PhysicalOffset& position_in_root_frame) {
LocalFrame* frame = GetFrame();
if (!frame)
return;
LocalFrameView* frame_view = frame->View();
if (!frame_view)
return;
PhysicalOffset absolute_position =
frame_view->ConvertFromRootFrame(position_in_root_frame);
ScrollRectToVisibleRecursive(
PhysicalRect(absolute_position,
PhysicalSize(LayoutUnit(1), LayoutUnit(1))),
WebScrollIntoViewParams(ScrollAlignment::kAlignToEdgeIfNeeded,
ScrollAlignment::kAlignToEdgeIfNeeded,
kUserScroll));
}
bool LayoutBox::CanAutoscroll() const {
// TODO(skobes): Remove one of these methods.
return CanBeScrolledAndHasScrollableArea();
}
// If specified point is outside the border-belt-excluded box (the border box
// inset by the autoscroll activation threshold), returned offset denotes
// direction of scrolling.
PhysicalOffset LayoutBox::CalculateAutoscrollDirection(
const FloatPoint& point_in_root_frame) const {
if (!GetFrame())
return PhysicalOffset();
LocalFrameView* frame_view = GetFrame()->View();
if (!frame_view)
return PhysicalOffset();
PhysicalRect absolute_scrolling_box(AbsoluteBoundingBoxRect());
// Exclude scrollbars so the border belt (activation area) starts from the
// scrollbar-content edge rather than the window edge.
ExcludeScrollbars(absolute_scrolling_box,
kExcludeOverlayScrollbarSizeForHitTesting);
PhysicalRect belt_box =
View()->GetFrameView()->ConvertToRootFrame(absolute_scrolling_box);
belt_box.Inflate(LayoutUnit(-kAutoscrollBeltSize));
FloatPoint point = point_in_root_frame;
if (point.X() < belt_box.X())
point.Move(-kAutoscrollBeltSize, 0);
else if (point.X() > belt_box.Right())
point.Move(kAutoscrollBeltSize, 0);
if (point.Y() < belt_box.Y())
point.Move(0, -kAutoscrollBeltSize);
else if (point.Y() > belt_box.Bottom())
point.Move(0, kAutoscrollBeltSize);
return PhysicalOffset::FromFloatSizeRound(point - point_in_root_frame);
}
LayoutBox* LayoutBox::FindAutoscrollable(LayoutObject* layout_object,
bool is_middle_click_autoscroll) {
while (layout_object && !(layout_object->IsBox() &&
ToLayoutBox(layout_object)->CanAutoscroll())) {
// Do not start selection-based autoscroll when the node is inside a
// fixed-position element.
if (!is_middle_click_autoscroll && layout_object->IsBox() &&
ToLayoutBox(layout_object)->HasLayer() &&
ToLayoutBox(layout_object)->Layer()->FixedToViewport()) {
return nullptr;
}
if (!layout_object->Parent() &&
layout_object->GetNode() == layout_object->GetDocument() &&
layout_object->GetDocument().LocalOwner())
layout_object =
layout_object->GetDocument().LocalOwner()->GetLayoutObject();
else
layout_object = layout_object->Parent();
}
return layout_object && layout_object->IsBox() ? ToLayoutBox(layout_object)
: nullptr;
}
void LayoutBox::MayUpdateHoverWhenContentUnderMouseChanged(
EventHandler& event_handler) {
const LayoutBoxModelObject& container = ContainerForPaintInvalidation();
PhysicalRect scroller_rect(VisualRectIncludingCompositedScrolling(container));
FloatQuad scroller_quad_in_frame =
container.LocalRectToAbsoluteQuad(scroller_rect);
event_handler.MayUpdateHoverAfterScroll(scroller_quad_in_frame);
}
void LayoutBox::ScrollByRecursively(const ScrollOffset& delta) {
if (delta.IsZero() || !HasOverflowClip())
return;
PaintLayerScrollableArea* scrollable_area = GetScrollableArea();
DCHECK(scrollable_area);
ScrollOffset new_scroll_offset = scrollable_area->GetScrollOffset() + delta;
scrollable_area->SetScrollOffset(new_scroll_offset, kProgrammaticScroll);
// If this layer can't do the scroll we ask the next layer up that can
// scroll to try.
ScrollOffset remaining_scroll_offset =
new_scroll_offset - scrollable_area->GetScrollOffset();
if (!remaining_scroll_offset.IsZero() && Parent()) {
if (LayoutBox* scrollable_box = EnclosingScrollableBox())
scrollable_box->ScrollByRecursively(remaining_scroll_offset);
LocalFrame* frame = GetFrame();
if (frame && frame->GetPage()) {
frame->GetPage()
->GetAutoscrollController()
.UpdateAutoscrollLayoutObject();
}
}
// FIXME: If we didn't scroll the whole way, do we want to try looking at
// the frames ownerElement?
// https://bugs.webkit.org/show_bug.cgi?id=28237
}
bool LayoutBox::NeedsPreferredWidthsRecalculation() const {
return StyleRef().PaddingStart().IsPercentOrCalc() ||
StyleRef().PaddingEnd().IsPercentOrCalc();
}
IntSize LayoutBox::OriginAdjustmentForScrollbars() const {
return IntSize(LeftScrollbarWidth().ToInt(), 0);
}
IntPoint LayoutBox::ScrollOrigin() const {
return GetScrollableArea() ? GetScrollableArea()->ScrollOrigin() : IntPoint();
}
LayoutSize LayoutBox::ScrolledContentOffset() const {
DCHECK(HasOverflowClip());
DCHECK(GetScrollableArea());
return LayoutSize(GetScrollableArea()->GetScrollOffset());
}
PhysicalRect LayoutBox::ClippingRect(const PhysicalOffset& location) const {
PhysicalRect result(PhysicalRect::InfiniteIntRect());
if (ShouldClipOverflow())
result = OverflowClipRect(location);
if (HasClip())
result.Intersect(ClipRect(location));
return result;
}
bool LayoutBox::MapVisualRectToContainer(
const LayoutObject* container_object,
const PhysicalOffset& container_offset,
const LayoutObject* ancestor,
VisualRectFlags visual_rect_flags,
TransformState& transform_state) const {
bool container_preserve_3d = container_object->StyleRef().Preserves3D();
TransformState::TransformAccumulation accumulation =
container_preserve_3d ? TransformState::kAccumulateTransform
: TransformState::kFlattenTransform;
// If there is no transform on this box, adjust for container offset and
// container scrolling, then apply container clip.
if (!ShouldUseTransformFromContainer(container_object)) {
transform_state.Move(container_offset, accumulation);
if (container_object->IsBox() && container_object != ancestor &&
!ToLayoutBox(container_object)
->MapContentsRectToBoxSpace(transform_state, accumulation, *this,
visual_rect_flags)) {
return false;
}
return true;
}
// Otherwise, do the following:
// 1. Expand for pixel snapping.
// 2. Generate transformation matrix combining, in this order
// a) transform,
// b) container offset,
// c) container scroll offset,
// d) perspective applied by container.
// 3. Apply transform Transform+flattening.
// 4. Apply container clip.
// 1. Expand for pixel snapping.
// Use EnclosingBoundingBox because we cannot properly compute pixel
// snapping for painted elements within the transform since we don't know
// the desired subpixel accumulation at this point, and the transform may
// include a scale. This only makes sense for non-preserve3D.
if (!StyleRef().Preserves3D()) {
transform_state.Flatten();
transform_state.SetQuad(
FloatQuad(transform_state.LastPlanarQuad().EnclosingBoundingBox()));
}
// 2. Generate transformation matrix.
// a) Transform.
TransformationMatrix transform;
if (Layer() && Layer()->Transform())
transform.Multiply(Layer()->CurrentTransform());
// b) Container offset.
transform.PostTranslate(container_offset.left.ToFloat(),
container_offset.top.ToFloat());
// c) Container scroll offset.
if (container_object->IsBox() && container_object != ancestor &&
ToLayoutBox(container_object)->ContainedContentsScroll(*this)) {
LayoutSize offset(-ToLayoutBox(container_object)->ScrolledContentOffset());
transform.PostTranslate(offset.Width(), offset.Height());
}
// d) Perspective applied by container.
if (container_object && container_object->HasLayer() &&
container_object->StyleRef().HasPerspective()) {
// Perspective on the container affects us, so we have to factor it in here.
DCHECK(container_object->HasLayer());
FloatPoint perspective_origin =
ToLayoutBoxModelObject(container_object)->Layer()->PerspectiveOrigin();
TransformationMatrix perspective_matrix;
perspective_matrix.ApplyPerspective(
container_object->StyleRef().Perspective());
perspective_matrix.ApplyTransformOrigin(perspective_origin.X(),
perspective_origin.Y(), 0);
transform = perspective_matrix * transform;
}
// 3. Apply transform and flatten.
transform_state.ApplyTransform(transform, accumulation);
if (!container_preserve_3d)
transform_state.Flatten();
// 4. Apply container clip.
if (container_object->IsBox() && container_object != ancestor &&
container_object->HasClipRelatedProperty()) {
return ToLayoutBox(container_object)
->ApplyBoxClips(transform_state, accumulation, visual_rect_flags);
}
return true;
}
bool LayoutBox::MapContentsRectToBoxSpace(
TransformState& transform_state,
TransformState::TransformAccumulation accumulation,
const LayoutObject& contents,
VisualRectFlags visual_rect_flags) const {
if (!HasClipRelatedProperty())
return true;
if (ContainedContentsScroll(contents))
transform_state.Move(PhysicalOffset(-ScrolledContentOffset()));
return ApplyBoxClips(transform_state, accumulation, visual_rect_flags);
}
bool LayoutBox::ContainedContentsScroll(const LayoutObject& contents) const {
if (IsLayoutView() &&
contents.StyleRef().GetPosition() == EPosition::kFixed) {
return false;
}
return HasOverflowClip();
}
bool LayoutBox::ApplyBoxClips(
TransformState& transform_state,
TransformState::TransformAccumulation accumulation,
VisualRectFlags visual_rect_flags) const {
// This won't work fully correctly for fixed-position elements, who should
// receive CSS clip but for whom the current object is not in the containing
// block chain.
PhysicalRect clip_rect = ClippingRect(PhysicalOffset());
transform_state.Flatten();
PhysicalRect rect(transform_state.LastPlanarQuad().EnclosingBoundingBox());
bool does_intersect;
if (visual_rect_flags & kEdgeInclusive) {
does_intersect = rect.InclusiveIntersect(clip_rect);
} else {
rect.Intersect(clip_rect);
does_intersect = !rect.IsEmpty();
}
transform_state.SetQuad(FloatQuad(FloatRect(rect)));
return does_intersect;
}
void LayoutBox::ComputeIntrinsicLogicalWidths(
LayoutUnit& min_logical_width,
LayoutUnit& max_logical_width) const {
min_logical_width =
MinPreferredLogicalWidth() - BorderAndPaddingLogicalWidth();
max_logical_width =
MaxPreferredLogicalWidth() - BorderAndPaddingLogicalWidth();
}
LayoutUnit LayoutBox::MinPreferredLogicalWidth() const {
if (PreferredLogicalWidthsDirty()) {
#if DCHECK_IS_ON()
SetLayoutNeededForbiddenScope layout_forbidden_scope(
const_cast<LayoutBox&>(*this));
#endif
const_cast<LayoutBox*>(this)->ComputePreferredLogicalWidths();
DCHECK(!PreferredLogicalWidthsDirty());
}
return min_preferred_logical_width_;
}
DISABLE_CFI_PERF
LayoutUnit LayoutBox::MaxPreferredLogicalWidth() const {
if (PreferredLogicalWidthsDirty()) {
#if DCHECK_IS_ON()
SetLayoutNeededForbiddenScope layout_forbidden_scope(
const_cast<LayoutBox&>(*this));
#endif
const_cast<LayoutBox*>(this)->ComputePreferredLogicalWidths();
DCHECK(!PreferredLogicalWidthsDirty());
}
return max_preferred_logical_width_;
}
LayoutUnit LayoutBox::OverrideLogicalWidth() const {
DCHECK(HasOverrideLogicalWidth());
if (extra_input_ && extra_input_->override_inline_size)
return *extra_input_->override_inline_size;
return rare_data_->override_logical_width_;
}
LayoutUnit LayoutBox::OverrideLogicalHeight() const {
DCHECK(HasOverrideLogicalHeight());
if (extra_input_ && extra_input_->override_block_size)
return *extra_input_->override_block_size;
return rare_data_->override_logical_height_;
}
bool LayoutBox::HasOverrideLogicalHeight() const {
if (extra_input_ && extra_input_->override_block_size)
return true;
return rare_data_ && rare_data_->override_logical_height_ != -1;
}
bool LayoutBox::HasOverrideLogicalWidth() const {
if (extra_input_ && extra_input_->override_inline_size)
return true;
return rare_data_ && rare_data_->override_logical_width_ != -1;
}
void LayoutBox::SetOverrideLogicalHeight(LayoutUnit height) {
DCHECK(!extra_input_);
DCHECK_GE(height, 0);
EnsureRareData().override_logical_height_ = height;
}
void LayoutBox::SetOverrideLogicalWidth(LayoutUnit width) {
DCHECK(!extra_input_);
DCHECK_GE(width, 0);
EnsureRareData().override_logical_width_ = width;
}
void LayoutBox::ClearOverrideLogicalHeight() {
DCHECK(!extra_input_);
if (rare_data_)
rare_data_->override_logical_height_ = LayoutUnit(-1);
}
void LayoutBox::ClearOverrideLogicalWidth() {
DCHECK(!extra_input_);
if (rare_data_)
rare_data_->override_logical_width_ = LayoutUnit(-1);
}
void LayoutBox::ClearOverrideSize() {
ClearOverrideLogicalHeight();
ClearOverrideLogicalWidth();
}
LayoutUnit LayoutBox::OverrideContentLogicalWidth() const {
return (OverrideLogicalWidth() - BorderAndPaddingLogicalWidth() -
ScrollbarLogicalWidth())
.ClampNegativeToZero();
}
LayoutUnit LayoutBox::OverrideContentLogicalHeight() const {
return (OverrideLogicalHeight() - BorderAndPaddingLogicalHeight() -
ScrollbarLogicalHeight())
.ClampNegativeToZero();
}
LayoutUnit LayoutBox::OverrideContainingBlockContentWidth() const {
DCHECK(HasOverrideContainingBlockContentWidth());
return ContainingBlock()->StyleRef().IsHorizontalWritingMode()
? OverrideContainingBlockContentLogicalWidth()
: OverrideContainingBlockContentLogicalHeight();
}
LayoutUnit LayoutBox::OverrideContainingBlockContentHeight() const {
DCHECK(HasOverrideContainingBlockContentHeight());
return ContainingBlock()->StyleRef().IsHorizontalWritingMode()
? OverrideContainingBlockContentLogicalHeight()
: OverrideContainingBlockContentLogicalWidth();
}
bool LayoutBox::HasOverrideContainingBlockContentWidth() const {
if (!ContainingBlock())
return false;
return ContainingBlock()->StyleRef().IsHorizontalWritingMode()
? HasOverrideContainingBlockContentLogicalWidth()
: HasOverrideContainingBlockContentLogicalHeight();
}
bool LayoutBox::HasOverrideContainingBlockContentHeight() const {
if (!ContainingBlock())
return false;
return ContainingBlock()->StyleRef().IsHorizontalWritingMode()
? HasOverrideContainingBlockContentLogicalHeight()
: HasOverrideContainingBlockContentLogicalWidth();
}
// TODO (lajava) Shouldn't we implement these functions based on physical
// direction ?.
LayoutUnit LayoutBox::OverrideContainingBlockContentLogicalWidth() const {
DCHECK(HasOverrideContainingBlockContentLogicalWidth());
if (extra_input_)
return extra_input_->containing_block_content_inline_size;
return rare_data_->override_containing_block_content_logical_width_;
}
// TODO (lajava) Shouldn't we implement these functions based on physical
// direction ?.
LayoutUnit LayoutBox::OverrideContainingBlockContentLogicalHeight() const {
DCHECK(HasOverrideContainingBlockContentLogicalHeight());
if (extra_input_)
return extra_input_->containing_block_content_block_size;
return rare_data_->override_containing_block_content_logical_height_;
}
// TODO (lajava) Shouldn't we implement these functions based on physical
// direction ?.
bool LayoutBox::HasOverrideContainingBlockContentLogicalWidth() const {
if (extra_input_)
return true;
return rare_data_ &&
rare_data_->has_override_containing_block_content_logical_width_;
}
// TODO (lajava) Shouldn't we implement these functions based on physical
// direction ?.
bool LayoutBox::HasOverrideContainingBlockContentLogicalHeight() const {
if (extra_input_)
return true;
return rare_data_ &&
rare_data_->has_override_containing_block_content_logical_height_;
}
// TODO (lajava) Shouldn't we implement these functions based on physical
// direction ?.
void LayoutBox::SetOverrideContainingBlockContentLogicalWidth(
LayoutUnit logical_width) {
DCHECK(!extra_input_);
DCHECK_GE(logical_width, LayoutUnit(-1));
EnsureRareData().override_containing_block_content_logical_width_ =
logical_width;
EnsureRareData().has_override_containing_block_content_logical_width_ = true;
}
// TODO (lajava) Shouldn't we implement these functions based on physical
// direction ?.
void LayoutBox::SetOverrideContainingBlockContentLogicalHeight(
LayoutUnit logical_height) {
DCHECK(!extra_input_);
DCHECK_GE(logical_height, LayoutUnit(-1));
EnsureRareData().override_containing_block_content_logical_height_ =
logical_height;
EnsureRareData().has_override_containing_block_content_logical_height_ = true;
}
// TODO (lajava) Shouldn't we implement these functions based on physical
// direction ?.
void LayoutBox::ClearOverrideContainingBlockContentSize() {
DCHECK(!extra_input_);
if (!rare_data_)
return;
EnsureRareData().has_override_containing_block_content_logical_width_ = false;
EnsureRareData().has_override_containing_block_content_logical_height_ =
false;
}
LayoutUnit LayoutBox::OverridePercentageResolutionBlockSize() const {
DCHECK(HasOverridePercentageResolutionBlockSize());
return rare_data_->override_percentage_resolution_block_size_;
}
bool LayoutBox::HasOverridePercentageResolutionBlockSize() const {
return rare_data_ &&
rare_data_->has_override_percentage_resolution_block_size_;
}
void LayoutBox::SetOverridePercentageResolutionBlockSize(
LayoutUnit logical_height) {
DCHECK_GE(logical_height, LayoutUnit(-1));
auto& rare_data = EnsureRareData();
rare_data.override_percentage_resolution_block_size_ = logical_height;
rare_data.has_override_percentage_resolution_block_size_ = true;
}
void LayoutBox::ClearOverridePercentageResolutionBlockSize() {
if (!rare_data_)
return;
EnsureRareData().has_override_percentage_resolution_block_size_ = false;
}
LayoutUnit LayoutBox::OverrideAvailableInlineSize() const {
DCHECK(HasOverrideAvailableInlineSize());
if (extra_input_)
return extra_input_->available_inline_size;
return LayoutUnit();
}
LayoutUnit LayoutBox::AdjustBorderBoxLogicalWidthForBoxSizing(
float width) const {
LayoutUnit borders_plus_padding = CollapsedBorderAndCSSPaddingLogicalWidth();
LayoutUnit result(width);
if (StyleRef().BoxSizing() == EBoxSizing::kContentBox)
return result + borders_plus_padding;
return std::max(result, borders_plus_padding);
}
LayoutUnit LayoutBox::AdjustBorderBoxLogicalHeightForBoxSizing(
float height) const {
LayoutUnit borders_plus_padding = CollapsedBorderAndCSSPaddingLogicalHeight();
LayoutUnit result(height);
if (StyleRef().BoxSizing() == EBoxSizing::kContentBox)
return result + borders_plus_padding;
return std::max(result, borders_plus_padding);
}
LayoutUnit LayoutBox::AdjustContentBoxLogicalWidthForBoxSizing(
float width) const {
LayoutUnit result(width);
if (StyleRef().BoxSizing() == EBoxSizing::kBorderBox)
result -= CollapsedBorderAndCSSPaddingLogicalWidth();
return std::max(LayoutUnit(), result);
}
LayoutUnit LayoutBox::AdjustContentBoxLogicalHeightForBoxSizing(
float height) const {
LayoutUnit result(height);
if (StyleRef().BoxSizing() == EBoxSizing::kBorderBox)
result -= CollapsedBorderAndCSSPaddingLogicalHeight();
return std::max(LayoutUnit(), result);
}
// Hit Testing
bool LayoutBox::HitTestAllPhases(HitTestResult& result,
const HitTestLocation& hit_test_location,
const PhysicalOffset& accumulated_offset,
HitTestFilter hit_test_filter) {
// Check if we need to do anything at all.
// If we have clipping, then we can't have any spillout.
// TODO(pdr): Why is this optimization not valid for the effective root?
if (!IsEffectiveRootScroller()) {
PhysicalRect overflow_box;
if (result.GetHitTestRequest().GetType() &
HitTestRequest::kHitTestVisualOverflow) {
overflow_box = PhysicalVisualOverflowRectIncludingFilters();
} else {
overflow_box = (HasOverflowClip() || ShouldApplyPaintContainment())
? PhysicalBorderBoxRect()
: PhysicalVisualOverflowRect();
}
PhysicalRect adjusted_overflow_box = overflow_box;
adjusted_overflow_box.Move(accumulated_offset);
if (!hit_test_location.Intersects(adjusted_overflow_box))
return false;
}
return LayoutObject::HitTestAllPhases(result, hit_test_location,
accumulated_offset, hit_test_filter);
}
bool LayoutBox::NodeAtPoint(HitTestResult& result,
const HitTestLocation& hit_test_location,
const PhysicalOffset& accumulated_offset,
HitTestAction action) {
bool should_hit_test_self = IsInSelfHitTestingPhase(action);
if (should_hit_test_self && HasOverflowClip() &&
HitTestOverflowControl(result, hit_test_location, accumulated_offset))
return true;
bool skip_children =
(result.GetHitTestRequest().GetStopNode() == this) ||
PaintBlockedByDisplayLock(DisplayLockLifecycleTarget::kChildren);
if (!skip_children && ShouldClipOverflow()) {
// PaintLayer::HitTestContentsForFragments checked the fragments'
// foreground rect for intersection if a layer is self painting,
// so only do the overflow clip check here for non-self-painting layers.
if (!HasSelfPaintingLayer() &&
!hit_test_location.Intersects(OverflowClipRect(
accumulated_offset, kExcludeOverlayScrollbarSizeForHitTesting))) {
skip_children = true;
}
if (!skip_children && StyleRef().HasBorderRadius()) {
PhysicalRect bounds_rect(accumulated_offset, Size());
skip_children = !hit_test_location.Intersects(
StyleRef().GetRoundedInnerBorderFor(bounds_rect.ToLayoutRect()));
}
}
if (!skip_children &&
HitTestChildren(result, hit_test_location, accumulated_offset, action)) {
return true;
}
if (StyleRef().HasBorderRadius() &&
HitTestClippedOutByBorder(hit_test_location, accumulated_offset))
return false;
// Now hit test ourselves.
if (should_hit_test_self &&
VisibleToHitTestRequest(result.GetHitTestRequest())) {
PhysicalRect bounds_rect;
if (result.GetHitTestRequest().GetType() &
HitTestRequest::kHitTestVisualOverflow) {
bounds_rect = PhysicalVisualOverflowRectIncludingFilters();
} else {
bounds_rect = PhysicalBorderBoxRect();
}
bounds_rect.Move(accumulated_offset);
if (hit_test_location.Intersects(bounds_rect)) {
UpdateHitTestResult(result,
hit_test_location.Point() - accumulated_offset);
if (result.AddNodeToListBasedTestResult(NodeForHitTest(),
hit_test_location,
bounds_rect) == kStopHitTesting)
return true;
}
}
return false;
}
bool LayoutBox::HitTestChildren(HitTestResult& result,
const HitTestLocation& hit_test_location,
const PhysicalOffset& accumulated_offset,
HitTestAction action) {
for (LayoutObject* child = SlowLastChild(); child;
child = child->PreviousSibling()) {
if (child->HasLayer() &&
ToLayoutBoxModelObject(child)->Layer()->IsSelfPaintingLayer())
continue;
PhysicalOffset child_accumulated_offset = accumulated_offset;
if (child->IsBox())
child_accumulated_offset += ToLayoutBox(child)->PhysicalLocation(this);
if (child->NodeAtPoint(result, hit_test_location, child_accumulated_offset,
action))
return true;
}
return false;
}
bool LayoutBox::HitTestClippedOutByBorder(
const HitTestLocation& hit_test_location,
const PhysicalOffset& border_box_location) const {
PhysicalRect border_rect = PhysicalBorderBoxRect();
border_rect.Move(border_box_location);
return !hit_test_location.Intersects(
StyleRef().GetRoundedBorderFor(border_rect.ToLayoutRect()));
}
void LayoutBox::Paint(const PaintInfo& paint_info) const {
BoxPainter(*this).Paint(paint_info);
}
void LayoutBox::PaintBoxDecorationBackground(
const PaintInfo& paint_info,
const PhysicalOffset& paint_offset) const {
BoxPainter(*this).PaintBoxDecorationBackground(paint_info, paint_offset);
}
bool LayoutBox::GetBackgroundPaintedExtent(PhysicalRect& painted_extent) const {
DCHECK(StyleRef().HasBackground());
// LayoutView is special in the sense that it expands to the whole canvas,
// thus can't be handled by this function.
DCHECK(!IsLayoutView());
PhysicalRect background_rect(PhysicalBorderBoxRect());
Color background_color = ResolveColor(GetCSSPropertyBackgroundColor());
if (background_color.Alpha()) {
painted_extent = background_rect;
return true;
}
if (!StyleRef().BackgroundLayers().GetImage() ||
StyleRef().BackgroundLayers().Next()) {
painted_extent = background_rect;
return true;
}
BackgroundImageGeometry geometry(*this);
// TODO(schenney): This function should be rethought as it's called during
// and outside of the paint phase. Potentially returning different results at
// different phases. crbug.com/732934
geometry.Calculate(nullptr, PaintPhase::kBlockBackground,
kGlobalPaintNormalPhase, StyleRef().BackgroundLayers(),
background_rect);
if (geometry.HasNonLocalGeometry())
return false;
painted_extent = PhysicalRect(geometry.SnappedDestRect());
return true;
}
bool LayoutBox::BackgroundIsKnownToBeOpaqueInRect(
const PhysicalRect& local_rect) const {
// If the background transfers to view, the used background of this object
// is transparent.
if (BackgroundTransfersToView())
return false;
// If the element has appearance, it might be painted by theme.
// We cannot be sure if theme paints the background opaque.
// In this case it is safe to not assume opaqueness.
// FIXME: May be ask theme if it paints opaque.
if (StyleRef().HasEffectiveAppearance())
return false;
// FIXME: Check the opaqueness of background images.
// FIXME: Use rounded rect if border radius is present.
if (StyleRef().HasBorderRadius())
return false;
if (HasClipPath())
return false;
if (StyleRef().HasBlendMode())
return false;
return PhysicalBackgroundRect(kBackgroundKnownOpaqueRect)
.Contains(local_rect);
}
static bool IsCandidateForOpaquenessTest(const LayoutBox& child_box) {
const ComputedStyle& child_style = child_box.StyleRef();
if (child_style.GetPosition() != EPosition::kStatic &&
child_box.ContainingBlock() != child_box.Parent())
return false;
if (child_style.Visibility() != EVisibility::kVisible ||
child_style.ShapeOutside())
return false;
// CSS clip is not considered in foreground or background opaqueness checks.
if (child_box.HasClip())
return false;
if (child_box.Size().IsZero())
return false;
if (PaintLayer* child_layer = child_box.Layer()) {
// FIXME: perhaps this could be less conservative?
if (child_layer->GetCompositingState() != kNotComposited)
return false;
// FIXME: Deal with z-index.
if (child_style.IsStackingContext())
return false;
if (child_layer->HasTransformRelatedProperty() ||
child_layer->IsTransparent() ||
child_layer->HasFilterInducingProperty())
return false;
if (child_box.HasOverflowClip() && child_style.HasBorderRadius())
return false;
}
return true;
}
bool LayoutBox::ForegroundIsKnownToBeOpaqueInRect(
const PhysicalRect& local_rect,
unsigned max_depth_to_test) const {
if (!max_depth_to_test)
return false;
for (LayoutObject* child = SlowFirstChild(); child;
child = child->NextSibling()) {
if (!child->IsBox())
continue;
LayoutBox* child_box = ToLayoutBox(child);
if (!IsCandidateForOpaquenessTest(*child_box))
continue;
PhysicalOffset child_location = child_box->PhysicalLocation();
if (child_box->IsInFlowPositioned())
child_location += child_box->OffsetForInFlowPosition();
PhysicalRect child_local_rect = local_rect;
child_local_rect.Move(-child_location);
if (child_local_rect.Y() < 0 || child_local_rect.X() < 0) {
// If there is unobscured area above/left of a static positioned box then
// the rect is probably not covered. This can cause false-negative in
// non-horizontal-tb writing mode but is allowed.
if (!child_box->IsPositioned())
return false;
continue;
}
if (child_local_rect.Bottom() > child_box->Size().Height() ||
child_local_rect.Right() > child_box->Size().Width())
continue;
if (child_box->BackgroundIsKnownToBeOpaqueInRect(child_local_rect))
return true;
if (child_box->ForegroundIsKnownToBeOpaqueInRect(child_local_rect,
max_depth_to_test - 1))
return true;
}
return false;
}
DISABLE_CFI_PERF
bool LayoutBox::ComputeBackgroundIsKnownToBeObscured() const {
if (ScrollsOverflow())
return false;
// Test to see if the children trivially obscure the background.
if (!StyleRef().HasBackground())
return false;
// Root background painting is special.
if (IsLayoutView())
return false;
// FIXME: box-shadow is painted while background painting.
if (StyleRef().BoxShadow())
return false;
PhysicalRect background_rect;
if (!GetBackgroundPaintedExtent(background_rect))
return false;
return ForegroundIsKnownToBeOpaqueInRect(background_rect,
kBackgroundObscurationTestMaxDepth);
}
void LayoutBox::PaintMask(const PaintInfo& paint_info,
const PhysicalOffset& paint_offset) const {
BoxPainter(*this).PaintMask(paint_info, paint_offset);
}
void LayoutBox::ImageChanged(WrappedImagePtr image,
CanDeferInvalidation defer) {
bool is_box_reflect_image =
(StyleRef().BoxReflect() && StyleRef().BoxReflect()->Mask().GetImage() &&
StyleRef().BoxReflect()->Mask().GetImage()->Data() == image);
if (is_box_reflect_image && HasLayer()) {
Layer()->SetFilterOnEffectNodeDirty();
SetNeedsPaintPropertyUpdate();
}
// TODO(chrishtr): support delayed paint invalidation for animated border
// images.
if ((StyleRef().BorderImage().GetImage() &&
StyleRef().BorderImage().GetImage()->Data() == image) ||
(StyleRef().MaskBoxImage().GetImage() &&
StyleRef().MaskBoxImage().GetImage()->Data() == image) ||
is_box_reflect_image) {
SetShouldDoFullPaintInvalidationWithoutGeometryChange(
PaintInvalidationReason::kImage);
} else {
for (const FillLayer* layer = &StyleRef().MaskLayers(); layer;
layer = layer->Next()) {
if (layer->GetImage() && image == layer->GetImage()->Data()) {
SetShouldDoFullPaintInvalidationWithoutGeometryChange(
PaintInvalidationReason::kImage);
break;
}
}
}
if (!BackgroundTransfersToView()) {
for (const FillLayer* layer = &StyleRef().BackgroundLayers(); layer;
layer = layer->Next()) {
if (layer->GetImage() && image == layer->GetImage()->Data()) {
bool maybe_animated =
layer->GetImage()->CachedImage() &&
layer->GetImage()->CachedImage()->GetImage() &&
layer->GetImage()->CachedImage()->GetImage()->MaybeAnimated();
if (defer == CanDeferInvalidation::kYes && maybe_animated)
SetMayNeedPaintInvalidationAnimatedBackgroundImage();
else
SetBackgroundNeedsFullPaintInvalidation();
break;
}
}
}
ShapeValue* shape_outside_value = StyleRef().ShapeOutside();
if (!GetFrameView()->IsInPerformLayout() && IsFloating() &&
shape_outside_value && shape_outside_value->GetImage() &&
shape_outside_value->GetImage()->Data() == image) {
ShapeOutsideInfo& info = ShapeOutsideInfo::EnsureInfo(*this);
if (!info.IsComputingShape()) {
info.MarkShapeAsDirty();
MarkShapeOutsideDependentsForLayout();
}
}
}
ResourcePriority LayoutBox::ComputeResourcePriority() const {
PhysicalRect view_bounds = ViewRect();
PhysicalRect object_bounds = PhysicalContentBoxRect();
// TODO(japhet): Is this IgnoreTransforms correct? Would it be better to use
// the visual rect (which has ancestor clips and transforms applied)? Should
// we map to the top-level viewport instead of the current (sub) frame?
object_bounds.Move(LocalToAbsolutePoint(PhysicalOffset(), kIgnoreTransforms));
// The object bounds might be empty right now, so intersects will fail since
// it doesn't deal with empty rects. Use LayoutRect::contains in that case.
bool is_visible;
if (!object_bounds.IsEmpty())
is_visible = view_bounds.Intersects(object_bounds);
else
is_visible = view_bounds.Contains(object_bounds);
PhysicalRect screen_rect;
if (!object_bounds.IsEmpty()) {
screen_rect = view_bounds;
screen_rect.Intersect(object_bounds);
}
int screen_area = 0;
if (!screen_rect.IsEmpty() && is_visible)
screen_area = (screen_rect.Width() * screen_rect.Height()).ToInt();
return ResourcePriority(
is_visible ? ResourcePriority::kVisible : ResourcePriority::kNotVisible,
screen_area);
}
void LayoutBox::LocationChanged() {
// The location may change because of layout of other objects. Should check
// this object for paint invalidation.
if (!NeedsLayout())
SetShouldCheckForPaintInvalidation();
}
void LayoutBox::SizeChanged() {
// The size may change because of layout of other objects. Should check this
// object for paint invalidation.
if (!NeedsLayout())
SetShouldCheckForPaintInvalidation();
if (auto* element = DynamicTo<Element>(GetNode())) {
element->SetNeedsResizeObserverUpdate();
}
}
bool LayoutBox::IntersectsVisibleViewport() const {
PhysicalRect rect = PhysicalVisualOverflowRect();
LayoutView* layout_view = View();
while (layout_view->GetFrame()->OwnerLayoutObject())
layout_view = layout_view->GetFrame()->OwnerLayoutObject()->View();
MapToVisualRectInAncestorSpace(layout_view, rect);
return rect.Intersects(PhysicalRect(
layout_view->GetFrameView()->GetScrollableArea()->VisibleContentRect()));
}
void LayoutBox::EnsureIsReadyForPaintInvalidation() {
LayoutBoxModelObject::EnsureIsReadyForPaintInvalidation();
bool new_obscured = ComputeBackgroundIsKnownToBeObscured();
if (BackgroundIsKnownToBeObscured() != new_obscured) {
SetBackgroundIsKnownToBeObscured(new_obscured);
SetBackgroundNeedsFullPaintInvalidation();
}
if (MayNeedPaintInvalidationAnimatedBackgroundImage() &&
!BackgroundIsKnownToBeObscured()) {
SetBackgroundNeedsFullPaintInvalidation();
SetShouldDelayFullPaintInvalidation();
}
if (!ShouldDelayFullPaintInvalidation() || !IntersectsVisibleViewport())
return;
// Do regular full paint invalidation if the object with delayed paint
// invalidation is onscreen. This will clear
// ShouldDelayFullPaintInvalidation() flag and enable previous
// BackgroundNeedsFullPaintInvalidaiton() if it's set.
SetShouldDoFullPaintInvalidationWithoutGeometryChange(
FullPaintInvalidationReason());
}
void LayoutBox::InvalidatePaint(const PaintInvalidatorContext& context) const {
BoxPaintInvalidator(*this, context).InvalidatePaint();
}
PhysicalRect LayoutBox::OverflowClipRect(
const PhysicalOffset& location,
OverlayScrollbarClipBehavior overlay_scrollbar_clip_behavior) const {
PhysicalRect clip_rect;
if (IsEffectiveRootScroller()) {
// If this box is the effective root scroller, use the viewport clipping
// rect since it will account for the URL bar correctly which the border
// box does not. We can do this because the effective root scroller is
// restricted such that it exactly fills the viewport. See
// RootScrollerController::IsValidRootScroller()
clip_rect = PhysicalRect(location, View()->ViewRect().size);
} else {
// FIXME: When overflow-clip (CSS3) is implemented, we'll obtain the
// property here.
clip_rect = PhysicalBorderBoxRect();
clip_rect.Move(location);
clip_rect.Contract(BorderBoxOutsets());
}
if (HasOverflowClip())
ExcludeScrollbars(clip_rect, overlay_scrollbar_clip_behavior);
if (HasControlClip())
clip_rect.Intersect(ControlClipRect(location));
return clip_rect;
}
void LayoutBox::ExcludeScrollbars(
PhysicalRect& rect,
OverlayScrollbarClipBehavior overlay_scrollbar_clip_behavior) const {
if (PaintLayerScrollableArea* scrollable_area = GetScrollableArea()) {
if (ShouldPlaceBlockDirectionScrollbarOnLogicalLeft()) {
rect.offset.left += scrollable_area->VerticalScrollbarWidth(
overlay_scrollbar_clip_behavior);
}
rect.size.width -= scrollable_area->VerticalScrollbarWidth(
overlay_scrollbar_clip_behavior);
rect.size.height -= scrollable_area->HorizontalScrollbarHeight(
overlay_scrollbar_clip_behavior);
}
}
PhysicalRect LayoutBox::ClipRect(const PhysicalOffset& location) const {
PhysicalRect clip_rect(location, Size());
LayoutUnit width = Size().Width();
LayoutUnit height = Size().Height();
if (!StyleRef().ClipLeft().IsAuto()) {
LayoutUnit c = ValueForLength(StyleRef().ClipLeft(), width);
clip_rect.offset.left += c;
clip_rect.size.width -= c;
}
if (!StyleRef().ClipRight().IsAuto()) {
clip_rect.size.width -=
width - ValueForLength(StyleRef().ClipRight(), width);
}
if (!StyleRef().ClipTop().IsAuto()) {
LayoutUnit c = ValueForLength(StyleRef().ClipTop(), height);
clip_rect.offset.top += c;
clip_rect.size.height -= c;
}
if (!StyleRef().ClipBottom().IsAuto()) {
clip_rect.size.height -=
height - ValueForLength(StyleRef().ClipBottom(), height);
}
return clip_rect;
}
static LayoutUnit PortionOfMarginNotConsumedByFloat(LayoutUnit child_margin,
LayoutUnit content_side,
LayoutUnit offset) {
if (child_margin <= 0)
return LayoutUnit();
LayoutUnit content_side_with_margin = content_side + child_margin;
if (offset > content_side_with_margin)
return child_margin;
return offset - content_side;
}
LayoutUnit LayoutBox::ShrinkLogicalWidthToAvoidFloats(
LayoutUnit child_margin_start,
LayoutUnit child_margin_end,
const LayoutBlockFlow* cb) const {
LayoutUnit logical_top_position = LogicalTop();
LayoutUnit start_offset_for_content = cb->StartOffsetForContent();
LayoutUnit end_offset_for_content = cb->EndOffsetForContent();
// NOTE: This call to LogicalHeightForChild is bad, as it may contain data
// from a previous layout.
LayoutUnit logical_height = cb->LogicalHeightForChild(*this);
LayoutUnit start_offset_for_avoiding_floats =
cb->StartOffsetForAvoidingFloats(logical_top_position, logical_height);
LayoutUnit end_offset_for_avoiding_floats =
cb->EndOffsetForAvoidingFloats(logical_top_position, logical_height);
// If there aren't any floats constraining us then allow the margins to
// shrink/expand the width as much as they want.
if (start_offset_for_content == start_offset_for_avoiding_floats &&
end_offset_for_content == end_offset_for_avoiding_floats)
return cb->AvailableLogicalWidthForAvoidingFloats(logical_top_position,
logical_height) -
child_margin_start - child_margin_end;
LayoutUnit width = cb->AvailableLogicalWidthForAvoidingFloats(
logical_top_position, logical_height);
width -= std::max(LayoutUnit(), child_margin_start);
width -= std::max(LayoutUnit(), child_margin_end);
// We need to see if margins on either the start side or the end side can
// contain the floats in question. If they can, then just using the line width
// is inaccurate. In the case where a float completely fits, we don't need to
// use the line offset at all, but can instead push all the way to the content
// edge of the containing block. In the case where the float doesn't fit, we
// can use the line offset, but we need to grow it by the margin to reflect
// the fact that the margin was "consumed" by the float. Negative margins
// aren't consumed by the float, and so we ignore them.
width += PortionOfMarginNotConsumedByFloat(child_margin_start,
start_offset_for_content,
start_offset_for_avoiding_floats);
width += PortionOfMarginNotConsumedByFloat(
child_margin_end, end_offset_for_content, end_offset_for_avoiding_floats);
return width;
}
LayoutUnit LayoutBox::ContainingBlockLogicalHeightForGetComputedStyle() const {
if (HasOverrideContainingBlockContentLogicalHeight())
return OverrideContainingBlockContentLogicalHeight();
if (!IsPositioned())
return ContainingBlockLogicalHeightForContent(kExcludeMarginBorderPadding);
LayoutBoxModelObject* cb = ToLayoutBoxModelObject(Container());
LayoutUnit height = ContainingBlockLogicalHeightForPositioned(
cb, /* check_for_perpendicular_writing_mode */ false);
if (IsInFlowPositioned())
height -= cb->PaddingLogicalHeight();
return height;
}
LayoutUnit LayoutBox::ContainingBlockLogicalWidthForContent() const {
if (HasOverrideContainingBlockContentLogicalWidth())
return OverrideContainingBlockContentLogicalWidth();
LayoutBlock* cb = ContainingBlock();
if (IsOutOfFlowPositioned())
return cb->ClientLogicalWidth();
return cb->AvailableLogicalWidth();
}
LayoutUnit LayoutBox::ContainingBlockLogicalHeightForContent(
AvailableLogicalHeightType height_type) const {
if (HasOverrideContainingBlockContentLogicalHeight())
return OverrideContainingBlockContentLogicalHeight();
LayoutBlock* cb = ContainingBlock();
return cb->AvailableLogicalHeight(height_type);
}
LayoutUnit LayoutBox::ContainingBlockAvailableLineWidth() const {
LayoutBlock* cb = ContainingBlock();
auto* child_block_flow = DynamicTo<LayoutBlockFlow>(cb);
if (child_block_flow) {
return child_block_flow->AvailableLogicalWidthForAvoidingFloats(
LogicalTop(), AvailableLogicalHeight(kIncludeMarginBorderPadding));
}
return LayoutUnit();
}
LayoutUnit LayoutBox::PerpendicularContainingBlockLogicalHeight() const {
if (HasOverrideContainingBlockContentLogicalHeight())
return OverrideContainingBlockContentLogicalHeight();
LayoutBlock* cb = ContainingBlock();
if (cb->HasOverrideLogicalHeight())
return cb->OverrideContentLogicalHeight();
const ComputedStyle& containing_block_style = cb->StyleRef();
const Length& logical_height_length = containing_block_style.LogicalHeight();
// FIXME: For now just support fixed heights. Eventually should support
// percentage heights as well.
if (!logical_height_length.IsFixed()) {
LayoutUnit fill_fallback_extent =
LayoutUnit(containing_block_style.IsHorizontalWritingMode()
? View()->GetFrameView()->Size().Height()
: View()->GetFrameView()->Size().Width());
LayoutUnit fill_available_extent =
ContainingBlock()->AvailableLogicalHeight(kExcludeMarginBorderPadding);
if (fill_available_extent == -1)
return fill_fallback_extent;
return std::min(fill_available_extent, fill_fallback_extent);
}
// Use the content box logical height as specified by the style.
return cb->AdjustContentBoxLogicalHeightForBoxSizing(
LayoutUnit(logical_height_length.Value()));
}
void LayoutBox::MapLocalToAncestor(const LayoutBoxModelObject* ancestor,
TransformState& transform_state,
MapCoordinatesFlags mode) const {
bool is_fixed_pos = StyleRef().GetPosition() == EPosition::kFixed;
// If this box has a transform or contains paint, it acts as a fixed position
// container for fixed descendants, and may itself also be fixed position. So
// propagate 'fixed' up only if this box is fixed position.
if (CanContainFixedPositionObjects() && !is_fixed_pos)
mode &= ~kIsFixed;
else if (is_fixed_pos)
mode |= kIsFixed;
LayoutBoxModelObject::MapLocalToAncestor(ancestor, transform_state, mode);
}
void LayoutBox::MapAncestorToLocal(const LayoutBoxModelObject* ancestor,
TransformState& transform_state,
MapCoordinatesFlags mode) const {
if (this == ancestor)
return;
bool is_fixed_pos = StyleRef().GetPosition() == EPosition::kFixed;
// If this box has a transform or contains paint, it acts as a fixed position
// container for fixed descendants, and may itself also be fixed position. So
// propagate 'fixed' up only if this box is fixed position.
if (CanContainFixedPositionObjects() && !is_fixed_pos)
mode &= ~kIsFixed;
else if (is_fixed_pos)
mode |= kIsFixed;
LayoutBoxModelObject::MapAncestorToLocal(ancestor, transform_state, mode);
}
PhysicalOffset LayoutBox::OffsetFromContainerInternal(
const LayoutObject* o,
bool ignore_scroll_offset) const {
DCHECK_EQ(o, Container());
PhysicalOffset offset;
if (IsInFlowPositioned())
offset += OffsetForInFlowPosition();
offset += PhysicalLocation();
if (o->HasOverflowClip())
offset += OffsetFromScrollableContainer(o, ignore_scroll_offset);
if (IsOutOfFlowPositioned() && o->IsLayoutInline() &&
o->CanContainOutOfFlowPositionedElement(StyleRef().GetPosition())) {
offset += ToLayoutInline(o)->OffsetForInFlowPositionedInline(*this);
}
return offset;
}
InlineBox* LayoutBox::CreateInlineBox() {
return new InlineBox(LineLayoutItem(this));
}
void LayoutBox::DirtyLineBoxes(bool full_layout) {
if (!IsInLayoutNGInlineFormattingContext() && inline_box_wrapper_) {
if (full_layout) {
inline_box_wrapper_->Destroy();
inline_box_wrapper_ = nullptr;
} else {
inline_box_wrapper_->DirtyLineBoxes();
}
}
}
void LayoutBox::SetFirstInlineFragment(NGPaintFragment* fragment) {
CHECK(IsInLayoutNGInlineFormattingContext()) << *this;
first_paint_fragment_ = fragment;
}
void LayoutBox::InLayoutNGInlineFormattingContextWillChange(bool new_value) {
DeleteLineBoxWrapper();
// Because |first_paint_fragment_| and |inline_box_wrapper_| are union, when
// one is deleted, the other should be initialized to nullptr.
DCHECK(new_value ? !first_paint_fragment_ : !inline_box_wrapper_);
}
void LayoutBox::SetCachedLayoutResult(const NGLayoutResult& layout_result,
const NGBreakToken* break_token) {
if (break_token)
return;
if (layout_result.Status() != NGLayoutResult::kSuccess)
return;
if (!layout_result.HasValidConstraintSpaceForCaching())
return;
if (layout_result.GetConstraintSpaceForCaching().IsIntermediateLayout())
return;
if (layout_result.PhysicalFragment().BreakToken())
return;
cached_layout_result_ = &layout_result;
}
scoped_refptr<const NGLayoutResult> LayoutBox::CachedLayoutResult(
const NGConstraintSpace& new_space,
const NGBreakToken* break_token,
base::Optional<NGFragmentGeometry>* initial_fragment_geometry,
NGLayoutCacheStatus* out_cache_status) {
*out_cache_status = NGLayoutCacheStatus::kNeedsLayout;
if (!RuntimeEnabledFeatures::LayoutNGFragmentCachingEnabled())
return nullptr;
const NGLayoutResult* cached_layout_result = GetCachedLayoutResult();
if (!cached_layout_result)
return nullptr;
// TODO(cbiesinger): Support caching fragmented boxes.
if (break_token)
return nullptr;
// Set our initial temporary cache status to "hit".
NGLayoutCacheStatus cache_status = NGLayoutCacheStatus::kHit;
// If the display-lock blocked child layout, then we don't clear child needs
// layout bits. However, we can still use the cached result, since we will
// re-layout when unlocking.
bool child_needs_layout_unless_locked =
!LayoutBlockedByDisplayLock(DisplayLockLifecycleTarget::kChildren) &&
(PosChildNeedsLayout() || NormalChildNeedsLayout());
if (SelfNeedsLayoutForStyle() || child_needs_layout_unless_locked ||
NeedsSimplifiedNormalFlowLayout() ||
(NeedsPositionedMovementLayout() &&
!NeedsPositionedMovementLayoutOnly())) {
// Check if we only need "simplified" layout. We don't abort yet, as we
// need to check if other things (like floats) will require us to perform a
// full layout.
//
// We don't regenerate any lineboxes during our "simplified" layout pass.
// If something needs "simplified" layout within a linebox, (e.g. an
// atomic-inline) we miss the cache.
if (NeedsSimplifiedLayoutOnly() &&
(!ChildrenInline() || !NeedsSimplifiedNormalFlowLayout()))
cache_status = NGLayoutCacheStatus::kNeedsSimplifiedLayout;
else
return nullptr;
}
const NGPhysicalContainerFragment& physical_fragment =
cached_layout_result->PhysicalFragment();
DCHECK(!physical_fragment.BreakToken());
// If we have an orthogonal flow root descendant, we don't attempt to cache
// our layout result. This is because the initial containing block size may
// have changed, having a high likelihood of changing the size of the
// orthogonal flow root.
if (physical_fragment.HasOrthogonalFlowRoots())
return nullptr;
NGBlockNode node(this);
NGLayoutCacheStatus size_cache_status = CalculateSizeBasedLayoutCacheStatus(
node, *cached_layout_result, new_space, initial_fragment_geometry);
// If our size may change (or we know a descendants size may change), we miss
// the cache.
if (size_cache_status == NGLayoutCacheStatus::kNeedsLayout)
return nullptr;
// Update our temporary cache status, if the size cache check indicated we
// might need simplified layout.
if (size_cache_status == NGLayoutCacheStatus::kNeedsSimplifiedLayout)
cache_status = NGLayoutCacheStatus::kNeedsSimplifiedLayout;
LayoutUnit bfc_line_offset = new_space.BfcOffset().line_offset;
base::Optional<LayoutUnit> bfc_block_offset =
cached_layout_result->BfcBlockOffset();
LayoutUnit block_offset_delta;
NGMarginStrut end_margin_strut = cached_layout_result->EndMarginStrut();
const NGConstraintSpace& old_space =
cached_layout_result->GetConstraintSpaceForCaching();
// Check the BFC offset. Even if they don't match, there're some cases we can
// still reuse the fragment.
bool are_bfc_offsets_equal =
new_space.BfcOffset() == old_space.BfcOffset() &&
new_space.ExpectedBfcBlockOffset() ==
old_space.ExpectedBfcBlockOffset() &&
new_space.ForcedBfcBlockOffset() == old_space.ForcedBfcBlockOffset();
// Even for the first fragment, when block fragmentation is enabled, block
// offset changes should cause re-layout, since we will fragment at other
// locations than before.
if (UNLIKELY(!are_bfc_offsets_equal && new_space.HasBlockFragmentation())) {
DCHECK(old_space.HasBlockFragmentation());
return nullptr;
}
bool is_margin_strut_equal =
new_space.MarginStrut() == old_space.MarginStrut();
bool is_exclusion_space_equal =
new_space.ExclusionSpace() == old_space.ExclusionSpace();
bool is_new_formatting_context =
physical_fragment.IsBlockFormattingContextRoot();
// If a node *doesn't* establish a new formatting context it may be affected
// by floats, or clearance.
// If anything has changed prior to us (different exclusion space, etc), we
// need to perform a series of additional checks if we can still reuse this
// layout result.
if (!is_new_formatting_context &&
(!are_bfc_offsets_equal || !is_exclusion_space_equal ||
!is_margin_strut_equal ||
new_space.ClearanceOffset() != old_space.ClearanceOffset())) {
DCHECK(!CreatesNewFormattingContext());
// If we have a different BFC offset, or exclusion space we can't perform
// "simplified" layout.
// This may occur if our %-block-size has changed (allowing "simplified"
// layout), and we've been pushed down in the BFC coordinate space by a
// sibling.
// The "simplified" layout algorithm doesn't have the required logic to
// shift any added exclusions within the output exclusion space.
if (cache_status == NGLayoutCacheStatus::kNeedsSimplifiedLayout)
return nullptr;
DCHECK_EQ(cache_status, NGLayoutCacheStatus::kHit);
if (!MaySkipLayoutWithinBlockFormattingContext(
*cached_layout_result, new_space, &bfc_block_offset,
&block_offset_delta, &end_margin_strut))
return nullptr;
}
// We've performed all of the cache checks at this point. If we need
// "simplified" layout then abort now.
*out_cache_status = cache_status;
if (*out_cache_status == NGLayoutCacheStatus::kNeedsSimplifiedLayout)
return nullptr;
physical_fragment.CheckType();
DCHECK_EQ(*out_cache_status, NGLayoutCacheStatus::kHit);
// We can safely re-use this fragment if we are positioned, and only our
// position constraints changed (left/top/etc). However we need to clear the
// dirty layout bit(s). Note that we may be here because we are display locked
// and have cached a locked layout result. In that case, this function will
// not clear the child dirty bits.
ClearNeedsLayout();
// The checks above should be enough to bail if layout is incomplete, but
// let's verify:
DCHECK(IsBlockLayoutComplete(old_space, *cached_layout_result));
// OOF-positioned nodes have to two-tier cache. The additional cache check
// runs before the OOF-positioned sizing, and positioning calculations.
//
// This additional check compares the percentage resolution size.
//
// As a result, the cached layout result always needs to contain the previous
// percentage resolution size in order for the first-tier cache to work.
// See |NGBlockNode::CachedLayoutResultForOutOfFlowPositioned|.
bool needs_cached_result_update =
node.IsOutOfFlowPositioned() && new_space.PercentageResolutionSize() !=
old_space.PercentageResolutionSize();
// We can safely reuse this result if our BFC and "input" exclusion spaces
// were equal.
if (are_bfc_offsets_equal && is_exclusion_space_equal &&
is_margin_strut_equal && !needs_cached_result_update) {
// In order not to rebuild the internal derived-geometry "cache" of float
// data, we need to move this to the new "output" exclusion space.
cached_layout_result->ExclusionSpace().MoveAndUpdateDerivedGeometry(
new_space.ExclusionSpace());
return cached_layout_result;
}
scoped_refptr<const NGLayoutResult> new_result =
base::AdoptRef(new NGLayoutResult(*cached_layout_result, new_space,
end_margin_strut, bfc_line_offset,
bfc_block_offset, block_offset_delta));
if (needs_cached_result_update)
SetCachedLayoutResult(*new_result, break_token);
return new_result;
}
void LayoutBox::PositionLineBox(InlineBox* box) {
if (IsOutOfFlowPositioned()) {
// Cache the x position only if we were an INLINE type originally.
bool originally_inline = StyleRef().IsOriginalDisplayInlineType();
if (originally_inline) {
// The value is cached in the xPos of the box. We only need this value if
// our object was inline originally, since otherwise it would have ended
// up underneath the inlines.
RootInlineBox& root = box->Root();
root.Block().SetStaticInlinePositionForChild(LineLayoutBox(this),
box->LogicalLeft());
} else {
// Our object was a block originally, so we make our normal flow position
// be just below the line box (as though all the inlines that came before
// us got wrapped in an anonymous block, which is what would have happened
// had we been in flow). This value was cached in the y() of the box.
Layer()->SetStaticBlockPosition(box->LogicalTop());
}
if (Container()->IsLayoutInline())
MoveWithEdgeOfInlineContainerIfNecessary(box->IsHorizontal());
// Nuke the box.
box->Remove(kDontMarkLineBoxes);
box->Destroy();
} else if (IsAtomicInlineLevel()) {
SetLocationAndUpdateOverflowControlsIfNeeded(box->Location());
SetInlineBoxWrapper(box);
}
}
void LayoutBox::MoveWithEdgeOfInlineContainerIfNecessary(bool is_horizontal) {
DCHECK(IsOutOfFlowPositioned());
DCHECK(Container()->IsLayoutInline());
DCHECK(Container()->CanContainOutOfFlowPositionedElement(
StyleRef().GetPosition()));
// If this object is inside a relative positioned inline and its inline
// position is an explicit offset from the edge of its container then it will
// need to move if its inline container has changed width. We do not track if
// the width has changed but if we are here then we are laying out lines
// inside it, so it probably has - mark our object for layout so that it can
// move to the new offset created by the new width.
if (!NormalChildNeedsLayout() &&
!StyleRef().HasStaticInlinePosition(is_horizontal))
SetChildNeedsLayout(kMarkOnlyThis);
}
void LayoutBox::DeleteLineBoxWrapper() {
if (!IsInLayoutNGInlineFormattingContext() && inline_box_wrapper_) {
if (!DocumentBeingDestroyed())
inline_box_wrapper_->Remove();
inline_box_wrapper_->Destroy();
inline_box_wrapper_ = nullptr;
}
}
void LayoutBox::SetSpannerPlaceholder(
LayoutMultiColumnSpannerPlaceholder& placeholder) {
// Not expected to change directly from one spanner to another.
CHECK(!rare_data_ || !rare_data_->spanner_placeholder_);
EnsureRareData().spanner_placeholder_ = &placeholder;
}
void LayoutBox::ClearSpannerPlaceholder() {
if (!rare_data_)
return;
rare_data_->spanner_placeholder_ = nullptr;
}
void LayoutBox::SetPaginationStrut(LayoutUnit strut) {
if (!strut && !rare_data_)
return;
EnsureRareData().pagination_strut_ = strut;
}
bool LayoutBox::IsBreakBetweenControllable(EBreakBetween break_value) const {
if (break_value == EBreakBetween::kAuto)
return true;
// We currently only support non-auto break-before and break-after values on
// in-flow block level elements, which is the minimum requirement according to
// the spec.
if (IsInline() || IsFloatingOrOutOfFlowPositioned())
return false;
const LayoutBlock* curr = ContainingBlock();
if (!curr || !curr->IsLayoutBlockFlow())
return false;
const LayoutView* layout_view = View();
bool view_is_paginated = layout_view->FragmentationContext();
if (!view_is_paginated && !FlowThreadContainingBlock())
return false;
while (curr) {
if (curr == layout_view) {
return view_is_paginated && break_value != EBreakBetween::kColumn &&
break_value != EBreakBetween::kAvoidColumn;
}
if (curr->IsLayoutFlowThread()) {
if (break_value ==
EBreakBetween::kAvoid) // Valid in any kind of fragmentation context.
return true;
bool is_multicol_value = break_value == EBreakBetween::kColumn ||
break_value == EBreakBetween::kAvoidColumn;
if (is_multicol_value)
return true;
// If this is a flow thread for a multicol container, and we have a break
// value for paged, we need to keep looking.
}
if (curr->IsOutOfFlowPositioned())
return false;
curr = curr->ContainingBlock();
}
NOTREACHED();
return false;
}
bool LayoutBox::IsBreakInsideControllable(EBreakInside break_value) const {
if (break_value == EBreakInside::kAuto)
return true;
// First check multicol.
const LayoutFlowThread* flow_thread = FlowThreadContainingBlock();
// 'avoid-column' is only valid in a multicol context.
if (break_value == EBreakInside::kAvoidColumn)
return flow_thread;
// 'avoid' is valid in any kind of fragmentation context.
if (break_value == EBreakInside::kAvoid && flow_thread)
return true;
DCHECK(break_value == EBreakInside::kAvoidPage ||
break_value == EBreakInside::kAvoid);
if (View()->FragmentationContext())
return true; // The view is paginated, probably because we're printing.
if (!flow_thread)
return false; // We're not inside any pagination context
return false;
}
EBreakBetween LayoutBox::BreakAfter() const {
EBreakBetween break_value = StyleRef().BreakAfter();
if (break_value == EBreakBetween::kAuto ||
IsBreakBetweenControllable(break_value))
return break_value;
return EBreakBetween::kAuto;
}
EBreakBetween LayoutBox::BreakBefore() const {
EBreakBetween break_value = StyleRef().BreakBefore();
if (break_value == EBreakBetween::kAuto ||
IsBreakBetweenControllable(break_value))
return break_value;
return EBreakBetween::kAuto;
}
EBreakInside LayoutBox::BreakInside() const {
EBreakInside break_value = StyleRef().BreakInside();
if (break_value == EBreakInside::kAuto ||
IsBreakInsideControllable(break_value))
return break_value;
return EBreakInside::kAuto;
}
EBreakBetween LayoutBox::ClassABreakPointValue(
EBreakBetween previous_break_after_value) const {
// First assert that we're at a class A break point.
DCHECK(IsBreakBetweenControllable(previous_break_after_value));
return JoinFragmentainerBreakValues(previous_break_after_value,
BreakBefore());
}
bool LayoutBox::NeedsForcedBreakBefore(
EBreakBetween previous_break_after_value) const {
// Forced break values are only honored when specified on in-flow objects, but
// floats and out-of-flow positioned objects may be affected by a break-after
// value of the previous in-flow object, even though we're not at a class A
// break point.
EBreakBetween break_value =
IsFloatingOrOutOfFlowPositioned()
? previous_break_after_value
: ClassABreakPointValue(previous_break_after_value);
return IsForcedFragmentainerBreakValue(break_value);
}
bool LayoutBox::PaintedOutputOfObjectHasNoEffectRegardlessOfSize() const {
if (HasNonCompositedScrollbars() || IsSelected() ||
HasBoxDecorationBackground() || StyleRef().HasBoxDecorations() ||
StyleRef().HasVisualOverflowingEffect())
return false;
// Both mask and clip-path generates drawing display items that depends on
// the size of the box.
if (HasMask() || HasClipPath())
return false;
// If the box paints into its own backing, we can assume that it's painting
// may have some effect. For example, honoring the border-radius clip on
// a composited child paints into a mask for an otherwise non-painting
// element, because children of that element will require the mask.
if (HasLayer() && Layer()->GetCompositingState() == kPaintsIntoOwnBacking)
return false;
return true;
}
PhysicalRect LayoutBox::LocalVisualRectIgnoringVisibility() const {
return PhysicalSelfVisualOverflowRect();
}
void LayoutBox::InflateVisualRectForFilterUnderContainer(
TransformState& transform_state,
const LayoutObject& container,
const LayoutBoxModelObject* ancestor_to_stop_at) const {
transform_state.Flatten();
// Apply visual overflow caused by reflections and filters defined on objects
// between this object and container (not included) or ancestorToStopAt
// (included).
PhysicalOffset offset_from_container = OffsetFromContainer(&container);
transform_state.Move(offset_from_container);
for (LayoutObject* parent = Parent(); parent && parent != container;
parent = parent->Parent()) {
if (parent->IsBox()) {
// Convert rect into coordinate space of parent to apply parent's
// reflection and filter.
PhysicalOffset parent_offset = parent->OffsetFromAncestor(&container);
transform_state.Move(-parent_offset);
ToLayoutBox(parent)->InflateVisualRectForFilter(transform_state);
transform_state.Move(parent_offset);
}
if (parent == ancestor_to_stop_at)
break;
}
transform_state.Move(-offset_from_container);
}
bool LayoutBox::MapToVisualRectInAncestorSpaceInternal(
const LayoutBoxModelObject* ancestor,
TransformState& transform_state,
VisualRectFlags visual_rect_flags) const {
InflateVisualRectForFilter(transform_state);
if (ancestor == this)
return true;
AncestorSkipInfo skip_info(ancestor, true);
LayoutObject* container = Container(&skip_info);
LayoutBox* table_row_container = nullptr;
// Skip table row because cells and rows are in the same coordinate space (see
// below, however for more comments about when |ancestor| is the table row).
if (IsTableCell()) {
DCHECK(container->IsTableRow());
DCHECK_EQ(ParentBox(), container);
if (container != ancestor)
container = container->Parent();
else
table_row_container = ToLayoutBox(container);
}
if (!container)
return true;
PhysicalOffset container_offset;
if (container->IsBox()) {
container_offset += PhysicalLocation(ToLayoutBox(container));
// If the row is the ancestor, however, add its offset back in. In effect,
// this passes from the joint <td> / <tr> coordinate space to the parent
// space, then back to <tr> / <td>.
if (table_row_container) {
container_offset -=
table_row_container->PhysicalLocation(ToLayoutBox(container));
}
} else {
container_offset += PhysicalLocation();
}
const ComputedStyle& style_to_use = StyleRef();
EPosition position = style_to_use.GetPosition();
if (IsOutOfFlowPositioned() && container->IsLayoutInline() &&
container->CanContainOutOfFlowPositionedElement(position)) {
container_offset +=
ToLayoutInline(container)->OffsetForInFlowPositionedInline(*this);
} else if (style_to_use.HasInFlowPosition() && Layer()) {
// Apply the relative position offset when invalidating a rectangle. The
// layer is translated, but the layout box isn't, so we need to do this to
// get the right dirty rect. Since this is called from
// LayoutObject::setStyle, the relative position flag on the LayoutObject
// has been cleared, so use the one on the style().
container_offset += OffsetForInFlowPosition();
}
if (skip_info.FilterSkipped()) {
InflateVisualRectForFilterUnderContainer(transform_state, *container,
ancestor);
}
if (!MapVisualRectToContainer(container, container_offset, ancestor,
visual_rect_flags, transform_state))
return false;
if (skip_info.AncestorSkipped()) {
bool preserve3D = container->StyleRef().Preserves3D();
TransformState::TransformAccumulation accumulation =
preserve3D ? TransformState::kAccumulateTransform
: TransformState::kFlattenTransform;
// If the ancestor is below the container, then we need to map the rect into
// ancestor's coordinates.
PhysicalOffset container_offset = ancestor->OffsetFromAncestor(container);
transform_state.Move(-container_offset, accumulation);
return true;
}
if (container->IsLayoutView()) {
bool use_fixed_position_adjustment =
position == EPosition::kFixed && container == ancestor;
return ToLayoutView(container)->MapToVisualRectInAncestorSpaceInternal(
ancestor, transform_state, use_fixed_position_adjustment ? kIsFixed : 0,
visual_rect_flags);
} else {
return container->MapToVisualRectInAncestorSpaceInternal(
ancestor, transform_state, visual_rect_flags);
}
}
void LayoutBox::InflateVisualRectForFilter(
TransformState& transform_state) const {
if (!Layer() || !Layer()->PaintsWithFilters())
return;
transform_state.Flatten();
PhysicalRect rect = PhysicalRect::EnclosingRect(
transform_state.LastPlanarQuad().BoundingBox());
transform_state.SetQuad(
FloatQuad(FloatRect(Layer()->MapRectForFilter(rect))));
}
static bool ShouldRecalculateMinMaxWidthsAffectedByAncestor(
const LayoutBox* box) {
if (box->PreferredLogicalWidthsDirty()) {
// If the preferred widths are already dirty at this point (during layout),
// it actually means that we never need to calculate them, since that should
// have been carried out by an ancestor that's sized based on preferred
// widths (a shrink-to-fit container, for instance). In such cases the
// object will be left as dirty indefinitely, and it would just be a waste
// of time to calculate the preferred withs when nobody needs them.
return false;
}
if (const LayoutBox* containing_block = box->ContainingBlock()) {
if (containing_block->NeedsPreferredWidthsRecalculation() &&
!containing_block->PreferredLogicalWidthsDirty()) {
// If our containing block also has min/max widths that are affected by
// the ancestry, we have already dealt with this object as well. Avoid
// unnecessary work and O(n^2) time complexity.
return false;
}
}
return true;
}
void LayoutBox::UpdateLogicalWidth() {
if (NeedsPreferredWidthsRecalculation()) {
if (ShouldRecalculateMinMaxWidthsAffectedByAncestor(this)) {
// Laying out this object means that its containing block is also being
// laid out. This object is special, in that its min/max widths depend on
// the ancestry (min/max width calculation should ideally be strictly
// bottom-up, but that's not always the case), so since the containing
// block size may have changed, we need to recalculate the min/max widths
// of this object, and every child that has the same issue, recursively.
SetPreferredLogicalWidthsDirty(kMarkOnlyThis);
// Since all this takes place during actual layout, instead of being part
// of min/max the width calculation machinery, we need to enter said
// machinery here, to make sure that what was dirtied is actualy
// recalculated. Leaving things dirty would mean that any subsequent
// dirtying of descendants would fail.
ComputePreferredLogicalWidths();
}
}
LogicalExtentComputedValues computed_values;
ComputeLogicalWidth(computed_values);
SetLogicalWidth(computed_values.extent_);
SetLogicalLeft(computed_values.position_);
SetMarginStart(computed_values.margins_.start_);
SetMarginEnd(computed_values.margins_.end_);
}
static float GetMaxWidthListMarker(const LayoutBox* layout_object) {
#if DCHECK_IS_ON()
DCHECK(layout_object);
Node* parent_node = layout_object->GeneratingNode();
DCHECK(parent_node);
DCHECK(IsHTMLOListElement(parent_node) || IsHTMLUListElement(parent_node));
DCHECK_NE(layout_object->StyleRef().TextAutosizingMultiplier(), 1);
#endif
float max_width = 0;
for (LayoutObject* child = layout_object->SlowFirstChild(); child;
child = child->NextSibling()) {
if (!child->IsListItem())
continue;
LayoutBox* list_item = ToLayoutBox(child);
for (LayoutObject* item_child = list_item->SlowFirstChild(); item_child;
item_child = item_child->NextSibling()) {
if (!item_child->IsListMarker())
continue;
LayoutBox* item_marker = ToLayoutBox(item_child);
// Make sure to compute the autosized width.
if (item_marker->NeedsLayout())
item_marker->UpdateLayout();
max_width = std::max<float>(
max_width, ToLayoutListMarker(item_marker)->LogicalWidth().ToFloat());
break;
}
}
return max_width;
}
DISABLE_CFI_PERF
void LayoutBox::ComputeLogicalWidth(
LogicalExtentComputedValues& computed_values) const {
if (ShouldApplySizeContainment()) {
computed_values.extent_ = ContentLogicalWidthForSizeContainment() +
BorderAndPaddingLogicalWidth() +
ScrollbarLogicalWidth();
} else if (DisplayLockInducesSizeContainment()) {
computed_values.extent_ =
BorderAndPaddingLogicalWidth() + ScrollbarLogicalWidth() +
GetDisplayLockContext()->GetLockedContentLogicalWidth();
} else {
computed_values.extent_ = LogicalWidth();
}
computed_values.position_ = LogicalLeft();
computed_values.margins_.start_ = MarginStart();
computed_values.margins_.end_ = MarginEnd();
// The parent box is flexing us, so it has increased or decreased our
// width. Use the width from the style context.
if (HasOverrideLogicalWidth()) {
computed_values.extent_ = OverrideLogicalWidth();
return;
}
if (IsOutOfFlowPositioned()) {
ComputePositionedLogicalWidth(computed_values);
return;
}
// FIXME: Account for writing-mode in flexible boxes.
// https://bugs.webkit.org/show_bug.cgi?id=46418
bool in_vertical_box =
Parent()->IsDeprecatedFlexibleBox() &&
(Parent()->StyleRef().BoxOrient() == EBoxOrient::kVertical);
bool stretching =
(Parent()->StyleRef().BoxAlign() == EBoxAlignment::kStretch);
// TODO (lajava): Stretching is the only reason why we don't want the box to
// be treated as a replaced element, so we could perhaps refactor all this
// logic, not only for flex and grid since alignment is intended to be applied
// to any block.
bool treat_as_replaced = ShouldComputeSizeAsReplaced() &&
(!in_vertical_box || !stretching) &&
(!IsGridItem() || !HasStretchedLogicalWidth());
const ComputedStyle& style_to_use = StyleRef();
LayoutBlock* cb = ContainingBlock();
LayoutUnit container_logical_width =
std::max(LayoutUnit(), ContainingBlockLogicalWidthForContent());
bool has_perpendicular_containing_block =
cb->IsHorizontalWritingMode() != IsHorizontalWritingMode();
if (IsInline() && !IsInlineBlockOrInlineTable()) {
// just calculate margins
computed_values.margins_.start_ = MinimumValueForLength(
style_to_use.MarginStart(), container_logical_width);
computed_values.margins_.end_ = MinimumValueForLength(
style_to_use.MarginEnd(), container_logical_width);
if (treat_as_replaced) {
computed_values.extent_ = std::max(
ComputeReplacedLogicalWidth() + BorderAndPaddingLogicalWidth(),
MinPreferredLogicalWidth());
}
return;
}
LayoutUnit container_width_in_inline_direction = container_logical_width;
if (has_perpendicular_containing_block) {
// PerpendicularContainingBlockLogicalHeight() can return -1 in some
// situations but we cannot have a negative width, that's why we clamp it to
// zero.
container_width_in_inline_direction =
PerpendicularContainingBlockLogicalHeight().ClampNegativeToZero();
}
// Width calculations
if (treat_as_replaced) {
computed_values.extent_ =
ComputeReplacedLogicalWidth() + BorderAndPaddingLogicalWidth();
} else {
LayoutUnit preferred_width = ComputeLogicalWidthUsing(
kMainOrPreferredSize, style_to_use.LogicalWidth(),
container_width_in_inline_direction, cb);
computed_values.extent_ = ConstrainLogicalWidthByMinMax(
preferred_width, container_width_in_inline_direction, cb);
}
// Margin calculations.
ComputeMarginsForDirection(
kInlineDirection, cb, container_logical_width, computed_values.extent_,
computed_values.margins_.start_, computed_values.margins_.end_,
StyleRef().MarginStart(), StyleRef().MarginEnd());
if (!has_perpendicular_containing_block && container_logical_width &&
container_logical_width !=
(computed_values.extent_ + computed_values.margins_.start_ +
computed_values.margins_.end_) &&
!IsFloating() && !IsInline() &&
!cb->IsFlexibleBoxIncludingDeprecatedAndNG() && !cb->IsLayoutGrid()) {
LayoutUnit new_margin_total =
container_logical_width - computed_values.extent_;
bool has_inverted_direction = cb->StyleRef().IsLeftToRightDirection() !=
StyleRef().IsLeftToRightDirection();
if (has_inverted_direction) {
computed_values.margins_.start_ =
new_margin_total - computed_values.margins_.end_;
} else {
computed_values.margins_.end_ =
new_margin_total - computed_values.margins_.start_;
}
}
if (style_to_use.TextAutosizingMultiplier() != 1 &&
style_to_use.MarginStart().IsFixed()) {
Node* parent_node = GeneratingNode();
if (parent_node && (IsHTMLOListElement(*parent_node) ||
IsHTMLUListElement(*parent_node))) {
// Make sure the markers in a list are properly positioned (i.e. not
// chopped off) when autosized.
const float adjusted_margin =
(1 - 1.0 / style_to_use.TextAutosizingMultiplier()) *
GetMaxWidthListMarker(this);
bool has_inverted_direction = cb->StyleRef().IsLeftToRightDirection() !=
StyleRef().IsLeftToRightDirection();
if (has_inverted_direction)
computed_values.margins_.end_ += adjusted_margin;
else
computed_values.margins_.start_ += adjusted_margin;
}
}
}
LayoutUnit LayoutBox::FillAvailableMeasure(
LayoutUnit available_logical_width) const {
LayoutUnit margin_start;
LayoutUnit margin_end;
return FillAvailableMeasure(available_logical_width, margin_start,
margin_end);
}
LayoutUnit LayoutBox::FillAvailableMeasure(LayoutUnit available_logical_width,
LayoutUnit& margin_start,
LayoutUnit& margin_end) const {
DCHECK_GE(available_logical_width, 0);
bool isOrthogonalElement =
IsHorizontalWritingMode() != ContainingBlock()->IsHorizontalWritingMode();
LayoutUnit available_size_for_resolving_margin =
isOrthogonalElement ? ContainingBlockLogicalWidthForContent()
: available_logical_width;
margin_start = MinimumValueForLength(StyleRef().MarginStart(),
available_size_for_resolving_margin);
margin_end = MinimumValueForLength(StyleRef().MarginEnd(),
available_size_for_resolving_margin);
if (HasOverrideAvailableInlineSize())
available_logical_width = OverrideAvailableInlineSize();
LayoutUnit available = available_logical_width - margin_start - margin_end;
available = std::max(available, LayoutUnit());
return available;
}
DISABLE_CFI_PERF
LayoutUnit LayoutBox::ComputeIntrinsicLogicalWidthUsing(
const Length& logical_width_length,
LayoutUnit available_logical_width,
LayoutUnit border_and_padding) const {
if (logical_width_length.IsFillAvailable()) {
if (!IsA<HTMLMarqueeElement>(GetNode())) {
UseCounter::Count(GetDocument(),
WebFeature::kCSSFillAvailableLogicalWidth);
}
return std::max(border_and_padding,
FillAvailableMeasure(available_logical_width));
}
LayoutUnit min_logical_width;
LayoutUnit max_logical_width;
ComputeIntrinsicLogicalWidths(min_logical_width, max_logical_width);
if (logical_width_length.IsMinContent())
return min_logical_width + border_and_padding;
if (logical_width_length.IsMaxContent())
return max_logical_width + border_and_padding;
if (logical_width_length.IsFitContent()) {
min_logical_width += border_and_padding;
max_logical_width += border_and_padding;
return std::max(min_logical_width,
std::min(max_logical_width,
FillAvailableMeasure(available_logical_width)));
}
NOTREACHED();
return LayoutUnit();
}
DISABLE_CFI_PERF
LayoutUnit LayoutBox::ComputeLogicalWidthUsing(
SizeType width_type,
const Length& logical_width,
LayoutUnit available_logical_width,
const LayoutBlock* cb) const {
DCHECK(width_type == kMinSize || width_type == kMainOrPreferredSize ||
!logical_width.IsAuto());
if (width_type == kMinSize && logical_width.IsAuto())
return AdjustBorderBoxLogicalWidthForBoxSizing(0);
if (!logical_width.IsIntrinsicOrAuto()) {
// FIXME: If the containing block flow is perpendicular to our direction we
// need to use the available logical height instead.
return AdjustBorderBoxLogicalWidthForBoxSizing(
ValueForLength(logical_width, available_logical_width));
}
if (logical_width.IsIntrinsic())
return ComputeIntrinsicLogicalWidthUsing(
logical_width, available_logical_width, BorderAndPaddingLogicalWidth());
LayoutUnit margin_start;
LayoutUnit margin_end;
LayoutUnit logical_width_result =
FillAvailableMeasure(available_logical_width, margin_start, margin_end);
auto* child_block_flow = DynamicTo<LayoutBlockFlow>(cb);
if (ShrinkToAvoidFloats() && child_block_flow &&
child_block_flow->ContainsFloats()) {
logical_width_result = std::min(
logical_width_result, ShrinkLogicalWidthToAvoidFloats(
margin_start, margin_end, child_block_flow));
}
if (width_type == kMainOrPreferredSize &&
SizesLogicalWidthToFitContent(logical_width)) {
// Reset width so that any percent margins on inline children do not
// use it when calculating min/max preferred width.
// TODO(crbug.com/710026): Remove const_cast
LayoutUnit w = LogicalWidth();
const_cast<LayoutBox*>(this)->SetLogicalWidth(LayoutUnit());
LayoutUnit result =
std::max(MinPreferredLogicalWidth(),
std::min(MaxPreferredLogicalWidth(), logical_width_result));
const_cast<LayoutBox*>(this)->SetLogicalWidth(w);
return result;
}
return logical_width_result;
}
bool LayoutBox::ColumnFlexItemHasStretchAlignment() const {
// auto margins mean we don't stretch. Note that this function will only be
// used for widths, so we don't have to check marginBefore/marginAfter.
const auto& parent_style = Parent()->StyleRef();
DCHECK(parent_style.ResolvedIsColumnFlexDirection());
if (StyleRef().MarginStart().IsAuto() || StyleRef().MarginEnd().IsAuto())
return false;
return StyleRef()
.ResolvedAlignSelf(
ContainingBlock()->SelfAlignmentNormalBehavior(),
&parent_style)
.GetPosition() == ItemPosition::kStretch;
}
bool LayoutBox::IsStretchingColumnFlexItem() const {
LayoutObject* parent = Parent();
if (parent->IsDeprecatedFlexibleBox() &&
parent->StyleRef().BoxOrient() == EBoxOrient::kVertical &&
parent->StyleRef().BoxAlign() == EBoxAlignment::kStretch)
return true;
// We don't stretch multiline flexboxes because they need to apply line
// spacing (align-content) first.
if (parent->IsFlexibleBoxIncludingNG() &&
parent->StyleRef().FlexWrap() == EFlexWrap::kNowrap &&
parent->StyleRef().ResolvedIsColumnFlexDirection() &&
ColumnFlexItemHasStretchAlignment())
return true;
return false;
}
// TODO (lajava) Can/Should we move this inside specific layout classes (flex.
// grid)? Can we refactor columnFlexItemHasStretchAlignment logic?
bool LayoutBox::HasStretchedLogicalWidth() const {
const ComputedStyle& style = StyleRef();
if (!style.LogicalWidth().IsAuto() || style.MarginStart().IsAuto() ||
style.MarginEnd().IsAuto())
return false;
LayoutBlock* cb = ContainingBlock();
if (!cb) {
// We are evaluating align-self/justify-self, which default to 'normal' for
// the root element. The 'normal' value behaves like 'start' except for
// Flexbox Items, which obviously should have a container.
return false;
}
if (cb->IsHorizontalWritingMode() != IsHorizontalWritingMode()) {
return style
.ResolvedAlignSelf(cb->SelfAlignmentNormalBehavior(this),
cb->Style())
.GetPosition() == ItemPosition::kStretch;
}
return style
.ResolvedJustifySelf(cb->SelfAlignmentNormalBehavior(this),
cb->Style())
.GetPosition() == ItemPosition::kStretch;
}
bool LayoutBox::SizesLogicalWidthToFitContent(
const Length& logical_width) const {
if (IsFloating() || IsInlineBlockOrInlineTable() ||
StyleRef().HasOutOfFlowPosition())
return true;
if (IsGridItem())
return !HasStretchedLogicalWidth();
// Flexible box items should shrink wrap, so we lay them out at their
// intrinsic widths. In the case of columns that have a stretch alignment, we
// go ahead and layout at the stretched size to avoid an extra layout when
// applying alignment.
if (Parent()->IsFlexibleBoxIncludingNG()) {
// For multiline columns, we need to apply align-content first, so we can't
// stretch now.
if (!Parent()->StyleRef().ResolvedIsColumnFlexDirection() ||
Parent()->StyleRef().FlexWrap() != EFlexWrap::kNowrap)
return true;
if (!ColumnFlexItemHasStretchAlignment())
return true;
}
// Flexible horizontal boxes lay out children at their intrinsic widths. Also
// vertical boxes that don't stretch their kids lay out their children at
// their intrinsic widths.
// FIXME: Think about writing-mode here.
// https://bugs.webkit.org/show_bug.cgi?id=46473
if (Parent()->IsDeprecatedFlexibleBox() &&
(Parent()->StyleRef().BoxOrient() == EBoxOrient::kHorizontal ||
Parent()->StyleRef().BoxAlign() != EBoxAlignment::kStretch))
return true;
// Button, input, select, textarea, and legend treat width value of 'auto' as
// 'intrinsic' unless it's in a stretching column flexbox.
// FIXME: Think about writing-mode here.
// https://bugs.webkit.org/show_bug.cgi?id=46473
if (logical_width.IsAuto() && !IsStretchingColumnFlexItem() &&
AutoWidthShouldFitContent())
return true;
if (IsHorizontalWritingMode() != ContainingBlock()->IsHorizontalWritingMode())
return true;
if (IsCustomItem())
return IsCustomItemShrinkToFit();
return false;
}
bool LayoutBox::AutoWidthShouldFitContent() const {
return GetNode() &&
(IsHTMLInputElement(*GetNode()) || IsHTMLSelectElement(*GetNode()) ||
IsA<HTMLButtonElement>(*GetNode()) ||
IsHTMLTextAreaElement(*GetNode()) || IsRenderedLegend());
}
void LayoutBox::ComputeMarginsForDirection(MarginDirection flow_direction,
const LayoutBlock* containing_block,
LayoutUnit container_width,
LayoutUnit child_width,
LayoutUnit& margin_start,
LayoutUnit& margin_end,
Length margin_start_length,
Length margin_end_length) const {
// First assert that we're not calling this method on box types that don't
// support margins.
DCHECK(!IsTableCell());
DCHECK(!IsTableRow());
DCHECK(!IsTableSection());
DCHECK(!IsLayoutTableCol());
if (flow_direction == kBlockDirection || IsFloating() || IsInline()) {
// Margins are calculated with respect to the logical width of
// the containing block (8.3)
// Inline blocks/tables and floats don't have their margins increased.
margin_start = MinimumValueForLength(margin_start_length, container_width);
margin_end = MinimumValueForLength(margin_end_length, container_width);
return;
}
if (containing_block->IsFlexibleBoxIncludingNG()) {
// We need to let flexbox handle the margin adjustment - otherwise, flexbox
// will think we're wider than we actually are and calculate line sizes
// wrong. See also https://drafts.csswg.org/css-flexbox/#auto-margins
if (margin_start_length.IsAuto())
margin_start_length = Length::Fixed(0);
if (margin_end_length.IsAuto())
margin_end_length = Length::Fixed(0);
}
LayoutUnit margin_start_width =
MinimumValueForLength(margin_start_length, container_width);
LayoutUnit margin_end_width =
MinimumValueForLength(margin_end_length, container_width);
LayoutUnit available_width = container_width;
auto* containing_block_flow = DynamicTo<LayoutBlockFlow>(containing_block);
if (CreatesNewFormattingContext() && containing_block_flow &&
containing_block_flow->ContainsFloats()) {
available_width = ContainingBlockAvailableLineWidth();
if (ShrinkToAvoidFloats() && available_width < container_width) {
margin_start = std::max(LayoutUnit(), margin_start_width);
margin_end = std::max(LayoutUnit(), margin_end_width);
}
}
// CSS 2.1 (10.3.3): "If 'width' is not 'auto' and 'border-left-width' +
// 'padding-left' + 'width' + 'padding-right' + 'border-right-width' (plus any
// of 'margin-left' or 'margin-right' that are not 'auto') is larger than the
// width of the containing block, then any 'auto' values for 'margin-left' or
// 'margin-right' are, for the following rules, treated as zero.
LayoutUnit margin_box_width =
child_width + (!StyleRef().Width().IsAuto()
? margin_start_width + margin_end_width
: LayoutUnit());
if (margin_box_width < available_width) {
// CSS 2.1: "If both 'margin-left' and 'margin-right' are 'auto', their used
// values are equal. This horizontally centers the element with respect to
// the edges of the containing block."
const ComputedStyle& containing_block_style = containing_block->StyleRef();
if ((margin_start_length.IsAuto() && margin_end_length.IsAuto()) ||
(!margin_start_length.IsAuto() && !margin_end_length.IsAuto() &&
containing_block_style.GetTextAlign() == ETextAlign::kWebkitCenter)) {
// Other browsers center the margin box for align=center elements so we
// match them here.
LayoutUnit centered_margin_box_start =
std::max(LayoutUnit(), (available_width - child_width -
margin_start_width - margin_end_width) /
2);
margin_start = centered_margin_box_start + margin_start_width;
margin_end =
available_width - child_width - margin_start + margin_end_width;
return;
}
// Adjust margins for the align attribute
if ((!containing_block_style.IsLeftToRightDirection() &&
containing_block_style.GetTextAlign() == ETextAlign::kWebkitLeft) ||
(containing_block_style.IsLeftToRightDirection() &&
containing_block_style.GetTextAlign() == ETextAlign::kWebkitRight)) {
if (containing_block_style.IsLeftToRightDirection() !=
StyleRef().IsLeftToRightDirection()) {
if (!margin_start_length.IsAuto())
margin_end_length = Length::Auto();
} else {
if (!margin_end_length.IsAuto())
margin_start_length = Length::Auto();
}
}
// CSS 2.1: "If there is exactly one value specified as 'auto', its used
// value follows from the equality."
if (margin_end_length.IsAuto()) {
margin_start = margin_start_width;
margin_end = available_width - child_width - margin_start;
return;
}
if (margin_start_length.IsAuto()) {
margin_end = margin_end_width;
margin_start = available_width - child_width - margin_end;
return;
}
}
// Either no auto margins, or our margin box width is >= the container width,
// auto margins will just turn into 0.
margin_start = margin_start_width;
margin_end = margin_end_width;
}
DISABLE_CFI_PERF
void LayoutBox::UpdateLogicalHeight() {
if (!HasOverrideLogicalHeight()) {
// If we have an override height, our children will have sized themselves
// relative to our override height, which would make our intrinsic size
// incorrect (too big).
intrinsic_content_logical_height_ = ContentLogicalHeight();
}
LogicalExtentComputedValues computed_values;
ComputeLogicalHeight(computed_values);
SetLogicalHeight(computed_values.extent_);
SetLogicalTop(computed_values.position_);
SetMarginBefore(computed_values.margins_.before_);
SetMarginAfter(computed_values.margins_.after_);
}
static inline const Length& HeightForDocumentElement(const Document& document) {
return document.documentElement()
->GetLayoutObject()
->StyleRef()
.LogicalHeight();
}
void LayoutBox::ComputeLogicalHeight(
LogicalExtentComputedValues& computed_values) const {
LayoutUnit height;
// TODO(962979): Implement grid layout with display locking. We need to figure
// out what happens here if IsLayoutGrid() is true and size containment is
// specified while the box is locked.
if (ShouldApplySizeContainment() && !IsLayoutGrid()) {
height = ContentLogicalHeightForSizeContainment() +
BorderAndPaddingLogicalHeight() + ScrollbarLogicalHeight();
} else if (DisplayLockInducesSizeContainment()) {
height = BorderAndPaddingLogicalHeight() + ScrollbarLogicalHeight() +
GetDisplayLockContext()->GetLockedContentLogicalHeight();
} else {
height = LogicalHeight();
}
ComputeLogicalHeight(height, LogicalTop(), computed_values);
}
void LayoutBox::ComputeLogicalHeight(
LayoutUnit logical_height,
LayoutUnit logical_top,
LogicalExtentComputedValues& computed_values) const {
computed_values.extent_ = logical_height;
computed_values.position_ = logical_top;
// Cell height is managed by the table.
if (IsTableCell())
return;
Length h;
if (IsOutOfFlowPositioned()) {
ComputePositionedLogicalHeight(computed_values);
if (HasOverrideLogicalHeight())
computed_values.extent_ = OverrideLogicalHeight();
} else {
LayoutBlock* cb = ContainingBlock();
// If we are perpendicular to our containing block then we need to resolve
// our block-start and block-end margins so that if they are 'auto' we are
// centred or aligned within the inline flow containing block: this is done
// by computing the margins as though they are inline.
// Note that as this is the 'sizing phase' we are using our own writing mode
// rather than the containing block's. We use the containing block's writing
// mode when figuring out the block-direction margins for positioning in
// |computeAndSetBlockDirectionMargins| (i.e. margin collapsing etc.).
// http://www.w3.org/TR/2014/CR-css-writing-modes-3-20140320/#orthogonal-flows
MarginDirection flow_direction =
IsHorizontalWritingMode() != cb->IsHorizontalWritingMode()
? kInlineDirection
: kBlockDirection;
// For tables, calculate margins only.
if (IsTable()) {
ComputeMarginsForDirection(
flow_direction, cb, ContainingBlockLogicalWidthForContent(),
computed_values.extent_, computed_values.margins_.before_,
computed_values.margins_.after_, StyleRef().MarginBefore(),
StyleRef().MarginAfter());
return;
}
// FIXME: Account for writing-mode in flexible boxes.
// https://bugs.webkit.org/show_bug.cgi?id=46418
bool in_horizontal_box =
Parent()->IsDeprecatedFlexibleBox() &&
Parent()->StyleRef().BoxOrient() == EBoxOrient::kHorizontal;
bool stretching =
Parent()->StyleRef().BoxAlign() == EBoxAlignment::kStretch;
bool treat_as_replaced =
ShouldComputeSizeAsReplaced() && (!in_horizontal_box || !stretching);
bool check_min_max_height = false;
// The parent box is flexing us, so it has increased or decreased our
// height. We have to grab our cached flexible height.
if (HasOverrideLogicalHeight()) {
h = Length::Fixed(OverrideLogicalHeight());
} else if (treat_as_replaced) {
h = Length::Fixed(ComputeReplacedLogicalHeight() +
BorderAndPaddingLogicalHeight());
} else {
h = StyleRef().LogicalHeight();
check_min_max_height = true;
}
// Block children of horizontal flexible boxes fill the height of the box.
// FIXME: Account for writing-mode in flexible boxes.
// https://bugs.webkit.org/show_bug.cgi?id=46418
if (h.IsAuto() && in_horizontal_box &&
ToLayoutDeprecatedFlexibleBox(Parent())->IsStretchingChildren()) {
h = Length::Fixed(ParentBox()->ContentLogicalHeight() - MarginBefore() -
MarginAfter());
check_min_max_height = false;
}
LayoutUnit height_result;
if (check_min_max_height) {
height_result = ComputeLogicalHeightUsing(
kMainOrPreferredSize, StyleRef().LogicalHeight(),
computed_values.extent_ - BorderAndPaddingLogicalHeight());
if (height_result == -1)
height_result = computed_values.extent_;
height_result = ConstrainLogicalHeightByMinMax(
height_result,
computed_values.extent_ - BorderAndPaddingLogicalHeight());
} else {
DCHECK(h.IsFixed());
height_result = LayoutUnit(h.Value());
}
computed_values.extent_ = height_result;
ComputeMarginsForDirection(
flow_direction, cb, ContainingBlockLogicalWidthForContent(),
computed_values.extent_, computed_values.margins_.before_,
computed_values.margins_.after_, StyleRef().MarginBefore(),
StyleRef().MarginAfter());
}
// WinIE quirk: The <html> block always fills the entire canvas in quirks
// mode. The <body> always fills the <html> block in quirks mode. Only apply
// this quirk if the block is normal flow and no height is specified. When
// we're printing, we also need this quirk if the body or root has a
// percentage height since we don't set a height in LayoutView when we're
// printing. So without this quirk, the height has nothing to be a percentage
// of, and it ends up being 0. That is bad.
bool paginated_content_needs_base_height =
GetDocument().Printing() && h.IsPercentOrCalc() &&
(IsDocumentElement() ||
(IsBody() &&
HeightForDocumentElement(GetDocument()).IsPercentOrCalc())) &&
!IsInline();
if (StretchesToViewport() || paginated_content_needs_base_height) {
LayoutUnit margins = CollapsedMarginBefore() + CollapsedMarginAfter();
LayoutUnit visible_height = View()->ViewLogicalHeightForPercentages();
if (IsDocumentElement()) {
computed_values.extent_ =
std::max(computed_values.extent_, visible_height - margins);
} else {
LayoutUnit margins_borders_padding =
margins + ParentBox()->MarginBefore() + ParentBox()->MarginAfter() +
ParentBox()->BorderAndPaddingLogicalHeight();
computed_values.extent_ = std::max(
computed_values.extent_, visible_height - margins_borders_padding);
}
}
}
LayoutUnit LayoutBox::ComputeLogicalHeightWithoutLayout() const {
LogicalExtentComputedValues computed_values;
if (!SelfNeedsLayout()) {
if (ShouldApplySizeContainment()) {
ComputeLogicalHeight(ContentLogicalHeightForSizeContainment() +
BorderAndPaddingLogicalHeight(),
LayoutUnit(), computed_values);
} else if (DisplayLockInducesSizeContainment()) {
ComputeLogicalHeight(
BorderAndPaddingLogicalHeight() +
GetDisplayLockContext()->GetLockedContentLogicalHeight(),
LayoutUnit(), computed_values);
}
} else {
// TODO(cbiesinger): We should probably return something other than just
// border + padding, but for now we have no good way to do anything else
// without layout, so we just use that.
ComputeLogicalHeight(BorderAndPaddingLogicalHeight(), LayoutUnit(),
computed_values);
}
return computed_values.extent_;
}
LayoutUnit LayoutBox::ComputeLogicalHeightUsing(
SizeType height_type,
const Length& height,
LayoutUnit intrinsic_content_height) const {
LayoutUnit logical_height = ComputeContentAndScrollbarLogicalHeightUsing(
height_type, height, intrinsic_content_height);
if (logical_height != -1) {
if (height.IsSpecified())
logical_height = AdjustBorderBoxLogicalHeightForBoxSizing(logical_height);
else
logical_height += BorderAndPaddingLogicalHeight();
}
return logical_height;
}
LayoutUnit LayoutBox::ComputeContentLogicalHeight(
SizeType height_type,
const Length& height,
LayoutUnit intrinsic_content_height) const {
LayoutUnit height_including_scrollbar =
ComputeContentAndScrollbarLogicalHeightUsing(height_type, height,
intrinsic_content_height);
if (height_including_scrollbar == -1)
return LayoutUnit(-1);
LayoutUnit adjusted = height_including_scrollbar;
if (height.IsSpecified()) {
// Keywords don't get adjusted for box-sizing
adjusted =
AdjustContentBoxLogicalHeightForBoxSizing(height_including_scrollbar);
}
return std::max(LayoutUnit(), adjusted - ScrollbarLogicalHeight());
}
LayoutUnit LayoutBox::ComputeIntrinsicLogicalContentHeightUsing(
const Length& logical_height_length,
LayoutUnit intrinsic_content_height,
LayoutUnit border_and_padding) const {
// FIXME(cbiesinger): The css-sizing spec is considering changing what
// min-content/max-content should resolve to.
// If that happens, this code will have to change.
if (logical_height_length.IsMinContent() ||
logical_height_length.IsMaxContent() ||
logical_height_length.IsFitContent()) {
if (IsAtomicInlineLevel() && !IsFlexibleBoxIncludingNG() && !IsLayoutGrid())
return IntrinsicSize().Height();
return intrinsic_content_height;
}
if (logical_height_length.IsFillAvailable()) {
if (!IsA<HTMLMarqueeElement>(GetNode())) {
UseCounter::Count(GetDocument(),
WebFeature::kCSSFillAvailableLogicalHeight);
}
return ContainingBlock()->AvailableLogicalHeight(
kExcludeMarginBorderPadding) -
border_and_padding;
}
NOTREACHED();
return LayoutUnit();
}
LayoutUnit LayoutBox::ComputeContentAndScrollbarLogicalHeightUsing(
SizeType height_type,
const Length& height,
LayoutUnit intrinsic_content_height) const {
if (height.IsAuto())
return height_type == kMinSize ? LayoutUnit() : LayoutUnit(-1);
// FIXME(cbiesinger): The css-sizing spec is considering changing what
// min-content/max-content should resolve to.
// If that happens, this code will have to change.
if (height.IsIntrinsic()) {
if (intrinsic_content_height == -1)
return LayoutUnit(-1); // Intrinsic height isn't available.
return ComputeIntrinsicLogicalContentHeightUsing(
height, intrinsic_content_height,
BorderAndPaddingLogicalHeight()) +
ScrollbarLogicalHeight();
}
if (height.IsFixed())
return LayoutUnit(height.Value());
if (height.IsPercentOrCalc())
return ComputePercentageLogicalHeight(height);
return LayoutUnit(-1);
}
bool LayoutBox::StretchesToViewportInQuirksMode() const {
if (!IsDocumentElement() && !IsBody())
return false;
return StyleRef().LogicalHeight().IsAuto() &&
!IsFloatingOrOutOfFlowPositioned() && !IsInline() &&
!FlowThreadContainingBlock();
}
bool LayoutBox::SkipContainingBlockForPercentHeightCalculation(
const LayoutBox* containing_block) {
// Anonymous blocks should not impede percentage resolution on a child.
// Examples of such anonymous blocks are blocks wrapped around inlines that
// have block siblings (from the CSS spec) and multicol flow threads (an
// implementation detail). Another implementation detail, ruby runs, create
// anonymous inline-blocks, so skip those too. All other types of anonymous
// objects, such as table-cells, will be treated just as if they were
// non-anonymous.
if (containing_block->IsAnonymous()) {
EDisplay display = containing_block->StyleRef().Display();
return display == EDisplay::kBlock || display == EDisplay::kInlineBlock ||
display == EDisplay::kFlowRoot;
}
// For quirks mode, we skip most auto-height containing blocks when computing
// percentages.
return containing_block->GetDocument().InQuirksMode() &&
containing_block->StyleRef().LogicalHeight().IsAuto() &&
!containing_block->IsTableCell() &&
!containing_block->IsOutOfFlowPositioned() &&
!containing_block->HasOverridePercentageResolutionBlockSize() &&
!containing_block->IsLayoutGrid() &&
!containing_block->IsFlexibleBoxIncludingDeprecatedAndNG() &&
!containing_block->IsLayoutNGCustom();
}
LayoutUnit LayoutBox::ContainingBlockLogicalHeightForPercentageResolution(
LayoutBlock** out_cb,
bool* out_skipped_auto_height_containing_block) const {
LayoutBlock* cb = ContainingBlock();
const LayoutBlock* const real_cb = cb;
const LayoutBox* containing_block_child = this;
bool skipped_auto_height_containing_block = false;
LayoutUnit root_margin_border_padding_height;
while (!cb->IsLayoutView() &&
(IsHorizontalWritingMode() == cb->IsHorizontalWritingMode() &&
SkipContainingBlockForPercentHeightCalculation(cb))) {
if ((cb->IsBody() || cb->IsDocumentElement()) &&
!HasOverrideContainingBlockContentLogicalHeight())
root_margin_border_padding_height += cb->MarginBefore() +
cb->MarginAfter() +
cb->BorderAndPaddingLogicalHeight();
skipped_auto_height_containing_block = true;
containing_block_child = cb;
cb = cb->ContainingBlock();
}
if (out_cb)
*out_cb = cb;
if (out_skipped_auto_height_containing_block) {
*out_skipped_auto_height_containing_block =
skipped_auto_height_containing_block;
}
LayoutUnit available_height(-1);
if (containing_block_child->HasOverridePercentageResolutionBlockSize()) {
available_height =
containing_block_child->OverridePercentageResolutionBlockSize();
} else if (cb->HasOverridePercentageResolutionBlockSize()) {
available_height = cb->OverridePercentageResolutionBlockSize();
} else if (HasOverrideContainingBlockContentLogicalWidth() &&
IsHorizontalWritingMode() != real_cb->IsHorizontalWritingMode()) {
available_height = OverrideContainingBlockContentLogicalWidth();
} else if (HasOverrideContainingBlockContentLogicalHeight() &&
IsHorizontalWritingMode() == real_cb->IsHorizontalWritingMode()) {
available_height = OverrideContainingBlockContentLogicalHeight();
} else if (IsHorizontalWritingMode() != cb->IsHorizontalWritingMode()) {
available_height =
containing_block_child->ContainingBlockLogicalWidthForContent();
} else if (cb->IsTableCell()) {
if (!skipped_auto_height_containing_block) {
// Table cells violate what the CSS spec says to do with heights.
// Basically we don't care if the cell specified a height or not. We just
// always make ourselves be a percentage of the cell's current content
// height.
if (!cb->HasOverrideLogicalHeight()) {
// https://drafts.csswg.org/css-tables-3/#row-layout:
// For the purpose of calculating [the minimum height of a row],
// descendants of table cells whose height depends on percentages
// of their parent cell's height are considered to have an auto
// height if they have overflow set to visible or hidden or if
// they are replaced elements, and a 0px height if they have not.
const LayoutNGTableCellInterface* cell =
ToInterface<LayoutNGTableCellInterface>(cb);
if (StyleRef().OverflowY() != EOverflow::kVisible &&
StyleRef().OverflowY() != EOverflow::kHidden &&
!ShouldBeConsideredAsReplaced() &&
(!cb->StyleRef().LogicalHeight().IsAuto() || !cell->TableInterface()
->ToLayoutObject()
->StyleRef()
.LogicalHeight()
.IsAuto()))
return LayoutUnit();
return LayoutUnit(-1);
}
available_height = cb->OverrideLogicalHeight() -
cb->CollapsedBorderAndCSSPaddingLogicalHeight() -
cb->ScrollbarLogicalHeight();
}
} else {
available_height = cb->AvailableLogicalHeightForPercentageComputation();
}
if (available_height == -1)
return available_height;
available_height -= root_margin_border_padding_height;
// LayoutNG already includes padding in
// OverrideContainingBlockContentLogicalHeight so we only need to add it here
// for legacy containing blocks.
if (IsTable() && IsOutOfFlowPositioned() && !cb->IsLayoutNGObject())
available_height += cb->PaddingLogicalHeight();
return available_height;
}
LayoutUnit LayoutBox::ComputePercentageLogicalHeight(
const Length& height) const {
bool skipped_auto_height_containing_block = false;
LayoutBlock* cb = nullptr;
LayoutUnit available_height =
ContainingBlockLogicalHeightForPercentageResolution(
&cb, &skipped_auto_height_containing_block);
DCHECK(cb);
cb->AddPercentHeightDescendant(const_cast<LayoutBox*>(this));
if (available_height == -1)
return available_height;
LayoutUnit result = ValueForLength(height, available_height);
// |OverrideLogicalHeight| is the maximum height made available by the
// cell to its percent height children when we decide they can determine the
// height of the cell. If the percent height child is box-sizing:content-box
// then we must subtract the border and padding from the cell's
// |available_height| (given by |OverrideLogicalHeight|) to arrive
// at the child's computed height.
bool subtract_border_and_padding =
IsTable() ||
(cb->IsTableCell() && !skipped_auto_height_containing_block &&
cb->HasOverrideLogicalHeight() &&
StyleRef().BoxSizing() == EBoxSizing::kContentBox);
if (subtract_border_and_padding) {
result -= BorderAndPaddingLogicalHeight();
return std::max(LayoutUnit(), result);
}
return result;
}
LayoutUnit LayoutBox::ComputeReplacedLogicalWidth(
ShouldComputePreferred should_compute_preferred) const {
return ComputeReplacedLogicalWidthRespectingMinMaxWidth(
ComputeReplacedLogicalWidthUsing(kMainOrPreferredSize,
StyleRef().LogicalWidth()),
should_compute_preferred);
}
LayoutUnit LayoutBox::ComputeReplacedLogicalWidthRespectingMinMaxWidth(
LayoutUnit logical_width,
ShouldComputePreferred should_compute_preferred) const {
LayoutUnit min_logical_width =
(should_compute_preferred == kComputePreferred &&
StyleRef().LogicalMinWidth().IsPercentOrCalc())
? logical_width
: ComputeReplacedLogicalWidthUsing(kMinSize,
StyleRef().LogicalMinWidth());
LayoutUnit max_logical_width =
(should_compute_preferred == kComputePreferred &&
StyleRef().LogicalMaxWidth().IsPercentOrCalc()) ||
StyleRef().LogicalMaxWidth().IsMaxSizeNone()
? logical_width
: ComputeReplacedLogicalWidthUsing(kMaxSize,
StyleRef().LogicalMaxWidth());
return std::max(min_logical_width,
std::min(logical_width, max_logical_width));
}
LayoutUnit LayoutBox::ComputeReplacedLogicalWidthUsing(
SizeType size_type,
const Length& logical_width) const {
DCHECK(size_type == kMinSize || size_type == kMainOrPreferredSize ||
!logical_width.IsAuto());
if (size_type == kMinSize && logical_width.IsAuto())
return AdjustContentBoxLogicalWidthForBoxSizing(LayoutUnit());
switch (logical_width.GetType()) {
case Length::kFixed:
return AdjustContentBoxLogicalWidthForBoxSizing(logical_width.Value());
case Length::kMinContent:
case Length::kMaxContent: {
// MinContent/MaxContent don't need the availableLogicalWidth argument.
LayoutUnit available_logical_width;
return ComputeIntrinsicLogicalWidthUsing(logical_width,
available_logical_width,
BorderAndPaddingLogicalWidth()) -
BorderAndPaddingLogicalWidth();
}
case Length::kFitContent:
case Length::kFillAvailable:
case Length::kPercent:
case Length::kCalculated: {
LayoutUnit cw;
if (IsOutOfFlowPositioned()) {
cw = ContainingBlockLogicalWidthForPositioned(
ToLayoutBoxModelObject(Container()));
} else {
cw = IsHorizontalWritingMode() ==
ContainingBlock()->IsHorizontalWritingMode()
? ContainingBlockLogicalWidthForContent()
: PerpendicularContainingBlockLogicalHeight();
}
const Length& container_logical_width =
ContainingBlock()->StyleRef().LogicalWidth();
// FIXME: Handle cases when containing block width is calculated or
// viewport percent. https://bugs.webkit.org/show_bug.cgi?id=91071
if (logical_width.IsIntrinsic())
return ComputeIntrinsicLogicalWidthUsing(
logical_width, cw, BorderAndPaddingLogicalWidth()) -
BorderAndPaddingLogicalWidth();
if (cw > 0 || (!cw && (container_logical_width.IsFixed() ||
container_logical_width.IsPercentOrCalc())))
return AdjustContentBoxLogicalWidthForBoxSizing(
MinimumValueForLength(logical_width, cw));
return LayoutUnit();
}
case Length::kAuto:
case Length::kMaxSizeNone:
return IntrinsicLogicalWidth();
case Length::kExtendToZoom:
case Length::kDeviceWidth:
case Length::kDeviceHeight:
break;
}
NOTREACHED();
return LayoutUnit();
}
LayoutUnit LayoutBox::ComputeReplacedLogicalHeight(LayoutUnit) const {
return ComputeReplacedLogicalHeightRespectingMinMaxHeight(
ComputeReplacedLogicalHeightUsing(kMainOrPreferredSize,
StyleRef().LogicalHeight()));
}
bool LayoutBox::LogicalHeightComputesAsNone(SizeType size_type) const {
DCHECK(size_type == kMinSize || size_type == kMaxSize);
const Length& logical_height = size_type == kMinSize
? StyleRef().LogicalMinHeight()
: StyleRef().LogicalMaxHeight();
// Note that the values 'min-content', 'max-content' and 'fit-content' should
// behave as the initial value if specified in the block direction.
if (logical_height.IsMinContent() || logical_height.IsMaxContent() ||
logical_height.IsFitContent())
return true;
Length initial_logical_height =
size_type == kMinSize ? ComputedStyleInitialValues::InitialMinHeight()
: ComputedStyleInitialValues::InitialMaxHeight();
if (logical_height == initial_logical_height)
return true;
// CustomLayout items can resolve their percentages against an available or
// percentage size override.
if (IsCustomItem() && (HasOverrideContainingBlockContentLogicalHeight() ||
HasOverridePercentageResolutionBlockSize()))
return false;
if (LayoutBlock* cb = ContainingBlockForAutoHeightDetection(logical_height))
return cb->HasAutoHeightOrContainingBlockWithAutoHeight();
return false;
}
LayoutUnit LayoutBox::ComputeReplacedLogicalHeightRespectingMinMaxHeight(
LayoutUnit logical_height) const {
// If the height of the containing block is not specified explicitly (i.e., it
// depends on content height), and this element is not absolutely positioned,
// the percentage value is treated as '0' (for 'min-height') or 'none' (for
// 'max-height').
LayoutUnit min_logical_height;
if (!LogicalHeightComputesAsNone(kMinSize)) {
min_logical_height = ComputeReplacedLogicalHeightUsing(
kMinSize, StyleRef().LogicalMinHeight());
}
LayoutUnit max_logical_height = logical_height;
if (!LogicalHeightComputesAsNone(kMaxSize)) {
max_logical_height = ComputeReplacedLogicalHeightUsing(
kMaxSize, StyleRef().LogicalMaxHeight());
}
return std::max(min_logical_height,
std::min(logical_height, max_logical_height));
}
LayoutUnit LayoutBox::ComputeReplacedLogicalHeightUsing(
SizeType size_type,
const Length& logical_height) const {
DCHECK(size_type == kMinSize || size_type == kMainOrPreferredSize ||
!logical_height.IsAuto());
if (size_type == kMinSize && logical_height.IsAuto())
return AdjustContentBoxLogicalHeightForBoxSizing(LayoutUnit());
switch (logical_height.GetType()) {
case Length::kFixed:
return AdjustContentBoxLogicalHeightForBoxSizing(logical_height.Value());
case Length::kPercent:
case Length::kCalculated: {
// TODO(rego): Check if we can somehow reuse
// LayoutBox::computePercentageLogicalHeight() and/or
// LayoutBlock::availableLogicalHeightForPercentageComputation() (see
// http://crbug.com/635655).
LayoutObject* cb =
IsOutOfFlowPositioned() ? Container() : ContainingBlock();
while (cb->IsAnonymous())
cb = cb->ContainingBlock();
bool has_perpendicular_containing_block =
cb->IsHorizontalWritingMode() != IsHorizontalWritingMode();
LayoutUnit stretched_height(-1);
auto* block = DynamicTo<LayoutBlock>(cb);
if (block) {
block->AddPercentHeightDescendant(const_cast<LayoutBox*>(this));
if (block->IsFlexItem()) {
const LayoutFlexibleBox* flex_box =
ToLayoutFlexibleBox(block->Parent());
if (flex_box->UseOverrideLogicalHeightForPerentageResolution(*block))
stretched_height = block->OverrideContentLogicalHeight();
} else if (block->IsGridItem() && block->HasOverrideLogicalHeight() &&
!has_perpendicular_containing_block) {
stretched_height = block->OverrideContentLogicalHeight();
}
}
LayoutUnit available_height;
if (IsOutOfFlowPositioned()) {
available_height = ContainingBlockLogicalHeightForPositioned(
ToLayoutBoxModelObject(cb));
} else if (stretched_height != -1) {
available_height = stretched_height;
} else if (HasOverridePercentageResolutionBlockSize()) {
available_height = OverridePercentageResolutionBlockSize();
} else {
available_height = has_perpendicular_containing_block
? ContainingBlockLogicalWidthForContent()
: ContainingBlockLogicalHeightForContent(
kIncludeMarginBorderPadding);
// It is necessary to use the border-box to match WinIE's broken
// box model. This is essential for sizing inside
// table cells using percentage heights.
// FIXME: This needs to be made writing-mode-aware. If the cell and
// image are perpendicular writing-modes, this isn't right.
// https://bugs.webkit.org/show_bug.cgi?id=46997
while (cb && !cb->IsLayoutView() &&
(cb->StyleRef().LogicalHeight().IsAuto() ||
cb->StyleRef().LogicalHeight().IsPercentOrCalc())) {
if (cb->IsTableCell()) {
// Don't let table cells squeeze percent-height replaced elements
// <http://bugs.webkit.org/show_bug.cgi?id=15359>
available_height =
std::max(available_height, IntrinsicLogicalHeight());
return ValueForLength(
logical_height,
available_height - BorderAndPaddingLogicalHeight());
}
To<LayoutBlock>(cb)->AddPercentHeightDescendant(
const_cast<LayoutBox*>(this));
cb = cb->ContainingBlock();
}
}
return AdjustContentBoxLogicalHeightForBoxSizing(
ValueForLength(logical_height, available_height));
}
case Length::kMinContent:
case Length::kMaxContent:
case Length::kFitContent:
case Length::kFillAvailable:
return AdjustContentBoxLogicalHeightForBoxSizing(
ComputeIntrinsicLogicalContentHeightUsing(logical_height,
IntrinsicLogicalHeight(),
BorderAndPaddingHeight()));
default:
return IntrinsicLogicalHeight();
}
}
LayoutUnit LayoutBox::AvailableLogicalHeight(
AvailableLogicalHeightType height_type) const {
if (RuntimeEnabledFeatures::LayoutNGEnabled()) {
// LayoutNG code is correct, Legacy code incorrectly ConstrainsMinMax
// when height is -1, and returns 0, not -1.
// The reason this code is NG-only is that this code causes performance
// regression for nested-percent-height-tables test case.
// This code gets executed 740 times in the test case.
// https://chromium-review.googlesource.com/c/chromium/src/+/1103289
LayoutUnit height =
AvailableLogicalHeightUsing(StyleRef().LogicalHeight(), height_type);
if (UNLIKELY(height == -1))
return height;
return ConstrainContentBoxLogicalHeightByMinMax(height, LayoutUnit(-1));
}
// http://www.w3.org/TR/CSS2/visudet.html#propdef-height - We are interested
// in the content height.
// FIXME: Should we pass intrinsicContentLogicalHeight() instead of -1 here?
return ConstrainContentBoxLogicalHeightByMinMax(
AvailableLogicalHeightUsing(StyleRef().LogicalHeight(), height_type),
LayoutUnit(-1));
}
LayoutUnit LayoutBox::AvailableLogicalHeightUsing(
const Length& h,
AvailableLogicalHeightType height_type) const {
if (IsLayoutView()) {
return LayoutUnit(IsHorizontalWritingMode()
? ToLayoutView(this)->GetFrameView()->Size().Height()
: ToLayoutView(this)->GetFrameView()->Size().Width());
}
// We need to stop here, since we don't want to increase the height of the
// table artificially. We're going to rely on this cell getting expanded to
// some new height, and then when we lay out again we'll use the calculation
// below.
if (IsTableCell() && (h.IsAuto() || h.IsPercentOrCalc())) {
if (HasOverrideLogicalHeight()) {
return OverrideLogicalHeight() -
CollapsedBorderAndCSSPaddingLogicalHeight() -
ScrollbarLogicalHeight();
}
return LogicalHeight() - BorderAndPaddingLogicalHeight();
}
if (IsFlexItem()) {
const LayoutFlexibleBox& flex_box = ToLayoutFlexibleBox(*Parent());
if (flex_box.UseOverrideLogicalHeightForPerentageResolution(*this))
return OverrideContentLogicalHeight();
}
if (h.IsPercentOrCalc() && IsOutOfFlowPositioned()) {
// FIXME: This is wrong if the containingBlock has a perpendicular writing
// mode.
LayoutUnit available_height =
ContainingBlockLogicalHeightForPositioned(ContainingBlock());
return AdjustContentBoxLogicalHeightForBoxSizing(
ValueForLength(h, available_height));
}
// FIXME: Should we pass intrinsicContentLogicalHeight() instead of -1 here?
LayoutUnit height_including_scrollbar =
ComputeContentAndScrollbarLogicalHeightUsing(kMainOrPreferredSize, h,
LayoutUnit(-1));
if (height_including_scrollbar != -1)
return std::max(LayoutUnit(), AdjustContentBoxLogicalHeightForBoxSizing(
height_including_scrollbar) -
ScrollbarLogicalHeight());
// FIXME: Check logicalTop/logicalBottom here to correctly handle vertical
// writing-mode.
// https://bugs.webkit.org/show_bug.cgi?id=46500
auto* curr_layout_block = DynamicTo<LayoutBlock>(this);
if (curr_layout_block && IsOutOfFlowPositioned() &&
StyleRef().Height().IsAuto() &&
!(StyleRef().Top().IsAuto() || StyleRef().Bottom().IsAuto())) {
LayoutBlock* block = const_cast<LayoutBlock*>(curr_layout_block);
LogicalExtentComputedValues computed_values;
block->ComputeLogicalHeight(block->LogicalHeight(), LayoutUnit(),
computed_values);
return computed_values.extent_ - block->BorderAndPaddingLogicalHeight() -
block->ScrollbarLogicalHeight();
}
// FIXME: This is wrong if the containingBlock has a perpendicular writing
// mode.
LayoutUnit available_height =
ContainingBlockLogicalHeightForContent(height_type);
// FIXME: This is incorrect if available_height == -1 || 0
if (height_type == kExcludeMarginBorderPadding) {
// FIXME: Margin collapsing hasn't happened yet, so this incorrectly removes
// collapsed margins.
available_height -=
MarginBefore() + MarginAfter() + BorderAndPaddingLogicalHeight();
}
return available_height;
}
void LayoutBox::ComputeAndSetBlockDirectionMargins(
const LayoutBlock* containing_block) {
LayoutUnit margin_before;
LayoutUnit margin_after;
DCHECK(containing_block);
ComputeMarginsForDirection(
kBlockDirection, containing_block,
ContainingBlockLogicalWidthForContent(), LogicalHeight(), margin_before,
margin_after, StyleRef().MarginBeforeUsing(containing_block->StyleRef()),
StyleRef().MarginAfterUsing(containing_block->StyleRef()));
// Note that in this 'positioning phase' of the layout we are using the
// containing block's writing mode rather than our own when calculating
// margins.
// http://www.w3.org/TR/2014/CR-css-writing-modes-3-20140320/#orthogonal-flows
containing_block->SetMarginBeforeForChild(*this, margin_before);
containing_block->SetMarginAfterForChild(*this, margin_after);
}
LayoutUnit LayoutBox::ContainingBlockLogicalWidthForPositioned(
const LayoutBoxModelObject* containing_block,
bool check_for_perpendicular_writing_mode) const {
if (check_for_perpendicular_writing_mode &&
containing_block->IsHorizontalWritingMode() != IsHorizontalWritingMode())
return ContainingBlockLogicalHeightForPositioned(containing_block, false);
// Use viewport as container for top-level fixed-position elements.
if (StyleRef().GetPosition() == EPosition::kFixed &&
containing_block->IsLayoutView() && !GetDocument().Printing()) {
const LayoutView* view = ToLayoutView(containing_block);
if (LocalFrameView* frame_view = view->GetFrameView()) {
// Don't use visibleContentRect since the PaintLayer's size has not been
// set yet.
LayoutSize viewport_size(
frame_view->LayoutViewport()->ExcludeScrollbars(frame_view->Size()));
return LayoutUnit(containing_block->IsHorizontalWritingMode()
? viewport_size.Width()
: viewport_size.Height());
}
}
if (HasOverrideContainingBlockContentLogicalWidth())
return OverrideContainingBlockContentLogicalWidth();
if (containing_block->IsAnonymousBlock() &&
containing_block->IsRelPositioned()) {
// Ensure we compute our width based on the width of our rel-pos inline
// container rather than any anonymous block created to manage a block-flow
// ancestor of ours in the rel-pos inline's inline flow.
containing_block = ToLayoutBox(containing_block)->Continuation();
// There may be nested parallel inline continuations. We have now found the
// innermost inline (which may not be relatively positioned). Locate the
// inline that serves as the containing block of this box.
while (!containing_block->CanContainOutOfFlowPositionedElement(
StyleRef().GetPosition())) {
containing_block = ToLayoutBoxModelObject(containing_block->Container());
DCHECK(containing_block->IsLayoutInline());
}
} else if (containing_block->IsBox()) {
return std::max(LayoutUnit(),
ToLayoutBox(containing_block)->ClientLogicalWidth());
}
DCHECK(containing_block->IsLayoutInline());
DCHECK(containing_block->CanContainOutOfFlowPositionedElement(
StyleRef().GetPosition()));
const LayoutInline* flow = ToLayoutInline(containing_block);
InlineFlowBox* first = flow->FirstLineBox();
InlineFlowBox* last = flow->LastLineBox();
// If the containing block is empty, return a width of 0.
if (!first || !last)
return LayoutUnit();
LayoutUnit from_left;
LayoutUnit from_right;
if (containing_block->StyleRef().IsLeftToRightDirection()) {
from_left = first->LogicalLeft() + first->BorderLogicalLeft();
from_right =
last->LogicalLeft() + last->LogicalWidth() - last->BorderLogicalRight();
} else {
from_right = first->LogicalLeft() + first->LogicalWidth() -
first->BorderLogicalRight();
from_left = last->LogicalLeft() + last->BorderLogicalLeft();
}
return std::max(LayoutUnit(), from_right - from_left);
}
LayoutUnit LayoutBox::ContainingBlockLogicalHeightForPositioned(
const LayoutBoxModelObject* containing_block,
bool check_for_perpendicular_writing_mode) const {
if (check_for_perpendicular_writing_mode &&
containing_block->IsHorizontalWritingMode() != IsHorizontalWritingMode())
return ContainingBlockLogicalWidthForPositioned(containing_block, false);
// Use viewport as container for top-level fixed-position elements.
if (StyleRef().GetPosition() == EPosition::kFixed &&
containing_block->IsLayoutView() && !GetDocument().Printing()) {
const LayoutView* view = ToLayoutView(containing_block);
if (LocalFrameView* frame_view = view->GetFrameView()) {
// Don't use visibleContentRect since the PaintLayer's size has not been
// set yet.
LayoutSize viewport_size(
frame_view->LayoutViewport()->ExcludeScrollbars(frame_view->Size()));
return containing_block->IsHorizontalWritingMode()
? viewport_size.Height()
: viewport_size.Width();
}
}
if (HasOverrideContainingBlockContentLogicalHeight())
return OverrideContainingBlockContentLogicalHeight();
if (containing_block->IsBox())
return ToLayoutBox(containing_block)->ClientLogicalHeight();
DCHECK(containing_block->IsLayoutInline());
DCHECK(containing_block->CanContainOutOfFlowPositionedElement(
StyleRef().GetPosition()));
const LayoutInline* flow = ToLayoutInline(containing_block);
// If the containing block is empty, return a height of 0.
if (flow->IsEmpty())
return LayoutUnit();
LayoutUnit height_result;
auto bounding_box_size = flow->PhysicalLinesBoundingBox().size;
if (containing_block->IsHorizontalWritingMode())
height_result = bounding_box_size.height;
else
height_result = bounding_box_size.width;
height_result -=
(containing_block->BorderBefore() + containing_block->BorderAfter());
return height_result;
}
static LayoutUnit AccumulateStaticOffsetForFlowThread(
LayoutBox& layout_box,
LayoutUnit inline_position,
LayoutUnit& block_position) {
if (layout_box.IsTableRow())
return LayoutUnit();
block_position += layout_box.LogicalTop();
if (!layout_box.IsLayoutFlowThread())
return LayoutUnit();
LayoutUnit previous_inline_position = inline_position;
// We're walking out of a flowthread here. This flow thread is not in the
// containing block chain, so we need to convert the position from the
// coordinate space of this flowthread to the containing coordinate space.
ToLayoutFlowThread(layout_box)
.FlowThreadToContainingCoordinateSpace(block_position, inline_position);
return inline_position - previous_inline_position;
}
void LayoutBox::ComputeInlineStaticDistance(
Length& logical_left,
Length& logical_right,
const LayoutBox* child,
const LayoutBoxModelObject* container_block,
LayoutUnit container_logical_width,
const NGBoxFragmentBuilder* fragment_builder) {
if (!logical_left.IsAuto() || !logical_right.IsAuto())
return;
LayoutObject* parent = child->Parent();
TextDirection parent_direction = parent->StyleRef().Direction();
// This method is using EnclosingBox() which is wrong for absolutely
// positioned grid items, as they rely on the grid area. So for grid items if
// both "left" and "right" properties are "auto", we can consider that one of
// them (depending on the direction) is simply "0".
if (parent->IsLayoutGrid() && parent == child->ContainingBlock()) {
if (parent_direction == TextDirection::kLtr)
logical_left = Length::Fixed(0);
else
logical_right = Length::Fixed(0);
return;
}
// For multicol we also need to keep track of the block position, since that
// determines which column we're in and thus affects the inline position.
LayoutUnit static_block_position = child->Layer()->StaticBlockPosition();
// FIXME: The static distance computation has not been patched for mixed
// writing modes yet.
if (parent_direction == TextDirection::kLtr) {
LayoutUnit static_position = child->Layer()->StaticInlinePosition() -
container_block->BorderLogicalLeft();
for (LayoutObject* curr = child->Parent(); curr && curr != container_block;
curr = curr->Container()) {
if (curr->IsBox()) {
static_position +=
(fragment_builder &&
fragment_builder->GetLayoutObject() == curr->Parent())
? fragment_builder->GetChildOffset(curr).inline_offset
: ToLayoutBox(curr)->LogicalLeft();
if (ToLayoutBox(curr)->IsInFlowPositioned())
static_position += ToLayoutBox(curr)->OffsetForInFlowPosition().left;
if (curr->IsInsideFlowThread())
static_position += AccumulateStaticOffsetForFlowThread(
*ToLayoutBox(curr), static_position, static_block_position);
} else if (curr->IsInline()) {
if (curr->IsInFlowPositioned()) {
if (!curr->StyleRef().LogicalLeft().IsAuto())
static_position +=
ValueForLength(curr->StyleRef().LogicalLeft(),
curr->ContainingBlock()->AvailableWidth());
else
static_position -=
ValueForLength(curr->StyleRef().LogicalRight(),
curr->ContainingBlock()->AvailableWidth());
}
}
}
logical_left = Length::Fixed(static_position);
} else {
LayoutBox* enclosing_box = child->Parent()->EnclosingBox();
LayoutUnit static_position = child->Layer()->StaticInlinePosition() +
container_logical_width +
container_block->BorderLogicalLeft();
if (container_block->IsBox()) {
static_position +=
ToLayoutBox(container_block)->LogicalLeftScrollbarWidth();
}
for (LayoutObject* curr = child->Parent(); curr; curr = curr->Container()) {
if (curr->IsBox()) {
if (curr == enclosing_box)
static_position -= enclosing_box->LogicalWidth();
if (curr != container_block) {
static_position -=
(fragment_builder &&
fragment_builder->GetLayoutObject() == curr->Parent())
? fragment_builder->GetChildOffset(curr).inline_offset
: ToLayoutBox(curr)->LogicalLeft();
if (ToLayoutBox(curr)->IsInFlowPositioned()) {
static_position -=
ToLayoutBox(curr)->OffsetForInFlowPosition().left;
}
if (curr->IsInsideFlowThread())
static_position -= AccumulateStaticOffsetForFlowThread(
*ToLayoutBox(curr), static_position, static_block_position);
}
} else if (curr->IsInline()) {
if (curr->IsInFlowPositioned()) {
if (!curr->StyleRef().LogicalLeft().IsAuto())
static_position -=
ValueForLength(curr->StyleRef().LogicalLeft(),
curr->ContainingBlock()->AvailableWidth());
else
static_position +=
ValueForLength(curr->StyleRef().LogicalRight(),
curr->ContainingBlock()->AvailableWidth());
}
}
if (curr == container_block)
break;
}
logical_right = Length::Fixed(static_position);
}
}
void LayoutBox::ComputePositionedLogicalWidth(
LogicalExtentComputedValues& computed_values) const {
// QUESTIONS
// FIXME 1: Should we still deal with these the cases of 'left' or 'right'
// having the type 'static' in determining whether to calculate the static
// distance?
// NOTE: 'static' is not a legal value for 'left' or 'right' as of CSS 2.1.
// FIXME 2: Can perhaps optimize out cases when max-width/min-width are
// greater than or less than the computed width(). Be careful of box-sizing
// and percentage issues.
// The following is based off of the W3C Working Draft from April 11, 2006 of
// CSS 2.1: Section 10.3.7 "Absolutely positioned, non-replaced elements"
// <http://www.w3.org/TR/CSS21/visudet.html#abs-non-replaced-width>
// (block-style-comments in this function and in
// computePositionedLogicalWidthUsing() correspond to text from the spec)
// We don't use containingBlock(), since we may be positioned by an enclosing
// relative positioned inline.
const LayoutBoxModelObject* container_block =
ToLayoutBoxModelObject(Container());
const LayoutUnit container_logical_width =
ContainingBlockLogicalWidthForPositioned(container_block);
// Use the container block's direction except when calculating the static
// distance. This conforms with the reference results for
// abspos-replaced-width-margin-000.htm of the CSS 2.1 test suite.
TextDirection container_direction = container_block->StyleRef().Direction();
bool is_horizontal = IsHorizontalWritingMode();
const LayoutUnit borders_plus_padding = BorderAndPaddingLogicalWidth();
const Length& margin_logical_left =
is_horizontal ? StyleRef().MarginLeft() : StyleRef().MarginTop();
const Length& margin_logical_right =
is_horizontal ? StyleRef().MarginRight() : StyleRef().MarginBottom();
Length logical_left_length = StyleRef().LogicalLeft();
Length logical_right_length = StyleRef().LogicalRight();
// ---------------------------------------------------------------------------
// For the purposes of this section and the next, the term "static position"
// (of an element) refers, roughly, to the position an element would have had
// in the normal flow. More precisely:
//
// * The static position for 'left' is the distance from the left edge of the
// containing block to the left margin edge of a hypothetical box that
// would have been the first box of the element if its 'position' property
// had been 'static' and 'float' had been 'none'. The value is negative if
// the hypothetical box is to the left of the containing block.
// * The static position for 'right' is the distance from the right edge of
// the containing block to the right margin edge of the same hypothetical
// box as above. The value is positive if the hypothetical box is to the
// left of the containing block's edge.
//
// But rather than actually calculating the dimensions of that hypothetical
// box, user agents are free to make a guess at its probable position.
//
// For the purposes of calculating the static position, the containing block
// of fixed positioned elements is the initial containing block instead of
// the viewport, and all scrollable boxes should be assumed to be scrolled to
// their origin.
// ---------------------------------------------------------------------------
// see FIXME 1
// Calculate the static distance if needed.
ComputeInlineStaticDistance(logical_left_length, logical_right_length, this,
container_block, container_logical_width);
// Calculate constraint equation values for 'width' case.
ComputePositionedLogicalWidthUsing(
kMainOrPreferredSize, StyleRef().LogicalWidth(), container_block,
container_direction, container_logical_width, borders_plus_padding,
logical_left_length, logical_right_length, margin_logical_left,
margin_logical_right, computed_values);
// Calculate constraint equation values for 'max-width' case.
if (!StyleRef().LogicalMaxWidth().IsMaxSizeNone()) {
LogicalExtentComputedValues max_values;
ComputePositionedLogicalWidthUsing(
kMaxSize, StyleRef().LogicalMaxWidth(), container_block,
container_direction, container_logical_width, borders_plus_padding,
logical_left_length, logical_right_length, margin_logical_left,
margin_logical_right, max_values);
if (computed_values.extent_ > max_values.extent_) {
computed_values.extent_ = max_values.extent_;
computed_values.position_ = max_values.position_;
computed_values.margins_.start_ = max_values.margins_.start_;
computed_values.margins_.end_ = max_values.margins_.end_;
}
}
// Calculate constraint equation values for 'min-width' case.
if (!StyleRef().LogicalMinWidth().IsZero() ||
StyleRef().LogicalMinWidth().IsIntrinsic()) {
LogicalExtentComputedValues min_values;
ComputePositionedLogicalWidthUsing(
kMinSize, StyleRef().LogicalMinWidth(), container_block,
container_direction, container_logical_width, borders_plus_padding,
logical_left_length, logical_right_length, margin_logical_left,
margin_logical_right, min_values);
if (computed_values.extent_ < min_values.extent_) {
computed_values.extent_ = min_values.extent_;
computed_values.position_ = min_values.position_;
computed_values.margins_.start_ = min_values.margins_.start_;
computed_values.margins_.end_ = min_values.margins_.end_;
}
}
computed_values.extent_ += borders_plus_padding;
}
void LayoutBox::ComputeLogicalLeftPositionedOffset(
LayoutUnit& logical_left_pos,
const LayoutBox* child,
LayoutUnit logical_width_value,
const LayoutBoxModelObject* container_block,
LayoutUnit container_logical_width) {
if (child->IsHorizontalWritingMode()) {
if (container_block->HasFlippedBlocksWritingMode()) {
// Deal with differing writing modes here. Our offset needs to be in the
// containing block's coordinate space. If the containing block is flipped
// along this axis, then we need to flip the coordinate. This can only
// happen if the containing block has flipped mode and is perpendicular
// to us.
logical_left_pos =
container_logical_width - logical_width_value - logical_left_pos;
logical_left_pos += container_block->BorderRight();
if (container_block->IsBox())
logical_left_pos += ToLayoutBox(container_block)->RightScrollbarWidth();
} else {
logical_left_pos += container_block->BorderLeft();
if (container_block->IsBox())
logical_left_pos += ToLayoutBox(container_block)->LeftScrollbarWidth();
}
} else {
logical_left_pos += container_block->BorderTop();
}
}
LayoutUnit LayoutBox::ShrinkToFitLogicalWidth(
LayoutUnit available_logical_width,
LayoutUnit borders_plus_padding) const {
LayoutUnit preferred_logical_width =
MaxPreferredLogicalWidth() - borders_plus_padding;
LayoutUnit preferred_min_logical_width =
MinPreferredLogicalWidth() - borders_plus_padding;
return std::min(
std::max(preferred_min_logical_width, available_logical_width),
preferred_logical_width);
}
void LayoutBox::ComputePositionedLogicalWidthUsing(
SizeType width_size_type,
const Length& logical_width,
const LayoutBoxModelObject* container_block,
TextDirection container_direction,
LayoutUnit container_logical_width,
LayoutUnit borders_plus_padding,
const Length& logical_left,
const Length& logical_right,
const Length& margin_logical_left,
const Length& margin_logical_right,
LogicalExtentComputedValues& computed_values) const {
LayoutUnit logical_width_value;
DCHECK(width_size_type == kMinSize ||
width_size_type == kMainOrPreferredSize || !logical_width.IsAuto());
if (width_size_type == kMinSize && logical_width.IsAuto())
logical_width_value = LayoutUnit();
else if (logical_width.IsIntrinsic())
logical_width_value =
ComputeIntrinsicLogicalWidthUsing(
logical_width, container_logical_width, borders_plus_padding) -
borders_plus_padding;
else
logical_width_value = AdjustContentBoxLogicalWidthForBoxSizing(
ValueForLength(logical_width, container_logical_width));
// 'left' and 'right' cannot both be 'auto' because one would of been
// converted to the static position already
DCHECK(!(logical_left.IsAuto() && logical_right.IsAuto()));
// minimumValueForLength will convert 'auto' to 0 so that it doesn't impact
// the available space computation below.
LayoutUnit logical_left_value =
MinimumValueForLength(logical_left, container_logical_width);
LayoutUnit logical_right_value =
MinimumValueForLength(logical_right, container_logical_width);
const LayoutUnit container_relative_logical_width =
ContainingBlockLogicalWidthForPositioned(container_block, false);
bool logical_width_is_auto = logical_width.IsAuto();
bool logical_left_is_auto = logical_left.IsAuto();
bool logical_right_is_auto = logical_right.IsAuto();
LayoutUnit& margin_logical_left_value = StyleRef().IsLeftToRightDirection()
? computed_values.margins_.start_
: computed_values.margins_.end_;
LayoutUnit& margin_logical_right_value =
StyleRef().IsLeftToRightDirection() ? computed_values.margins_.end_
: computed_values.margins_.start_;
if (!logical_left_is_auto && !logical_width_is_auto &&
!logical_right_is_auto) {
// -------------------------------------------------------------------------
// If none of the three is 'auto': If both 'margin-left' and 'margin-
// right' are 'auto', solve the equation under the extra constraint that
// the two margins get equal values, unless this would make them negative,
// in which case when direction of the containing block is 'ltr' ('rtl'),
// set 'margin-left' ('margin-right') to zero and solve for 'margin-right'
// ('margin-left'). If one of 'margin-left' or 'margin-right' is 'auto',
// solve the equation for that value. If the values are over-constrained,
// ignore the value for 'left' (in case the 'direction' property of the
// containing block is 'rtl') or 'right' (in case 'direction' is 'ltr')
// and solve for that value.
// -------------------------------------------------------------------------
// NOTE: It is not necessary to solve for 'right' in the over constrained
// case because the value is not used for any further calculations.
computed_values.extent_ = logical_width_value;
const LayoutUnit available_space =
container_logical_width -
(logical_left_value + computed_values.extent_ + logical_right_value +
borders_plus_padding);
// Margins are now the only unknown
if (margin_logical_left.IsAuto() && margin_logical_right.IsAuto()) {
// Both margins auto, solve for equality
if (available_space >= 0) {
margin_logical_left_value =
available_space / 2; // split the difference
margin_logical_right_value =
available_space -
margin_logical_left_value; // account for odd valued differences
} else {
// Use the containing block's direction rather than the parent block's
// per CSS 2.1 reference test abspos-non-replaced-width-margin-000.
if (container_direction == TextDirection::kLtr) {
margin_logical_left_value = LayoutUnit();
margin_logical_right_value = available_space; // will be negative
} else {
margin_logical_left_value = available_space; // will be negative
margin_logical_right_value = LayoutUnit();
}
}
} else if (margin_logical_left.IsAuto()) {
// Solve for left margin
margin_logical_right_value = ValueForLength(
margin_logical_right, container_relative_logical_width);
margin_logical_left_value = available_space - margin_logical_right_value;
} else if (margin_logical_right.IsAuto()) {
// Solve for right margin
margin_logical_left_value =
ValueForLength(margin_logical_left, container_relative_logical_width);
margin_logical_right_value = available_space - margin_logical_left_value;
} else {
// Over-constrained, solve for left if direction is RTL
margin_logical_left_value =
ValueForLength(margin_logical_left, container_relative_logical_width);
margin_logical_right_value = ValueForLength(
margin_logical_right, container_relative_logical_width);
// Use the containing block's direction rather than the parent block's
// per CSS 2.1 reference test abspos-non-replaced-width-margin-000.
if (container_direction == TextDirection::kRtl)
logical_left_value = (available_space + logical_left_value) -
margin_logical_left_value -
margin_logical_right_value;
}
} else {
// -------------------------------------------------------------------------
// Otherwise, set 'auto' values for 'margin-left' and 'margin-right'
// to 0, and pick the one of the following six rules that applies.
//
// 1. 'left' and 'width' are 'auto' and 'right' is not 'auto', then the
// width is shrink-to-fit. Then solve for 'left'
//
// OMIT RULE 2 AS IT SHOULD NEVER BE HIT
// ------------------------------------------------------------------
// 2. 'left' and 'right' are 'auto' and 'width' is not 'auto', then if
// the 'direction' property of the containing block is 'ltr' set
// 'left' to the static position, otherwise set 'right' to the
// static position. Then solve for 'left' (if 'direction is 'rtl')
// or 'right' (if 'direction' is 'ltr').
// ------------------------------------------------------------------
//
// 3. 'width' and 'right' are 'auto' and 'left' is not 'auto', then the
// width is shrink-to-fit . Then solve for 'right'
// 4. 'left' is 'auto', 'width' and 'right' are not 'auto', then solve
// for 'left'
// 5. 'width' is 'auto', 'left' and 'right' are not 'auto', then solve
// for 'width'
// 6. 'right' is 'auto', 'left' and 'width' are not 'auto', then solve
// for 'right'
//
// Calculation of the shrink-to-fit width is similar to calculating the
// width of a table cell using the automatic table layout algorithm.
// Roughly: calculate the preferred width by formatting the content without
// breaking lines other than where explicit line breaks occur, and also
// calculate the preferred minimum width, e.g., by trying all possible line
// breaks. CSS 2.1 does not define the exact algorithm.
// Thirdly, calculate the available width: this is found by solving for
// 'width' after setting 'left' (in case 1) or 'right' (in case 3) to 0.
//
// Then the shrink-to-fit width is:
// min(max(preferred minimum width, available width), preferred width).
// -------------------------------------------------------------------------
// NOTE: For rules 3 and 6 it is not necessary to solve for 'right'
// because the value is not used for any further calculations.
// Calculate margins, 'auto' margins are ignored.
margin_logical_left_value = MinimumValueForLength(
margin_logical_left, container_relative_logical_width);
margin_logical_right_value = MinimumValueForLength(
margin_logical_right, container_relative_logical_width);
const LayoutUnit available_space =
container_logical_width -
(margin_logical_left_value + margin_logical_right_value +
logical_left_value + logical_right_value + borders_plus_padding);
// FIXME: Is there a faster way to find the correct case?
// Use rule/case that applies.
if (logical_left_is_auto && logical_width_is_auto &&
!logical_right_is_auto) {
// RULE 1: (use shrink-to-fit for width, and solve of left)
computed_values.extent_ =
ShrinkToFitLogicalWidth(available_space, borders_plus_padding);
logical_left_value = available_space - computed_values.extent_;
} else if (!logical_left_is_auto && logical_width_is_auto &&
logical_right_is_auto) {
// RULE 3: (use shrink-to-fit for width, and no need solve of right)
computed_values.extent_ =
ShrinkToFitLogicalWidth(available_space, borders_plus_padding);
} else if (logical_left_is_auto && !logical_width_is_auto &&
!logical_right_is_auto) {
// RULE 4: (solve for left)
computed_values.extent_ = logical_width_value;
logical_left_value = available_space - computed_values.extent_;
} else if (!logical_left_is_auto && logical_width_is_auto &&
!logical_right_is_auto) {
// RULE 5: (solve for width)
if (AutoWidthShouldFitContent())
computed_values.extent_ =
ShrinkToFitLogicalWidth(available_space, borders_plus_padding);
else
computed_values.extent_ = std::max(LayoutUnit(), available_space);
} else if (!logical_left_is_auto && !logical_width_is_auto &&
logical_right_is_auto) {
// RULE 6: (no need solve for right)
computed_values.extent_ = logical_width_value;
}
}
// Use computed values to calculate the horizontal position.
// FIXME: This hack is needed to calculate the logical left position for a
// 'rtl' relatively positioned, inline because right now, it is using the
// logical left position of the first line box when really it should use the
// last line box. When this is fixed elsewhere, this block should be removed.
if (container_block->IsLayoutInline() &&
!container_block->StyleRef().IsLeftToRightDirection()) {
const LayoutInline* flow = ToLayoutInline(container_block);
InlineFlowBox* first_line = flow->FirstLineBox();
InlineFlowBox* last_line = flow->LastLineBox();
if (first_line && last_line && first_line != last_line) {
computed_values.position_ =
logical_left_value + margin_logical_left_value +
last_line->BorderLogicalLeft() +
(last_line->LogicalLeft() - first_line->LogicalLeft());
return;
}
}
computed_values.position_ = logical_left_value + margin_logical_left_value;
ComputeLogicalLeftPositionedOffset(computed_values.position_, this,
computed_values.extent_, container_block,
container_logical_width);
}
void LayoutBox::ComputeBlockStaticDistance(
Length& logical_top,
Length& logical_bottom,
const LayoutBox* child,
const LayoutBoxModelObject* container_block,
const NGBoxFragmentBuilder* fragment_builder) {
if (!logical_top.IsAuto() || !logical_bottom.IsAuto())
return;
// FIXME: The static distance computation has not been patched for mixed
// writing modes.
LayoutUnit static_logical_top = child->Layer()->StaticBlockPosition();
for (LayoutObject* curr = child->Parent(); curr && curr != container_block;
curr = curr->Container()) {
if (!curr->IsBox() || curr->IsTableRow())
continue;
const LayoutBox& box = *ToLayoutBox(curr);
static_logical_top +=
(fragment_builder &&
fragment_builder->GetLayoutObject() == box.Parent())
? fragment_builder->GetChildOffset(&box).block_offset
: box.LogicalTop();
if (box.IsInFlowPositioned())
static_logical_top += box.OffsetForInFlowPosition().top;
if (!box.IsLayoutFlowThread())
continue;
// We're walking out of a flowthread here. This flow thread is not in the
// containing block chain, so we need to convert the position from the
// coordinate space of this flowthread to the containing coordinate space.
// The inline position cannot affect the block position, so we don't bother
// calculating it.
LayoutUnit dummy_inline_position;
ToLayoutFlowThread(box).FlowThreadToContainingCoordinateSpace(
static_logical_top, dummy_inline_position);
}
// Now static_logical_top is relative to container_block's logical top.
// Convert it to be relative to containing_block's logical client top.
static_logical_top -= container_block->BorderBefore();
if (container_block->IsBox()) {
static_logical_top -=
ToLayoutBox(container_block)->LogicalTopScrollbarHeight();
}
logical_top = Length::Fixed(static_logical_top);
}
void LayoutBox::ComputePositionedLogicalHeight(
LogicalExtentComputedValues& computed_values) const {
// The following is based off of the W3C Working Draft from April 11, 2006 of
// CSS 2.1: Section 10.6.4 "Absolutely positioned, non-replaced elements"
// <http://www.w3.org/TR/2005/WD-CSS21-20050613/visudet.html#abs-non-replaced-height>
// (block-style-comments in this function and in
// computePositionedLogicalHeightUsing()
// correspond to text from the spec)
// We don't use containingBlock(), since we may be positioned by an enclosing
// relpositioned inline.
const LayoutBoxModelObject* container_block =
ToLayoutBoxModelObject(Container());
const LayoutUnit container_logical_height =
ContainingBlockLogicalHeightForPositioned(container_block);
const ComputedStyle& style_to_use = StyleRef();
const LayoutUnit borders_plus_padding = BorderAndPaddingLogicalHeight();
const Length& margin_before = style_to_use.MarginBefore();
const Length& margin_after = style_to_use.MarginAfter();
Length logical_top_length = style_to_use.LogicalTop();
Length logical_bottom_length = style_to_use.LogicalBottom();
// ---------------------------------------------------------------------------
// For the purposes of this section and the next, the term "static position"
// (of an element) refers, roughly, to the position an element would have had
// in the normal flow. More precisely, the static position for 'top' is the
// distance from the top edge of the containing block to the top margin edge
// of a hypothetical box that would have been the first box of the element if
// its 'position' property had been 'static' and 'float' had been 'none'. The
// value is negative if the hypothetical box is above the containing block.
//
// But rather than actually calculating the dimensions of that hypothetical
// box, user agents are free to make a guess at its probable position.
//
// For the purposes of calculating the static position, the containing block
// of fixed positioned elements is the initial containing block instead of
// the viewport.
// ---------------------------------------------------------------------------
// see FIXME 1
// Calculate the static distance if needed.
ComputeBlockStaticDistance(logical_top_length, logical_bottom_length, this,
container_block);
// Calculate constraint equation values for 'height' case.
LayoutUnit logical_height = computed_values.extent_;
ComputePositionedLogicalHeightUsing(
kMainOrPreferredSize, style_to_use.LogicalHeight(), container_block,
container_logical_height, borders_plus_padding, logical_height,
logical_top_length, logical_bottom_length, margin_before, margin_after,
computed_values);
// Avoid doing any work in the common case (where the values of min-height and
// max-height are their defaults).
// see FIXME 2
// Calculate constraint equation values for 'max-height' case.
const Length& logical_max_height = style_to_use.LogicalMaxHeight();
if (!logical_max_height.IsMaxSizeNone() &&
!logical_max_height.IsMinContent() &&
!logical_max_height.IsMaxContent() &&
!logical_max_height.IsFitContent()) {
LogicalExtentComputedValues max_values;
ComputePositionedLogicalHeightUsing(
kMaxSize, logical_max_height, container_block, container_logical_height,
borders_plus_padding, logical_height, logical_top_length,
logical_bottom_length, margin_before, margin_after, max_values);
if (computed_values.extent_ > max_values.extent_) {
computed_values.extent_ = max_values.extent_;
computed_values.position_ = max_values.position_;
computed_values.margins_.before_ = max_values.margins_.before_;
computed_values.margins_.after_ = max_values.margins_.after_;
}
}
// Calculate constraint equation values for 'min-height' case.
Length logical_min_height = style_to_use.LogicalMinHeight();
if (logical_min_height.IsMinContent() || logical_min_height.IsMaxContent() ||
logical_min_height.IsFitContent())
logical_min_height = Length::Auto();
if (!logical_min_height.IsZero() || logical_min_height.IsFillAvailable()) {
LogicalExtentComputedValues min_values;
ComputePositionedLogicalHeightUsing(
kMinSize, logical_min_height, container_block, container_logical_height,
borders_plus_padding, logical_height, logical_top_length,
logical_bottom_length, margin_before, margin_after, min_values);
if (computed_values.extent_ < min_values.extent_) {
computed_values.extent_ = min_values.extent_;
computed_values.position_ = min_values.position_;
computed_values.margins_.before_ = min_values.margins_.before_;
computed_values.margins_.after_ = min_values.margins_.after_;
}
}
// Set final height value.
computed_values.extent_ += borders_plus_padding;
}
void LayoutBox::ComputeLogicalTopPositionedOffset(
LayoutUnit& logical_top_pos,
const LayoutBox* child,
LayoutUnit logical_height_value,
const LayoutBoxModelObject* container_block,
LayoutUnit container_logical_height) {
// Deal with differing writing modes here. Our offset needs to be in the
// containing block's coordinate space. If the containing block is flipped
// along this axis, then we need to flip the coordinate. This can only happen
// if the containing block is both a flipped mode and perpendicular to us.
if ((child->StyleRef().IsFlippedBlocksWritingMode() &&
child->IsHorizontalWritingMode() !=
container_block->IsHorizontalWritingMode()) ||
(child->StyleRef().IsFlippedBlocksWritingMode() !=
container_block->StyleRef().IsFlippedBlocksWritingMode() &&
child->IsHorizontalWritingMode() ==
container_block->IsHorizontalWritingMode())) {
logical_top_pos =
container_logical_height - logical_height_value - logical_top_pos;
}
// Convert logical_top_pos from container's client space to container's border
// box space.
if (child->IsHorizontalWritingMode()) {
logical_top_pos += container_block->BorderTop();
} else if (container_block->HasFlippedBlocksWritingMode()) {
logical_top_pos += container_block->BorderRight();
if (container_block->IsBox())
logical_top_pos += ToLayoutBox(container_block)->RightScrollbarWidth();
} else {
logical_top_pos += container_block->BorderLeft();
if (container_block->IsBox())
logical_top_pos += ToLayoutBox(container_block)->LeftScrollbarWidth();
}
}
void LayoutBox::ComputePositionedLogicalHeightUsing(
SizeType height_size_type,
Length logical_height_length,
const LayoutBoxModelObject* container_block,
LayoutUnit container_logical_height,
LayoutUnit borders_plus_padding,
LayoutUnit logical_height,
const Length& logical_top,
const Length& logical_bottom,
const Length& margin_before,
const Length& margin_after,
LogicalExtentComputedValues& computed_values) const {
DCHECK(height_size_type == kMinSize ||
height_size_type == kMainOrPreferredSize ||
!logical_height_length.IsAuto());
if (height_size_type == kMinSize && logical_height_length.IsAuto())
logical_height_length = Length::Fixed(0);
// 'top' and 'bottom' cannot both be 'auto' because 'top would of been
// converted to the static position in computePositionedLogicalHeight()
DCHECK(!(logical_top.IsAuto() && logical_bottom.IsAuto()));
LayoutUnit logical_height_value;
LayoutUnit content_logical_height = logical_height - borders_plus_padding;
const LayoutUnit container_relative_logical_width =
ContainingBlockLogicalWidthForPositioned(container_block, false);
LayoutUnit logical_top_value;
bool logical_height_is_auto = logical_height_length.IsAuto();
bool logical_top_is_auto = logical_top.IsAuto();
bool logical_bottom_is_auto = logical_bottom.IsAuto();
LayoutUnit resolved_logical_height;
// Height is never unsolved for tables.
if (IsTable()) {
resolved_logical_height = content_logical_height;
logical_height_is_auto = false;
} else {
if (logical_height_length.IsIntrinsic())
resolved_logical_height = ComputeIntrinsicLogicalContentHeightUsing(
logical_height_length, content_logical_height, borders_plus_padding);
else
resolved_logical_height = AdjustContentBoxLogicalHeightForBoxSizing(
ValueForLength(logical_height_length, container_logical_height));
}
if (!logical_top_is_auto && !logical_height_is_auto &&
!logical_bottom_is_auto) {
// -------------------------------------------------------------------------
// If none of the three are 'auto': If both 'margin-top' and 'margin-bottom'
// are 'auto', solve the equation under the extra constraint that the two
// margins get equal values. If one of 'margin-top' or 'margin- bottom' is
// 'auto', solve the equation for that value. If the values are over-
// constrained, ignore the value for 'bottom' and solve for that value.
// -------------------------------------------------------------------------
// NOTE: It is not necessary to solve for 'bottom' in the over constrained
// case because the value is not used for any further calculations.
logical_height_value = resolved_logical_height;
logical_top_value = ValueForLength(logical_top, container_logical_height);
const LayoutUnit available_space =
container_logical_height -
(logical_top_value + logical_height_value +
ValueForLength(logical_bottom, container_logical_height) +
borders_plus_padding);
// Margins are now the only unknown
if (margin_before.IsAuto() && margin_after.IsAuto()) {
// Both margins auto, solve for equality
// NOTE: This may result in negative values.
computed_values.margins_.before_ =
available_space / 2; // split the difference
computed_values.margins_.after_ =
available_space - computed_values.margins_
.before_; // account for odd valued differences
} else if (margin_before.IsAuto()) {
// Solve for top margin
computed_values.margins_.after_ =
ValueForLength(margin_after, container_relative_logical_width);
computed_values.margins_.before_ =
available_space - computed_values.margins_.after_;
} else if (margin_after.IsAuto()) {
// Solve for bottom margin
computed_values.margins_.before_ =
ValueForLength(margin_before, container_relative_logical_width);
computed_values.margins_.after_ =
available_space - computed_values.margins_.before_;
} else {
// Over-constrained, (no need solve for bottom)
computed_values.margins_.before_ =
ValueForLength(margin_before, container_relative_logical_width);
computed_values.margins_.after_ =
ValueForLength(margin_after, container_relative_logical_width);
}
} else {
// -------------------------------------------------------------------------
// Otherwise, set 'auto' values for 'margin-top' and 'margin-bottom'
// to 0, and pick the one of the following six rules that applies.
//
// 1. 'top' and 'height' are 'auto' and 'bottom' is not 'auto', then
// the height is based on the content, and solve for 'top'.
//
// OMIT RULE 2 AS IT SHOULD NEVER BE HIT
// ------------------------------------------------------------------
// 2. 'top' and 'bottom' are 'auto' and 'height' is not 'auto', then
// set 'top' to the static position, and solve for 'bottom'.
// ------------------------------------------------------------------
//
// 3. 'height' and 'bottom' are 'auto' and 'top' is not 'auto', then
// the height is based on the content, and solve for 'bottom'.
// 4. 'top' is 'auto', 'height' and 'bottom' are not 'auto', and
// solve for 'top'.
// 5. 'height' is 'auto', 'top' and 'bottom' are not 'auto', and
// solve for 'height'.
// 6. 'bottom' is 'auto', 'top' and 'height' are not 'auto', and
// solve for 'bottom'.
// -------------------------------------------------------------------------
// NOTE: For rules 3 and 6 it is not necessary to solve for 'bottom'
// because the value is not used for any further calculations.
// Calculate margins, 'auto' margins are ignored.
computed_values.margins_.before_ =
MinimumValueForLength(margin_before, container_relative_logical_width);
computed_values.margins_.after_ =
MinimumValueForLength(margin_after, container_relative_logical_width);
const LayoutUnit available_space =
container_logical_height -
(computed_values.margins_.before_ + computed_values.margins_.after_ +
borders_plus_padding);
// Use rule/case that applies.
if (logical_top_is_auto && logical_height_is_auto &&
!logical_bottom_is_auto) {
// RULE 1: (height is content based, solve of top)
logical_height_value = content_logical_height;
logical_top_value =
available_space -
(logical_height_value +
ValueForLength(logical_bottom, container_logical_height));
} else if (!logical_top_is_auto && logical_height_is_auto &&
logical_bottom_is_auto) {
// RULE 3: (height is content based, no need solve of bottom)
logical_top_value = ValueForLength(logical_top, container_logical_height);
logical_height_value = content_logical_height;
} else if (logical_top_is_auto && !logical_height_is_auto &&
!logical_bottom_is_auto) {
// RULE 4: (solve of top)
logical_height_value = resolved_logical_height;
logical_top_value =
available_space -
(logical_height_value +
ValueForLength(logical_bottom, container_logical_height));
} else if (!logical_top_is_auto && logical_height_is_auto &&
!logical_bottom_is_auto) {
// RULE 5: (solve of height)
logical_top_value = ValueForLength(logical_top, container_logical_height);
logical_height_value = std::max(
LayoutUnit(),
available_space -
(logical_top_value +
ValueForLength(logical_bottom, container_logical_height)));
} else if (!logical_top_is_auto && !logical_height_is_auto &&
logical_bottom_is_auto) {
// RULE 6: (no need solve of bottom)
logical_height_value = resolved_logical_height;
logical_top_value = ValueForLength(logical_top, container_logical_height);
}
}
computed_values.extent_ = logical_height_value;
// Use computed values to calculate the vertical position.
computed_values.position_ =
logical_top_value + computed_values.margins_.before_;
ComputeLogicalTopPositionedOffset(computed_values.position_, this,
logical_height_value, container_block,
container_logical_height);
}
LayoutRect LayoutBox::LocalCaretRect(
const InlineBox* box,
int caret_offset,
LayoutUnit* extra_width_to_end_of_line) const {
// VisiblePositions at offsets inside containers either a) refer to the
// positions before/after those containers (tables and select elements) or
// b) refer to the position inside an empty block.
// They never refer to children.
// FIXME: Paint the carets inside empty blocks differently than the carets
// before/after elements.
LayoutUnit caret_width = GetFrameView()->CaretWidth();
LayoutRect rect(Location(), LayoutSize(caret_width, Size().Height()));
bool ltr =
box ? box->IsLeftToRightDirection() : StyleRef().IsLeftToRightDirection();
if ((!caret_offset) ^ ltr)
rect.Move(LayoutSize(Size().Width() - caret_width, LayoutUnit()));
if (box) {
const RootInlineBox& root_box = box->Root();
LayoutUnit top = root_box.LineTop();
rect.SetY(top);
rect.SetHeight(root_box.LineBottom() - top);
}
// If height of box is smaller than font height, use the latter one,
// otherwise the caret might become invisible.
//
// Also, if the box is not an atomic inline-level element, always use the font
// height. This prevents the "big caret" bug described in:
// <rdar://problem/3777804> Deleting all content in a document can result in
// giant tall-as-window insertion point
//
// FIXME: ignoring :first-line, missing good reason to take care of
const SimpleFontData* font_data = StyleRef().GetFont().PrimaryFont();
LayoutUnit font_height =
LayoutUnit(font_data ? font_data->GetFontMetrics().Height() : 0);
if (font_height > rect.Height() || (!IsAtomicInlineLevel() && !IsTable()))
rect.SetHeight(font_height);
if (extra_width_to_end_of_line)
*extra_width_to_end_of_line = Location().X() + Size().Width() - rect.MaxX();
// Move to local coords
rect.MoveBy(-Location());
// FIXME: Border/padding should be added for all elements but this workaround
// is needed because we use offsets inside an "atomic" element to represent
// positions before and after the element in deprecated editing offsets.
if (GetNode() &&
!(EditingIgnoresContent(*GetNode()) || IsDisplayInsideTable(GetNode()))) {
rect.SetX(rect.X() + BorderLeft() + PaddingLeft());
rect.SetY(rect.Y() + PaddingTop() + BorderTop());
}
if (!IsHorizontalWritingMode())
return rect.TransposedRect();
return rect;
}
PositionWithAffinity LayoutBox::PositionForPoint(
const PhysicalOffset& point) const {
// no children...return this layout object's element, if there is one, and
// offset 0
LayoutObject* first_child = SlowFirstChild();
if (!first_child)
return CreatePositionWithAffinity(
NonPseudoNode() ? FirstPositionInOrBeforeNode(*NonPseudoNode())
: Position());
if (IsTable() && NonPseudoNode()) {
const Node& node = *NonPseudoNode();
LayoutUnit x_in_block_direction = FlipForWritingMode(point.left);
if (x_in_block_direction < 0 || x_in_block_direction > Size().Width() ||
point.top < 0 || point.top > Size().Height()) {
if (x_in_block_direction <= Size().Width() / 2) {
return CreatePositionWithAffinity(FirstPositionInOrBeforeNode(node));
}
return CreatePositionWithAffinity(LastPositionInOrAfterNode(node));
}
}
// Pass off to the closest child.
LayoutUnit min_dist = LayoutUnit::Max();
LayoutBox* closest_layout_object = nullptr;
PhysicalOffset adjusted_point = point;
if (IsTableRow())
adjusted_point += PhysicalLocation();
for (LayoutObject* layout_object = first_child; layout_object;
layout_object = layout_object->NextSibling()) {
if ((!layout_object->SlowFirstChild() && !layout_object->IsInline() &&
!layout_object->IsLayoutBlockFlow()) ||
layout_object->StyleRef().Visibility() != EVisibility::kVisible)
continue;
if (!layout_object->IsBox())
continue;
LayoutBox* layout_box = ToLayoutBox(layout_object);
LayoutUnit top = layout_box->BorderTop() + layout_box->PaddingTop() +
(IsTableRow() ? LayoutUnit() : layout_box->Location().Y());
LayoutUnit bottom = top + layout_box->ContentHeight();
LayoutUnit left =
layout_box->BorderLeft() + layout_box->PaddingLeft() +
(IsTableRow() ? LayoutUnit() : layout_box->PhysicalLocation().left);
LayoutUnit right = left + layout_box->ContentWidth();
if (point.left <= right && point.left >= left && point.top <= top &&
point.top >= bottom) {
if (layout_box->IsTableRow()) {
return layout_box->PositionForPoint(point + adjusted_point -
layout_box->PhysicalLocation());
}
return layout_box->PositionForPoint(point -
layout_box->PhysicalLocation());
}
// Find the distance from (x, y) to the box. Split the space around the box
// into 8 pieces and use a different compare depending on which piece (x, y)
// is in.
PhysicalOffset cmp;
if (point.left > right) {
if (point.top < top)
cmp = PhysicalOffset(right, top);
else if (point.top > bottom)
cmp = PhysicalOffset(right, bottom);
else
cmp = PhysicalOffset(right, point.top);
} else if (point.left < left) {
if (point.top < top)
cmp = PhysicalOffset(left, top);
else if (point.top > bottom)
cmp = PhysicalOffset(left, bottom);
else
cmp = PhysicalOffset(left, point.top);
} else {
if (point.top < top)
cmp = PhysicalOffset(point.left, top);
else
cmp = PhysicalOffset(point.left, bottom);
}
PhysicalOffset difference = cmp - point;
LayoutUnit dist =
difference.left * difference.left + difference.top * difference.top;
if (dist < min_dist) {
closest_layout_object = layout_box;
min_dist = dist;
}
}
if (closest_layout_object) {
return closest_layout_object->PositionForPoint(
adjusted_point - closest_layout_object->PhysicalLocation());
}
return CreatePositionWithAffinity(
NonPseudoNode() ? FirstPositionInOrBeforeNode(*NonPseudoNode())
: Position());
}
DISABLE_CFI_PERF
bool LayoutBox::ShrinkToAvoidFloats() const {
// Floating objects don't shrink. Objects that don't avoid floats don't
// shrink.
if (IsInline() || !CreatesNewFormattingContext() || IsFloating())
return false;
// Only auto width objects can possibly shrink to avoid floats.
if (!StyleRef().Width().IsAuto())
return false;
// If the containing block is LayoutNG, we will not let legacy layout deal
// with positioning of floats or sizing of auto-width new formatting context
// block level objects adjacent to them.
if (const auto* containing_block = ContainingBlock()) {
if (containing_block->IsLayoutNGMixin())
return false;
}
// Legends are taken out of the normal flow, and are laid out at the very
// start of the fieldset, and are therefore not affected by floats (that may
// appear earlier in the DOM).
if (IsRenderedLegend())
return false;
return true;
}
DISABLE_CFI_PERF
bool LayoutBox::ShouldBeConsideredAsReplaced() const {
if (IsAtomicInlineLevel())
return true;
// We need to detect all types of objects that should be treated as replaced.
// Callers of this method will use the result for various things, such as
// determining how to size the object, or whether it needs to avoid adjacent
// floats, just like objects that establish a new formatting context.
// IsAtomicInlineLevel() will not catch all the cases. Objects may be
// block-level and still replaced, and we cannot deduce this from the
// LayoutObject type. Checkboxes and radio buttons are such examples. We need
// to check the Element type. This also applies to images, since we may have
// created a block-flow LayoutObject for the ALT text (which still counts as
// replaced).
auto* element = DynamicTo<Element>(GetNode());
if (!element)
return false;
if (element->IsFormControlElement()) {
// Form control elements are generally replaced objects. Fieldsets are not,
// though. A fieldset is (almost) a regular block container, and should be
// treated as such.
return !IsA<HTMLFieldSetElement>(element);
}
return IsHTMLImageElement(element);
}
bool LayoutBox::HasNonCompositedScrollbars() const {
if (PaintLayerScrollableArea* scrollable_area = GetScrollableArea()) {
if (scrollable_area->HasHorizontalScrollbar() &&
!scrollable_area->LayerForHorizontalScrollbar())
return true;
if (scrollable_area->HasVerticalScrollbar() &&
!scrollable_area->LayerForVerticalScrollbar())
return true;
}
return false;
}
void LayoutBox::UpdateFragmentationInfoForChild(LayoutBox& child) {
LayoutState* layout_state = View()->GetLayoutState();
DCHECK(layout_state->IsPaginated());
child.SetOffsetToNextPage(LayoutUnit());
if (!IsPageLogicalHeightKnown())
return;
LayoutUnit logical_top = child.LogicalTop();
LayoutUnit logical_height = child.LogicalHeightWithVisibleOverflow();
LayoutUnit space_left = PageRemainingLogicalHeightForOffset(
logical_top, kAssociateWithLatterPage);
if (space_left < logical_height)
child.SetOffsetToNextPage(space_left);
}
bool LayoutBox::ChildNeedsRelayoutForPagination(const LayoutBox& child) const {
// TODO(mstensho): Should try to get this to work for floats too, instead of
// just marking and bailing here.
if (child.IsFloating())
return true;
const LayoutFlowThread* flow_thread = child.FlowThreadContainingBlock();
// Figure out if we really need to force re-layout of the child. We only need
// to do this if there's a chance that we need to recalculate pagination
// struts inside.
if (IsPageLogicalHeightKnown()) {
LayoutUnit logical_top = child.LogicalTop();
LayoutUnit logical_height = child.LogicalHeightWithVisibleOverflow();
LayoutUnit remaining_space = PageRemainingLogicalHeightForOffset(
logical_top, kAssociateWithLatterPage);
if (child.OffsetToNextPage()) {
// We need to relayout unless we're going to break at the exact same
// location as before.
if (child.OffsetToNextPage() != remaining_space)
return true;
// If column height isn't guaranteed to be uniform, we have no way of
// telling what has happened after the first break.
if (flow_thread && flow_thread->MayHaveNonUniformPageLogicalHeight())
return true;
} else if (logical_height > remaining_space) {
// Last time we laid out this child, we didn't need to break, but now we
// have to. So we need to relayout.
return true;
}
} else if (child.OffsetToNextPage()) {
// This child did previously break, but it won't anymore, because we no
// longer have a known fragmentainer height.
return true;
}
// It seems that we can skip layout of this child, but we need to ask the flow
// thread for permission first. We currently cannot skip over objects
// containing column spanners.
return flow_thread && !flow_thread->CanSkipLayout(child);
}
void LayoutBox::MarkChildForPaginationRelayoutIfNeeded(
LayoutBox& child,
SubtreeLayoutScope& layout_scope) {
DCHECK(!child.NeedsLayout() || child.LayoutBlockedByDisplayLock(
DisplayLockLifecycleTarget::kChildren));
LayoutState* layout_state = View()->GetLayoutState();
if (layout_state->PaginationStateChanged() ||
(layout_state->IsPaginated() && ChildNeedsRelayoutForPagination(child)))
layout_scope.SetChildNeedsLayout(&child);
}
void LayoutBox::MarkOrthogonalWritingModeRoot() {
DCHECK(GetFrameView());
GetFrameView()->AddOrthogonalWritingModeRoot(*this);
}
void LayoutBox::UnmarkOrthogonalWritingModeRoot() {
DCHECK(GetFrameView());
GetFrameView()->RemoveOrthogonalWritingModeRoot(*this);
}
// Children of LayoutCustom object's are only considered "items" when it has a
// loaded algorithm.
bool LayoutBox::IsCustomItem() const {
auto* parent_layout_box = DynamicTo<LayoutNGCustom>(Parent());
return parent_layout_box && parent_layout_box->IsLoaded();
}
// LayoutCustom items are only shrink-to-fit during the web-developer defined
// layout phase (not during fallback).
bool LayoutBox::IsCustomItemShrinkToFit() const {
DCHECK(IsCustomItem());
return To<LayoutNGCustom>(Parent())->IsLoaded();
}
void LayoutBox::AddVisualEffectOverflow() {
if (!StyleRef().HasVisualOverflowingEffect())
return;
// Add in the final overflow with shadows, outsets and outline combined.
PhysicalRect visual_effect_overflow = PhysicalBorderBoxRect();
LayoutRectOutsets outsets = ComputeVisualEffectOverflowOutsets();
visual_effect_overflow.Expand(outsets);
AddSelfVisualOverflow(visual_effect_overflow);
if (VisualOverflowIsSet()) {
overflow_->visual_overflow->SetHasSubpixelVisualEffectOutsets(
!IsIntegerValue(outsets.Top()) || !IsIntegerValue(outsets.Right()) ||
!IsIntegerValue(outsets.Bottom()) || !IsIntegerValue(outsets.Left()));
}
}
LayoutRectOutsets LayoutBox::ComputeVisualEffectOverflowOutsets() {
const ComputedStyle& style = StyleRef();
DCHECK(style.HasVisualOverflowingEffect());
LayoutRectOutsets outsets = style.BoxDecorationOutsets();
if (style.HasOutline()) {
Vector<PhysicalRect> outline_rects = OutlineRects(
PhysicalOffset(), OutlineRectsShouldIncludeBlockVisualOverflow());
PhysicalRect rect = UnionRectEvenIfEmpty(outline_rects);
bool outline_affected = rect.size != PhysicalSizeToBeNoop(Size());
SetOutlineMayBeAffectedByDescendants(outline_affected);
rect.Inflate(LayoutUnit(style.OutlineOutsetExtent()));
outsets.Unite(LayoutRectOutsets(-rect.Y(), rect.Right() - Size().Width(),
rect.Bottom() - Size().Height(),
-rect.X()));
}
return outsets;
}
void LayoutBox::AddVisualOverflowFromChild(const LayoutBox& child,
const LayoutSize& delta) {
// Never allow flow threads to propagate overflow up to a parent.
if (child.IsLayoutFlowThread())
return;
// Add in visual overflow from the child. Even if the child clips its
// overflow, it may still have visual overflow of its own set from box shadows
// or reflections. It is unnecessary to propagate this overflow if we are
// clipping our own overflow.
if (child.HasSelfPaintingLayer())
return;
LayoutRect child_visual_overflow_rect =
child.VisualOverflowRectForPropagation();
child_visual_overflow_rect.Move(delta);
AddContentsVisualOverflow(child_visual_overflow_rect);
}
DISABLE_CFI_PERF
void LayoutBox::AddLayoutOverflowFromChild(const LayoutBox& child,
const LayoutSize& delta) {
// Never allow flow threads to propagate overflow up to a parent.
if (child.IsLayoutFlowThread())
return;
// Only propagate layout overflow from the child if the child isn't clipping
// its overflow. If it is, then its overflow is internal to it, and we don't
// care about it. LayoutOverflowRectForPropagation takes care of this and just
// propagates the border box rect instead.
LayoutRect child_layout_overflow_rect =
child.LayoutOverflowRectForPropagation(this);
child_layout_overflow_rect.Move(delta);
AddLayoutOverflow(child_layout_overflow_rect);
}
void LayoutBox::SetLayoutClientAfterEdge(LayoutUnit client_after_edge) {
if (LayoutOverflowIsSet())
overflow_->layout_overflow->SetLayoutClientAfterEdge(client_after_edge);
}
LayoutUnit LayoutBox::LayoutClientAfterEdge() const {
return LayoutOverflowIsSet()
? overflow_->layout_overflow->LayoutClientAfterEdge()
: ClientLogicalBottom();
}
PhysicalRect LayoutBox::PhysicalVisualOverflowRectIncludingFilters() const {
PhysicalRect bounds_rect = PhysicalVisualOverflowRect();
if (!StyleRef().HasFilter())
return bounds_rect;
FloatRect float_rect = Layer()->MapRectForFilter(FloatRect(bounds_rect));
float_rect.UniteIfNonZero(Layer()->FilterReferenceBox());
bounds_rect = PhysicalRect::EnclosingRect(float_rect);
return bounds_rect;
}
bool LayoutBox::HasTopOverflow() const {
return !StyleRef().IsLeftToRightDirection() && !IsHorizontalWritingMode();
}
bool LayoutBox::HasLeftOverflow() const {
return !StyleRef().IsLeftToRightDirection() && IsHorizontalWritingMode();
}
DISABLE_CFI_PERF
void LayoutBox::AddLayoutOverflow(const LayoutRect& rect) {
if (rect.IsEmpty())
return;
LayoutRect client_box = NoOverflowRect();
if (client_box.Contains(rect))
return;
// For overflow clip objects, we don't want to propagate overflow into
// unreachable areas.
LayoutRect overflow_rect(rect);
if (HasOverflowClip() || IsLayoutView()) {
// Overflow is in the block's coordinate space and thus is flipped for
// vertical-rl writing
// mode. At this stage that is actually a simplification, since we can
// treat vertical-lr/rl
// as the same.
if (HasTopOverflow())
overflow_rect.ShiftMaxYEdgeTo(
std::min(overflow_rect.MaxY(), client_box.MaxY()));
else
overflow_rect.ShiftYEdgeTo(std::max(overflow_rect.Y(), client_box.Y()));
if (HasLeftOverflow())
overflow_rect.ShiftMaxXEdgeTo(
std::min(overflow_rect.MaxX(), client_box.MaxX()));
else
overflow_rect.ShiftXEdgeTo(std::max(overflow_rect.X(), client_box.X()));
// Now re-test with the adjusted rectangle and see if it has become
// unreachable or fully
// contained.
if (client_box.Contains(overflow_rect) || overflow_rect.IsEmpty())
return;
}
if (!LayoutOverflowIsSet()) {
if (!overflow_)
overflow_ = std::make_unique<BoxOverflowModel>();
overflow_->layout_overflow.emplace(client_box);
}
overflow_->layout_overflow->AddLayoutOverflow(overflow_rect);
}
void LayoutBox::AddSelfVisualOverflow(const LayoutRect& rect) {
if (rect.IsEmpty())
return;
LayoutRect border_box = BorderBoxRect();
if (border_box.Contains(rect))
return;
if (!VisualOverflowIsSet()) {
if (!overflow_)
overflow_ = std::make_unique<BoxOverflowModel>();
overflow_->visual_overflow.emplace(border_box);
}
overflow_->visual_overflow->AddSelfVisualOverflow(rect);
}
void LayoutBox::AddContentsVisualOverflow(const LayoutRect& rect) {
if (rect.IsEmpty())
return;
// If hasOverflowClip() we always save contents visual overflow because we
// need it
// e.g. to determine whether to apply rounded corner clip on contents.
// Otherwise we save contents visual overflow only if it overflows the border
// box.
LayoutRect border_box = BorderBoxRect();
if (!HasOverflowClip() && border_box.Contains(rect))
return;
if (!VisualOverflowIsSet()) {
if (!overflow_)
overflow_ = std::make_unique<BoxOverflowModel>();
overflow_->visual_overflow.emplace(border_box);
}
overflow_->visual_overflow->AddContentsVisualOverflow(rect);
}
void LayoutBox::ClearLayoutOverflow() {
if (!overflow_)
return;
overflow_->layout_overflow.reset();
if (!overflow_->visual_overflow)
overflow_.reset();
}
void LayoutBox::ClearVisualOverflow() {
if (!overflow_)
return;
overflow_->visual_overflow.reset();
if (!overflow_->layout_overflow)
overflow_.reset();
}
bool LayoutBox::PercentageLogicalHeightIsResolvable() const {
Length fake_length = Length::Percent(100);
return ComputePercentageLogicalHeight(fake_length) != -1;
}
DISABLE_CFI_PERF
bool LayoutBox::HasUnsplittableScrollingOverflow() const {
// We will paginate as long as we don't scroll overflow in the pagination
// direction.
bool is_horizontal = IsHorizontalWritingMode();
if ((is_horizontal && !ScrollsOverflowY()) ||
(!is_horizontal && !ScrollsOverflowX()))
return false;
// Fragmenting scrollbars is only problematic in interactive media, e.g.
// multicol on a screen. If we're printing, which is non-interactive media, we
// should allow objects with non-visible overflow to be paginated as normally.
if (GetDocument().Printing())
return false;
// We do have overflow. We'll still be willing to paginate as long as the
// block has auto logical height, auto or undefined max-logical-height and a
// zero or auto min-logical-height.
// Note this is just a heuristic, and it's still possible to have overflow
// under these conditions, but it should work out to be good enough for common
// cases. Paginating overflow with scrollbars present is not the end of the
// world and is what we used to do in the old model anyway.
return !StyleRef().LogicalHeight().IsIntrinsicOrAuto() ||
(!StyleRef().LogicalMaxHeight().IsIntrinsicOrAuto() &&
!StyleRef().LogicalMaxHeight().IsMaxSizeNone() &&
(!StyleRef().LogicalMaxHeight().IsPercentOrCalc() ||
PercentageLogicalHeightIsResolvable())) ||
(!StyleRef().LogicalMinHeight().IsIntrinsicOrAuto() &&
StyleRef().LogicalMinHeight().IsPositive() &&
(!StyleRef().LogicalMinHeight().IsPercentOrCalc() ||
PercentageLogicalHeightIsResolvable()));
}
LayoutBox::PaginationBreakability LayoutBox::GetPaginationBreakability() const {
if (ShouldBeConsideredAsReplaced() || HasUnsplittableScrollingOverflow() ||
(Parent() && IsWritingModeRoot()) ||
(IsOutOfFlowPositioned() &&
StyleRef().GetPosition() == EPosition::kFixed) ||
ShouldApplySizeContainment() || DisplayLockInducesSizeContainment() ||
IsFrameSet())
return kForbidBreaks;
EBreakInside break_value = BreakInside();
if (break_value == EBreakInside::kAvoid ||
break_value == EBreakInside::kAvoidPage ||
break_value == EBreakInside::kAvoidColumn)
return kAvoidBreaks;
return kAllowAnyBreaks;
}
LayoutUnit LayoutBox::LineHeight(bool /*firstLine*/,
LineDirectionMode direction,
LinePositionMode /*linePositionMode*/) const {
if (IsAtomicInlineLevel()) {
return direction == kHorizontalLine ? MarginHeight() + Size().Height()
: MarginWidth() + Size().Width();
}
return LayoutUnit();
}
DISABLE_CFI_PERF
LayoutUnit LayoutBox::BaselinePosition(
FontBaseline baseline_type,
bool /*firstLine*/,
LineDirectionMode direction,
LinePositionMode line_position_mode) const {
DCHECK_EQ(line_position_mode, kPositionOnContainingLine);
if (IsAtomicInlineLevel()) {
LayoutUnit result = direction == kHorizontalLine
? MarginHeight() + Size().Height()
: MarginWidth() + Size().Width();
if (baseline_type == kAlphabeticBaseline)
return result;
return result - result / 2;
}
return LayoutUnit();
}
PaintLayer* LayoutBox::EnclosingFloatPaintingLayer() const {
const LayoutObject* curr = this;
while (curr) {
PaintLayer* layer = curr->HasLayer() && curr->IsBox()
? ToLayoutBox(curr)->Layer()
: nullptr;
if (layer && layer->IsSelfPaintingLayer())
return layer;
curr = curr->Parent();
}
return nullptr;
}
const LayoutBlock& LayoutBox::EnclosingScrollportBox() const {
const LayoutBlock* ancestor = ContainingBlock();
for (; ancestor; ancestor = ancestor->ContainingBlock()) {
if (ancestor->HasOverflowClip())
return *ancestor;
}
NOTREACHED();
return *ancestor;
}
LayoutRect LayoutBox::LogicalVisualOverflowRectForPropagation() const {
LayoutRect rect = VisualOverflowRectForPropagation();
if (!Parent()->StyleRef().IsHorizontalWritingMode())
return rect.TransposedRect();
return rect;
}
DISABLE_CFI_PERF
LayoutRect LayoutBox::RectForOverflowPropagation(const LayoutRect& rect) const {
// If the child and parent are in the same blocks direction, then we don't
// have to do anything fancy. Just return the rect.
if (Parent()->StyleRef().IsFlippedBlocksWritingMode() ==
StyleRef().IsFlippedBlocksWritingMode())
return rect;
// Convert the rect into parent's blocks direction by flipping along the y
// axis.
LayoutRect result = rect;
result.SetX(Size().Width() - rect.MaxX());
return result;
}
DISABLE_CFI_PERF
LayoutRect LayoutBox::LogicalLayoutOverflowRectForPropagation(
LayoutObject* container) const {
LayoutRect rect = LayoutOverflowRectForPropagation(container);
if (!Parent()->StyleRef().IsHorizontalWritingMode())
return rect.TransposedRect();
return rect;
}
DISABLE_CFI_PERF
LayoutRect LayoutBox::LayoutOverflowRectForPropagation(
LayoutObject* container) const {
// Only propagate interior layout overflow if we don't clip it.
LayoutRect rect = BorderBoxRect();
// We want to include the margin, but only when it adds height. Quirky margins
// don't contribute height nor do the margins of self-collapsing blocks.
if (!StyleRef().HasMarginAfterQuirk() && !IsSelfCollapsingBlock()) {
const ComputedStyle* container_style =
container ? container->Style() : nullptr;
rect.Expand(IsHorizontalWritingMode()
? LayoutSize(LayoutUnit(), MarginAfter(container_style))
: LayoutSize(MarginAfter(container_style), LayoutUnit()));
}
if (!ShouldClipOverflow() && !ShouldApplyLayoutContainment())
rect.Unite(LayoutOverflowRect());
bool has_transform = HasLayer() && Layer()->Transform();
if (IsInFlowPositioned() || has_transform) {
// If we are relatively positioned or if we have a transform, then we have
// to convert this rectangle into physical coordinates, apply relative
// positioning and transforms to it, and then convert it back.
DeprecatedFlipForWritingMode(rect);
PhysicalOffset container_offset;
if (IsRelPositioned())
container_offset = RelativePositionOffset();
if (ShouldUseTransformFromContainer(container)) {
TransformationMatrix t;
GetTransformFromContainer(container ? container : Container(),
container_offset, t);
rect = t.MapRect(rect);
} else {
rect.Move(container_offset.ToLayoutSize());
}
// Now we need to flip back.
DeprecatedFlipForWritingMode(rect);
}
return RectForOverflowPropagation(rect);
}
DISABLE_CFI_PERF
LayoutRect LayoutBox::NoOverflowRect() const {
return FlipForWritingMode(PhysicalPaddingBoxRect());
}
LayoutRect LayoutBox::VisualOverflowRect() const {
if (!VisualOverflowIsSet())
return BorderBoxRect();
if (HasOverflowClip() || HasMask())
return overflow_->visual_overflow->SelfVisualOverflowRect();
return UnionRect(overflow_->visual_overflow->SelfVisualOverflowRect(),
overflow_->visual_overflow->ContentsVisualOverflowRect());
}
PhysicalOffset LayoutBox::OffsetPoint(const Element* parent) const {
return AdjustedPositionRelativeTo(PhysicalLocation(), parent);
}
LayoutUnit LayoutBox::OffsetLeft(const Element* parent) const {
return OffsetPoint(parent).left;
}
LayoutUnit LayoutBox::OffsetTop(const Element* parent) const {
return OffsetPoint(parent).top;
}
LayoutBox* LayoutBox::LocationContainer() const {
// Location of a non-root SVG object derived from LayoutBox should not be
// affected by writing-mode of the containing box (SVGRoot).
if (IsSVGChild())
return nullptr;
// Normally the box's location is relative to its containing box.
LayoutObject* container = Container();
while (container && !container->IsBox())
container = container->Container();
return ToLayoutBox(container);
}
bool LayoutBox::HasRelativeLogicalWidth() const {
return StyleRef().LogicalWidth().IsPercentOrCalc() ||
StyleRef().LogicalMinWidth().IsPercentOrCalc() ||
StyleRef().LogicalMaxWidth().IsPercentOrCalc();
}
bool LayoutBox::HasRelativeLogicalHeight() const {
return StyleRef().LogicalHeight().IsPercentOrCalc() ||
StyleRef().LogicalMinHeight().IsPercentOrCalc() ||
StyleRef().LogicalMaxHeight().IsPercentOrCalc();
}
static void MarkBoxForRelayoutAfterSplit(LayoutBox* box) {
// FIXME: The table code should handle that automatically. If not,
// we should fix it and remove the table part checks.
if (box->IsTable()) {
// Because we may have added some sections with already computed column
// structures, we need to sync the table structure with them now. This
// avoids crashes when adding new cells to the table.
ToInterface<LayoutNGTableInterface>(box)->ForceSectionsRecalc();
} else if (box->IsTableSection()) {
ToInterface<LayoutNGTableSectionInterface>(box)->SetNeedsCellRecalc();
}
box->SetNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(
layout_invalidation_reason::kAnonymousBlockChange);
}
static void CollapseLoneAnonymousBlockChild(LayoutBox* parent,
LayoutObject* child) {
auto* child_block_flow = DynamicTo<LayoutBlockFlow>(child);
auto* parent_block_flow = DynamicTo<LayoutBlockFlow>(parent);
if (!child->IsAnonymousBlock() || !child_block_flow)
return;
if (!parent_block_flow)
return;
parent_block_flow->CollapseAnonymousBlockChild(child_block_flow);
}
LayoutObject* LayoutBox::SplitAnonymousBoxesAroundChild(
LayoutObject* before_child) {
LayoutBox* box_at_top_of_new_branch = nullptr;
while (before_child->Parent() != this) {
LayoutBox* box_to_split = ToLayoutBox(before_child->Parent());
if (box_to_split->SlowFirstChild() != before_child &&
box_to_split->IsAnonymous()) {
// We have to split the parent box into two boxes and move children
// from |beforeChild| to end into the new post box.
LayoutBox* post_box =
box_to_split->CreateAnonymousBoxWithSameTypeAs(this);
post_box->SetChildrenInline(box_to_split->ChildrenInline());
LayoutBox* parent_box = ToLayoutBox(box_to_split->Parent());
// We need to invalidate the |parentBox| before inserting the new node
// so that the table paint invalidation logic knows the structure is
// dirty. See for example LayoutTableCell:localVisualRect().
MarkBoxForRelayoutAfterSplit(parent_box);
parent_box->VirtualChildren()->InsertChildNode(
parent_box, post_box, box_to_split->NextSibling());
box_to_split->MoveChildrenTo(post_box, before_child, nullptr, true);
LayoutObject* child = post_box->SlowFirstChild();
DCHECK(child);
if (child && !child->NextSibling())
CollapseLoneAnonymousBlockChild(post_box, child);
child = box_to_split->SlowFirstChild();
DCHECK(child);
if (child && !child->NextSibling())
CollapseLoneAnonymousBlockChild(box_to_split, child);
MarkBoxForRelayoutAfterSplit(box_to_split);
MarkBoxForRelayoutAfterSplit(post_box);
box_at_top_of_new_branch = post_box;
before_child = post_box;
} else {
before_child = box_to_split;
}
}
// Splitting the box means the left side of the container chain will lose any
// percent height descendants below |boxAtTopOfNewBranch| on the right hand
// side.
if (box_at_top_of_new_branch) {
box_at_top_of_new_branch->ClearPercentHeightDescendants();
MarkBoxForRelayoutAfterSplit(this);
}
DCHECK_EQ(before_child->Parent(), this);
return before_child;
}
LayoutUnit LayoutBox::OffsetFromLogicalTopOfFirstPage() const {
LayoutState* layout_state = View()->GetLayoutState();
if (!layout_state || !layout_state->IsPaginated())
return LayoutUnit();
if (layout_state->GetLayoutObject() == this) {
LayoutSize offset = layout_state->PaginationOffset();
return IsHorizontalWritingMode() ? offset.Height() : offset.Width();
}
// A LayoutBlock always establishes a layout state, and this method is only
// meant to be called on the object currently being laid out.
DCHECK(!IsLayoutBlock());
// In case this box doesn't establish a layout state, try the containing
// block.
LayoutBlock* container_block = ContainingBlock();
DCHECK(layout_state->GetLayoutObject() == container_block);
return container_block->OffsetFromLogicalTopOfFirstPage() + LogicalTop();
}
void LayoutBox::SetOffsetToNextPage(LayoutUnit offset) {
if (!rare_data_ && !offset)
return;
EnsureRareData().offset_to_next_page_ = offset;
}
void LayoutBox::LogicalExtentAfterUpdatingLogicalWidth(
const LayoutUnit& new_logical_top,
LayoutBox::LogicalExtentComputedValues& computed_values) {
// FIXME: None of this is right for perpendicular writing-mode children.
LayoutUnit old_logical_width = LogicalWidth();
LayoutUnit old_logical_left = LogicalLeft();
LayoutUnit old_margin_left = MarginLeft();
LayoutUnit old_margin_right = MarginRight();
LayoutUnit old_logical_top = LogicalTop();
SetLogicalTop(new_logical_top);
UpdateLogicalWidth();
computed_values.extent_ = LogicalWidth();
computed_values.position_ = LogicalLeft();
computed_values.margins_.start_ = MarginStart();
computed_values.margins_.end_ = MarginEnd();
SetLogicalTop(old_logical_top);
SetLogicalWidth(old_logical_width);
SetLogicalLeft(old_logical_left);
SetMarginLeft(old_margin_left);
SetMarginRight(old_margin_right);
}
ShapeOutsideInfo* LayoutBox::GetShapeOutsideInfo() const {
return ShapeOutsideInfo::Info(*this);
}
void LayoutBox::ClearPreviousVisualRects() {
LayoutBoxModelObject::ClearPreviousVisualRects();
if (PaintLayerScrollableArea* scrollable_area = GetScrollableArea())
scrollable_area->ClearPreviousVisualRects();
}
void LayoutBox::SetPercentHeightContainer(LayoutBlock* container) {
DCHECK(!container || !PercentHeightContainer());
if (!container && !rare_data_)
return;
EnsureRareData().percent_height_container_ = container;
}
void LayoutBox::RemoveFromPercentHeightContainer() {
if (!PercentHeightContainer())
return;
DCHECK(PercentHeightContainer()->HasPercentHeightDescendant(this));
PercentHeightContainer()->RemovePercentHeightDescendant(this);
// The above call should call this object's
// setPercentHeightContainer(nullptr).
DCHECK(!PercentHeightContainer());
}
void LayoutBox::ClearPercentHeightDescendants() {
for (LayoutObject* curr = SlowFirstChild(); curr;
curr = curr->NextInPreOrder(this)) {
if (curr->IsBox())
ToLayoutBox(curr)->RemoveFromPercentHeightContainer();
}
}
LayoutUnit LayoutBox::PageLogicalHeightForOffset(LayoutUnit offset) const {
// We need to have calculated some fragmentainer logical height (even a
// tentative one will do, though) in order to tell how tall one fragmentainer
// is.
DCHECK(IsPageLogicalHeightKnown());
LayoutView* layout_view = View();
LayoutFlowThread* flow_thread = FlowThreadContainingBlock();
LayoutUnit page_logical_height;
if (!flow_thread) {
page_logical_height = layout_view->PageLogicalHeight();
} else {
page_logical_height = flow_thread->PageLogicalHeightForOffset(
offset + OffsetFromLogicalTopOfFirstPage());
}
DCHECK_GT(page_logical_height, LayoutUnit());
return page_logical_height;
}
bool LayoutBox::IsPageLogicalHeightKnown() const {
if (const LayoutFlowThread* flow_thread = FlowThreadContainingBlock())
return flow_thread->IsPageLogicalHeightKnown();
return View()->PageLogicalHeight();
}
LayoutUnit LayoutBox::PageRemainingLogicalHeightForOffset(
LayoutUnit offset,
PageBoundaryRule page_boundary_rule) const {
DCHECK(IsPageLogicalHeightKnown());
LayoutView* layout_view = View();
offset += OffsetFromLogicalTopOfFirstPage();
LayoutUnit footer_height =
View()->GetLayoutState()->HeightOffsetForTableFooters();
LayoutFlowThread* flow_thread = FlowThreadContainingBlock();
LayoutUnit remaining_height;
if (!flow_thread) {
LayoutUnit page_logical_height = layout_view->PageLogicalHeight();
remaining_height =
page_logical_height - IntMod(offset, page_logical_height);
if (page_boundary_rule == kAssociateWithFormerPage) {
// An offset exactly at a page boundary will act as being part of the
// former page in question (i.e. no remaining space), rather than being
// part of the latter (i.e. one whole page length of remaining space).
remaining_height = IntMod(remaining_height, page_logical_height);
}
} else {
remaining_height = flow_thread->PageRemainingLogicalHeightForOffset(
offset, page_boundary_rule);
}
return remaining_height - footer_height;
}
bool LayoutBox::CrossesPageBoundary(LayoutUnit offset,
LayoutUnit logical_height) const {
if (!IsPageLogicalHeightKnown())
return false;
return PageRemainingLogicalHeightForOffset(offset, kAssociateWithLatterPage) <
logical_height;
}
LayoutUnit LayoutBox::CalculatePaginationStrutToFitContent(
LayoutUnit offset,
LayoutUnit content_logical_height) const {
LayoutUnit strut_to_next_page =
PageRemainingLogicalHeightForOffset(offset, kAssociateWithLatterPage);
LayoutState* layout_state = View()->GetLayoutState();
strut_to_next_page += layout_state->HeightOffsetForTableFooters();
// If we're inside a cell in a row that straddles a page then avoid the
// repeating header group if necessary. If we're a table section we're
// already accounting for it.
if (!IsTableSection()) {
strut_to_next_page += layout_state->HeightOffsetForTableHeaders();
}
LayoutUnit next_page_logical_top = offset + strut_to_next_page;
if (PageLogicalHeightForOffset(next_page_logical_top) >=
content_logical_height)
return strut_to_next_page; // Content fits just fine in the next page or
// column.
// Moving to the top of the next page or column doesn't result in enough space
// for the content that we're trying to fit. If we're in a nested
// fragmentation context, we may find enough space if we move to a column
// further ahead, by effectively breaking to the next outer fragmentainer.
LayoutFlowThread* flow_thread = FlowThreadContainingBlock();
if (!flow_thread) {
// If there's no flow thread, we're not nested. All pages have the same
// height. Give up.
return strut_to_next_page;
}
// Start searching for a suitable offset at the top of the next page or
// column.
LayoutUnit flow_thread_offset =
OffsetFromLogicalTopOfFirstPage() + next_page_logical_top;
return strut_to_next_page +
flow_thread->NextLogicalTopForUnbreakableContent(
flow_thread_offset, content_logical_height) -
flow_thread_offset;
}
LayoutBox* LayoutBox::SnapContainer() const {
return rare_data_ ? rare_data_->snap_container_ : nullptr;
}
void LayoutBox::SetSnapContainer(LayoutBox* new_container) {
LayoutBox* old_container = SnapContainer();
if (old_container == new_container)
return;
if (old_container)
old_container->RemoveSnapArea(*this);
EnsureRareData().snap_container_ = new_container;
if (new_container)
new_container->AddSnapArea(*this);
}
void LayoutBox::ClearSnapAreas() {
if (SnapAreaSet* areas = SnapAreas()) {
for (auto* const snap_area : *areas)
snap_area->rare_data_->snap_container_ = nullptr;
areas->clear();
}
}
void LayoutBox::AddSnapArea(const LayoutBox& snap_area) {
EnsureRareData().EnsureSnapAreas().insert(&snap_area);
}
void LayoutBox::RemoveSnapArea(const LayoutBox& snap_area) {
if (rare_data_ && rare_data_->snap_areas_) {
rare_data_->snap_areas_->erase(&snap_area);
}
}
bool LayoutBox::AllowedToPropagateRecursiveScrollToParentFrame(
const WebScrollIntoViewParams& params) {
if (!GetFrameView()->SafeToPropagateScrollToParent())
return false;
if (params.GetScrollType() != kProgrammaticScroll)
return true;
return !GetDocument().IsVerticalScrollEnforced();
}
SnapAreaSet* LayoutBox::SnapAreas() const {
return rare_data_ ? rare_data_->snap_areas_.get() : nullptr;
}
CustomLayoutChild* LayoutBox::GetCustomLayoutChild() const {
DCHECK(rare_data_);
DCHECK(rare_data_->layout_child_);
return rare_data_->layout_child_.Get();
}
void LayoutBox::AddCustomLayoutChildIfNeeded() {
if (!IsCustomItem())
return;
const AtomicString& name = Parent()->StyleRef().DisplayLayoutCustomName();
LayoutWorklet* worklet = LayoutWorklet::From(*GetDocument().domWindow());
const CSSLayoutDefinition* definition =
worklet->Proxy()->FindDefinition(name);
// If there isn't a definition yet, the web developer defined layout isn't
// loaded yet (or is invalid). The layout tree will get re-attached when
// loaded, so don't bother creating a script representation of this node yet.
if (!definition)
return;
EnsureRareData().layout_child_ =
MakeGarbageCollected<CustomLayoutChild>(*definition, NGBlockNode(this));
}
void LayoutBox::ClearCustomLayoutChild() {
if (!rare_data_)
return;
if (rare_data_->layout_child_)
rare_data_->layout_child_->ClearLayoutNode();
rare_data_->layout_child_ = nullptr;
}
PhysicalRect LayoutBox::DebugRect() const {
return PhysicalRect(PhysicalLocation(), Size());
}
bool LayoutBox::ComputeShouldClipOverflow() const {
return HasOverflowClip() || ShouldApplyPaintContainment() || HasControlClip();
}
void LayoutBox::MutableForPainting::
SavePreviousContentBoxRectAndLayoutOverflowRect() {
auto& rare_data = GetLayoutBox().EnsureRareData();
rare_data.has_previous_content_box_rect_and_layout_overflow_rect_ = true;
rare_data.previous_physical_content_box_rect_ =
GetLayoutBox().PhysicalContentBoxRect();
rare_data.previous_physical_layout_overflow_rect_ =
GetLayoutBox().PhysicalLayoutOverflowRect();
}
float LayoutBox::VisualRectOutsetForRasterEffects() const {
// If the box has subpixel visual effect outsets, as the visual effect may be
// painted along the pixel-snapped border box, the pixels on the anti-aliased
// edge of the effect may overflow the calculated visual rect. Expand visual
// rect by one pixel in the case.
return VisualOverflowIsSet() &&
overflow_->visual_overflow->HasSubpixelVisualEffectOutsets()
? 1
: 0;
}
TextDirection LayoutBox::ResolvedDirection() const {
if (IsInline() && IsAtomicInlineLevel()) {
const auto fragments = NGPaintFragment::InlineFragmentsFor(this);
if (fragments.IsInLayoutNGInlineFormattingContext()) {
if (!fragments.IsEmpty()) {
return fragments.front().PhysicalFragment().ResolvedDirection();
}
} else if (InlineBoxWrapper()) {
return InlineBoxWrapper()->Direction();
}
}
return StyleRef().Direction();
}
} // namespace blink
| [
"huhibrowser@gmail.com"
] | huhibrowser@gmail.com |
a268086faf95e61514f16a28d0561de307300ac1 | a1f2aed3f1360ea7d889dc8e3a06725a97f0dcb0 | /tensorflow/contrib/periodic_resample/kernels/periodic_resample_op.cc | 9cee405cef25f54fd064f8002265c42016c4fa50 | [
"Apache-2.0"
] | permissive | Rezduan83/tensorflow | 3692715fc48709eac5824dbe34705cc49f8537d3 | f68404bdd10a4b6ef2a50439efac4614de024636 | refs/heads/master | 2022-10-10T07:33:09.209037 | 2018-01-27T23:01:31 | 2018-01-27T23:01:31 | 119,279,326 | 1 | 0 | Apache-2.0 | 2022-10-05T00:00:25 | 2018-01-28T17:07:26 | C++ | UTF-8 | C++ | false | false | 1,113 | cc | // =============================================================================
// Copyright 2016 The TensorFlow Authors. All Rights Reserved.
//
// 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 "tensorflow/core/framework/register_types.h"
#include "tensorflow/contrib/periodic_resample/kernels/periodic_resample_op.h"
namespace tensorflow {
REGISTER_KERNEL_BUILDER(Name("PeriodicResample")
.Device(DEVICE_CPU),
PeriodicResampleOp);
} // namespace tensorflow
| [
"1517779+sb2nov@users.noreply.github.com"
] | 1517779+sb2nov@users.noreply.github.com |
1837ea9e9f87e1ccf7baac6b0e5190350de528fc | e015dfd93cd71c9a4510d225902a97400ccbeb35 | /Compile Project/objCode.cpp | 56f1654fc5df49e54b814412a79802061ef0970b | [
"Apache-2.0"
] | permissive | luo-junyu/Compile-Project | 5b84b786a07f83578d1e2ab7db4d566d533b8810 | e4d430aba61ebc3d52e9780d15fec8e2ecdc1f8b | refs/heads/master | 2022-03-24T08:25:50.105547 | 2019-12-23T16:21:32 | 2019-12-23T16:21:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,073 | cpp | #include "objCode.h"
objCode::objCode(Instr _instr, Reg _t0, Reg _t1, Reg _t2, int _mem, std::string _str) {
this->instr = _instr;
this->t0 = _t0;
this->t1 = _t1;
this->t2 = _t2;
this->value = _mem;
this->label = _str;
}
void objCode::output(ofstream& output_file) {
switch (this->instr) {
case(Instr::add):
output_file << "add " << reg2string(t0) << " " << reg2string(t1) << " " << reg2string(t2) << endl;
break;
case(Instr::addi):
output_file << "addi " << reg2string(t0) << " " << reg2string(t1) << " " << value << endl;
break;
case(Instr::sub):
output_file << "sub " << reg2string(t0) << " " << reg2string(t1) << " " << reg2string(t2) << endl;
break;
case(Instr::subi):
output_file << "addi " << reg2string(t0) << " " << reg2string(t1) << " " << -1 * value << endl;
break;
case(Instr::mul):
output_file << "mul " << reg2string(t0) << " " << reg2string(t1) << " " << reg2string(t2) << endl;
break;
case(Instr::div):
output_file << "div " << reg2string(t1) << " " << reg2string(t2) << endl;
output_file << "mflo " << reg2string(t0) << endl;
break;
case(Instr::mod):
output_file << "div " << reg2string(t1) << " " << reg2string(t2) << endl;
output_file << "mfhi " << reg2string(t0) << endl;
break;
case(Instr::lw):
if (value != 0) {
output_file << "lw " << reg2string(t0) << " " << value << "(" << reg2string(t1) << ")" << endl;
} else {
if (t1 == Reg::zero) {
output_file << "lw " << reg2string(t0) << " " << label << endl;
} else {
output_file << "lw " << reg2string(t0) << " " << label << "(" << reg2string(t1) << ")" << endl;
}
}
break;
case(Instr::sw) :
if (value != 0) {
output_file << "sw " << reg2string(t0) << " " << value << "(" << reg2string(t1) << ")" << endl;
} else {
if (t1 == Reg::zero) {
output_file << "sw " << reg2string(t0) << " " << label << endl;
} else {
output_file << "sw " << reg2string(t0) << " " << label << "(" << reg2string(t1) << ")" << endl;
}
}
break;
case(Instr::bgt):
output_file << "bgt " << reg2string(t0) << " " << reg2string(t1) << " " << label << endl;
break;
case(Instr::bge):
output_file << "bge " << reg2string(t0) << " " << reg2string(t1) << " " << label << endl;
break;
case(Instr::blt):
output_file << "blt " << reg2string(t0) << " " << reg2string(t1) << " " << label << endl;
break;
case(Instr::ble):
output_file << "ble " << reg2string(t0) << " " << reg2string(t1) << " " << label << endl;
break;
case(Instr::beq):
output_file << "beq " << reg2string(t0) << " " << reg2string(t1) << " " << label << endl;
break;
case(Instr::bne):
output_file << "bne " << reg2string(t0) << " " << reg2string(t1) << " " << label << endl;
break;
case(Instr::jal):
output_file << "jal " << label << endl;
break;
case(Instr::jr):
output_file << "jr " << reg2string(t0) << endl;
break;
case(Instr::j):
output_file << "j " << label << endl;
break;
case(Instr::la) :
output_file << "la " << reg2string(t0) << " " << label << endl;
break;
case(Instr::li):
output_file << "li " << reg2string(t0) << " " << value << endl;
break;
case(Instr::move):
output_file << "move " << reg2string(t0) << " " << reg2string(t1) << endl;
break;
case(Instr::sll):
output_file << "sll " << reg2string(t0) << " " << reg2string(t1) << " " << value << endl;
break;
case(Instr::syscall):
output_file << "syscall" << endl;
break;
case(Instr::label):
output_file << endl << label << ": " << endl;
break;
case(Instr::data):
output_file << endl << ".data" << endl;
break;
case(Instr::data_identifier):
// array: .space 128
output_file << '\t' << label << ": .space " << value << endl;
break;
case(Instr::data_string) :
// string: .asciiz "nihao"
output_file << '\t' << label << endl;
break;
case(Instr::data_align):
output_file << '\t' << ".align " << value << endl;
break;
case(Instr::text):
output_file << ".text" << endl << endl;
break;
default:
assert(0);
}
}
string objCode::reg2string(Reg reg) {
switch (reg) {
case Reg::zero:
return "$zero";
case Reg::at:
return "$at";
case Reg::v0:
return "$v0";
case Reg::v1:
return "$v1";
case Reg::a0:
return "$a0";
case Reg::a1:
return "$a1";
case Reg::a2:
return "$a2";
case Reg::a3:
return "$a3";
case Reg::s0:
return "$s0";
case Reg::s1:
return "$s1";
case Reg::s2:
return "$s2";
case Reg::s3:
return "$s3";
case Reg::s4:
return "$s4";
case Reg::s5:
return "$s5";
case Reg::s6:
return "$s6";
case Reg::s7:
return "$s7";
case Reg::t0:
return "$t0";
case Reg::t1:
return "$t1";
case Reg::t2:
return "$t2";
case Reg::t3:
return "$t3";
case Reg::t4:
return "$t4";
case Reg::t5:
return "$t5";
case Reg::t6:
return "$t6";
case Reg::t7:
return "$t7";
case Reg::t8:
return "$t8";
case Reg::t9:
return "$t9";
case Reg::k1:
return "$k1";
case Reg::k0:
return "$k0";
case Reg::gp:
return "$gp";
case Reg::sp:
return "$sp";
case Reg::fp:
return "$fp";
case Reg::ra:
return "$ra";
default:
assert(0);
}
return "";
} | [
"luojunyu@buaa.edu.cn"
] | luojunyu@buaa.edu.cn |
883dc8f881a378fedcc5cf31673a8189ff23697a | 83e81c25b1f74f88ed0f723afc5d3f83e7d05da8 | /startop/view_compiler/util.cc | 7c44fc79761ab290fc4d3c62243b9a825dbd8736 | [
"Apache-2.0",
"LicenseRef-scancode-unicode"
] | permissive | Ankits-lab/frameworks_base | 8a63f39a79965c87a84e80550926327dcafb40b7 | 150a9240e5a11cd5ebc9bb0832ce30e9c23f376a | refs/heads/main | 2023-02-06T03:57:44.893590 | 2020-11-14T09:13:40 | 2020-11-14T09:13:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,144 | cc | /*
* Copyright (C) 2018 The Android Open Source Project
*
* 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 "util.h"
using std::string;
namespace startop {
namespace util {
// TODO: see if we can borrow this from somewhere else, like aapt2.
string FindLayoutNameFromFilename(const string& filename) {
size_t start = filename.rfind('/');
if (start == string::npos) {
start = 0;
} else {
start++; // advance past '/' character
}
size_t end = filename.find('.', start);
return filename.substr(start, end - start);
}
} // namespace util
} // namespace startop
| [
"keneankit01@gmail.com"
] | keneankit01@gmail.com |
849a688878f40013087f50a78ad6759c2c871093 | 5a157ee5838918ef1fe6624cdbcd9d5408e498e8 | /Programmers/RaceTrack.cpp | 5b33555d207aa751b0055dc9558e1b8bb3d8dd82 | [] | no_license | rlagksruf16/Algorithm_Everyday | 93e1071ef667e0a3417104cb1d6f14a5f39967ae | cf9032a04d8be7732a71b874dde124e0cb06421e | refs/heads/master | 2023-06-22T01:55:20.751238 | 2021-07-15T08:01:48 | 2021-07-15T08:01:48 | 217,672,321 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,283 | cpp | #include <iostream>
#include <algorithm>
#include <queue>
#include <vector>
using namespace std;
class Car{
public:
int x,y,cost, dir;
};
int solution(vector<vector<int>> board) {
int answer = 999999999, mx[] = {0,1,0,-1}, my[] = {1,0,-1,0}, N = board.size();
queue<Car> q;
Car c;
c.x = 0, c.y = 0, c.cost = 0, c.dir = 10;
q.push(c);
board[0][0] = 1;
while(!q.empty())
{
Car a = q.front();
q.pop();
if(a.x == N - 1 && a.y == N - 1)
{
if(answer > a.cost) answer = a.cost;
continue;
}
for(int i=0;i<4;i++)
{
int nx = a.x + mx[i];
int ny = a.y + my[i];
if( nx<0 || ny<0 || nx>=N || ny>=N || board[nx][ny] == 1) continue;
int nc = 0;
if(a.dir == 10 || a.dir == i)
nc = a.cost + 100;
else if(a.dir != i)
nc = a.cost + 600;
if(board[nx][ny] == 0 || board[nx][ny] >= nc)
{
board[nx][ny] = nc;
Car p;
p.x = nx, p.y = ny, p.cost = nc, p.dir = i;
q.push(p);
}
}
}
return answer;
} | [
"rlagksruf16@gmail.com"
] | rlagksruf16@gmail.com |
77c9dbdc516e8a96623741338e65b866628349d5 | b1a3302817b9157fe6e69a98d7dbcef59c419c60 | /SDX/tmu/proxydll.cpp | 3fc3aacafa35d950c3bbca3b24678d3fcd7555c1 | [] | no_license | grasmanek94/CodeDump | 3d5c9992b1ddcff74208905a776f756ffc99b179 | 33f53ee6924c32eac8505756d99951e1029d6178 | refs/heads/master | 2021-01-10T10:55:15.964167 | 2015-11-17T12:53:21 | 2015-11-17T12:53:21 | 46,346,695 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,430 | cpp | // proxydll.cpp
#include "proxydll.h"
// global variables
#pragma data_seg (".d3d9_shared")
myIDirect3DSwapChain9* gl_pmyIDirect3DSwapChain9;
myIDirect3DDevice9* gl_pmyIDirect3DDevice9;
myIDirect3D9* gl_pmyIDirect3D9;
HINSTANCE gl_hOriginalDll;
#pragma data_seg ()
void LoadOriginalDll(void);
// Exported function (faking d3d9.dll's one-and-only export)
IDirect3D9* WINAPI Direct3DCreate9(UINT SDKVersion)
{
bool Load = false;
if (!gl_hOriginalDll)
{
LoadOriginalDll(); // looking for the "right d3d9.dll"
Load = true;
}
// Hooking IDirect3D Object from Original Library
typedef IDirect3D9 *(WINAPI* D3D9_Type)(UINT SDKVersion);
D3D9_Type D3DCreate9_fn = (D3D9_Type) GetProcAddress( gl_hOriginalDll, "Direct3DCreate9");
// Debug
if (!D3DCreate9_fn)
{
OutputDebugString("PROXYDLL: Pointer to original D3DCreate9 function not received ERROR ****\r\n");
::ExitProcess(0); // exit the hard way
}
// Request pointer from Original Dll.
IDirect3D9 *pIDirect3D9_orig = D3DCreate9_fn(SDKVersion);
// Create my IDirect3D8 object and store pointer to original object there.
// note: the object will delete itself once Ref count is zero (similar to COM objects)
gl_pmyIDirect3D9 = new myIDirect3D9(pIDirect3D9_orig);
//if(Load)
// SDX::OnLoad();
// Return pointer to hooking Object instead of "real one"
return (gl_pmyIDirect3D9);
}
void LoadOriginalDll(void)
{
char buffer[MAX_PATH];
// Getting path to system dir and to d3d8.dll
::GetSystemDirectory(buffer,MAX_PATH);
// Append dll name
strcat(buffer,"\\d3d9.dll");
// try to load the system's d3d9.dll, if pointer empty
if (!gl_hOriginalDll) gl_hOriginalDll = ::LoadLibrary(buffer);
// Debug
if (!gl_hOriginalDll)
{
OutputDebugString("PROXYDLL: Original d3d9.dll not loaded ERROR ****\r\n");
::ExitProcess(0); // exit the hard way
}
}
void ExitInstance()
{
//SDX::OnUnload();
OutputDebugString("PROXYDLL: ExitInstance called.\r\n");
// Release the system's d3d9.dll
if (gl_hOriginalDll)
{
::FreeLibrary(gl_hOriginalDll);
gl_hOriginalDll = NULL;
}
}
//man, i'm hungry... *getting some food*
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
DisableThreadLibraryCalls(hModule);
break;
case DLL_PROCESS_DETACH:
ExitInstance();
break;
}
return true;
} | [
"grasmanek94@gmail.com"
] | grasmanek94@gmail.com |
a3c2336bfc156414083b9091ac2bf18b2b995807 | d7836bcbb15b185151037c69683f2679f6ee2abb | /Audio_Attempt/Audio_Attempt.ino | ca4807e0afaa5206fc9d89abd6f168adcd6546f2 | [] | no_license | ZoabKapoor/Hmc-Arduino-Stuff | fa816e358849137917c949b4cf31a2bf5a639cae | 71d181b8458a014c43e7b7ea255a33f3d7778a52 | refs/heads/master | 2021-01-01T20:41:24.996244 | 2014-06-18T17:41:44 | 2014-06-18T17:41:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 625 | ino | #include <ArduinoRobot.h>
void setup(){
Robot.begin();
Robot.beginTFT();//Initialize the TFT module
Robot.beginSpeaker();
}
void loop(){
Robot.clearScreen();
Robot.text("starting!!!!", 20, 20);
Robot.motorsWrite(255,255);
delay(2000);
Robot.motorsWrite(0,0);
delay(2000);
Robot.motorsWrite(-255,-255);
delay(2000);
Robot.clearScreen();
Robot.text("finished!!", 20, 20);
delay(1000);
/* Robot.text("Robot",0,0);
delay(2000);
Robot.clearScreen();
Robot.text("controls",0,0);
delay(2000);
Robot.clearScreen();
Robot.text("all!",0,0);
delay(2000);
Robot.clearScreen();
*/
}
| [
"zoab95@hotmail.com"
] | zoab95@hotmail.com |
e890db3976d49164d02db7ba309a63d836b6115c | 67150b01d76303682f18551cf37a3a4f9851e71e | /LW - Dual/Batman_V1/Batman_V1.ino | 8f03ff280470987646ef482ff75caca22762de78 | [] | no_license | jasanchez1/LW | 86ecab4c44ba97d2cc12ba48f66a1c49269ff39d | 51c84277604fe688bfdea2107cb0d6e8ef0f654b | refs/heads/main | 2023-04-26T07:04:22.206007 | 2021-05-24T15:49:38 | 2021-05-24T15:49:38 | 370,402,465 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,746 | ino |
//Outputs
int ledDone = 12; //Green led: Indicates when the system is ON
int ledWarning = 14; //Yellow led: indicates a safety sensor was triggered
int ledModeOpen = 27; //Led which indactes Mode Close is Running
int ledModeClose = 21; //Led which indactes Mode Open is Running
//Inputs
int modeOpen = 35; //Triggers mode Open
int modeClose = 34; //Triggers mode Close
int master = 23; //ON-OFF
int microswitch = 16; //Triggers security mesures when the doors are opened in an unintended moment
int movement = 17; //Triggers security mesures when movement is detected in an unintended moment
//AC Relays
int lightsA = 5; //Relay Lights 72W
int lightsB = 19; //Relay Lights 72W
int air = 18; //Relay DC Electromechanic
//Parameters
bool safety = true; //Turns true when there isn't safety sensors triggered
bool ventilation = false; //Turns true when ventilation are supposed to be working
bool lights = false; //Turns true when lights are supposed to be working
bool masterStatus = false; //Represents weather the Master Button is in HIGH status or in LOW status
bool modeOpenStatus = false; //Represents weather the Open Status is in HIGH status or in LOW status
bool modeCloseStatus = false; //Represents weather the Close Status is in HIGH status or in LOW status
//Time control
long int tOpen = 134400; //Time of light exposure (10 minutes)
long int msecs = 0; //General time of action
long int tpulse = 0; //Time pulse
long int await = 14000; // Await for Open Mode
long int tawait = 0; // Time await control
int functionPulse; // makes a led pulse
void setup() {
//Serial monitor
Serial.begin(115200);
//Setting outputs
pinMode(ledDone, OUTPUT);
pinMode(ledWarning, OUTPUT);
pinMode(ledModeOpen, OUTPUT);
pinMode(ledModeClose, OUTPUT);
pinMode(lightsA, OUTPUT);
pinMode(lightsB, OUTPUT);
pinMode(air, OUTPUT);
//Setting inputs
pinMode(modeOpen, INPUT);
pinMode(modeClose, INPUT);
pinMode(master, INPUT);
pinMode(microswitch, INPUT);
pinMode(movement, INPUT);
//Each system must start OFF whe plugged in
digitalWrite(lightsA, LOW);
digitalWrite(ventilation, LOW);
//Led status: Ready to open or start
digitalWrite(ledDone, LOW);
digitalWrite(ledWarning, LOW);
digitalWrite(ledModeOpen, LOW);
digitalWrite(ledModeClose, LOW);
}
void loop(){
Serial.print(msecs, DEC);
Serial.print("\n");
// E1: Master button setup
if(digitalRead(master) == HIGH){
Serial.print("\n E1 high");
masterStatus = true;}
if(digitalRead(master) == LOW){
Serial.print("\n E1 low");
masterStatus = false;
digitalWrite(lightsA, LOW);
digitalWrite(lightsB, LOW);
digitalWrite(air, LOW);
modeOpenStatus = false;
modeCloseStatus = false;
msecs = 0;
tawait = 0;
}
if(digitalRead(modeOpen) == HIGH && modeOpenStatus == false && modeCloseStatus == false){
modeOpenStatus = true;
digitalWrite(ledModeOpen, HIGH);
digitalWrite(ledDone, LOW);
delay(2000);
}
else if (digitalRead(modeOpen) == HIGH && modeOpenStatus == true){
digitalWrite(lightsA, LOW);
digitalWrite(lightsB, LOW);
digitalWrite(air, LOW);
modeOpenStatus = false;
modeCloseStatus = false;
msecs = 0;
tawait = 0;
digitalWrite(ledModeOpen, LOW);
digitalWrite(ledDone, HIGH);
delay(2000);
}
if(digitalRead(modeClose) == HIGH && modeCloseStatus == false && modeOpenStatus == false){
modeCloseStatus = true;
digitalWrite(ledModeClose, HIGH);
digitalWrite(ledDone, LOW);
modeOpenStatus = false;
delay(2000);
}
else if (digitalRead(modeClose) == HIGH && modeCloseStatus == true){
modeCloseStatus = false;
digitalWrite(lightsA, LOW);
digitalWrite(lightsB, LOW);
digitalWrite(air, LOW);
digitalWrite(ledModeClose, LOW);
digitalWrite(ledDone, HIGH);
delay(2000);
}
// E2: Pulse LED'S Behavior wheng plugged in, but not turned ON
if(masterStatus == true && modeCloseStatus == false && modeOpenStatus == false){
Serial.print("\n E2.1");
digitalWrite(ledModeOpen, LOW);
digitalWrite(ledModeClose, LOW);
digitalWrite(ledDone, HIGH);
digitalWrite(ledWarning, LOW);
} else if(masterStatus == false){
Serial.print("\n E2.2");
Serial.print("\n tpulse:");
Serial.print(tpulse, DEC);
Serial.print("\n");
lights = false;
ventilation = false;
modeOpenStatus = false;
modeCloseStatus = false;
if(tpulse <= 100){
tpulse += 1;
digitalWrite(ledModeOpen, HIGH);
digitalWrite(ledModeClose, LOW);
digitalWrite(ledDone, LOW);
digitalWrite(ledWarning, LOW);
} else if(tpulse > 100 && tpulse <= 200){
tpulse += 1;
digitalWrite(ledModeOpen, LOW);
digitalWrite(ledModeClose, HIGH);
digitalWrite(ledDone, LOW);
digitalWrite(ledWarning, LOW);
} else if(tpulse > 200 && tpulse <= 300){
tpulse += 1;
digitalWrite(ledModeOpen, LOW);
digitalWrite(ledModeClose, LOW);
digitalWrite(ledDone, HIGH);
digitalWrite(ledWarning, LOW);
} else if(tpulse > 300 && tpulse < 400){
tpulse += 1;
digitalWrite(ledModeOpen, LOW);
digitalWrite(ledModeClose, LOW);
digitalWrite(ledDone, LOW);
digitalWrite(ledWarning, HIGH);
} else {
tpulse=0;
digitalWrite(ledModeOpen, LOW);
digitalWrite(ledModeClose, LOW);
digitalWrite(ledDone, LOW);
digitalWrite(ledWarning, LOW);
}
} else {
Serial.print("\n E2.3");
digitalWrite(ledDone, LOW);
}
// E3: Seting up turn on and turn off of Relays
if(lights == true){
Serial.print("\n E3.1");
digitalWrite(lightsA, HIGH);
digitalWrite(lightsB, HIGH);
} else {
Serial.print("\n E3.2");
digitalWrite(lightsA, LOW);
digitalWrite(lightsB, LOW);
}
if(ventilation == true){
Serial.print("\n E3.3");
digitalWrite(air, HIGH);
} else {
Serial.print("\n E3.4");
digitalWrite(air, LOW);
}
//Setting up functions operations
// E4: Mode Open set up
if(modeOpenStatus == true){ //Mode open begins
Serial.print("\n E4.1");
digitalWrite(ledModeOpen, HIGH);
digitalWrite(ledModeClose, LOW);
digitalWrite(ledDone, LOW);
digitalWrite(ledWarning, LOW);
}
// E5: Mode Close set up
if(modeCloseStatus == true){ //Mode close begins
Serial.print("\n E5.1");
digitalWrite(ledModeClose, HIGH);
digitalWrite(ledModeOpen, LOW);
digitalWrite(ledDone, LOW);
digitalWrite(ledWarning, LOW);
}
// E6 Safety readings
if(digitalRead(movement)== HIGH && modeOpenStatus == true && tawait > await){
Serial.print("\n E6.1");
safety = false;
digitalWrite(ledWarning, HIGH);
} else if(digitalRead(microswitch) == LOW && modeCloseStatus == true){
Serial.print("\n E6.2");
safety = false;
digitalWrite(ledWarning, HIGH);
} else {
Serial.print("\n E6.3");
safety = true;
digitalWrite(ledWarning, LOW);
}
// E7 Safety mesures: Everything gotta be off
if(safety == false){
Serial.print("\n E7.1");
lights = false;
ventilation = false;
}
if(modeCloseStatus == true && safety){
Serial.print("\n E7.2");
lights = true;
ventilation = true;
} else if (modeCloseStatus== false && modeOpenStatus == false){
Serial.print("\n E7.3");
lights = false;
ventilation = false;
}
if(modeOpenStatus == true && msecs == 0 && tawait <= await && digitalRead(microswitch) == LOW) {
Serial.print("\n E7.4");
tawait += 1;
lights = false;
ventilation = false;
if (functionPulse <= 70 ){
functionPulse += 1;
digitalWrite(ledModeOpen, LOW);
} else if(functionPulse > 70 && functionPulse < 140) {
functionPulse += 1;
digitalWrite(ledModeOpen, HIGH);
} else {
functionPulse = 0;
}
} else if (modeOpenStatus == true && msecs == 0 && tawait > await && digitalRead(microswitch) == HIGH && safety) {
Serial.print("\n E7.5");
digitalWrite(ledModeOpen, HIGH);
digitalWrite(ledWarning, LOW);
msecs += 1;
} else if(modeOpenStatus == true && msecs <= tOpen && tawait > await && safety == true && digitalRead(microswitch) == LOW) {
Serial.print("\n E7.6");
msecs += 1;
lights = true;
ventilation = true;
digitalWrite(ledWarning, LOW);
} else if(modeOpenStatus == true && msecs > tOpen && safety == true){
Serial.print("\n E7.7");
lights = false;
ventilation = false;
modeOpenStatus = false;
msecs = 0;
tawait = 0;
digitalWrite(ledWarning, LOW);
} else if (modeOpenStatus == true && msecs == 0 && tawait < await && digitalRead(microswitch) == HIGH && safety) {
Serial.print("\n E7.5");
digitalWrite(ledModeOpen, HIGH);
digitalWrite(ledWarning, HIGH);
}
}
| [
"jasanchez1@uc.cl"
] | jasanchez1@uc.cl |
6b69dbcf3e65681a89a86f04fa7d76e1e25dc5c8 | aaa1346a54efe75cc6a4f6749c79ed9b316056e3 | /Playa/src/PlayaDenseLUSolver.hpp | 0faf63dc7e5f0fb7c960c1cb60df82e32d7ddaeb | [
"BSD-2-Clause"
] | permissive | trilinos/Sundance | e34c87159d8196d95f049d3cc8aa00ae7003c301 | f4c26e7babb5b9ba6cdadec499d9123273e390b0 | refs/heads/master | 2020-04-06T15:00:47.864668 | 2019-05-28T19:03:02 | 2019-05-28T19:03:02 | 47,220,438 | 3 | 2 | NOASSERTION | 2019-05-28T19:03:03 | 2015-12-01T22:07:02 | C++ | UTF-8 | C++ | false | false | 3,409 | hpp | /* @HEADER@ */
// ************************************************************************
//
// Playa: Programmable Linear Algebra
// Copyright 2012 Sandia Corporation
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. 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.
//
// 3. Neither the name of the Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE
// 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.
//
// Questions? Contact Kevin Long (kevin.long@ttu.edu)
//
/* @HEADER@ */
#ifndef PLAYA_AMESOSSOLVER_HPP
#define PLAYA_AMESOSSOLVER_HPP
#include "PlayaDefs.hpp"
#include "PlayaLinearSolverBaseDecl.hpp"
#include "PlayaHandleable.hpp"
#include "PlayaPrintable.hpp"
#include "Teuchos_Describable.hpp"
#include "Teuchos_Array.hpp"
#include "Teuchos_RefCountPtr.hpp"
#include "Teuchos_ParameterList.hpp"
namespace Playa
{
using namespace Teuchos;
/**
*
*/
class DenseLUSolver : public LinearSolverBase<double>,
public Playa::Handleable<LinearSolverBase<double> >,
public Printable,
public Describable
{
public:
/** */
DenseLUSolver();
/** */
virtual ~DenseLUSolver(){;}
/** \name Printable interface */
//@{
/** Write to a stream */
void print(std::ostream& os) const
{
os << description() << std::endl;
}
//@}
/** \name Describable interface */
//@{
/** Write a brief description */
std::string description() const {return "DenseLUSolver";}
//@}
/** */
virtual SolverState<double> solve(const LinearOperator<double>& op,
const Vector<double>& rhs,
Vector<double>& soln) const ;
/** \name Handleable interface */
//@{
/** Return a ref count pointer to a newly created object */
virtual RCP<LinearSolverBase<double> > getRcp()
{return rcp(this);}
//@}
protected:
private:
};
}
#endif
| [
"kevin.long@ttu.edu"
] | kevin.long@ttu.edu |
8ee4eb72ffb42cfed7dc074d2f85718073e6695b | 358262c0d75cfea5dbec263939a9fb70720daf66 | /src/gui/vector_display_thread.h | 29a00478e927b75aa0169f16c801f331e2956cae | [] | no_license | ut-amrl/LaserEmbeddings | 5896c4553cbeb0c7014a6b0e9137512602fe9163 | 045abb73b0d88bf579a82798e51b229f1a224d54 | refs/heads/master | 2021-04-06T02:15:07.365591 | 2019-02-25T07:06:06 | 2019-02-25T07:06:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,957 | h | //========================================================================
// This software is free: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License Version 3,
// as published by the Free Software Foundation.
//
// This software is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// Version 3 in the file COPYING that came with this distribution.
// If not, see <http://www.gnu.org/licenses/>.
//========================================================================
/*!
\file vector_display_thread.h
\brief Thread to run the GUI for Vector Localization; C++ Implementation: VectorDisplayThread
\author Joydeep Biswas, (C) 2010
*/
//========================================================================
#ifndef VECTOR_DISPLAY_THREAD_H_
#define VECTOR_DISPLAY_THREAD_H_
#include <stdio.h>
#include <algorithm>
#include <eigen3/Eigen/Dense>
#include <QtGui/QApplication>
#include <QWidget>
#include <QObject>
#include <QThread>
#include <string>
#include <vector>
#include <geometry_msgs/PoseWithCovarianceStamped.h>
#include <ros/package.h>
#include <ros/ros.h>
#include <sensor_msgs/LaserScan.h>
#include <sensor_msgs/PointCloud.h>
#include "gui_msgs/LidarDisplayMsg.h"
//#include "gui_msgs/CobotHumansDetected.h"
//#include "gui_msgs/CobotHumansClassified.h"
#include "gui_msgs/CobotRemoteInterfaceSrv.h"
#include "gui_msgs/CobotStatusMsg.h"
#include "gui_msgs/CobotLocalizationMsg.h"
#include "gui_msgs/CobotAnomalyMonitorRectangleMsg.h"
#include "vector_display.h"
//#include "../map/vector_map.h"
//#include "../map/navigation_map.h"
class ScopedFile;
class VectorDisplayThread : public QThread {
// Q_OBJECT
private:
ros::NodeHandle *node_handle_;
bool runApp;
bool testMode;
bool mapEditMode;
// bool navMapMode;
bool semanticMapMode;
bool semanticViewMode;
bool navViewMode;
bool viewVectorFile;
bool liveView;
bool persistentDisplay;
bool blankDisplay;
bool showAnomalyProb;
bool saveLocs;
bool saveOrientations;
bool clearDisplay;
bool autoUpdateMap;
// Maximum display refresh rate.
float maxFps;
geometry_msgs::PoseWithCovarianceStamped localizationInitMsg;
ros::Publisher initialPosePublisher;
ros::ServiceClient client;
ros::ServiceClient localizationClient;
ros::ServiceClient managerClient;
ros::ServiceClient autoLocalizeClient;
QApplication* app;
VectorDisplay* display;
std::string map_name_;
// NavigationMap navMap;
std::string mapsFolder;
//VectorMap vectorMap;
std::vector<Eigen::Vector2f> pathPlan;
Eigen::Vector2f robotLoc;
float robotAngle;
float anomalyLLX;
float anomalyLLY;
float anomalyURX;
float anomalyURY;
float anomaly;
//gui_msgs::CobotHumansDetected humansMsg;
//gui_msgs::CobotHumansClassified classifiedHumansMsg;
sensor_msgs::LaserScan laserScanMsg;
sensor_msgs::LaserScan kinectScanMsg;
sensor_msgs::PointCloud pointCloudMsg;
std::vector<gui_msgs::LidarDisplayMsg> displayMsgs;
std::vector<std::string> displayProviders;
double tPathPlan, tLaser, tPointCloud, tHumanDetect, tHumanTrack;
std::vector<VectorDisplay::Line> lines;
std::vector<Eigen::Vector2f> points;
std::vector<Eigen::Vector2f> circles;
std::vector<VectorDisplay::Quad> quads;
std::vector<VectorDisplay::Color> circleColors;
std::vector<VectorDisplay::Color> lineColors;
std::vector<VectorDisplay::Color> pointColors;
std::vector<VectorDisplay::Color> quadColors;
std::vector<std::string> textStrings;
std::vector<Eigen::Vector2f> textLocs;
std::vector<float> textHeights;
std::vector<VectorDisplay::Color> textColors;
std::vector<bool> textInWindowCoords;
ScopedFile* saveLocsFile;
public:
void Zoom(float zoom);
std::string GetMapName() { return map_name_; }
bool GetNavEdgeParams(
float* width,
float* max_speed,
bool* has_door);
bool GetSemanticType(
const std::vector<std::string>& types,
std::string* selected_type);
bool GetSemanticTypeAndLabel(
const std::vector<std::string>& types,
std::string* selected_type,
std::string* label);
void ChangeMap();
void AutoLocalize();
void KeyboardEventCallback(uint32_t key_code, uint32_t modifiers);
void MouseEventCallback(
const Eigen::Vector2f& mouse_down,
const Eigen::Vector2f& mouse_up, float orientation,
uint32_t modifiers);
void drawMap(std::vector<VectorDisplay::Line>* lines,
std::vector<VectorDisplay::Color>* lineColors);
void cobotLocalizationCallback(
const gui_msgs::CobotLocalizationMsg& msg);
void cobotAnomalyCallback(
const gui_msgs::CobotAnomalyMonitorRectangleMsg& msg);
void kinectScanCallback(const sensor_msgs::LaserScan& msg);
void laserCallback(const sensor_msgs::LaserScan& msg);
void cobotStatusCallback(const gui_msgs::CobotStatusMsg& msg);
//void humanDetectionCallback(const gui_msgs::CobotHumansDetected& msg);
//void humanTrackingCallback(const gui_msgs::CobotHumansClassified& msg);
void statusCallback(
const ros::MessageEvent<const gui_msgs::LidarDisplayMsg>& msgEvent);
void filteredPointCloudCallback(const sensor_msgs::PointCloud& msg);
void clearDisplayMessages();
void compileDisplay();
void setRunApp(bool newRunApp) {
runApp = newRunApp;
}
void setLiveView(bool liveView) {
this->liveView = liveView;
}
// void setOptions(
// bool testMode, std::string mapName, bool saveLocs, bool liveView,
// bool persistentDisplay, bool saveOrientations, bool blankDisplay,
// float maxFps, bool mapEditMode, bool navMapMode, bool semanticMapMode,
// bool semanticViewMode, bool navViewMode, bool viewVectorFile);
void setOptions(
bool testMode, std::string mapName, bool saveLocs, bool liveView,
bool persistentDisplay, bool saveOrientations, bool blankDisplay,
float maxFps, bool mapEditMode, bool semanticMapMode,
bool semanticViewMode, bool navViewMode, bool viewVectorFile);
protected:
void run();
// Edit the localization map
void editMap(const Eigen::Vector2f& mouse_down,
const Eigen::Vector2f& mouse_up, float orientation,
uint32_t modifiers);
// Edit the navigation map or semantic map (both are really graphs)
void editGraph(const Eigen::Vector2f& mouse_down,
const Eigen::Vector2f& mouse_up, float orientation,
uint32_t modifiers);
public:
VectorDisplayThread(
const std::string& _mapsFolder, VectorDisplay* disp,
ros::NodeHandle* node_handle, QApplication* qapp = 0,
QObject* parent = 0);
~VectorDisplayThread();
};
#endif /* VECTOR_DISPLAY_THREAD_H_ */
| [
"snashed@cs.umass.edu"
] | snashed@cs.umass.edu |
bd799f71fb290aef76b32e703df2035c3b486c6e | 562ef9ed4004007d5bbd56ff77cac62f375b56fd | /STG/Player.cpp | fe8c84ec0fda269bf97b9ccc65eb0680f6037748 | [] | no_license | DrDoker/Game_Cpp | 612f4fc6a9fab89dd8885b0d8fbc9ca5bfecaf25 | 2bf0ba4d789a6215d6e8538b3f48ce1002657bde | refs/heads/master | 2020-06-17T19:16:31.959198 | 2019-07-09T14:54:20 | 2019-07-09T14:54:20 | 196,021,085 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 7,616 | cpp | #pragma once
#include "Player.h"
int Player::GetPlayerScore() { return playerScore; }
bool Player::GetOnLadder() { return onLadder; }
bool Player::GetNextLvl() { return nextLvl; }
bool Player::GetFire() { return fire; }
void Player::SetPlayerScore(int setPlayerScore) { playerScore = setPlayerScore; }
void Player::SetOnLadder(bool setOnLadder) { onLadder = setOnLadder; }
void Player::SetNextLvl(bool setNextLvl) { nextLvl = setNextLvl; }
void Player::SetFire(bool setFire) { fire = setFire; }
Player::Player(Image &image, String Name, Level &lvl, float X, float Y, int W, int H) :Entity(image, Name, lvl, X, Y, W, H) {
playerScore = 0;
CurrentFrame = 0;
state = stay;
onLadder = false;
nextLvl = false;
fire = false;
if (name == "Player1") {
sprite.setTextureRect(IntRect(0, 90, w, h));
}
}
Player::~Player() {
}
void Player::control(float time) {
sprite.setTextureRect(IntRect(0, 90, 70, 90));
if (life == true) {
if (Keyboard::isKeyPressed(Keyboard::Left)) {
state = left;
speed = 0.135;
CurrentFrame += 0.0055*time;
if (CurrentFrame > 6)
CurrentFrame -= 6;
sprite.setTextureRect(IntRect(70 * (1 + int(CurrentFrame)) + 70, 90, -70, 90)); //через объект p класса player меняем спрайт, делая анимацию (используя оператор точку)
}
if (Keyboard::isKeyPressed(Keyboard::Right)) {
state = right;
speed = 0.135;//направление вправо, см выше
CurrentFrame += 0.0055*time;
if (CurrentFrame > 6)
CurrentFrame -= 6;
sprite.setTextureRect(IntRect(70 * (1 + int(CurrentFrame)), 90, 70, 90)); //через объект p класса player меняем спрайт, делая анимацию (используя оператор точку)
}
if (Keyboard::isKeyPressed(Keyboard::Space) && (onGround)) {
state = jump;
dy = -0.65;
onGround = false;
CurrentFrame += 0.005*time;
if (CurrentFrame > 6)
CurrentFrame -= 6;
sprite.setTextureRect(IntRect(70 * (1 + int(CurrentFrame)), 90, 70, 90)); //через объект p класса player меняем спрайт, делая анимацию (используя оператор точку)
}
if (Keyboard::isKeyPressed(Keyboard::Up) && (onLadder == true)) {
state = up;
CurrentFrame += 0.005*time; //служит для прохождения по "кадрам". переменная доходит до трех суммируя произведение времени и скорости. изменив 0.005 можно изменить скорость анимации
if (CurrentFrame > 8)
CurrentFrame -= 8; //проходимся по кадрам с первого по третий включительно. если пришли к третьему кадру - откидываемся назад.
sprite.setTextureRect(IntRect(70 * int(CurrentFrame) + 70, 0, -70, 90)); //проходимся по координатам Х. получается 96,96*2,96*3 и опять 96
}
if (Keyboard::isKeyPressed(Keyboard::Down) && (onLadder == true)) {
state = down;
CurrentFrame += 0.005*time; //служит для прохождения по "кадрам". переменная доходит до трех суммируя произведение времени и скорости. изменив 0.005 можно изменить скорость анимации
if (CurrentFrame > 8)
CurrentFrame -= 8; //проходимся по кадрам с первого по третий включительно. если пришли к третьему кадру - откидываемся назад.
sprite.setTextureRect(IntRect(70 * int(CurrentFrame) + 70, 0, -70, 90)); //проходимся по координатам Х. получается 96,96*2,96*3 и опять 96
}
if (Keyboard::isKeyPressed(Keyboard::Z)) {
fire = true;
if (dx == 0) {
sprite.setTextureRect(IntRect(70, 90, 70, 90));
}
}
}
}
void Player::update(float time) {}
void Player::updatePlayer(float time, Camera &camera) //функция "оживления" объекта класса. update - обновление. принимает в себя время SFML , вследствие чего работает бесконечно, давая персонажу движение.
{
control(time);
camera.setPlayerCoordinateForView(x, y);
switch (state)//реализуем поведение в зависимости от направления. (каждая цифра соответствует направлению)
{
case right: dx = speed; break;//по иксу задаем положительную скорость, по игреку зануляем. получаем, что персонаж идет только вправо
case left: dx = -speed; break;//по иксу задаем отрицательную скорость, по игреку зануляем. получается, что персонаж идет только влево
case up: dy = 0; break;//по иксу задаем нулевое значение, по игреку положительное. получается, что персонаж идет только вниз
case down: dy = 0; break;//по иксу задаем нулевое значение, по игреку отрицательное. получается, что персонаж идет только вверх
case jump: break;
case stay: break;
}
x += dx*time;//то движение из прошлого урока. наше ускорение на время получаем смещение координат и как следствие движение
checkCollisionWithMap(dx, 0);
y += dy*time;//аналогично по игреку
checkCollisionWithMap(0, dy);
dy += 0.0015*time;
speed = 0;
sprite.setPosition(x + w / 2, y + h / 2); //выводим спрайт в позицию x y , посередине. бесконечно выводим в этой функции, иначе бы наш спрайт стоял на месте.
if (health <= 0) {
life = false;
sprite.setTextureRect(IntRect(490, 90, 70, 90));
health = 0;
}
if (health > 100) {
health = 100;
}
}
void Player::checkCollisionWithMap(float Dx, float Dy)//ф-ция взаимодействия с картой
{
for (int i = 0; i < obj.size(); i++)//проходимся по объектам
if (getRect().intersects(obj[i].rect))//проверяем пересечение игрока с объектом
{
if (obj[i].name == "solid")//если встретили препятствие
{
if (Dy>0) { y = obj[i].rect.top - h; dy = 0; onGround = true; }
if (Dy<0) { y = obj[i].rect.top + obj[i].rect.height; dy = 0; }
if (Dx>0) { x = obj[i].rect.left - w; }
if (Dx<0) { x = obj[i].rect.left + obj[i].rect.width; }
}
if (obj[i].name == "lesn")
{
if (((obj[i].rect.left) < (x + w / 2)) && ((x + w / 2) < (obj[i].rect.left + obj[i].rect.width))) {
if ((Keyboard::isKeyPressed(Keyboard::Up)))
{
dx = 0;
dy = -0.2; onLadder = true;
}
else if ((Keyboard::isKeyPressed(Keyboard::Down)))
{
dy = 0;
dy = 0.2; onLadder = true;
}
else {
onLadder = false; //можно нажимать вверх и низ только на леснице
}
}
}
if (obj[i].name == "nextLvl")
{
nextLvl = true;
}
if (obj[i].name == "fire")
{
life = false;
health = 0;
}
}
}
| [
"doker.tk@gmail.com"
] | doker.tk@gmail.com |
2c63ff9e07918d9ce17942675c713b309b40482c | ab6da308587027661132050681c118435a08cce2 | /marshall.cpp | 9166dd523877db28a931d5609c1811a885f821e4 | [] | no_license | marcottelab/phenomatrixpp | a5cabc86a51961472eefdbad3167b34c98eac1a4 | 7677061988ae77374f64b0c77b6a17fe30748edc | refs/heads/master | 2016-09-05T16:46:46.887481 | 2010-05-18T21:16:10 | 2010-05-18T21:16:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,424 | cpp | /*
* File: marshall.cpp
* Author: jwoods
*
* Created on July 28, 2009, 4:24 PM
*/
#include "marshall.h"
// Actual constructor for Hs x nonHs and Hs x Hs matrices (source, not prediction).
// Takes two association files. The first argument is a file containing a list of
// orthologs between the two species.
// The first of each pair is the species identifier (Hs, Mm, etc).
void marshall::construct() {
// Check correctness.
size_t throwcount = 0;
if (!exists(orthologs_filename.c_str())) {
cerr << "Error: File with list of orthologs for source/dest combination " << source_species_info.first << "/" << dest_species_info.first << " not found." << endl;
cerr << "Filename should be " << orthologs_filename << endl;
throwcount++;
}
if (!exists(source_species_info.second)) {
cerr << "Error: Source species associations file '" << source_species_info.second << "' not found." << endl;
throwcount++;
}
if (dest_species_info.second != "" && !exists(dest_species_info.second)) {
cerr << "Error: Destination species association file '" << dest_species_info.second << "' not found." << endl;
throwcount++;
}
if (throwcount > 0) throw;
source_species_ = source_species_info.first;
cout << "Opening orthologs file: " << orthologs_filename << endl;
// Read the set of orthologs
ifstream oin(orthologs_filename.c_str());
ignore_header(oin);
set<gene_id_t> Orthologs = read_set<gene_id_t>(oin);
oin.close();
cout << "Opening source gene-phenotype file: " << source_species_info.second << endl;
// First read the organism which is the primary source of information.
// This sets how we will read the destination organism.
ifstream sin(source_species_info.second.c_str());
ignore_header(sin);
set<phene_id_t> local_phenes;
// Get all of them
multimap<gene_id_t,phene_id_t> Smap(read_associations<gene_id_t,phene_id_t>(sin));
if (dest_species_info.first != source_species_info.first) {
// Keep track of phenes which are the source species.
for (multimap<gene_id_t,phene_id_t>::iterator i = Smap.begin(); i != Smap.end(); ++i)
local_phenes.insert(i->second);
}
if (Smap.size() == 0) {
cerr << "Error: Source species had 0 associations." << endl;
throw;
} else cout << "Read " << Smap.size() << " associations." << endl;
map<phene_id_t, size_t> Dphene_genes; // keep track of number of genes per phene.
multimap<phene_id_t,gene_id_t> rDmap; // reversed from Smap so we can count entries.
sin.close();
if (dest_species_info.second != "") {
cout << "Opening destination gene-phenotype file: " << dest_species_info.second << endl;
ifstream din(dest_species_info.second.c_str());
ignore_header(din);
gene_id_t dgene;
phene_id_t dphene;
din >> dgene;
din >> dphene;
while (din) {
rDmap.insert(make_pair(dphene, dgene));
// Read the next line
din >> dgene;
din >> dphene;
}
// Take elements from rDmap and insert them in Smap.
for (multimap<phene_id_t,gene_id_t>::const_iterator i = rDmap.begin(); i != rDmap.end(); ++i) {
if (rDmap.count(i->first) >= min_genes && Smap.find(dgene) != Smap.end()) {
// Only allow this entry to be included in the matrix if:
// * there are at least min_genes in the dest phenotype
// * the gene exists in the source species already.
Smap.insert(make_pair(i->second, i->first));
}
}
}
// Get the unique values in the maps.
set<phene_id_t> phenes;
for (multimap<gene_id_t,phene_id_t>::iterator i = Smap.begin(); i != Smap.end(); ++i)
phenes.insert(i->second);
// Figure out which distance function to use.
//double (*distfn)(size_t,size_t,size_t,size_t) = switch_distance_function(distance_measure);
double (*distfn)(size_t,size_t,size_t,size_t) = NULL;
if (distance_measure == "hypergeometric") distfn = &hypergeometric;
else if (distance_measure == "euclidean") distfn = &euclidean;
else if (distance_measure == "manhattan") distfn = &manhattan;
else { cerr << "Error: Distance measure not recognized." << endl; throw; }
cout << "Creating matrix for species pair: " << dest_species_info.first << ", " << source_species_info.first << endl;
// Create matrix.
// Set species information.
if (dest_species_info.first == source_species_info.first)
Matrix = shared_ptr<genephene>(new genephene(distfn, Orthologs, phenes.size(), Smap, matrix_identifier, set<phene_id_t>()));
else
Matrix = shared_ptr<genephene>(new genephene(distfn, Orthologs, phenes.size(), Smap, matrix_identifier, local_phenes));
Matrix->species1(dest_species_info.first);
Matrix->species2(source_species_info.first);
source_species_ = source_species_info.first;
}
// Constructor for prediction matrix
void marshall::construct(bool weighted = false) {
// Check correctness.
size_t throwcount = 0;
if (!exists(orthologs_filename)) {
cerr << "Error: File with list of orthologs for " << dest_species_info.first << ", '" << orthologs_filename << "' << not found." << endl;
throwcount++;
}
if (!exists(phenotypes_filename)) {
cerr << "Error: File with list of phenotypes for " << dest_species_info.second << ", '" << phenotypes_filename << "' << not found." << endl;
throwcount++;
}
if (throwcount > 0) throw;
// Read the set of orthologs
ifstream oin(orthologs_filename.c_str());
ignore_header(oin);
set<gene_id_t> Orthologs = read_set<gene_id_t>(oin);
oin.close();
ifstream pin(phenotypes_filename.c_str());
ignore_header(pin);
set<phene_id_t> Phenotypes = read_set<phene_id_t>(pin);
pin.close();
// Figure out which distance function to use.
double (*distfn)(size_t,size_t,size_t,size_t) = switch_distance_function(distance_measure);
// Create matrix.
// Set species information.
Matrix = shared_ptr<genephene>(
new genephene(distfn, Orthologs, Phenotypes, weighted)
);
Matrix->species1(dest_species_info.first);
Matrix->species2(dest_species_info.first);
source_species_ = dest_species_info.first;
}
/*
marshall::marshall(const marshall& orig) {
throw;
} */
marshall::~marshall() {
}
void marshall::ignore_header(istream& in) const {
// Figure out what line we're on.
char c = in.get();
char d = in.get();
while ((c >= 'A' && c <= 'Z' && d >= 'a' && d <= 'z') || (c >= 'a' && d <= 'z')) {
// Put them back so we can say what we ignored.
in.putback(d);
in.putback(c);
// Ignore the header
string header;
getline(in, header);
cerr << "Ignored header line '" << header << "'" << endl;
if (has_numeric_component(header)) {
cerr << "Error: Header line contains numeric component. This is like a gene or phenotype label, and ignore_header needs to be modified." << endl;
throw;
}
// Get the next two characters.
c = in.get();
d = in.get();
}
// When the loop fails put them back.
in.putback(d);
in.putback(c);
// Now we're done.
}
| [
"john.woods@marcottelab.org"
] | john.woods@marcottelab.org |
6daf3c8c3bcb37e191a55ef2f647a8ff52074b6a | 8a8888bde6f563bfe1a3fc877bc0537875c7c675 | /deps_leveldb_port_port_posix.cc | 445a5c870ed562fde85326562f76e5a2b6379dff | [
"MIT"
] | permissive | DataDog/leveldb | 66c826e477fc16bc56bb0bfda6e060c5fe9a9e80 | 0631e62f1233ef6b823a5ab19a28dc8cd6d229d2 | refs/heads/master | 2023-08-25T11:31:10.125661 | 2021-01-22T15:40:18 | 2021-01-22T15:40:18 | 66,093,652 | 4 | 1 | MIT | 2023-04-08T10:35:21 | 2016-08-19T15:46:24 | Go | UTF-8 | C++ | false | false | 31 | cc | deps/leveldb/port/port_posix.cc | [
"matthieu.hauglustaine@datadoghq.com"
] | matthieu.hauglustaine@datadoghq.com |
4a871dbc5528406f801a990e22ef0652a5877a28 | cb6f7a0f76e481a1be405936843a6fe5afeb6003 | /include/texture_loader.hpp | 257719af8cd2e392c674cc285dbbf546fc7de641 | [] | no_license | Mooksc/RTS-Engine | 6300264e780bd232291f81cbae8df90fb7da20b7 | ec6616b8b5ce817ed42c15b34f2bb280dad7d524 | refs/heads/master | 2020-05-15T05:18:35.148988 | 2019-04-18T14:33:01 | 2019-04-18T14:33:01 | 182,103,219 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 353 | hpp | void texture_loader(std::string file_to_load) {
if(!texture.loadFromFile(file_to_load)) {
std::cout
<< "error?"
<< std::endl;
}
texture.loadFromFile(file_to_load);
sprite.setTexture(texture);
sf::Vector2u s = texture.getSize();
sprite.setPosition(400, 300);
sprite.setTextureRect(sf::IntRect(32, 0, 128, 128));
}; | [
"noreply@github.com"
] | noreply@github.com |
d30f4d51ac0064e69b7e493d3ebc21fd27bc9a6e | e237e934f9fb773687d8b8111421bd437fefc3c2 | /src/libCli/Completion.cpp | 185c4f3ef094e4a999abfd1b5f96c534bd849910 | [
"Apache-2.0"
] | permissive | ericboehmler/gWhisper | 8db588915d208891786e28cb6c65a93cc1e39bfb | ed7a48724a518e67203ad6dd60f1faeb12a024c0 | refs/heads/master | 2020-04-27T17:44:31.819496 | 2019-03-11T08:05:10 | 2019-03-11T08:05:10 | 174,535,073 | 0 | 0 | null | 2019-03-08T12:35:58 | 2019-03-08T12:35:58 | null | UTF-8 | C++ | false | false | 3,062 | cpp | // Copyright 2019 IBM Corporation
//
// 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 <libCli/Completion.hpp>
using namespace ArgParse;
namespace cli
{
void printBashCompletions( std::vector<std::shared_ptr<ParsedElement> > & f_candidates, ParsedElement & f_parseTree, const std::string & f_args, bool f_debug)
{
// completion requested :)
if(f_debug)
{
std::cerr << "Input string \"" << f_args << "\"\nCandidates:\n" << std::endl;
size_t n = f_parseTree.getMatchedString().size();
for(auto candidate : f_candidates)
{
std::string candidateStr =candidate->getMatchedString();
printf("pre: '%s'\n", candidateStr.c_str());
}
}
//size_t n = parseTree.getMatchedString().size();
size_t n = f_args.size();
for(auto candidate : f_candidates)
{
std::string candidateStr =candidate->getMatchedString();
std::string suggestion;
size_t start = n;
size_t end;
if(f_debug)
{
printf("candidateStr[n=%zu] = '%c'\n", n, candidateStr[n]);
}
if(
(candidateStr[n] != ' ')
&&
(candidateStr[n] != '=')
&&
(candidateStr[n] != ',')
&&
(candidateStr[n] != ':')
)
{
// bash always expects completion suggestions to start from the last token.
// Now we need to find out where the last token has started
// We need to "simulate" bash tokenizer here. tokens are delimited by ' ' '=' or ':'
start = candidateStr.find_last_of(" =:,", n)+1;
if(start == std::string::npos)
{
start = 0;
}
end = candidateStr.find_first_of(" ", n)-1;
//printf("cand='%s', n=%zu, start=%zu, end = %zu\n",candidateStr.c_str(), n, start, end);
}
else
{
start = candidateStr.find_last_of(" =:", n-1)+1;
//end = candidateStr.find_first_of(' ', n+1);
end = n;
}
//printf("start=%zu, end=%zu\n", start, end);
//suggestion = candidateStr.substr(n, std::string::npos);
suggestion = candidateStr.substr(start, std::string::npos);
//suggestion = candidateStr.substr(start, end-start+1);
if(f_debug)
{
printf("post: '%s'\n", suggestion.c_str());
}
else
{
printf("%s\n", suggestion.c_str());
}
}
}
}
| [
"rschoe@de.ibm.com"
] | rschoe@de.ibm.com |
1168bf0b8aac9ab565b215eb2acd0dffe6a089c3 | 30bdd8ab897e056f0fb2f9937dcf2f608c1fd06a | /CodesNew/4085.cpp | 91386e527feeef11fdbbde676f772b6c5c79cf62 | [] | no_license | thegamer1907/Code_Analysis | 0a2bb97a9fb5faf01d983c223d9715eb419b7519 | 48079e399321b585efc8a2c6a84c25e2e7a22a61 | refs/heads/master | 2020-05-27T01:20:55.921937 | 2019-11-20T11:15:11 | 2019-11-20T11:15:11 | 188,403,594 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 652 | cpp | #include<bits/stdc++.h>
using namespace std;
#define MAXN 200005
#define LL long long
LL sum[MAXN];
int a[MAXN];
int n,q;
//k hurts
int getans(LL k)
{
int mid;
int f=0,r=n+1;
while(r-f>1){
mid=(f+r)>>1;
if(sum[mid]>k)
r=mid;
else
f=mid;
}
return f;
}
int main()
{
int i,j;
LL k;
scanf("%d%d",&n,&q);
for(i=1;i<=n;i++){
scanf("%d",a+i);
sum[i]=sum[i-1]+a[i];
}
sum[n+1]=(LL)2e15;
LL nk;
k=0;
for(i=1;i<=q;i++){
scanf("%I64d",&nk);
k+=nk;
j=getans(k);
if(j==n){
k=0;
j=0;
}
printf("%d\n",n-j);
}
return 0;
}
| [
"harshitagar1907@gmail.com"
] | harshitagar1907@gmail.com |
1ecc5aa5f27ab0889755c9ead5a6efea2bd34107 | 33841dc85bc0ec7ef3eba6bef98ecd41ca86a3d5 | /editor/echo/Editor/UI/ShaderEditor/DataModel/Math/Functions/ModDataModel.cpp | 6bd973921bfa75a682d2d6113bdaa3d98f5f1f5d | [
"MIT"
] | permissive | haiyangfenghuo/echo | 02511bdd46f3950ca3747106eb81f0932e4e09e0 | 10d7cea46b15ce807b92041c5ffe0a8daac22c46 | refs/heads/master | 2023-01-19T07:19:09.355206 | 2020-11-11T18:19:55 | 2020-11-11T18:19:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,033 | cpp | #include "ModDataModel.h"
#include <QtCore/QJsonValue>
#include <QtGui/QDoubleValidator>
#include "DataFloat.h"
#include "DataVector2.h"
#include "DataVector3.h"
#include "DataVector4.h"
#include "DataInvalid.h"
#include "ShaderScene.h"
#include "OperationRules.h"
namespace DataFlowProgramming
{
ModDataModel::ModDataModel()
{
m_inputDataTypes =
{
{"any", "A"},
{"any", "B"},
};
m_inputs.resize(m_inputDataTypes.size());
m_outputs.resize(1);
m_outputs[0] = std::make_shared<DataInvalid>(this);
m_outputs[0]->setVariableName(getVariableName());
}
QJsonObject ModDataModel::save() const
{
QJsonObject modelJson = NodeDataModel::save();
return modelJson;
}
void ModDataModel::restore(QJsonObject const &p)
{
}
void ModDataModel::setInData(std::shared_ptr<NodeData> nodeData, PortIndex portIndex)
{
m_inputs[portIndex] = std::dynamic_pointer_cast<ShaderData>(nodeData);
if (m_inputs[0] && m_inputs[1])
{
m_outputs[0] = OperationRules::instance().NewMinOutput( DataAny::getInternalData(m_inputs[0])->type().id, DataAny::getInternalData(m_inputs[1])->type().id, this);
m_outputs[0]->setVariableName(getVariableName());
}
else
{
m_outputs[0] = std::make_shared<DataInvalid>(this);
m_outputs[0]->setVariableName(getVariableName());
}
checkValidation();
Q_EMIT dataUpdated(0);
}
bool ModDataModel::generateCode(ShaderCompiler& compiler)
{
if (m_inputs[0] && m_inputs[1])
{
compiler.addCode(Echo::StringUtil::Format("\t%s %s = mod(%s, %s);\n",
m_outputs[0]->type().id.c_str(),
m_outputs[0]->getVariableName().c_str(),
DataAny::getInternalData(m_inputs[0])->getVariableName().c_str(),
DataAny::getInternalData(m_inputs[1])->getVariableName().c_str()));
}
return true;
}
}
| [
"qq79402005@gmail.com"
] | qq79402005@gmail.com |
b1dcfbf032e2ddbb54d34301829f5d0d757d0242 | a7b670687a192cffcc9355691549478ff22d1fa3 | /frc-cpp-sim/WPILib-2012/NetworkTables/NetworkQueue.h | 246720612f4e3e95a8751b48fa0e3708d149fc6f | [] | no_license | anidev/frc-simulator | f226d9af0bcb4fc25f33ad3a28dceb0fbadac109 | 3c60daa84acbabdcde5aa9de6935e1950b48e4c3 | refs/heads/master | 2020-12-24T17:35:21.255684 | 2014-02-04T04:45:21 | 2014-02-04T04:45:21 | 7,597,042 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,516 | h | /*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2011. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
#ifndef __NETWORK_QUEUE_H__
#define __NETWORK_QUEUE_H__
#include "NetworkTables/NetworkTable.h"
#include <map>
#include <deque>
namespace NetworkTables
{
class Entry;
class Confirmation;
class Denial;
class TransactionStart;
class TransactionEnd;
class Data;
class NetworkQueue
{
friend class Connection;
typedef std::deque<std::pair<Data *, bool> > DataQueue_t;
typedef std::map<UINT32, DataQueue_t::iterator> DataHash_t;
public:
NetworkQueue();
~NetworkQueue();
void Offer(TransactionStart *value);
void Offer(TransactionEnd *value);
void Offer(Data *value, bool needsDelete=false);
void Offer(std::unique_ptr<Data> value);
bool IsEmpty();
bool ContainsKey(Key *key);
std::pair<Data *, bool> Poll();
void Clear();
Data *Peek();
DataQueue_t::const_iterator GetQueueHead() {return m_dataQueue.begin();}
bool IsQueueEnd(DataQueue_t::const_iterator it) {return m_dataQueue.end() == it;}
private:
SEM_ID m_dataLock;
DataQueue_t m_dataQueue;
DataHash_t m_latestDataHash;
bool m_inTransaction;
};
}
#endif // __NETWORK_QUEUE_H__
| [
"anidev.aelico@gmail.com"
] | anidev.aelico@gmail.com |
2eb97364dc490ccadc4ba1904babaa72db466e67 | 5e49c789e91ba5c7c1919af37bc13997f43c2013 | /opssimu.h | 90453fcb39f36a3407feff2d27d58d235e23be84 | [] | no_license | minamijoyo/ops | 01d8e4e86ef8be2e32ce7297b9f1d90c86ea9022 | 85e087f18a153b3aa99e73eb412049dc19984f6c | refs/heads/master | 2021-01-02T22:44:43.421878 | 2015-02-23T03:47:33 | 2015-02-23T03:47:33 | 31,192,997 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 1,876 | h | #ifndef _OPSSIMU_H__
#define _OPSSIMU_H__
//opssimu.h
#include<string>
#include"simuframe.h"
#include"opsnetwork.h"
namespace opssimu{
using simuframe::ISimu;
using simuframe::ISimuProperty;
/////////////////////////////////////////////////
// enum ENodeType
/////////////////////////////////////////////////
//ノードの種類を表すフラグ
struct ENodeType{
enum{ FIX=0,REF,DEF,RDF };//固定、反射、迂回、提案
};
/////////////////////////////////////////////////
// class COpsSimuProperty
/////////////////////////////////////////////////
//シミュレーション固有の初期化
class COpsSimuProperty:public ISimuProperty{
public:
struct SSimuSetting{
std::string filename_;
simuframe::simutime_t end_time_;
int node_type_;
double lambda_;
double ttl_margin_;
double buf_th_;
unsigned int buf_sz_;
unsigned int seed_;
SSimuSetting(){}
SSimuSetting(const std::string& filename,const simuframe::simutime_t end_time,
const int node_type,const double lambda,const double ttl_margin,const double buf_th,
const unsigned int buf_sz,const unsigned int seed){}
};
private:
SSimuSetting setting_;
opsnetwork::CTopology* p_topology_;
opsnetwork::COpsNetwork* p_network_;
opsnetwork::INodeMaker* p_node_maker_;
opsnetwork::COpsNetwork::SNetworkSetting* p_network_setting_;
public:
COpsSimuProperty(const SSimuSetting& setting):setting_(setting),p_topology_(0),p_network_(0)
,p_node_maker_(0),p_network_setting_(0){}
~COpsSimuProperty(){}
bool init(ISimu* const p_simu);//CSimu::init()からコールされる
bool clean_up();//CSimu::clean=up()からコールされる
private:
opsnetwork::INodeMaker* new_node_maker(const int type);//ノード生成インターフェイス
};
}//end of namespace opssimu
//end of opssimu.h
#endif //_OPSSIMU_H__
| [
"minamijoyo@gmail.com"
] | minamijoyo@gmail.com |
1cac3eb465e917c49693c4588b592cb3e5ac6854 | 25293f0351b32a522d93e9184af85c5151c2676a | /ktl/tjs_adapter.hpp | accb2ce681f29a3d485f80c2a545a0408df67ffc | [
"BSL-1.0"
] | permissive | milizhang/KTL | 98c8ea6f0621162cc0705c0ed8a3ef046e9d75e7 | 579aa0d8b9225401231aedd490168a889e2a04c1 | refs/heads/master | 2020-12-24T10:58:02.113675 | 2012-10-16T13:31:32 | 2012-10-16T13:31:32 | 6,148,529 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 725 | hpp | #ifndef KTL_TJS_ADAPTER_HPP
#define KTL_TJS_ADAPTER_HPP
#include <sprig/config/config.hpp>
#ifdef SPRIG_USING_PRAGMA_ONCE
# pragma once
#endif // #ifdef SPRIG_USING_PRAGMA_ONCE
#include <ktl/config.hpp>
#include <ktl/config/lib/ktl_tjs_adapter.hpp>
#include <boost/smart_ptr/shared_ptr.hpp>
#include <boost/noncopyable.hpp>
namespace ktl {
//
// TJSAdapterImpl
//
class TJSAdapterImpl;
//
// TJSAdapter
//
class TJSAdapter
: private boost::noncopyable
{
private:
boost::shared_ptr<TJSAdapterImpl> impl_;
public:
TJSAdapter();
~TJSAdapter() throw();
void/*iTJSDispatch2*/* GetGlobal();
void/*iTJSDispatch2*/* GetGlobalNoAddRef() const;
};
} // namespace ktl
#endif // #ifndef KTL_TJS_ADAPTER_HPP
| [
"bolero.murakami@gmail.com"
] | bolero.murakami@gmail.com |
0d3d1beaeb121919f2551b0c233933c93b09aaee | df2a1ab772768d97e0ee6d5d15c9aa8e89a0b2a2 | /AMI_merging/stator/constant/polyMesh/boundary | 875dbee575fb812ae8dcc8f912c962748eef4f51 | [] | no_license | pruthvi1991/AMI_cases | 0cb9b258909b1977c3a0d3dcf0707335d412341f | 848342220482a72879f288e2c868be2d74bd4bab | refs/heads/master | 2021-01-10T22:13:19.307328 | 2015-03-22T22:07:34 | 2015-03-22T22:07:34 | 27,009,158 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,490 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 2.3.x |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class polyBoundaryMesh;
location "constant/polyMesh";
object boundary;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
5
(
inlet
{
type patch;
nFaces 10;
startFace 1140;
}
outlet
{
type patch;
nFaces 10;
startFace 1150;
}
topandbottom
{
type patch;
nFaces 40;
startFace 1160;
}
couple2
{
type patch;
nFaces 60;
startFace 1200;
}
frontandback
{
type empty;
inGroups 1(empty);
nFaces 1200;
startFace 1260;
}
)
// ************************************************************************* //
| [
"pruthvi.krishnaaa@gmail.com"
] | pruthvi.krishnaaa@gmail.com | |
4582457a30c14104d49e2e4261e0179444e89097 | 1a220abd21c56728aa3368534506bfc9ced8ad46 | /3.beakjoon/삼성/백준_16235_나무재테크_BFS_삼성.cpp | 4e9a497177afead738bb8b78ee781b818a12ca76 | [] | no_license | JeonJe/Algorithm | 0ff0cbf47900e7877be077e1ffeee0c1cd50639a | 6f8da6dbeef350f71b7c297502a37f87eb7d0823 | refs/heads/main | 2023-08-23T11:08:17.781953 | 2023-08-23T08:31:41 | 2023-08-23T08:31:41 | 197,085,186 | 0 | 0 | null | 2023-02-21T03:26:41 | 2019-07-15T23:22:55 | Python | UHC | C++ | false | false | 4,917 | cpp | //https://www.acmicpc.net/problem/16235
#include <iostream>
#include <algorithm>
#include <stdio.h>
using namespace std;
struct TREE{
int y, x, age;
};
bool cmp(TREE& a, TREE&b) {
return (a.age < b.age); // 나무의 나이거 어린순으로 정렬
//초기 나무 입력의 정렬에 사용
}
struct QUEUE {
int f, b; //front, back
TREE tree[684000];
QUEUE() {
init();
}
void init() {
f = 0;
b = 0;
}
bool isempty() {
return (f == b);
}
void push(TREE val) {
tree[b++] = val; // 맨뒤에 추가하고 b 증가
}
void pop() {
++f;
}
TREE front() {
return tree[f];
}
int size() {
return (b - f);
}
};
const int MAX = 100;
int n, m, k;
QUEUE tree[2];
TREE init_tree[100]; //초기 입력받는 트리
QUEUE new_tree; //초기에는 아무것도 없고 번식하게 되면 여기에 들어옴
QUEUE dead_tree, birth_of_child_tree; // 올해 죽은 나무의 큐와 번식이 가능한 나무의 큐
int map[10][10], add[10][10];
//양분을 저장할 map 배열 , 추가적인 양분을 저장할 add 배열
int main() {
cin >> n >> m >> k;
//N X N
//m개 줄에는 심은 나무의 정보를 나타내는 x,y,z (x,y)는 위치 z는 나이
//k 는 몇년 후에도 살아있는지
for (int y = 0; y < n; ++y) {
for (int x = 0; x < n; ++x) {
cin >> add[y][x];
map[y][x] = 5;
}
}
for (int i = 0; i < m; ++i) { //초기 나무 정보 입력
cin >> init_tree[i].y >> init_tree[i].x >> init_tree[i].age;
init_tree[i].y--, init_tree[i].x--; // 배열을 0부터 사용하기 때문에 하나 줄임
}
sort(init_tree, init_tree + m, cmp); //나무의 나이가 작은것부터 큰것까지
int cur = 0, next = 0;
for (int i = 0; i < m; ++i) {
tree[cur].push(init_tree[i]); //cur 트리에는 나이가 어린 나무부터 저장
}
for (int i = 0; i < k; ++i) { // 0부터 k년까지
next = (cur + 1) % 2; // 현재가 0 이면 next는 1
// next가 현재가 되면 cur 는 1, next는 0이 됨
//배열 2개로 올해, 내년을 나누기 위해 사용
dead_tree.init();
birth_of_child_tree.init(); // main 에서 큐를 정의하면 stack에 쌓이므로 큰 배열로 잡지못함
tree[next].init(); //글로벌에서 정의하여 힙을 사용해야함
while (!new_tree.isempty()) { //어린 나무부터 양분흡수
TREE cur_tree = new_tree.front(); new_tree.pop();
if (map[cur_tree.y][cur_tree.x] >= cur_tree.age) { //살아 남을 수 있는 트리, 나이보다 양분이 많음
map[cur_tree.y][cur_tree.x] -= cur_tree.age; //양분을 흡수했으므로 업데이트
++cur_tree.age; //내년으로 가기전에 나이를 한살올림
tree[next].push(cur_tree); //넥스트 트리에 넣음 (다음년도에 사용하는 나무)
}
else
dead_tree.push(cur_tree); // 양분흡수 못했으므로 죽은 나무 큐에 삽입
}
while (!tree[cur].isempty()) { //기존에 살아있는 나무 양분흡수
TREE cur_tree = tree[cur].front(); tree[cur].pop();
if (map[cur_tree.y][cur_tree.x] >= cur_tree.age) { //살아 남을 수 있는 트리, 나이보다 양분이 많음
map[cur_tree.y][cur_tree.x] -= cur_tree.age; //양분 흡수
++cur_tree.age; //내년으로 가기전에 나이를 한살올림
tree[next].push(cur_tree); //넥스트 트리에 넣음
if ((cur_tree.age % 5) == 0) //번식이 가능한 트리, 나이가 5의 배수인 나무는 번식 가능한 나무 큐에 추가
birth_of_child_tree.push(cur_tree);
}
else
dead_tree.push(cur_tree); // 양분흡수 못했으므로 죽은 나무
}
while (!dead_tree.isempty()) { //여름에 할일, 죽은 나무만 확인
TREE cur_tree = dead_tree.front(); dead_tree.pop();
map[cur_tree.y][cur_tree.x] += (cur_tree.age / 2); // 나무가 있던 칸에 양분으로 추가
}
const int dy[] = { -1,-1,-1,0,0,+1,+1,+1 };
const int dx[] = { -1,0,+1,-1,+1,-1,0,+1 }; //팔방향
new_tree.init(); // 사용하기 전에 초기화 한번
while (!birth_of_child_tree.isempty()) { //가을이 되면 번식
TREE cur_tree = birth_of_child_tree.front(); birth_of_child_tree.pop(); //번식 가능한 나무들
for (int dir = 0; dir < 8; ++dir) { //8방향으로
TREE next_tree;
next_tree.y = cur_tree.y + dy[dir];
next_tree.x = cur_tree.x + dx[dir];
next_tree.age = 1; //1살짜리 나무
if (next_tree.y < 0 || next_tree.y >= n || next_tree.x < 0 || next_tree.x >= n) continue;
new_tree.push(next_tree); //한 살짜리 나무 번식(새로운 나무 큐에 삽입)
}
}
for (int y = 0; y < n; ++y) { //겨울에 할 일
for (int x = 0; x < n; ++x) {
map[y][x] += add[y][x]; //입력받은 양분 추가
}
}
cur = next; // 해가 바뀌었으므로 현재 queue에는 내년이 들어감
}
cout << tree[next].size() + new_tree.size() << endl;
return 0;
} | [
"whssodi@gmail.com"
] | whssodi@gmail.com |
4b4915c409bd608c6efc6035d7d37b9157508763 | 071e5df15eccb0af9438683709ef322bc7696a98 | /Sketch/libraries/CNCLib/src/ControlImplementation.h | 9f0369b42c052c918a0c0875c84fe735bf0dfded | [] | no_license | VB6Hobbyst7/CNCStepper | cc70db9c5ca98cfd1aa9adf574b5ad42e6ee8424 | e4292c1715c50e7e7c97969fd09b125bb6ede8d7 | refs/heads/master | 2020-12-23T12:19:46.443057 | 2020-01-28T15:15:09 | 2020-01-28T15:15:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,183 | h | /*
This file is part of CNCLib - A library for stepper motors.
Copyright (c) Herbert Aitenbichler
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.
*/
////////////////////////////////////////////////////////
#pragma once
////////////////////////////////////////////////////////
#include <Control.h>
#include <ConfigEeprom.h>
#include <OnOffIOControl.h>
#include <Analog8IOControl.h>
#include <Analog8IOControlSmooth.h>
#include <Analog8XIOControlSmooth.h>
#include <ReadPinIOControl.h>
#include <PushButtonLow.h>
#include <DummyIOControl.h>
////////////////////////////////////////////////////////
#ifndef SPINDLE_FADETIME
#define SPINDLE_FADETIME 8
#endif
#ifndef PROBE_INPUTPINMODE
#define PROBE_INPUTPINMODE INPUT_PULLUP
#endif
#ifndef KILL_INPUTPINMODE
#define KILL_INPUTPINMODE INPUT_PULLUP
#endif
////////////////////////////////////////////////////////
struct ControlData
{
#ifdef SPINDLE_ENABLE_PIN
#ifdef SPINDLE_ANALOGSPEED
#ifdef SPINDLE_ISLASER
CAnalog8IOControl<SPINDLE_ENABLE_PIN> _spindle;
inline uint8_t ConvertSpindleSpeedToIO(uint16_t level) { return (uint8_t)level; }
#elif defined(SPINDLE_FADE)
#ifdef SPINDLE_DIR_PIN
CAnalog8XIOControlSmooth<SPINDLE_ENABLE_PIN, SPINDLE_DIR_PIN> _spindle;
inline int16_t ConvertSpindleSpeedToIO(uint16_t level) { return CControl::ConvertSpindleSpeedToIO8(CConfigEeprom::GetConfigU16(offsetof(CConfigEeprom::SCNCEeprom, MaxSpindleSpeed)), level); }
#undef SPINDLE_DIR_PIN
#define SPINDLESPEEDISINT
#define SPINDLESMOOTH
#else
CAnalog8IOControlSmooth<SPINDLE_ENABLE_PIN> _spindle;
inline uint8_t ConvertSpindleSpeedToIO(uint16_t level) { return CControl::ConvertSpindleSpeedToIO8(CConfigEeprom::GetConfigU16(offsetof(CConfigEeprom::SCNCEeprom, MaxSpindleSpeed)), level); }
#define SPINDLESMOOTH
#endif
#else
CAnalog8IOControl<SPINDLE_ENABLE_PIN> _spindle;
inline uint8_t ConvertSpindleSpeedToIO(uint16_t level) { return CControl::ConvertSpindleSpeedToIO8(CConfigEeprom::GetConfigU16(offsetof(CConfigEeprom::SCNCEeprom, MaxSpindleSpeed)), level); }
#endif
#else
COnOffIOControl<SPINDLE_ENABLE_PIN, SPINDLE_DIGITAL_ON, SPINDLE_DIGITAL_OFF> _spindle;
inline uint8_t ConvertSpindleSpeedToIO(uint16_t level) { return (uint8_t)level; }
#endif
#ifdef SPINDLE_DIR_PIN
COnOffIOControl<SPINDLE_DIR_PIN, SPINDLE_DIR_CLW, SPINDLE_DIR_CCLW> _spindleDir;
#else
CDummyIOControl _spindleDir;
#endif
#else
CDummyIOControl _spindle;
CDummyIOControl _spindleDir;
inline uint8_t ConvertSpindleSpeedToIO(uint16_t level) { return uint8_t(level); }
#endif
#ifdef COOLANT_PIN
COnOffIOControl<COOLANT_PIN, COOLANT_PIN_ON, COOLANT_PIN_OFF> _coolant;
#else
CDummyIOControl _coolant;
#endif
#ifdef PROBE_PIN
CReadPinIOControl<PROBE_PIN, PROBE_PIN_ON> _probe;
#else
CDummyIOControl _probe;
#endif
#ifdef KILL_PIN
#ifdef KILL_ISTRIGGER
CReadPinIOTriggerControl<KILL_PIN, KILL_PIN_ON, 200> _kill;
#else
CReadPinIOControl<KILL_PIN, KILL_PIN_ON> _kill;
#endif
#else
CDummyIOControl _kill;
#endif
#if defined(HOLD_PIN) && defined(RESUME_PIN)
CPushButtonLow<HOLD_PIN, HOLD_PIN_ON> _hold;
CPushButtonLow<RESUME_PIN, RESUME_PIN_ON> _resume;
#else
CDummyIOControl _hold;
CDummyIOControl _resume;
#endif
#if defined(HOLDRESUME_PIN)
CPushButtonLow<HOLDRESUME_PIN, HOLDRESUME_PIN_ON> _holdresume;
#else
CDummyIOControl _holdresume;
#endif
#ifdef CONTROLLERFAN_FAN_PIN
#ifdef CONTROLLERFAN_ANALOGSPEED
#ifdef CONTROLLERFAN_ANALOGSPEED_INVERT
CAnalog8InvertIOControl<CONTROLLERFAN_FAN_PIN> _controllerfan;
#else
CAnalog8IOControl<CONTROLLERFAN_FAN_PIN> _controllerfan;
#endif
#else
COnOffIOControl<CONTROLLERFAN_FAN_PIN, CONTROLLERFAN_DIGITAL_ON, CONTROLLERFAN_DIGITAL_OFF> _controllerfan;
#endif
inline bool IsControllerFanTimeout() { return millis() - CStepper::GetInstance()->IdleTime() > CONTROLLERFAN_ONTIME; }
#else
CDummyIOControl _controllerfan;
inline bool IsControllerFanTimeout() { return false; }
#endif
inline void Init()
{
_controllerfan.Init(255);
_spindle.Init();
#ifdef SPINDLESMOOTH
_spindle.SetDelay(CConfigEeprom::GetConfigU8(offsetof(CConfigEeprom::SCNCEeprom, SpindleFadeTime)));
#endif
_probe.Init(PROBE_INPUTPINMODE);
_kill.Init(KILL_INPUTPINMODE);
_coolant.Init();
_hold.Init();
_resume.Init();
_holdresume.Init();
}
inline bool IOControl(uint8_t tool, uint16_t level)
{
switch (tool)
{
#ifdef SPINDLESPEEDISINT
case CControl::SpindleCW: _spindle.On(ConvertSpindleSpeedToIO(level));
return true;
case CControl::SpindleCCW: _spindle.On(-ConvertSpindleSpeedToIO(level));
return true;
#else
case CControl::SpindleCW:
case CControl::SpindleCCW:
{
_spindle.On(ConvertSpindleSpeedToIO(level));
_spindleDir.Set(tool == CControl::SpindleCCW);
return true;
}
#endif
case CControl::Coolant:
{
_coolant.Set(level > 0);
return true;
}
case CControl::ControllerFan:
{
_controllerfan.SetLevel(uint8_t(level));
return true;
}
default: break;
}
return false;
}
inline void Kill()
{
_spindle.Off();
_coolant.Set(false);
}
inline bool IsKill()
{
if (_kill.IsOn())
{
return true;
}
return false;
}
inline void TimerInterrupt()
{
_hold.Check();
_resume.Check();
_holdresume.Check();
_spindle.Poll();
}
inline void Initialized()
{
_controllerfan.SetLevel(128);
}
inline void OnEvent(EnumAsByte(CControl::EStepperControlEvent) eventType, uintptr_t /* addInfo */)
{
switch (eventType)
{
case CControl::OnStartEvent:
_controllerfan.On();
break;
case CControl::OnIdleEvent:
if (IsControllerFanTimeout())
{
_controllerfan.Off();
}
break;
default: break;
}
}
};
////////////////////////////////////////////////////////
constexpr uint16_t GetInfo1a()
{
return
#ifdef SPINDLE_ENABLE_PIN
CConfigEeprom::HAVE_SPINDLE |
#ifdef SPINDLE_ANALOGSPEED
CConfigEeprom::HAVE_SPINDLE_ANALOG |
#endif
#if defined(SPINDLE_DIR_PIN) || defined(SPINDLESPEEDISINT)
CConfigEeprom::HAVE_SPINDLE_DIR |
#endif
#endif
#ifdef SPINDLE_ISLASER
CConfigEeprom::IS_LASER |
#endif
#ifdef COOLANT_PIN
CConfigEeprom::HAVE_COOLANT |
#endif
#ifdef PROBE_PIN
CConfigEeprom::HAVE_PROBE |
#endif
#ifdef KILL_PIN
CConfigEeprom::HAVE_KILL |
#endif
#ifdef HOLD_PIN
CConfigEeprom::HAVE_HOLD |
#endif
#ifdef RESUME_PIN
CConfigEeprom::HAVE_RESUME |
#endif
#ifdef HOLDRESUME_PIN
CConfigEeprom::HAVE_HOLDRESUME |
#endif
#ifndef REDUCED_SIZE
CConfigEeprom::CAN_ROTATE |
#endif
#if defined(__AVR_ARCH__) || defined(__SAMD21G18A__)
CConfigEeprom::HAVE_EEPROM |
#elif defined(__SAM3X8E__)
// (CHAL::HaveEeprom() ? CConfigEeprom::HAVE_EEPROM : 0) |
#endif
#ifdef MYUSE_LCD
CConfigEeprom::HAVE_SD |
#endif
#ifdef REDUCED_SIZE
COMMANDSYNTAX_VALUE(CConfigEeprom::GCodeBasic) |
#else
COMMANDSYNTAX_VALUE(CConfigEeprom::GCode) |
#endif
CConfigEeprom::NONE1a;
}
constexpr uint16_t GetInfo1b()
{
return
#if defined(__SAMD21G18A__)
CConfigEeprom::EEPROM_NEED_EEPROM_FLUSH |
CConfigEeprom::EEPROM_NEED_DTR |
#else
CConfigEeprom::EEPROM_DTRISRESET |
#endif
#ifndef REDUCED_SIZE
WORKOFFSETCOUNT_VALUE(G54ARRAYSIZE) |
#endif
CConfigEeprom::NONE1b;
}
| [
"h.aitenbichler@eduhi.at"
] | h.aitenbichler@eduhi.at |
aa5a74d5dc136424a5d7a1bd482974a1729f4525 | 8585a14a5994a44f104718aa8c471c6847f55a6e | /Stack/implement two stack using array.cpp | 061a45cda7bacf9d714740551288ee61eeea46da | [] | no_license | AdityaGattu/Placement-Preparation | 0e43cf7872bf4ef25ee996f2ed8740d0eb8e06da | fc655aa59e9b5b2715eece8248e64c9788efc240 | refs/heads/master | 2022-11-28T12:18:07.894663 | 2020-07-31T16:59:17 | 2020-07-31T16:59:17 | 281,722,243 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 588 | cpp | #include<bits/stdc++.h>
#include<iostream>
using namespace std;
int main()
{
//type your code
int n;
cin>>n;
stack<int> s1;
stack<int> s2;
for(int i=0;i<n;i++)
{
int y;
cin>>y;
if(i%2==1)
{cout<<"Enter the value to be pushed in stack 2:\n";
s2.push(y);}
else
{cout<<"Enter the value to be pushed in stack 1:\n";
s1.push(y);}
}
cout<<"Stack 1:"<<"\n";
while(!s1.empty())
{
cout<<s1.top()<<" ";
s1.pop();
}
cout<<"\nStack 2:"<<"\n";
while(!s2.empty())
{
cout<<s2.top()<<" ";
s2.pop();
}
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
11ae63059cefef39203d5856ba9466995096e848 | 243250a03190d041b80d16555b77c3f99cf1ffb3 | /DEMEditor.h | e827a4d38f75eb7388f1a6734452df808f929149 | [] | no_license | eglrp/DEMEditor | 6b302be4acd21a9fbf728d2729ed173c6b003c77 | 97322aec8f4a09da3d935f96acd8f0ac81318b79 | refs/heads/master | 2020-06-23T07:46:51.970505 | 2018-01-03T14:12:41 | 2018-01-03T14:12:41 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,164 | h | // 这段 MFC 示例源代码演示如何使用 MFC Microsoft Office Fluent 用户界面
// (“Fluent UI”)。该示例仅供参考,
// 用以补充《Microsoft 基础类参考》和
// MFC C++ 库软件随附的相关电子文档。
// 复制、使用或分发 Fluent UI 的许可条款是单独提供的。
// 若要了解有关 Fluent UI 许可计划的详细信息,请访问
// http://go.microsoft.com/fwlink/?LinkId=238214。
//
// 版权所有(C) Microsoft Corporation
// 保留所有权利。
// DEMEditor.h : DEMEditor 应用程序的主头文件
//
#pragma once
#ifndef __AFXWIN_H__
#error "在包含此文件之前包含“stdafx.h”以生成 PCH 文件"
#endif
#include "resource.h" // 主符号
// CDEMEditorApp:
// 有关此类的实现,请参阅 DEMEditor.cpp
//
class CDEMEditorApp : public CWinAppEx
{
public:
CDEMEditorApp();
// 重写
public:
virtual BOOL InitInstance();
virtual int ExitInstance();
// 实现
UINT m_nAppLook;
virtual void PreLoadState();
virtual void LoadCustomState();
virtual void SaveCustomState();
afx_msg void OnAppAbout();
DECLARE_MESSAGE_MAP()
};
extern CDEMEditorApp theApp;
| [
"songmengxiao@outlook.com"
] | songmengxiao@outlook.com |
8eb3f84b0cd9381357f0d156952d1c1adde00f51 | 92ad59b4ac7fb384d1e8f69c64d94f7d1bb0292a | /src/qt/askpassphrasedialog.h | d337ee5c2979b73f493a6cb4a9de3660518aa351 | [
"MIT"
] | permissive | sp1k31973/dequant | da876fd99bbb58df97330699673e01a369f426fc | 9621b4bf2530d631946744ab98c87624bbe25a4b | refs/heads/master | 2020-04-22T01:31:00.601165 | 2019-02-11T18:12:53 | 2019-02-11T18:12:53 | 170,016,457 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,216 | h | // Copyright (c) 2011-2013 The Bitcoin developers
// Copyright (c) 2017-2018 The PIVX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_QT_ASKPASSPHRASEDIALOG_H
#define BITCOIN_QT_ASKPASSPHRASEDIALOG_H
#include <QDialog>
class WalletModel;
namespace Ui
{
class AskPassphraseDialog;
}
/** Multifunctional dialog to ask for passphrases. Used for encryption, unlocking, and changing the passphrase.
*/
class AskPassphraseDialog : public QDialog
{
Q_OBJECT
public:
enum class Mode {
Encrypt, /**< Ask passphrase twice and encrypt */
UnlockAnonymize, /**< Ask passphrase and unlock only for anonymization */
Unlock, /**< Ask passphrase and unlock */
ChangePass, /**< Ask old passphrase + new passphrase twice */
Decrypt /**< Ask passphrase and decrypt wallet */
};
// Context from where / for what the passphrase dialog was called to set the status of the checkbox
// Partly redundant to Mode above, but offers more flexibility for future enhancements
enum class Context {
Unlock_Menu, /** Unlock wallet from menu */
Unlock_Full, /** Wallet needs to be fully unlocked */
Encrypt, /** Encrypt unencrypted wallet */
ToggleLock, /** Toggle wallet lock state */
ChangePass, /** Change passphrase */
Send_DEQ, /** Send DEQ */
Send_zDEQ, /** Send zDEQ */
Mint_zDEQ, /** Mint zDEQ */
BIP_38, /** BIP38 menu */
Multi_Sig, /** Multi-Signature dialog */
Sign_Message /** Sign/verify message dialog */
};
explicit AskPassphraseDialog(Mode mode, QWidget* parent, WalletModel* model, Context context);
~AskPassphraseDialog();
void accept();
private:
Ui::AskPassphraseDialog* ui;
Mode mode;
WalletModel* model;
Context context;
bool fCapsLock;
private slots:
void textChanged();
protected:
bool event(QEvent* event);
bool eventFilter(QObject* object, QEvent* event);
};
#endif // BITCOIN_QT_ASKPASSPHRASEDIALOG_H
| [
"sp1k3.admin@googlemail.com"
] | sp1k3.admin@googlemail.com |
e747d7fb04024b82bdb2d3f83a117ae5cc2c31d3 | 4d7bc4aafc46e7d5678b73e5aeea2990a63a8927 | /userinfo.h | af82f87c48fea18eb48e9ff06038571d9b679491 | [] | no_license | bdjomo/My-project | 9a1e44ce584cf640c21a7fb261f71fb02a4c70f9 | 87e2afae23e35fea54e977a346462a4c06b40cd0 | refs/heads/master | 2021-01-17T08:31:20.656265 | 2016-06-15T17:50:59 | 2016-06-15T17:50:59 | 61,228,700 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 435 | h | #ifndef USERINFO_H
#define USERINFO_H
#include <QDialog>
#include "adminintration.h"
namespace Ui {
class UserInfo;
}
class UserInfo : public QDialog
{
Q_OBJECT
public:
explicit UserInfo(QWidget *parent = 0);
~UserInfo();
private slots:
void on_pushButtonClose_clicked();
void on_pushButton_Admin_clicked();
void on_pushButton_UserInfo_clicked();
private:
Ui::UserInfo *ui;
};
#endif // USERINFO_H
| [
"blaisevincentdjomo@hotmail.com"
] | blaisevincentdjomo@hotmail.com |
dfbf1e232e74970526f886b825b66ae043b8a0bf | 45a061e740afe6d98a35159c5e1dd0a4ab4dec3d | /binary_trees/symmetry.cpp | b0544db325a34e70ef1e367a99a64de4b46ee965 | [] | no_license | harshbajaj2296/data-structure | 653ca735445a811c4ef3f334d810d66815ebe311 | 47a1be3b64185e2a6679a8670b15db0177b61aa8 | refs/heads/master | 2023-06-05T20:02:29.114732 | 2021-06-23T22:05:17 | 2021-06-23T22:05:17 | 339,493,093 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,161 | cpp | #include<bits/stdc++.h>
using namespace std;
struct node
{
int data;
node* left;
node* right;
node(int n)
{
this->data=n;
left=right=NULL;
}
};
typedef node* ptr;
int symmetry(ptr l1,ptr l2)
{
if(l1==NULL&&l2==NULL)
return 1;
if((l1==NULL&&l2!=NULL)||(l2==NULL&&l1!=NULL)||(l1->data!=l2->data))
return 0;
int b=symmetry(l1->left,l2->left);
if(b==1)
return(symmetry(l1->right,l2->right));
else
return 0;
}
int main ()
{
ptr root=NULL;
root= new node(2);
root->left = new node(7);
root->right = new node(5);
root->left->right = new node(6);
root->left->right->left = new node(1);
root->left->right->right = new node(11);
root->right->right = new node(9);
root->right->right->left = new node(4);
ptr root1=NULL;
root1= new node(2);
root1->left = new node(7);
root1->right = new node(5);
root1->left->right = new node(6);
root1->left->right->left = new node(1);
root1->left->right->right = new node(11);
root1->right->right = new node(9);
root1->right->right->left = new node(4);
cout<<symmetry(root,root1);
} | [
"harshbajaj22222@gmail.com"
] | harshbajaj22222@gmail.com |
f03ab64fc418035687a9050cdad2b25fc3490b1f | 47110a195995bd1a88e3c70e9f87252541ca0200 | /src/AppInstallerCLICore/Workflows/ManifestComparator.h | 2745ded84fd860ed575a7266d4797be785f13219 | [
"LicenseRef-scancode-generic-cla",
"BSD-3-Clause",
"MIT",
"BSL-1.0",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LGPL-2.1-or-later"
] | permissive | fzanollo/winget-cli | 2ccbd9c0ea810137707310ac28dc5e564497ad7d | 57be9d49eda3c2b96e9d4b14fffda4712d562094 | refs/heads/master | 2023-08-27T02:58:14.540556 | 2021-08-03T18:14:55 | 2021-08-03T18:14:55 | 371,502,063 | 1 | 0 | MIT | 2021-08-06T18:40:25 | 2021-05-27T20:56:36 | C++ | UTF-8 | C++ | false | false | 2,760 | h | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#pragma once
#include "ExecutionArgs.h"
#include <winget/Manifest.h>
#include <AppInstallerRepositorySearch.h>
#include <memory>
#include <string>
#include <string_view>
#include <vector>
namespace AppInstaller::CLI::Workflow
{
namespace details
{
// An interface for defining new filters based on user inputs.
struct FilterField
{
FilterField(std::string_view name) : m_name(name) {}
virtual ~FilterField() = default;
std::string_view Name() const { return m_name; }
// Determines if the installer is applicable based on this field alone.
virtual bool IsApplicable(const Manifest::ManifestInstaller& installer) = 0;
// Explains why the filter regarded this installer as inapplicable.
// Will only be called when IsApplicable returns false.
virtual std::string ExplainInapplicable(const Manifest::ManifestInstaller& installer) = 0;
private:
std::string_view m_name;
};
// An interface for defining new comparisons based on user inputs.
struct ComparisonField : public FilterField
{
using FilterField::FilterField;
virtual ~ComparisonField() = default;
// Determines if the first installer is a better choice based on this field alone.
virtual bool IsFirstBetter(const Manifest::ManifestInstaller& first, const Manifest::ManifestInstaller& second) = 0;
};
}
// Class in charge of comparing manifest entries
struct ManifestComparator
{
ManifestComparator(const Execution::Args&, const Repository::IPackageVersion::Metadata& installationMetadata);
// Gets the best installer from the manifest, if at least one is applicable.
std::optional<Manifest::ManifestInstaller> GetPreferredInstaller(const Manifest::Manifest& manifest);
// Determines if an installer is applicable.
bool IsApplicable(const Manifest::ManifestInstaller& installer);
// Determines if the first installer is a better choice.
bool IsFirstBetter(
const Manifest::ManifestInstaller& first,
const Manifest::ManifestInstaller& second);
private:
void AddFilter(std::unique_ptr<details::FilterField>&& filter);
void AddComparator(std::unique_ptr<details::ComparisonField>&& comparator);
std::vector<std::unique_ptr<details::FilterField>> m_filters;
// Non-owning pointers to values in m_filters.
std::vector<details::ComparisonField*> m_comparators;
};
} | [
"noreply@github.com"
] | noreply@github.com |
f3320a26cbe30b5d555a445ecf7973ab4298aa99 | c1f89beed3118eed786415e2a6d378c28ecbf6bb | /src/jit/vartype.h | ed7fae2dcb312b9c2ce6165d9522992355ac9dbb | [
"MIT"
] | permissive | mono/coreclr | 0d85c616ffc8db17f9a588e0448f6b8547324015 | 90f7060935732bb624e1f325d23f63072433725f | refs/heads/mono | 2023-08-23T10:17:23.811021 | 2019-03-05T18:50:49 | 2019-03-05T18:50:49 | 45,067,402 | 10 | 4 | NOASSERTION | 2019-03-05T18:50:51 | 2015-10-27T20:15:09 | C# | UTF-8 | C++ | false | false | 7,197 | h | //
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
/*****************************************************************************/
#ifndef _VARTYPE_H_
#define _VARTYPE_H_
/*****************************************************************************/
#include "error.h"
enum var_types_classification
{
VTF_ANY = 0x0000,
VTF_INT = 0x0001,
VTF_UNS = 0x0002, // type is unsigned
VTF_FLT = 0x0004,
VTF_GCR = 0x0008, // type is GC ref
VTF_BYR = 0x0010, // type is Byref
VTF_I = 0x0020, // is machine sized
};
DECLARE_TYPED_ENUM(var_types,BYTE)
{
#define DEF_TP(tn,nm,jitType,verType,sz,sze,asze,st,al,tf,howUsed) TYP_##tn,
#include "typelist.h"
#undef DEF_TP
TYP_COUNT,
TYP_lastIntrins = TYP_DOUBLE
}
END_DECLARE_TYPED_ENUM(var_types,BYTE)
/*****************************************************************************
* C-style pointers are implemented as TYP_INT or TYP_LONG depending on the
* platform
*/
#ifdef _WIN64
#define TYP_I_IMPL TYP_LONG
#define TYP_U_IMPL TYP_ULONG
#define TYPE_REF_IIM TYPE_REF_LNG
#else
#define TYP_I_IMPL TYP_INT
#define TYP_U_IMPL TYP_UINT
#define TYPE_REF_IIM TYPE_REF_INT
#ifdef _PREFAST_
// We silence this in the 32-bit build because for portability, we like to have asserts like this:
// assert(op2->gtType == TYP_INT || op2->gtType == TYP_I_IMPL);
// This is obviously redundant for 32-bit builds, but we don't want to have ifdefs and different
// asserts just for 64-bit builds, so for now just silence the assert
#pragma warning(disable: 6287) // warning 6287: the left and right sub-expressions are identical
#endif //_PREFAST_
#endif
/*****************************************************************************/
const extern BYTE varTypeClassification[TYP_COUNT];
// make any class with a TypeGet member also have a function TypeGet() that does the same thing
template<class T>
inline var_types TypeGet(T * t) { return t->TypeGet(); }
// make a TypeGet function which is the identity function for var_types
// the point of this and the preceding template is now you can make template functions
// that work on var_types as well as any object that exposes a TypeGet method.
// such as all of these varTypeIs* functions
inline var_types TypeGet(var_types v) { return v; }
#ifdef FEATURE_SIMD
template <class T>
inline bool varTypeIsSIMD(T vt)
{
if (TypeGet(vt) == TYP_SIMD12)
{
return true;
}
if (TypeGet(vt) == TYP_SIMD16)
{
return true;
}
#ifdef FEATURE_AVX_SUPPORT
if (TypeGet(vt) == TYP_SIMD32)
{
return true;
}
#endif // FEATURE_AVX_SUPPORT
return false;
}
#else // FEATURE_SIMD
// Always return false if FEATURE_SIMD is not enabled
template <class T>
inline bool varTypeIsSIMD(T vt)
{
return false;
}
#endif // !FEATURE_SIMD
template <class T>
inline bool varTypeIsIntegral(T vt)
{
return ((varTypeClassification[TypeGet(vt)] & (VTF_INT )) != 0);
}
template <class T>
inline bool varTypeIsIntegralOrI(T vt)
{
return ((varTypeClassification[TypeGet(vt)] & (VTF_INT|VTF_I )) != 0);
}
template <class T>
inline bool varTypeIsUnsigned (T vt)
{
return ((varTypeClassification[TypeGet(vt)] & (VTF_UNS )) != 0);
}
// If "vt" is an unsigned integral type, returns the corresponding signed integral type, otherwise
// return "vt".
inline var_types varTypeUnsignedToSigned(var_types vt)
{
if (varTypeIsUnsigned(vt))
{
switch (vt)
{
case TYP_BOOL:
case TYP_UBYTE: return TYP_BYTE;
case TYP_USHORT:
case TYP_CHAR: return TYP_SHORT;
case TYP_UINT: return TYP_INT;
case TYP_ULONG: return TYP_LONG;
default:
unreached();
}
}
else
{
return vt;
}
}
template <class T>
inline bool varTypeIsFloating (T vt)
{
return ((varTypeClassification[TypeGet(vt)] & (VTF_FLT )) != 0);
}
template <class T>
inline bool varTypeIsArithmetic(T vt)
{
return ((varTypeClassification[TypeGet(vt)] & (VTF_INT|VTF_FLT)) != 0);
}
template <class T>
inline unsigned varTypeGCtype (T vt)
{
return (unsigned)(varTypeClassification[TypeGet(vt)] & (VTF_GCR|VTF_BYR));
}
template <class T>
inline bool varTypeIsGC (T vt)
{
return (varTypeGCtype(vt) != 0);
}
template <class T>
inline bool varTypeIsI (T vt)
{
return ((varTypeClassification[TypeGet(vt)] & VTF_I) != 0);
}
template <class T>
inline bool varTypeCanReg (T vt)
{
return ((varTypeClassification[TypeGet(vt)] & (VTF_INT|VTF_I|VTF_FLT)) != 0);
}
template <class T>
inline bool varTypeIsByte (T vt)
{
return (TypeGet(vt) >= TYP_BOOL) && (TypeGet(vt) <= TYP_UBYTE);
}
template <class T>
inline bool varTypeIsShort (T vt)
{
return (TypeGet(vt) >= TYP_CHAR) && (TypeGet(vt) <= TYP_USHORT);
}
template <class T>
inline bool varTypeIsSmall (T vt)
{
return (TypeGet(vt) >= TYP_BOOL) && (TypeGet(vt) <= TYP_USHORT);
}
template <class T>
inline bool varTypeIsSmallInt (T vt)
{
return (TypeGet(vt) >= TYP_BYTE) && (TypeGet(vt) <= TYP_USHORT);
}
template <class T>
inline bool varTypeIsIntOrI (T vt)
{
return ((TypeGet(vt) == TYP_INT)
#ifdef _TARGET_64BIT_
|| (TypeGet(vt) == TYP_I_IMPL)
#endif // _TARGET_64BIT_
);
}
template <class T>
inline bool genActualTypeIsIntOrI (T vt)
{
return ((TypeGet(vt) >= TYP_BOOL) && (TypeGet(vt) <= TYP_U_IMPL));
}
template <class T>
inline bool varTypeIsLong (T vt)
{
return (TypeGet(vt) >= TYP_LONG) && (TypeGet(vt) <= TYP_ULONG);
}
template <class T>
inline bool varTypeIsMultiReg (T vt)
{
#ifdef _TARGET_64BIT_
return false;
#else
return (TypeGet(vt) == TYP_LONG);
#endif
}
template <class T>
inline bool varTypeIsSingleReg (T vt)
{
return !varTypeIsMultiReg(vt);
}
template <class T>
inline bool varTypeIsComposite(T vt)
{
return (!varTypeIsArithmetic(TypeGet(vt)) && TypeGet(vt) != TYP_VOID);
}
// Is this type promotable?
// In general only structs are promotable.
// However, a SIMD type, e.g. TYP_SIMD may be handled as either a struct, OR a
// fully-promoted register type.
// On 32-bit systems longs are split into an upper and lower half, and they are
// handled as if they are structs with two integer fields.
template <class T>
inline bool varTypeIsPromotable(T vt)
{
return (TypeGet(vt) == TYP_STRUCT ||
(TypeGet(vt) == TYP_BLK) ||
#if !defined(_TARGET_64BIT_)
varTypeIsLong(vt) ||
#endif // !defined(_TARGET_64BIT_)
varTypeIsSIMD(vt));
}
/*****************************************************************************/
#endif // _VARTYPE_H_
/*****************************************************************************/
| [
"dotnet-bot@microsoft.com"
] | dotnet-bot@microsoft.com |
3e53634a02f4d3902faac38cbc35c9d3395a50ff | 1ef09822bfb243f9e94112482fea75a71073dd6a | /src/mainsub_opbr_plyascii.cpp | d654d6082c39f477d776b93baea46053d416202d | [] | no_license | tom-uchida/SPBR_Brightness-Adjustment-Uniform | 3382523bef2f76fd32a2c51e6d05b81b91f4896e | d8d3515a5cdaed1da0b976ca2f9526c24b54bf39 | refs/heads/master | 2023-03-02T19:30:56.407652 | 2021-02-09T07:42:42 | 2021-02-09T07:42:42 | 299,392,197 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,121 | cpp | //////////////////////////////////////
///// mainsub_opbr_plyascii.cpp /////
//////////////////////////////////////
#include <kvs/glut/Application>
#include <kvs/Version> //KVS2
#if KVS_VERSION_MAJOR == 1
#include <kvs/glew/PointRenderer> //KVS1
#elif KVS_VERSION_MAJOR == 2
#include <kvs/PointRenderer> //KVS2
#endif
#include <kvs/glut/Screen>
#include <kvs/RotationMatrix33>
#include <cstring>
#include <iostream>
#include "fpscount.h"
#include "event_control.h"
#include "wireframebox.h"
#include "spbr.h"
#include "version.h"
#include "display_opbr_usage.h"
#include "toolxform.h"
#include "mainfn_utility.h"
//#define DEBUG_MAIN
//-----
int mainsub_opbr_plyascii ( int argc, char** argv )
{
// Create an application
kvs::glut::Application app( argc, argv );
InitializeEvent init;
KeyPressEvent key;
// Read the first data file (argv[1])
SPBR* spbr_engine = new SPBR( argv[1], PLY_ASCII );
kvs::PointObject* object = spbr_engine ;
// Read and append the remaining files:
// argv[2], argv[3], ..., argv[argc-1]
for (int i = 3; i <= argc; i++) {
if ( isASCII_PLY_File(argv[i - 1]) ) {
SPBR* spbr_tmp = new SPBR(argv[i - 1], PLY_ASCII);
object->add(*kvs::PointObject::DownCast(spbr_tmp));
}
else if ( isBINARY_PLY_File(argv[i - 1]) ) {
SPBR* spbr_tmp = new SPBR(argv[i - 1], PLY_BINARY);
object->add(*kvs::PointObject::DownCast(spbr_tmp));
}
else if ( isBinarySPBR_File(argv[i - 1]) ) {
SPBR* spbr_tmp = new SPBR(argv[i - 1], SPBR_BINARY);
object->add(*kvs::PointObject::DownCast(spbr_tmp));
}
else {
SPBR* spbr_tmp = new SPBR(argv[i - 1], SPBR_ASCII);
object->add(*kvs::PointObject::DownCast(spbr_tmp));
}
}//for
// Set the total bounding box
// Note: This updates the total bounding box of the
// read point objects.
addBoundingBoxToScene ( spbr_engine ) ;
#if defined DEBUG_MAIN
std::cout << *object << std::endl;
#endif
#if KVS_VERSION_MAJOR == 1
kvs::glew::PointRenderer* renderer = new kvs::glew::PointRenderer();//KVS1
#elif KVS_VERSION_MAJOR == 2
kvs::glsl::PointRenderer* renderer = new kvs::glsl::PointRenderer(); //KVS2
#endif
// Set Lambert shading or keep Phong shading
setShadingType ( spbr_engine, renderer ) ;
// Shading control
if( spbr_engine->isShading() == false ) {
std::cout << "** Shading is off" << std::endl;
renderer->disableShading();
}
// Create a screen and make registration
kvs::glut::Screen screen( &app );
screen.registerObject( object, renderer );
// Mouse rotation speed //ROTSPEED
double mouse_rot_speed = spbr_engine->mouseRotSpeed(); // get scaling factor
double virtual_sphere_size = screen.scene()->mouse()->trackball().size();
virtual_sphere_size /= mouse_rot_speed ;
screen.scene()->mouse()->trackball().setSize( virtual_sphere_size );
// Mouse zoom speed //ZOOMSPEED
double mouse_zoom_speed = spbr_engine->mouseZoomSpeed(); // get scaling factor
mouse_zoom_speed *= screen.scene()->mouse()->trackball().scalingFactor();
screen.scene()->mouse()->trackball().setScalingFactor( mouse_zoom_speed );
/////2018/10/17
//// Object rotation (Z==>X)
if ( spbr_engine->isZXRotation() ) {
double zrot_deg = spbr_engine->objectZXRotAngle (0) ;
double xrot_deg = spbr_engine->objectZXRotAngle (1) ;
ToolXform::rotateZX( object, zrot_deg, xrot_deg, kvs::Vector3f( 0, 0, 0 ) );
} // if object rotation (Z==>X)
// Create wireframe-box line object if required
drawWireframeBox( spbr_engine, &screen );
// Set camera type (orthogonal/perspective) and
// other camera parameters:
// camera position, look-at position, and view angle
setCameraParameters ( spbr_engine, &screen );
// Window title
char WINDOW_TITLE[256];
strcpy( WINDOW_TITLE, OPBR_WINDOW_TITLE );
strcat( WINDOW_TITLE, " with GLSL" );
strcat( WINDOW_TITLE, " (" );
strcat( WINDOW_TITLE, argv[1] );
strcat( WINDOW_TITLE, ")" );
// Set camera type (orthogonal/perspective) and
// other camera parameters:
// camera position, look-at position, and view angle
//setCameraParameters ( spbr_engine, &screen );
// Draw
unsigned int img_resoln = spbr_engine->imageResolution();
screen.setGeometry( 0, 0, img_resoln, img_resoln );
#if KVS_VERSION_MAJOR == 1
screen.background()->setColor( spbr_engine->backGroundColor() ); //KVS1
#elif KVS_VERSION_MAJOR == 2
screen.setBackgroundColor ( spbr_engine->backGroundColor() );//KVS2
#endif
screen.setTitle( WINDOW_TITLE );
screen.addEvent( &init );
screen.addEvent( &key );
screen.show();
std::cout << "** Executing particle-based rendering..." << std::endl;
key.displayMenu();
// FPS count
// Draw FPS count inside the view window
// Revise and moved here to use kvs::Label
drawFPS ( spbr_engine, &screen );//draw FPSLabel
// Start
return( app.run() );
} // mainsub_opbr_plyascii ()
| [
"tomomasa.is.0930@gmail.com"
] | tomomasa.is.0930@gmail.com |
7438177cc6e45e2842bc75658defe99411b9d6e7 | e69b3c0559e0768d0283dbfd2e895256594969e6 | /src/gpu_benchmark.h | c69c7a18df55886f02aab0f301eaa4d6d794fad8 | [] | no_license | llgeek/Hardware-benchmarking | 560aa477e46ca33672690f80af63a22386d71c15 | fd6464569ef478df0c4c5b0c7fe81c7e24ae5bbf | refs/heads/master | 2020-03-09T03:48:56.973733 | 2018-04-07T22:20:43 | 2018-04-07T22:20:43 | 128,573,334 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,112 | h | #ifndef _GPU_H_
#define _GPU_H_
#include <cstddef>
#include <string>
#define FLOP 0 //double precision float 64-bit
#define IOP 1 //integer precision 32-bit
#define HOP 2 //half precision 16-bit
#define QOP 3 //quater precision 8-bit
#define KB_IN_BYTE(KB) (KB*ONEKB) //KB in Bytes
#define MB_IN_BYTE(MB) (MB*ONEMB) //MB in Bytes
#define GB_IN_BYTE(GB) (GB*ONEGB) //GB in Bytes
#define BYTE_IN_KB(B) ((double)B/ONEKB) //Bytes in KB
#define BYTE_IN_MB(B) ((double)B/ONEMB) //Bytes in MB
#define BYTE_IN_GB(B) ((double)B/ONEGB) //Bytes in GB
#define DEFAULTLOOP 8e8 //default value for loop_num
#define BLOCKSIZE MB_IN_BYTE(80L)
typedef int OP_TYPE;
const char* op[] = {"DoubleFloat", "Integer", "HalfPrecision", "QuaterPrecision"};
/*
* global variabls
*/
bool testBandwidth = false;
OP_TYPE op_type = FLOP; //opeartion type: float or integer, default = float
long loop_num = DEFAULTLOOP; //loop num, default = 8e9
std::size_t block_num = 1000; //number of blocks to be written in GPU
int repeat_num = 1; //repeat test num, defeault = 1
int core_num = 0;
/*
functions declaration
*/
#endif | [
"angleflycll@gmail.com"
] | angleflycll@gmail.com |
3a12cc77ae6294c8dca69786f2451e785eee0e66 | 7601f733578ce0a7017d13579ae32bd666327436 | /CalibFormats/SiPixelObjects/src/PixelTBMSettings.cc | 5f2867d0cf58b8c8cc3cc466651501728b6d09c6 | [] | no_license | radtek/PixelOnlineSoftware | 03c50f9cda443f95b83b2f5709edeb39e4cad148 | 7a7ae00f724df4998135f3176db60dfc81cfeb3b | refs/heads/master | 2021-02-26T12:08:27.890083 | 2015-08-20T21:38:35 | 2015-08-20T21:38:35 | 245,524,297 | 1 | 0 | null | 2020-03-06T22:01:13 | 2020-03-06T22:01:12 | null | UTF-8 | C++ | false | false | 9,583 | cc | //
// This class provide a base class for the
// pixel ROC DAC data for the pixel FEC configuration
//
//
//
//
#include "CalibFormats/SiPixelObjects/interface/PixelTBMSettings.h"
#include "CalibFormats/SiPixelObjects/interface/PixelTimeFormatter.h"
#include <fstream>
#include <sstream>
#include <iostream>
#include <ios>
#include <assert.h>
#include <stdexcept>
using namespace pos;
PixelTBMSettings::PixelTBMSettings(std::vector < std::vector< std::string> > &tableMat):PixelConfigBase("","",""){
std::cout << "This constructor is not supported" << std::endl;
assert(0);
/*std::string mthn = "]\t[PixelTBMSettings::PixelTBMSettings()]\t\t\t " ;
std::vector< std::string > ins = tableMat[0];
std::map<std::string , int > colM;
std::vector<std::string > colNames;
EXTENSION_TABLE_NAME: (VIEW:)
CONFIG_KEY NOT NULL VARCHAR2(80)
KEY_TYPE NOT NULL VARCHAR2(80)
KEY_ALIAS NOT NULL VARCHAR2(80)
VERSION VARCHAR2(40)
KIND_OF_COND NOT NULL VARCHAR2(40)
TBM_NAME VARCHAR2(200)
MODULE_NAME NOT NULL VARCHAR2(200)
HUB_ADDRS NUMBER(38)
TBM_MODE VARCHAR2(200)
ANLG_INBIAS_ADDR NUMBER(38)
ANLG_INBIAS_VAL NOT NULL NUMBER(38)
ANLG_OUTBIAS_ADDR NUMBER(38)
ANLG_OUTBIAS_VAL NOT NULL NUMBER(38)
ANLG_OUTGAIN_ADDR NUMBER(38)
ANLG_OUTGAIN_VAL NOT NULL NUMBER(38)
N.B.: Here we should (MUST) get a single row referring to a particula module for a particula version.
colNames.push_back("CONFIG_KEY" );
colNames.push_back("KEY_TYPE" );
colNames.push_back("KEY_ALIAS" );
colNames.push_back("VERSION" );
colNames.push_back("KIND_OF_COND" );
colNames.push_back("TBM_NAME" );
colNames.push_back("MODULE_NAME" );
colNames.push_back("HUB_ADDRS" );
colNames.push_back("TBM_MODE" );
colNames.push_back("ANLG_INBIAS_ADDR" );
colNames.push_back("ANLG_INBIAS_VAL" );
colNames.push_back("ANLG_OUTBIAS_ADDR");
colNames.push_back("ANLG_OUTBIAS_VAL" );
colNames.push_back("ANLG_OUTGAIN_ADDR");
colNames.push_back("ANLG_OUTGAIN_VAL" );
for(unsigned int c = 0 ; c < ins.size() ; c++){
for(unsigned int n=0; n<colNames.size(); n++){
if(tableMat[0][c] == colNames[n]){
colM[colNames[n]] = c;
break;
}
}
}//end for
for(unsigned int n=0; n<colNames.size(); n++){
if(colM.find(colNames[n]) == colM.end()){
std::cerr << __LINE__ << mthn << "Couldn't find in the database the column with name " << colNames[n] << std::endl;
assert(0);
}
}
if(tableMat.size() >1)
{
//std::cout << __LINE__ << mthn << "Module from DB: " << tableMat[1][colM["MODULE_NAME"]]<< std::endl ;
PixelROCName tmp(tableMat[1][colM["MODULE_NAME"]]);
rocid_ = tmp ;
//std::cout << __LINE__ << mthn << "Built ROCNAME: " << rocid_.rocname()<< std::endl ;
analogInputBias_ = atoi(tableMat[1][colM["ANLG_INBIAS_VAL"]].c_str());
analogOutputBias_ = atoi(tableMat[1][colM["ANLG_OUTBIAS_VAL"]].c_str());
analogOutputGain_ = atoi(tableMat[1][colM["ANLG_OUTGAIN_VAL"]].c_str());
if( tableMat[1][colM["TBM_MODE"]] == "SingleMode"){
singlemode_=true;
}
else{
singlemode_=false;
}
}*/
}//end contructor
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
PixelTBMSettings::PixelTBMSettings(std::string filename):
PixelConfigBase("","",""){
std::string mthn = "]\t[PixelTBMSettings::PixelTBMSettings()]\t\t\t " ;
if (filename[filename.size()-1]=='t'){
std::ifstream in(filename.c_str());
if (!in.good()){
std::cout << __LINE__ << mthn << "Could not open:"<<filename<<std::endl;
throw std::runtime_error("Failed to open file "+filename);
}
else {
// std::cout << "Opened:"<<filename<<std::endl;
}
std::string tag;
in >> tag;
if(tag.compare("digital")==0){//digital
tbmType_= true;
std::cout << "digital TBM" << std::endl;
in >> tag;
tbmP1 = new PixelP1TBMSettings(in,tag);
}
else{//analog
tbmType_ = false;
std::cout<< "analog TBM, tag: " << tag << std::endl;
if(tag.compare("analog")==0){
in >> tag;
}
std::cout<< "tag is now: " << tag << std::endl;
tbmP0 = new PixelP0TBMSettings(in,tag);
}
}
else{
std::cout << "ERROR: Binary not supported" << std::endl;
assert(0);
}
}
void PixelTBMSettings::setTBMGenericValue(std::string what, int value)
{
if(tbmType_ == true ){
tbmP1->setTBMGenericValue(what, value);
}
else{
tbmP0->setTBMGenericValue(what, value);
}
}
void PixelTBMSettings::writeBinary(std::string filename) const {
std::ofstream out(filename.c_str(),std::ios::binary);
if(tbmType_ == true){
tbmP1->writeBinary(out);
}
else{
tbmP0->writeBinary(out);
}
}
void PixelTBMSettings::writeASCII(std::string dir) const {
if(tbmType_ == true){
tbmP1->writeASCII(dir);
}
else{
tbmP0->writeASCII(dir);
}
}
void PixelTBMSettings::generateConfiguration(PixelFECConfigInterface* pixelFEC,
PixelNameTranslation* trans,
bool physics, bool doResets) const{
if (tbmType_== true){//have a digital one
//do digital stuff
tbmP1->generateConfiguration(pixelFEC, trans, physics, doResets);
}
else{//analog
tbmP0->generateConfiguration(pixelFEC, trans, physics, doResets);
}
}
//=============================================================================================
void PixelTBMSettings::writeXMLHeader(pos::PixelConfigKey key,
int version,
std::string path,
std::ofstream *outstream,
std::ofstream *out1stream,
std::ofstream *out2stream) const
{
std::string mthn = "]\t[PixelTBMSettings::writeXMLHeader()]\t\t\t " ;
std::stringstream fullPath ;
fullPath << path << "/Pixel_TbmParameters_" << PixelTimeFormatter::getmSecTime() << ".xml" ;
std::cout << __LINE__ << mthn << "Writing to: " << fullPath.str() << std::endl ;
outstream->open(fullPath.str().c_str()) ;
*outstream << "<?xml version='1.0' encoding='UTF-8' standalone='yes'?>" << std::endl ;
*outstream << "<ROOT xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>" << std::endl ;
*outstream << " <HEADER>" << std::endl ;
*outstream << " <TYPE>" << std::endl ;
*outstream << " <EXTENSION_TABLE_NAME>PIXEL_TBM_PARAMETERS</EXTENSION_TABLE_NAME>" << std::endl ;
*outstream << " <NAME>Pixel TBM Parameters</NAME>" << std::endl ;
*outstream << " </TYPE>" << std::endl ;
*outstream << " <RUN>" << std::endl ;
*outstream << " <RUN_TYPE>Pixel TBM Parameters</RUN_TYPE>" << std::endl ;
*outstream << " <RUN_NUMBER>1</RUN_NUMBER>" << std::endl ;
*outstream << " <RUN_BEGIN_TIMESTAMP>" << pos::PixelTimeFormatter::getTime() << "</RUN_BEGIN_TIMESTAMP>" << std::endl ;
*outstream << " <LOCATION>CERN P5</LOCATION>" << std::endl ;
*outstream << " </RUN>" << std::endl ;
*outstream << " </HEADER>" << std::endl ;
*outstream << "" << std::endl ;
*outstream << " <DATA_SET>" << std::endl ;
*outstream << " <PART>" << std::endl ;
*outstream << " <NAME_LABEL>CMS-PIXEL-ROOT</NAME_LABEL>" << std::endl ;
*outstream << " <KIND_OF_PART>Detector ROOT</KIND_OF_PART>" << std::endl ;
*outstream << " </PART>" << std::endl ;
*outstream << " <VERSION>" << version << "</VERSION>" << std::endl ;
*outstream << " <COMMENT_DESCRIPTION>" << getComment() << "</COMMENT_DESCRIPTION>" << std::endl ;
*outstream << " <CREATED_BY_USER>" << getAuthor() << "</CREATED_BY_USER>" << std::endl ;
*outstream << " " << std::endl ;
}
//=============================================================================================
void PixelTBMSettings::writeXML(std::ofstream *outstream,
std::ofstream *out1stream,
std::ofstream *out2stream) const
{
if(tbmType_ == true ){
tbmP1->writeXML(outstream, out1stream, out2stream);
}
else{
tbmP0->writeXML(outstream, out1stream, out2stream);
}
}
//=============================================================================================
void PixelTBMSettings::writeXMLTrailer(std::ofstream *outstream,
std::ofstream *out1stream,
std::ofstream *out2stream) const
{
std::string mthn = "]\t[PixelTBMSettings::writeXMLTrailer()]\t\t\t " ;
*outstream << " " << std::endl ;
*outstream << " </DATA_SET>" << std::endl ;
*outstream << "</ROOT> " << std::endl ;
outstream->close() ;
}
| [
"oaz2@cornell.edu"
] | oaz2@cornell.edu |
68ba1b8bec4e8b26ad4afc6c4fd82785acb615ec | 57b03d3041f17d749866eb082c6ae799b4b6d7e3 | /scann/scann/base/single_machine_factory_scann.cc | a99d9ea232260c0bc91e77c6b3ac2d4d817992d3 | [
"Apache-2.0",
"CC-BY-4.0"
] | permissive | ahxchzt/Google-Projects | 7606b1bbfe3f159e17221c4d1fcc8218f5207752 | 237582f2066108a6a8df3ad6ff24572a11532a31 | refs/heads/master | 2023-08-17T16:45:46.101941 | 2021-10-07T18:30:12 | 2021-10-07T18:30:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 31,063 | cc | // Copyright 2021 The Google Research Authors.
//
// 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 "scann/base/single_machine_factory_scann.h"
#include <functional>
#include <memory>
#include <type_traits>
#include "absl/base/casts.h"
#include "absl/base/optimization.h"
#include "absl/memory/memory.h"
#include "scann/base/internal/single_machine_factory_impl.h"
#include "scann/base/reordering_helper_factory.h"
#include "scann/base/single_machine_base.h"
#include "scann/base/single_machine_factory_options.h"
#include "scann/brute_force/brute_force.h"
#include "scann/brute_force/scalar_quantized_brute_force.h"
#include "scann/data_format/dataset.h"
#include "scann/distance_measures/distance_measure_factory.h"
#include "scann/oss_wrappers/scann_threadpool.h"
#include "scann/partitioning/kmeans_tree_like_partitioner.h"
#include "scann/partitioning/partitioner_factory.h"
#include "scann/partitioning/partitioner_factory_base.h"
#include "scann/partitioning/projecting_decorator.h"
#include "scann/proto/brute_force.pb.h"
#include "scann/proto/distance_measure.pb.h"
#include "scann/proto/exact_reordering.pb.h"
#include "scann/proto/scann.pb.h"
#include "scann/tree_x_hybrid/tree_ah_hybrid_residual.h"
#include "scann/tree_x_hybrid/tree_x_hybrid_smmd.h"
#include "scann/utils/factory_helpers.h"
#include "scann/utils/hash_leaf_helpers.h"
#include "scann/utils/scalar_quantization_helpers.h"
#include "scann/utils/types.h"
using std::dynamic_pointer_cast;
namespace research_scann {
namespace {
template <typename T>
StatusOr<unique_ptr<Partitioner<T>>> CreateTreeXPartitioner(
shared_ptr<const TypedDataset<T>> dataset, const ScannConfig& config,
SingleMachineFactoryOptions* opts) {
if (config.partitioning().num_partitioning_epochs() != 1) {
return InvalidArgumentError(
"num_partitioning_epochs must be == 1 for tree-X hybrids.");
}
unique_ptr<Partitioner<T>> partitioner;
if (opts->kmeans_tree) {
return InvalidArgumentError(
"pre-trained kmeans-tree partitioners are not supported.");
} else if (opts->serialized_partitioner) {
TF_ASSIGN_OR_RETURN(
partitioner, PartitionerFromSerialized<T>(*opts->serialized_partitioner,
config.partitioning()));
} else if (!config.partitioning().has_partitioner_prefix() ||
config.partitioning().partitioning_on_the_fly()) {
if (!dataset) {
return InvalidArgumentError(
"Partitioning_on_the_fly needs original dataset to proceed.");
}
TF_ASSIGN_OR_RETURN(
partitioner, PartitionerFactory<T>(dataset.get(), config.partitioning(),
opts->parallelization_pool));
} else {
return InvalidArgumentError("Loading a partitioner is not supported.");
}
if (!partitioner) {
return UnknownError("Error creating partitioner for tree-X hybrids.");
}
partitioner->set_tokenization_mode(UntypedPartitioner::DATABASE);
return std::move(partitioner);
}
template <typename T>
StatusOrSearcherUntyped AsymmetricHasherFactory(
shared_ptr<TypedDataset<T>> dataset, const ScannConfig& config,
SingleMachineFactoryOptions* opts, const GenericSearchParameters& params) {
const auto& ah_config = config.hash().asymmetric_hash();
shared_ptr<const DistanceMeasure> quantization_distance;
std::shared_ptr<ThreadPool> pool = opts->parallelization_pool;
if (ah_config.has_quantization_distance()) {
TF_ASSIGN_OR_RETURN(quantization_distance,
GetDistanceMeasure(ah_config.quantization_distance()));
} else {
quantization_distance = params.pre_reordering_dist;
}
internal::TrainedAsymmetricHashingResults<T> training_results;
if (config.hash().asymmetric_hash().has_centers_filename() ||
opts->ah_codebook.get()) {
TF_ASSIGN_OR_RETURN(
training_results,
internal::HashLeafHelpers<T>::LoadAsymmetricHashingModel(
ah_config, params, pool, opts->ah_codebook.get()));
} else {
if (!dataset) {
return InvalidArgumentError(
"Cannot train AH centers because the dataset is null.");
}
if (dataset->size() < ah_config.num_clusters_per_block()) {
return {make_unique<BruteForceSearcher<T>>(
params.pre_reordering_dist, dataset,
params.pre_reordering_num_neighbors, params.pre_reordering_epsilon)};
}
const int num_workers = (!pool) ? 0 : (pool->NumThreads());
LOG(INFO) << "Single-machine AH training with dataset size = "
<< dataset->size() << ", " << num_workers + 1 << " thread(s).";
TF_ASSIGN_OR_RETURN(
training_results,
internal::HashLeafHelpers<T>::TrainAsymmetricHashingModel(
dataset, ah_config, params, pool));
}
return internal::HashLeafHelpers<T>::AsymmetricHasherFactory(
dataset, opts->hashed_dataset, training_results, params, pool);
}
template <typename T>
StatusOrSearcherUntyped TreeAhHybridResidualFactory(
const ScannConfig& config, const shared_ptr<TypedDataset<T>>& dataset,
const GenericSearchParameters& params, SingleMachineFactoryOptions* opts) {
return InvalidArgumentError(
"Tree-AH with residual quantization only works with float data.");
}
template <>
StatusOrSearcherUntyped TreeAhHybridResidualFactory<float>(
const ScannConfig& config, const shared_ptr<TypedDataset<float>>& dataset,
const GenericSearchParameters& params, SingleMachineFactoryOptions* opts) {
unique_ptr<Partitioner<float>> partitioner;
if (config.partitioning().has_partitioner_prefix()) {
return InvalidArgumentError("Loading a partitioner is not supported.");
} else {
TF_ASSIGN_OR_RETURN(partitioner,
CreateTreeXPartitioner<float>(dataset, config, opts));
}
unique_ptr<KMeansTreeLikePartitioner<float>> kmeans_tree_partitioner(
dynamic_cast<KMeansTreeLikePartitioner<float>*>(partitioner.release()));
if (!kmeans_tree_partitioner) {
return InvalidArgumentError(
"Tree AH with residual quantization only works with KMeans tree as a "
"partitioner.");
}
auto dense = dynamic_pointer_cast<const DenseDataset<float>>(dataset);
if (dataset && !dense) {
return InvalidArgumentError(
"Tree-AH with residual quantization only works with dense data.");
}
if (params.pre_reordering_dist->specially_optimized_distance_tag() !=
DistanceMeasure::DOT_PRODUCT) {
return InvalidArgumentError(
"Tree-AH with residual quantization only works with dot product "
"distance for now.");
}
auto result = make_unique<TreeAHHybridResidual>(
dense, params.pre_reordering_num_neighbors,
params.pre_reordering_epsilon);
vector<std::vector<DatapointIndex>> datapoints_by_token = {};
if (dataset && dataset->empty()) {
datapoints_by_token.resize(kmeans_tree_partitioner->n_tokens());
} else {
if (opts->datapoints_by_token) {
datapoints_by_token = std::move(*opts->datapoints_by_token);
} else if (dense) {
TF_ASSIGN_OR_RETURN(datapoints_by_token,
kmeans_tree_partitioner->TokenizeDatabase(
*dense, opts->parallelization_pool.get()));
} else {
return InvalidArgumentError(
"For Tree-AH hybrid with residual quantization, either "
"database_wildcard or tokenized_database_wildcard must be provided.");
}
if (datapoints_by_token.size() > kmeans_tree_partitioner->n_tokens()) {
return InvalidArgumentError(
"The pre-tokenization (ie, datapoints_by_token) specifies %d "
"partitions, versus the kmeans partitioner, which only has %d "
"partitions",
datapoints_by_token.size(), kmeans_tree_partitioner->n_tokens());
}
if (datapoints_by_token.size() < kmeans_tree_partitioner->n_tokens()) {
datapoints_by_token.resize(kmeans_tree_partitioner->n_tokens());
}
}
shared_ptr<const asymmetric_hashing2::Model<float>> ah_model;
if (opts->ah_codebook) {
TF_ASSIGN_OR_RETURN(ah_model, asymmetric_hashing2::Model<float>::FromProto(
*opts->ah_codebook));
} else if (config.hash().asymmetric_hash().has_centers_filename()) {
return InvalidArgumentError("Centers files are not supported.");
} else if (dense) {
if (opts->hashed_dataset) {
return InvalidArgumentError(
"If a pre-computed hashed database is specified for tree-AH hybrid "
"then pre-computed AH centers must be specified too.");
}
TF_ASSIGN_OR_RETURN(
auto quantization_distance,
GetDistanceMeasure(
config.hash().asymmetric_hash().quantization_distance()));
TF_ASSIGN_OR_RETURN(
auto residuals,
TreeAHHybridResidual::ComputeResiduals(
*dense, kmeans_tree_partitioner.get(), datapoints_by_token,
config.hash()
.asymmetric_hash()
.use_normalized_residual_quantization()));
asymmetric_hashing2::TrainingOptions<float> training_opts(
config.hash().asymmetric_hash(), quantization_distance, residuals);
TF_ASSIGN_OR_RETURN(
ah_model, asymmetric_hashing2::TrainSingleMachine(
residuals, training_opts, opts->parallelization_pool));
} else {
return InvalidArgumentError(
"For Tree-AH hybrid with residual quantization, either "
"centers_filename or database_wildcard must be provided.");
}
if (!dense) {
DCHECK(opts->hashed_dataset);
SCANN_RETURN_IF_ERROR(result->set_docids(opts->hashed_dataset->docids()));
}
result->set_database_tokenizer(
absl::WrapUnique(down_cast<KMeansTreeLikePartitioner<float>*>(
kmeans_tree_partitioner->Clone().release())));
SCANN_RETURN_IF_ERROR(result->BuildLeafSearchers(
config.hash().asymmetric_hash(), std::move(kmeans_tree_partitioner),
std::move(ah_model), std::move(datapoints_by_token),
opts->hashed_dataset.get(), opts->parallelization_pool.get()));
opts->datapoints_by_token = nullptr;
{
AsymmetricHasherConfig ah_config = config.hash().asymmetric_hash();
if (ah_config.use_global_topn()) {
if (ah_config.lookup_type() != AsymmetricHasherConfig::INT8_LUT16)
return InvalidArgumentError("use_global_topn requires LUT16.");
if (ah_config.use_normalized_residual_quantization())
return InvalidArgumentError(
"use_global_topn can't be used in conjunction with "
"use_normalized_residual_quantization.");
result->AttemptEnableGlobalTopN();
}
}
return {std::move(result)};
}
std::vector<float> InverseMultiplier(PreQuantizedFixedPoint* fixed_point) {
std::vector<float> inverse_multipliers;
inverse_multipliers.resize(fixed_point->multiplier_by_dimension->size());
for (size_t i : Seq(inverse_multipliers.size())) {
inverse_multipliers[i] = 1.0f / fixed_point->multiplier_by_dimension->at(i);
}
return inverse_multipliers;
}
void PartitionPreQuantizedFixedPoint(
ConstSpan<std::vector<DatapointIndex>> datapoints_by_token,
PreQuantizedFixedPoint* whole_fp,
vector<DenseDataset<int8_t>>* tokenized_quantized_datasets,
vector<std::vector<float>>* tokenized_squared_l2_norms) {
auto& original = *(whole_fp->fixed_point_dataset);
auto& original_l2 = *(whole_fp->squared_l2_norm_by_datapoint);
tokenized_quantized_datasets->clear();
tokenized_quantized_datasets->resize(datapoints_by_token.size());
tokenized_squared_l2_norms->clear();
tokenized_squared_l2_norms->resize(datapoints_by_token.size());
for (size_t token : IndicesOf(datapoints_by_token)) {
const auto& subset = datapoints_by_token[token];
auto& tokenized = tokenized_quantized_datasets->at(token);
tokenized.set_packing_strategy(original.packing_strategy());
tokenized.set_dimensionality(original.dimensionality());
tokenized.Reserve(subset.size());
auto& tokenized_l2 = (*tokenized_squared_l2_norms)[token];
tokenized_l2.reserve(subset.size());
for (const DatapointIndex i : subset) {
tokenized.AppendOrDie(original[i], "");
}
if (!original_l2.empty()) {
for (const DatapointIndex i : subset) {
tokenized_l2.push_back(original_l2[i]);
}
}
tokenized.set_normalization_tag(original.normalization());
}
}
StatusOrSearcherUntyped PretrainedTreeSQFactoryFromAssets(
const ScannConfig& config, const GenericSearchParameters& params,
const vector<std::vector<DatapointIndex>>& datapoints_by_token,
unique_ptr<Partitioner<float>> partitioner,
shared_ptr<PreQuantizedFixedPoint> fp_assets) {
vector<DenseDataset<int8_t>> tokenized_quantized_datasets;
vector<std::vector<float>> tokenized_squared_l2_norms;
PartitionPreQuantizedFixedPoint(datapoints_by_token, fp_assets.get(),
&tokenized_quantized_datasets,
&tokenized_squared_l2_norms);
auto inverse_multipliers = InverseMultiplier(fp_assets.get());
if (params.pre_reordering_dist->name() == "SquaredL2Distance" &&
tokenized_squared_l2_norms.empty()) {
const auto num_tokens = tokenized_quantized_datasets.size();
tokenized_squared_l2_norms.reserve(num_tokens);
for (int i = 0; i < num_tokens; ++i) {
auto l2_or_error = ScalarQuantizedBruteForceSearcher::
ComputeSquaredL2NormsFromQuantizedDataset(
tokenized_quantized_datasets[i], inverse_multipliers);
SCANN_RETURN_IF_ERROR(l2_or_error.status());
tokenized_squared_l2_norms.push_back(std::move(l2_or_error.ValueOrDie()));
}
}
auto searcher = make_unique<TreeXHybridSMMD<float>>(
nullptr, nullptr, params.pre_reordering_num_neighbors,
params.pre_reordering_epsilon);
auto build_sq_leaf_lambda =
[&](DenseDataset<int8_t> scalar_quantized_partition,
std::vector<float> squared_l2_norms)
-> StatusOr<unique_ptr<SingleMachineSearcherBase<float>>> {
auto searcher_or_error = ScalarQuantizedBruteForceSearcher::
CreateFromQuantizedDatasetAndInverseMultipliers(
params.pre_reordering_dist, std::move(scalar_quantized_partition),
std::vector<float>(), std::move(squared_l2_norms),
params.pre_reordering_num_neighbors, params.pre_reordering_epsilon);
if (!searcher_or_error.ok()) return searcher_or_error.status();
auto searcher = std::move(searcher_or_error.ValueOrDie());
return std::unique_ptr<SingleMachineSearcherBase<float>>(
searcher.release());
};
SCANN_RETURN_IF_ERROR(
searcher->BuildPretrainedScalarQuantizationLeafSearchers(
std::move(datapoints_by_token),
std::move(tokenized_quantized_datasets),
std::move(tokenized_squared_l2_norms), build_sq_leaf_lambda));
searcher->set_leaf_searcher_optional_parameter_creator(
std::make_shared<TreeScalarQuantizationPreprocessedQueryCreator>(
std::move(inverse_multipliers)));
partitioner->set_tokenization_mode(UntypedPartitioner::QUERY);
searcher->set_query_tokenizer(std::move(partitioner));
SCANN_RETURN_IF_ERROR(
searcher->set_docids(fp_assets->fixed_point_dataset->docids()));
fp_assets->fixed_point_dataset = nullptr;
return {std::move(searcher)};
}
StatusOrSearcherUntyped PretrainedSQTreeXHybridFactory(
const ScannConfig& config, const shared_ptr<TypedDataset<float>>& dataset,
const GenericSearchParameters& params, SingleMachineFactoryOptions* opts) {
TF_ASSIGN_OR_RETURN(unique_ptr<Partitioner<float>> partitioner,
CreateTreeXPartitioner<float>(nullptr, config, opts));
DCHECK(partitioner);
vector<std::vector<DatapointIndex>> datapoints_by_token;
datapoints_by_token = std::move(*(opts->datapoints_by_token));
if (datapoints_by_token.size() < partitioner->n_tokens()) {
datapoints_by_token.resize(partitioner->n_tokens());
}
return PretrainedTreeSQFactoryFromAssets(config, params, datapoints_by_token,
std::move(partitioner),
opts->pre_quantized_fixed_point);
}
template <typename T>
StatusOrSearcherUntyped NonResidualTreeXHybridFactory(
const ScannConfig& config, const shared_ptr<TypedDataset<T>>& dataset,
const GenericSearchParameters& params, SingleMachineFactoryOptions* opts) {
TF_ASSIGN_OR_RETURN(auto partitioner,
CreateTreeXPartitioner<T>(dataset, config, opts));
DCHECK(partitioner);
bool use_serialized_per_leaf_hashers = false;
vector<std::vector<DatapointIndex>> datapoints_by_token;
bool using_pretokenized_database = false;
if (opts && opts->datapoints_by_token &&
!opts->datapoints_by_token->empty()) {
using_pretokenized_database = true;
datapoints_by_token = std::move(*(opts->datapoints_by_token));
if (datapoints_by_token.size() < partitioner->n_tokens()) {
datapoints_by_token.resize(partitioner->n_tokens());
}
use_serialized_per_leaf_hashers =
config.has_hash() &&
((config.hash().has_pca_hash() &&
config.hash().has_parameters_filename()) ||
(config.hash().has_asymmetric_hash() &&
config.hash().asymmetric_hash().has_centers_filename()));
}
if constexpr (std::is_same_v<T, float>) {
if (config.brute_force().fixed_point().enabled()) {
auto dense = std::dynamic_pointer_cast<DenseDataset<float>>(dataset);
if (!dense) {
return InvalidArgumentError(
"Dataset must be dense for scalar-quantized brute force.");
}
auto sq_config = config.brute_force().fixed_point();
auto sq_result = ScalarQuantizeFloatDataset(
*dense, sq_config.fixed_point_multiplier_quantile(),
sq_config.noise_shaping_threshold());
auto fp_assets = make_shared<PreQuantizedFixedPoint>();
fp_assets->fixed_point_dataset = make_shared<DenseDataset<int8_t>>(
std::move(sq_result.quantized_dataset));
fp_assets->multiplier_by_dimension = make_shared<vector<float>>(
std::move(sq_result.multiplier_by_dimension));
fp_assets->squared_l2_norm_by_datapoint = make_shared<vector<float>>();
if (!using_pretokenized_database) {
TF_ASSIGN_OR_RETURN(datapoints_by_token,
partitioner->TokenizeDatabase(
*dataset, opts->parallelization_pool.get()));
}
return PretrainedTreeSQFactoryFromAssets(
config, params, datapoints_by_token, std::move(partitioner),
fp_assets);
}
}
auto result = make_unique<TreeXHybridSMMD<T>>(
dataset, opts->hashed_dataset, params.pre_reordering_num_neighbors,
params.pre_reordering_epsilon);
if (config.hash().has_asymmetric_hash() &&
!config.hash().asymmetric_hash().use_per_leaf_partition_training()) {
const auto& ah_config = config.hash().asymmetric_hash();
internal::TrainedAsymmetricHashingResults<T> training_results;
if (config.hash().asymmetric_hash().has_centers_filename() ||
opts->ah_codebook.get()) {
TF_ASSIGN_OR_RETURN(
training_results,
internal::HashLeafHelpers<T>::LoadAsymmetricHashingModel(
ah_config, params, opts->parallelization_pool,
opts->ah_codebook.get()));
} else {
TF_ASSIGN_OR_RETURN(
training_results,
internal::HashLeafHelpers<T>::TrainAsymmetricHashingModel(
dataset, ah_config, params, opts->parallelization_pool));
}
auto leaf_searcher_builder_lambda =
[&](shared_ptr<TypedDataset<T>> leaf_dataset,
shared_ptr<DenseDataset<uint8_t>> leaf_hashed_dataset,
int32_t token) {
return internal::HashLeafHelpers<T>::AsymmetricHasherFactory(
leaf_dataset, leaf_hashed_dataset, training_results, params,
opts->parallelization_pool);
};
std::function<StatusOrSearcher<T>(
shared_ptr<TypedDataset<T>> dataset_partition,
shared_ptr<DenseDataset<uint8_t>> hashed_dataset_partition,
int32_t token)>
leaf_searcher_builder = leaf_searcher_builder_lambda;
if (using_pretokenized_database) {
SCANN_RETURN_IF_ERROR(result->BuildLeafSearchers(
std::move(datapoints_by_token), leaf_searcher_builder));
} else {
SCANN_RETURN_IF_ERROR(result->BuildLeafSearchers(
*partitioner, leaf_searcher_builder, opts->parallelization_pool));
}
result->set_leaf_searcher_optional_parameter_creator(
make_unique<
asymmetric_hashing2::PrecomputedAsymmetricLookupTableCreator<T>>(
training_results.queryer, training_results.lookup_type));
} else {
ScannConfig spec_config = config;
spec_config.clear_partitioning();
if (use_serialized_per_leaf_hashers) {
if (config.hash().has_pca_hash()) {
spec_config.mutable_hash()->clear_parameters_filename();
} else if (config.hash().has_asymmetric_hash()) {
spec_config.mutable_hash()
->mutable_asymmetric_hash()
->clear_centers_filename();
}
}
auto leaf_searcher_builder_lambda =
[&](shared_ptr<TypedDataset<T>> leaf_dataset,
shared_ptr<DenseDataset<uint8_t>> leaf_hashed_dataset,
int32_t token) -> StatusOrSearcher<T> {
SingleMachineFactoryOptions leaf_opts;
leaf_opts.hashed_dataset = leaf_hashed_dataset;
leaf_opts.parallelization_pool = opts->parallelization_pool;
TF_ASSIGN_OR_RETURN(auto leaf_searcher,
internal::SingleMachineFactoryLeafSearcherScann<T>(
spec_config, leaf_dataset, params, &leaf_opts));
return {unique_cast_unsafe<SingleMachineSearcherBase<T>>(
std::move(leaf_searcher))};
};
std::function<StatusOrSearcher<T>(
shared_ptr<TypedDataset<T>> dataset_partition,
shared_ptr<DenseDataset<uint8_t>> hashed_dataset_partition,
int32_t token)>
leaf_searcher_builder = leaf_searcher_builder_lambda;
if (using_pretokenized_database) {
SCANN_RETURN_IF_ERROR(result->BuildLeafSearchers(
std::move(datapoints_by_token), leaf_searcher_builder));
} else {
SCANN_RETURN_IF_ERROR(result->BuildLeafSearchers(
*partitioner, leaf_searcher_builder, opts->parallelization_pool));
}
}
if (config.has_input_output() &&
config.input_output().has_tokenized_database_wildcard() &&
config.has_hash() && config.hash().has_pca_hash() &&
config.hash().has_parameters_filename()) {
return InvalidArgumentError("Serialized hashers are not supported.");
}
if (result->hashed_dataset()) {
if (opts->hashed_dataset) opts->hashed_dataset.reset();
result->ReleaseHashedDataset();
}
result->set_database_tokenizer(partitioner->Clone());
partitioner->set_tokenization_mode(UntypedPartitioner::QUERY);
result->set_query_tokenizer(std::move(partitioner));
return {std::move(result)};
}
template <typename T>
StatusOrSearcherUntyped TreeXHybridFactory(
const ScannConfig& config, const shared_ptr<TypedDataset<T>>& dataset,
const GenericSearchParameters& params, SingleMachineFactoryOptions* opts) {
if (config.hash().asymmetric_hash().use_residual_quantization()) {
return TreeAhHybridResidualFactory<T>(config, dataset, params, opts);
} else if (std::is_same<T, float>::value &&
config.brute_force().fixed_point().enabled() &&
opts->pre_quantized_fixed_point) {
return PretrainedSQTreeXHybridFactory(config, nullptr, params, opts);
} else {
return NonResidualTreeXHybridFactory<T>(config, dataset, params, opts);
}
}
template <typename T>
StatusOrSearcherUntyped BruteForceFactory(
const BruteForceConfig& config, const shared_ptr<TypedDataset<T>>& dataset,
const GenericSearchParameters& params) {
if (config.fixed_point().enabled()) {
return InvalidArgumentError(
"Scalar-quantized brute force only works with float data.");
}
return {make_unique<BruteForceSearcher<T>>(
params.pre_reordering_dist, dataset, params.pre_reordering_num_neighbors,
params.pre_reordering_epsilon)};
}
StatusOrSearcherUntyped BruteForceFactory(const BruteForceConfig& config,
const GenericSearchParameters& params,
PreQuantizedFixedPoint* fixed_point) {
auto fixed_point_dataset = std::move(*(fixed_point->fixed_point_dataset));
std::vector<float> inverse_multipliers = InverseMultiplier(fixed_point);
auto squared_l2_norm_by_datapoint =
std::move(*fixed_point->squared_l2_norm_by_datapoint);
const auto& distance_type = typeid(*params.reordering_dist);
if (distance_type == typeid(const DotProductDistance) ||
distance_type == typeid(const CosineDistance) ||
distance_type == typeid(const SquaredL2Distance)) {
return {make_unique<ScalarQuantizedBruteForceSearcher>(
params.reordering_dist, std::move(squared_l2_norm_by_datapoint),
std::move(fixed_point_dataset), std::move(inverse_multipliers),
params.pre_reordering_num_neighbors, params.pre_reordering_epsilon)};
} else {
return InvalidArgumentError(
"Scalar bruteforce is supported only for dot product, cosine "
"and squared L2 distance.");
}
}
template <>
StatusOrSearcherUntyped BruteForceFactory<float>(
const BruteForceConfig& config,
const shared_ptr<TypedDataset<float>>& dataset,
const GenericSearchParameters& params) {
if (config.fixed_point().enabled()) {
const auto tag =
params.pre_reordering_dist->specially_optimized_distance_tag();
if (tag != DistanceMeasure::SQUARED_L2 && tag != DistanceMeasure::COSINE &&
tag != DistanceMeasure::DOT_PRODUCT) {
return InvalidArgumentError(
"Scalar-quantized brute force currently only works with "
"SquaredL2Distance, CosineDistance and DotProductDistance.");
}
auto dense = std::dynamic_pointer_cast<DenseDataset<float>>(dataset);
if (!dense) {
return InvalidArgumentError(
"Dataset must be dense for scalar-quantized brute force.");
}
if (config.fixed_point().fixed_point_multiplier_quantile() > 1.0f ||
config.fixed_point().fixed_point_multiplier_quantile() <= 0.0f) {
return InvalidArgumentError(
"scalar_quantization_multiplier_quantile must be in (0, 1].");
}
ScalarQuantizedBruteForceSearcher::Options opts;
opts.multiplier_quantile =
config.fixed_point().fixed_point_multiplier_quantile();
opts.noise_shaping_threshold =
config.scalar_quantization_noise_shaping_threshold();
return {make_unique<ScalarQuantizedBruteForceSearcher>(
params.pre_reordering_dist, dense, params.pre_reordering_num_neighbors,
params.pre_reordering_epsilon, opts)};
} else {
return {make_unique<BruteForceSearcher<float>>(
params.pre_reordering_dist, dataset,
params.pre_reordering_num_neighbors, params.pre_reordering_epsilon)};
}
}
template <typename T>
StatusOrSearcherUntyped HashFactory(shared_ptr<TypedDataset<T>> dataset,
const ScannConfig& config,
SingleMachineFactoryOptions* opts,
const GenericSearchParameters& params) {
const HashConfig& hash_config = config.hash();
const int num_hashes =
hash_config.has_asymmetric_hash() + hash_config.has_bit_sampling_hash() +
hash_config.has_min_hash() + hash_config.has_pca_hash();
if (num_hashes != 1) {
return InvalidArgumentError(
"Exactly one hash type must be configured in HashConfig if using "
"SingleMachineFactory.");
}
if (hash_config.has_asymmetric_hash()) {
return AsymmetricHasherFactory(dataset, config, opts, params);
} else {
return InvalidArgumentError(
"Asymmetric hashing is the only supported hash type.");
}
}
class ScannLeafSearcher {
public:
template <typename T>
static StatusOrSearcherUntyped SingleMachineFactoryLeafSearcher(
const ScannConfig& config, const shared_ptr<TypedDataset<T>>& dataset,
const GenericSearchParameters& params,
SingleMachineFactoryOptions* opts) {
if (internal::NumQueryDatabaseSearchTypesConfigured(config) != 1) {
return InvalidArgumentError(
"Exactly one single-machine search type must be configured in "
"ScannConfig if using SingleMachineFactory.");
}
if (config.has_partitioning()) {
return TreeXHybridFactory<T>(config, dataset, params, opts);
} else if (config.has_brute_force()) {
if (std::is_same<T, float>::value &&
config.brute_force().fixed_point().enabled() &&
opts->pre_quantized_fixed_point) {
return BruteForceFactory(config.brute_force(), params,
opts->pre_quantized_fixed_point.get());
} else {
return BruteForceFactory(config.brute_force(), dataset, params);
}
} else if (config.has_hash()) {
return HashFactory<T>(dataset, config, opts, params);
} else {
return UnknownError("Unhandled case");
}
}
};
} // namespace
template <typename T>
StatusOr<unique_ptr<SingleMachineSearcherBase<T>>> SingleMachineFactoryScann(
const ScannConfig& config, shared_ptr<TypedDataset<T>> dataset,
SingleMachineFactoryOptions opts) {
opts.type_tag = TagForType<T>();
TF_ASSIGN_OR_RETURN(auto searcher, SingleMachineFactoryUntypedScann(
config, dataset, std::move(opts)));
return {
unique_cast_unsafe<SingleMachineSearcherBase<T>>(std::move(searcher))};
}
StatusOrSearcherUntyped SingleMachineFactoryUntypedScann(
const ScannConfig& config, shared_ptr<Dataset> dataset,
SingleMachineFactoryOptions opts) {
return internal::SingleMachineFactoryUntypedImpl<ScannLeafSearcher>(
config, dataset, opts);
}
namespace internal {
template <typename T>
StatusOrSearcherUntyped SingleMachineFactoryLeafSearcherScann(
const ScannConfig& config, const shared_ptr<TypedDataset<T>>& dataset,
const GenericSearchParameters& params, SingleMachineFactoryOptions* opts) {
return ScannLeafSearcher::SingleMachineFactoryLeafSearcher(config, dataset,
params, opts);
}
} // namespace internal
SCANN_INSTANTIATE_SINGLE_MACHINE_FACTORY_SCANN();
} // namespace research_scann
| [
"copybara-worker@google.com"
] | copybara-worker@google.com |
04b9727a523924d3f78a5640c5ef61db7fe0ae06 | 9da899bf6541c6a0514219377fea97df9907f0ae | /Runtime/Engine/Private/DistanceFieldAtlas.cpp | 78284f2146b03aa5131e31520bcbbe101822e5a4 | [] | no_license | peichangliang123/UE4 | 1aa4df3418c077dd8f82439ecc808cd2e6de4551 | 20e38f42edc251ee96905ed8e96e1be667bc14a5 | refs/heads/master | 2023-08-17T11:31:53.304431 | 2021-09-15T00:31:03 | 2021-09-15T00:31:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 44,904 | cpp | // Copyright Epic Games, Inc. All Rights Reserved.
/*=============================================================================
DistanceFieldAtlas.cpp
=============================================================================*/
#include "DistanceFieldAtlas.h"
#include "HAL/RunnableThread.h"
#include "HAL/Runnable.h"
#include "Misc/App.h"
#include "Serialization/MemoryReader.h"
#include "Serialization/MemoryWriter.h"
#include "Modules/ModuleManager.h"
#include "StaticMeshResources.h"
#include "ProfilingDebugging/CookStats.h"
#include "Templates/UniquePtr.h"
#include "Engine/StaticMesh.h"
#include "Misc/AutomationTest.h"
#include "Async/ParallelFor.h"
#include "DistanceFieldDownsampling.h"
#include "GlobalShader.h"
#include "RenderGraph.h"
#include "MeshCardRepresentation.h"
#include "Misc/QueuedThreadPoolWrapper.h"
#include "Async/Async.h"
#include "ObjectCacheContext.h"
#if WITH_EDITOR
#include "DerivedDataCacheInterface.h"
#include "AssetCompilingManager.h"
#include "MeshUtilities.h"
#include "StaticMeshCompiler.h"
#endif
#if WITH_EDITORONLY_DATA
#include "IMeshBuilderModule.h"
#endif
CSV_DEFINE_CATEGORY(DistanceField, false);
#if ENABLE_COOK_STATS
namespace DistanceFieldCookStats
{
FCookStats::FDDCResourceUsageStats UsageStats;
static FCookStatsManager::FAutoRegisterCallback RegisterCookStats([](FCookStatsManager::AddStatFuncRef AddStat)
{
UsageStats.LogStats(AddStat, TEXT("DistanceField.Usage"), TEXT(""));
});
}
#endif
static TAutoConsoleVariable<int32> CVarDistField(
TEXT("r.GenerateMeshDistanceFields"),
0,
TEXT("Whether to build distance fields of static meshes, needed for distance field AO, which is used to implement Movable SkyLight shadows.\n")
TEXT("Enabling will increase mesh build times and memory usage. Changing this value will cause a rebuild of all static meshes."),
ECVF_ReadOnly);
static TAutoConsoleVariable<int32> CVarDistFieldRes(
TEXT("r.DistanceFields.MaxPerMeshResolution"),
512,
TEXT("Highest resolution (in one dimension) allowed for a single static mesh asset, used to cap the memory usage of meshes with a large scale.\n")
TEXT("Changing this will cause all distance fields to be rebuilt. Large values such as 512 can consume memory very quickly! (64Mb for one asset at 512)"),
ECVF_ReadOnly);
static TAutoConsoleVariable<float> CVarDistFieldResScale(
TEXT("r.DistanceFields.DefaultVoxelDensity"),
.2f,
TEXT("Determines how the default scale of a mesh converts into distance field voxel dimensions.\n")
TEXT("Changing this will cause all distance fields to be rebuilt. Large values can consume memory very quickly!"),
ECVF_ReadOnly);
static int32 GHeightFieldAtlasTileSize = 64;
static FAutoConsoleVariableRef CVarHeightFieldAtlasTileSize(
TEXT("r.HeightFields.AtlasTileSize"),
GHeightFieldAtlasTileSize,
TEXT("Suballocation granularity"),
ECVF_RenderThreadSafe);
static int32 GHeightFieldAtlasDimInTiles = 16;
static FAutoConsoleVariableRef CVarHeightFieldAtlasDimInTiles(
TEXT("r.HeightFields.AtlasDimInTiles"),
GHeightFieldAtlasDimInTiles,
TEXT("Number of tiles the atlas has in one dimension"),
ECVF_RenderThreadSafe);
static int32 GHeightFieldAtlasDownSampleLevel = 2;
static FAutoConsoleVariableRef CVarHeightFieldAtlasDownSampleLevel(
TEXT("r.HeightFields.AtlasDownSampleLevel"),
GHeightFieldAtlasDownSampleLevel,
TEXT("Max number of times a suballocation can be down-sampled"),
ECVF_RenderThreadSafe);
static int32 GHFVisibilityAtlasTileSize = 64;
static FAutoConsoleVariableRef CVarHFVisibilityAtlasTileSize(
TEXT("r.HeightFields.VisibilityAtlasTileSize"),
GHFVisibilityAtlasTileSize,
TEXT("Suballocation granularity"),
ECVF_RenderThreadSafe);
static int32 GHFVisibilityAtlasDimInTiles = 8;
static FAutoConsoleVariableRef CVarHFVisibilityAtlasDimInTiles(
TEXT("r.HeightFields.VisibilityAtlasDimInTiles"),
GHFVisibilityAtlasDimInTiles,
TEXT("Number of tiles the atlas has in one dimension"),
ECVF_RenderThreadSafe);
static int32 GHFVisibilityAtlasDownSampleLevel = 2;
static FAutoConsoleVariableRef CVarHFVisibilityAtlasDownSampleLevel(
TEXT("r.HeightFields.VisibilityAtlasDownSampleLevel"),
GHFVisibilityAtlasDownSampleLevel,
TEXT("Max number of times a suballocation can be down-sampled"),
ECVF_RenderThreadSafe);
TGlobalResource<FLandscapeTextureAtlas> GHeightFieldTextureAtlas(FLandscapeTextureAtlas::SAT_Height);
TGlobalResource<FLandscapeTextureAtlas> GHFVisibilityTextureAtlas(FLandscapeTextureAtlas::SAT_Visibility);
FDistanceFieldAsyncQueue* GDistanceFieldAsyncQueue = NULL;
#if WITH_EDITOR
// DDC key for distance field data, must be changed when modifying the generation code or data format
#define DISTANCEFIELD_DERIVEDDATA_VER TEXT("CD4A6506-C64C-A229-AA56-2B0A414AE96B")
FString BuildDistanceFieldDerivedDataKey(const FString& InMeshKey)
{
static const auto CVar = IConsoleManager::Get().FindTConsoleVariableDataInt(TEXT("r.DistanceFields.MaxPerMeshResolution"));
const int32 PerMeshMax = CVar->GetValueOnAnyThread();
const FString PerMeshMaxString = PerMeshMax == 128 ? TEXT("") : FString::Printf(TEXT("_%u"), PerMeshMax);
static const auto CVarDensity = IConsoleManager::Get().FindTConsoleVariableDataFloat(TEXT("r.DistanceFields.DefaultVoxelDensity"));
const float VoxelDensity = CVarDensity->GetValueOnAnyThread();
const FString VoxelDensityString = VoxelDensity == .1f ? TEXT("") : FString::Printf(TEXT("_%.3f"), VoxelDensity);
return FDerivedDataCacheInterface::BuildCacheKey(
TEXT("DIST"),
*FString::Printf(TEXT("%s_%s%s%s"), *InMeshKey, DISTANCEFIELD_DERIVEDDATA_VER, *PerMeshMaxString, *VoxelDensityString),
TEXT(""));
}
#endif
#if WITH_EDITORONLY_DATA
void FDistanceFieldVolumeData::CacheDerivedData(const FString& InStaticMeshDerivedDataKey, const ITargetPlatform* TargetPlatform, UStaticMesh* Mesh, FStaticMeshRenderData& RenderData, UStaticMesh* GenerateSource, float DistanceFieldResolutionScale, bool bGenerateDistanceFieldAsIfTwoSided)
{
FString DistanceFieldKey = BuildDistanceFieldDerivedDataKey(InStaticMeshDerivedDataKey);
for (int32 MaterialIndex = 0; MaterialIndex < Mesh->GetStaticMaterials().Num(); MaterialIndex++)
{
FSignedDistanceFieldBuildMaterialData MaterialData;
// Default material blend mode
MaterialData.BlendMode = BLEND_Opaque;
MaterialData.bTwoSided = false;
UMaterialInterface* MaterialInterface = Mesh->GetStaticMaterials()[MaterialIndex].MaterialInterface;
if (MaterialInterface)
{
MaterialData.BlendMode = MaterialInterface->GetBlendMode();
MaterialData.bTwoSided = MaterialInterface->IsTwoSided();
}
DistanceFieldKey += FString::Printf(TEXT("_M%u_%u"), (uint32)MaterialData.BlendMode, MaterialData.bTwoSided ? 1 : 0);
}
TArray<uint8> DerivedData;
COOK_STAT(auto Timer = DistanceFieldCookStats::UsageStats.TimeSyncWork());
if (GetDerivedDataCacheRef().GetSynchronous(*DistanceFieldKey, DerivedData, Mesh->GetPathName()))
{
COOK_STAT(Timer.AddHit(DerivedData.Num()));
FMemoryReader Ar(DerivedData, /*bIsPersistent=*/ true);
Serialize(Ar, Mesh);
BeginCacheMeshCardRepresentation(TargetPlatform, Mesh, RenderData, DistanceFieldKey, /*OptionalSourceMeshData*/ nullptr);
}
else
{
// We don't actually build the resource until later, so only track the cycles used here.
COOK_STAT(Timer.TrackCyclesOnly());
FAsyncDistanceFieldTask* NewTask = new FAsyncDistanceFieldTask;
NewTask->DDCKey = DistanceFieldKey;
check(Mesh && GenerateSource);
NewTask->TargetPlatform = TargetPlatform;
NewTask->StaticMesh = Mesh;
NewTask->GenerateSource = GenerateSource;
NewTask->DistanceFieldResolutionScale = DistanceFieldResolutionScale;
NewTask->bGenerateDistanceFieldAsIfTwoSided = bGenerateDistanceFieldAsIfTwoSided;
NewTask->GeneratedVolumeData = new FDistanceFieldVolumeData();
NewTask->GeneratedVolumeData->AssetName = Mesh->GetFName();
NewTask->GeneratedVolumeData->bAsyncBuilding = true;
for (int32 MaterialIndex = 0; MaterialIndex < Mesh->GetStaticMaterials().Num(); MaterialIndex++)
{
FSignedDistanceFieldBuildMaterialData MaterialData;
// Default material blend mode
MaterialData.BlendMode = BLEND_Opaque;
MaterialData.bTwoSided = false;
if (Mesh->GetStaticMaterials()[MaterialIndex].MaterialInterface)
{
MaterialData.BlendMode = Mesh->GetStaticMaterials()[MaterialIndex].MaterialInterface->GetBlendMode();
MaterialData.bTwoSided = Mesh->GetStaticMaterials()[MaterialIndex].MaterialInterface->IsTwoSided();
}
NewTask->MaterialBlendModes.Add(MaterialData);
}
// Nanite overrides source static mesh with a coarse representation. Need to load original data before we build the mesh SDF.
if (Mesh->NaniteSettings.bEnabled)
{
IMeshBuilderModule& MeshBuilderModule = IMeshBuilderModule::GetForPlatform(TargetPlatform);
if (!MeshBuilderModule.BuildMeshVertexPositions(Mesh, NewTask->SourceMeshData.TriangleIndices, NewTask->SourceMeshData.VertexPositions))
{
UE_LOG(LogStaticMesh, Error, TEXT("Failed to build static mesh. See previous line(s) for details."));
}
}
GDistanceFieldAsyncQueue->AddTask(NewTask);
}
}
#endif
uint64 NextDistanceFieldVolumeDataId = 1;
FDistanceFieldVolumeData::FDistanceFieldVolumeData() :
LocalSpaceMeshBounds(ForceInit),
bMostlyTwoSided(false),
bAsyncBuilding(false)
{
Id = NextDistanceFieldVolumeDataId;
NextDistanceFieldVolumeDataId++;
}
void FDistanceFieldVolumeData::Serialize(FArchive& Ar, UObject* Owner)
{
// Note: this is derived data, no need for versioning (bump the DDC guid)
Ar << LocalSpaceMeshBounds << bMostlyTwoSided << Mips << AlwaysLoadedMip;
StreamableMips.Serialize(Ar, Owner, 0);
}
int32 GUseAsyncDistanceFieldBuildQueue = 1;
static FAutoConsoleVariableRef CVarAOAsyncBuildQueue(
TEXT("r.AOAsyncBuildQueue"),
GUseAsyncDistanceFieldBuildQueue,
TEXT("Whether to asynchronously build distance field volume data from meshes."),
ECVF_Default | ECVF_ReadOnly
);
FAsyncDistanceFieldTask::FAsyncDistanceFieldTask()
: StaticMesh(nullptr)
, GenerateSource(nullptr)
, DistanceFieldResolutionScale(0.0f)
, bGenerateDistanceFieldAsIfTwoSided(false)
, GeneratedVolumeData(nullptr)
{
}
FDistanceFieldAsyncQueue::FDistanceFieldAsyncQueue()
{
#if WITH_EDITOR
MeshUtilities = NULL;
const int32 MaxConcurrency = -1;
// In Editor, we allow faster compilation by letting the asset compiler's scheduler organize work.
ThreadPool = MakeUnique<FQueuedThreadPoolWrapper>(FAssetCompilingManager::Get().GetThreadPool(), MaxConcurrency, [](EQueuedWorkPriority) { return EQueuedWorkPriority::Lowest; });
#else
const int32 MaxConcurrency = 1;
ThreadPool = MakeUnique<FQueuedThreadPoolWrapper>(GThreadPool, MaxConcurrency, [](EQueuedWorkPriority) { return EQueuedWorkPriority::Lowest; });
#endif
}
FDistanceFieldAsyncQueue::~FDistanceFieldAsyncQueue()
{
}
void FAsyncDistanceFieldTaskWorker::DoWork()
{
// Put on background thread to avoid interfering with game-thread bound tasks
FQueuedThreadPoolTaskGraphWrapper TaskGraphWrapper(ENamedThreads::AnyBackgroundThreadNormalTask);
GDistanceFieldAsyncQueue->Build(&Task, TaskGraphWrapper);
}
void FDistanceFieldAsyncQueue::CancelBackgroundTask(TArray<FAsyncDistanceFieldTask*> Tasks)
{
// Do all the cancellation first to make sure none of these tasks
// get scheduled as we're waiting for completion.
for (FAsyncDistanceFieldTask* Task : Tasks)
{
if (Task->AsyncTask)
{
Task->AsyncTask->Cancel();
}
}
for (FAsyncDistanceFieldTask* Task : Tasks)
{
if (Task->AsyncTask)
{
Task->AsyncTask->EnsureCompletion();
Task->AsyncTask.Reset();
}
}
}
void FDistanceFieldAsyncQueue::StartBackgroundTask(FAsyncDistanceFieldTask* Task)
{
check(Task->AsyncTask == nullptr);
Task->AsyncTask = MakeUnique<FAsyncTask<FAsyncDistanceFieldTaskWorker>>(*Task);
Task->AsyncTask->StartBackgroundTask(ThreadPool.Get(), EQueuedWorkPriority::Lowest);
}
void FDistanceFieldAsyncQueue::ProcessPendingTasks()
{
FScopeLock Lock(&CriticalSection);
TArray<FAsyncDistanceFieldTask*> Tasks = MoveTemp(PendingTasks);
for (FAsyncDistanceFieldTask* Task : Tasks)
{
if (Task->GenerateSource && Task->GenerateSource->IsCompiling())
{
PendingTasks.Add(Task);
}
else
{
StartBackgroundTask(Task);
}
}
}
void FDistanceFieldAsyncQueue::AddTask(FAsyncDistanceFieldTask* Task)
{
#if WITH_EDITOR
if (!MeshUtilities)
{
MeshUtilities = &FModuleManager::Get().LoadModuleChecked<IMeshUtilities>(TEXT("MeshUtilities"));
}
{
// Array protection when called from multiple threads
FScopeLock Lock(&CriticalSection);
ReferencedTasks.Add(Task);
}
// The Source Mesh's RenderData is not yet ready, postpone the build
if (Task->GenerateSource->IsCompiling())
{
// Array protection when called from multiple threads
FScopeLock Lock(&CriticalSection);
PendingTasks.Add(Task);
}
else
{
// If we're already in worker threads, there is no need to launch an async task.
if (GUseAsyncDistanceFieldBuildQueue || !IsInGameThread())
{
StartBackgroundTask(Task);
}
else
{
// To avoid deadlocks, we must queue the inner build tasks on another thread pool, so use the task graph.
// Put on background thread to avoid interfering with game-thread bound tasks
FQueuedThreadPoolTaskGraphWrapper TaskGraphWrapper(ENamedThreads::AnyBackgroundThreadNormalTask);
Build(Task, TaskGraphWrapper);
}
}
#else
UE_LOG(LogStaticMesh,Fatal,TEXT("Tried to build a distance field without editor support (this should have been done during cooking)"));
#endif
}
void FDistanceFieldAsyncQueue::CancelBuild(UStaticMesh* StaticMesh)
{
TRACE_CPUPROFILER_EVENT_SCOPE(FDistanceFieldAsyncQueue::CancelBuild)
TArray<FAsyncDistanceFieldTask*> TasksToCancel;
{
FScopeLock Lock(&CriticalSection);
TArray<FAsyncDistanceFieldTask*> Tasks = MoveTemp(PendingTasks);
PendingTasks.Reserve(Tasks.Num());
for (FAsyncDistanceFieldTask* Task : Tasks)
{
if (Task->GenerateSource != StaticMesh && Task->StaticMesh != StaticMesh)
{
PendingTasks.Add(Task);
}
}
Tasks = MoveTemp(ReferencedTasks);
ReferencedTasks.Reserve(Tasks.Num());
for (FAsyncDistanceFieldTask* Task : Tasks)
{
if (Task->GenerateSource != StaticMesh && Task->StaticMesh != StaticMesh)
{
ReferencedTasks.Add(Task);
}
else
{
TasksToCancel.Add(Task);
}
}
}
CancelBackgroundTask(TasksToCancel);
for (FAsyncDistanceFieldTask* Task : TasksToCancel)
{
if (Task->GeneratedVolumeData != nullptr)
{
// Rendering thread may still be referencing the old one, use the deferred cleanup interface to delete it next frame when it is safe
BeginCleanup(Task->GeneratedVolumeData);
}
delete Task;
}
}
void FDistanceFieldAsyncQueue::CancelAllOutstandingBuilds()
{
TRACE_CPUPROFILER_EVENT_SCOPE(FDistanceFieldAsyncQueue::CancelAllOutstandingBuilds)
TArray<FAsyncDistanceFieldTask*> OutstandingTasks;
{
FScopeLock Lock(&CriticalSection);
PendingTasks.Empty();
OutstandingTasks = MoveTemp(ReferencedTasks);
}
CancelBackgroundTask(OutstandingTasks);
for (FAsyncDistanceFieldTask* Task : OutstandingTasks)
{
delete Task;
}
}
void FDistanceFieldAsyncQueue::RescheduleBackgroundTask(FAsyncDistanceFieldTask* InTask, EQueuedWorkPriority InPriority)
{
if (InTask->AsyncTask)
{
if (InTask->AsyncTask->GetPriority() != InPriority)
{
InTask->AsyncTask->Reschedule(GThreadPool, InPriority);
}
}
}
void FDistanceFieldAsyncQueue::BlockUntilBuildComplete(UStaticMesh* StaticMesh, bool bWarnIfBlocked)
{
TRACE_CPUPROFILER_EVENT_SCOPE(FDistanceFieldAsyncQueue::BlockUntilBuildComplete)
// We will track the wait time here, but only the cycles used.
// This function is called whether or not an async task is pending,
// so we have to look elsewhere to properly count how many resources have actually finished building.
COOK_STAT(auto Timer = DistanceFieldCookStats::UsageStats.TimeAsyncWait());
COOK_STAT(Timer.TrackCyclesOnly());
bool bReferenced = false;
bool bHadToBlock = false;
double StartTime = 0;
TSet<UStaticMesh*> RequiredFinishCompilation;
do
{
ProcessAsyncTasks();
bReferenced = false;
RequiredFinishCompilation.Reset();
// Reschedule the tasks we're waiting on as highest prio
{
FScopeLock Lock(&CriticalSection);
for (int TaskIndex = 0; TaskIndex < ReferencedTasks.Num(); TaskIndex++)
{
if (ReferencedTasks[TaskIndex]->StaticMesh == StaticMesh ||
ReferencedTasks[TaskIndex]->GenerateSource == StaticMesh)
{
bReferenced = true;
// If the task we are waiting on depends on other static meshes
// we need to force finish them too.
#if WITH_EDITOR
if (ReferencedTasks[TaskIndex]->GenerateSource != nullptr &&
ReferencedTasks[TaskIndex]->GenerateSource->IsCompiling())
{
RequiredFinishCompilation.Add(ReferencedTasks[TaskIndex]->GenerateSource);
}
if (ReferencedTasks[TaskIndex]->StaticMesh != nullptr &&
ReferencedTasks[TaskIndex]->StaticMesh->IsCompiling())
{
RequiredFinishCompilation.Add(ReferencedTasks[TaskIndex]->StaticMesh);
}
#endif
RescheduleBackgroundTask(ReferencedTasks[TaskIndex], EQueuedWorkPriority::Highest);
}
}
}
#if WITH_EDITOR
// Call the finish compilation outside of the critical section since those compilations
// might need to register new distance field tasks which also uses the critical section.
if (RequiredFinishCompilation.Num())
{
FStaticMeshCompilingManager::Get().FinishCompilation(RequiredFinishCompilation.Array());
}
#endif
if (bReferenced)
{
if (!bHadToBlock)
{
StartTime = FPlatformTime::Seconds();
}
bHadToBlock = true;
FPlatformProcess::Sleep(.01f);
}
}
while (bReferenced);
if (bHadToBlock &&
bWarnIfBlocked
#if WITH_EDITOR
&& !FAutomationTestFramework::Get().GetCurrentTest() // HACK - Don't output this warning during automation test
#endif
)
{
UE_LOG(LogStaticMesh, Display, TEXT("Main thread blocked for %.3fs for async distance field build of %s to complete! This can happen if the mesh is rebuilt excessively."),
(float)(FPlatformTime::Seconds() - StartTime),
*StaticMesh->GetName());
}
}
void FDistanceFieldAsyncQueue::BlockUntilAllBuildsComplete()
{
TRACE_CPUPROFILER_EVENT_SCOPE(FDistanceFieldAsyncQueue::BlockUntilAllBuildsComplete)
do
{
#if WITH_EDITOR
FStaticMeshCompilingManager::Get().FinishAllCompilation();
#endif
// Reschedule as highest prio since we're explicitly waiting on them
{
FScopeLock Lock(&CriticalSection);
for (int TaskIndex = 0; TaskIndex < ReferencedTasks.Num(); TaskIndex++)
{
RescheduleBackgroundTask(ReferencedTasks[TaskIndex], EQueuedWorkPriority::Highest);
}
}
ProcessAsyncTasks();
FPlatformProcess::Sleep(.01f);
}
while (GetNumOutstandingTasks() > 0);
}
void FDistanceFieldAsyncQueue::Build(FAsyncDistanceFieldTask* Task, FQueuedThreadPool& BuildThreadPool)
{
#if WITH_EDITOR
// Editor 'force delete' can null any UObject pointers which are seen by reference collecting (eg FProperty or serialized)
if (Task->StaticMesh && Task->GenerateSource)
{
TRACE_CPUPROFILER_EVENT_SCOPE(FDistanceFieldAsyncQueue::Build);
const FStaticMeshLODResources& LODModel = Task->GenerateSource->GetRenderData()->LODResources[0];
MeshUtilities->GenerateSignedDistanceFieldVolumeData(
Task->StaticMesh->GetName(),
Task->SourceMeshData,
LODModel,
BuildThreadPool,
Task->MaterialBlendModes,
Task->GenerateSource->GetRenderData()->Bounds,
Task->DistanceFieldResolutionScale,
Task->bGenerateDistanceFieldAsIfTwoSided,
*Task->GeneratedVolumeData);
}
CompletedTasks.Push(Task);
#endif
}
void FDistanceFieldAsyncQueue::AddReferencedObjects(FReferenceCollector& Collector)
{
FScopeLock Lock(&CriticalSection);
for (int TaskIndex = 0; TaskIndex < ReferencedTasks.Num(); TaskIndex++)
{
// Make sure none of the UObjects referenced by the async tasks are GC'ed during the task
Collector.AddReferencedObject(ReferencedTasks[TaskIndex]->StaticMesh);
Collector.AddReferencedObject(ReferencedTasks[TaskIndex]->GenerateSource);
}
}
FString FDistanceFieldAsyncQueue::GetReferencerName() const
{
return TEXT("FDistanceFieldAsyncQueue");
}
void FDistanceFieldAsyncQueue::ProcessAsyncTasks(bool bLimitExecutionTime)
{
#if WITH_EDITOR
TRACE_CPUPROFILER_EVENT_SCOPE(FDistanceFieldAsyncQueue::ProcessAsyncTasks);
ProcessPendingTasks();
FObjectCacheContextScope ObjectCacheScope;
const double MaxProcessingTime = 0.016f;
double StartTime = FPlatformTime::Seconds();
while (!bLimitExecutionTime || (FPlatformTime::Seconds() - StartTime) < MaxProcessingTime)
{
FAsyncDistanceFieldTask* Task = CompletedTasks.Pop();
if (Task == nullptr)
{
break;
}
// We want to count each resource built from a DDC miss, so count each iteration of the loop separately.
COOK_STAT(auto Timer = DistanceFieldCookStats::UsageStats.TimeSyncWork());
bool bWasCancelled = false;
{
FScopeLock Lock(&CriticalSection);
bWasCancelled = ReferencedTasks.Remove(Task) == 0;
}
if (bWasCancelled)
{
continue;
}
if (Task->AsyncTask)
{
Task->AsyncTask->EnsureCompletion();
Task->AsyncTask.Reset();
}
// Editor 'force delete' can null any UObject pointers which are seen by reference collecting (eg FProperty or serialized)
if (Task->StaticMesh)
{
Task->GeneratedVolumeData->bAsyncBuilding = false;
FDistanceFieldVolumeData* OldVolumeData = Task->StaticMesh->GetRenderData()->LODResources[0].DistanceFieldData;
// Assign the new volume data, this is safe because the render thread makes a copy of the pointer at scene proxy creation time.
Task->StaticMesh->GetRenderData()->LODResources[0].DistanceFieldData = Task->GeneratedVolumeData;
// Renderstates are not initialized between UStaticMesh::PreEditChange() and UStaticMesh::PostEditChange()
if (Task->StaticMesh->GetRenderData()->IsInitialized())
{
for (UStaticMeshComponent* Component : ObjectCacheScope.GetContext().GetStaticMeshComponents(Task->StaticMesh))
{
if (Component->IsRegistered() && Component->IsRenderStateCreated())
{
Component->MarkRenderStateDirty();
}
}
}
if (OldVolumeData)
{
// Rendering thread may still be referencing the old one, use the deferred cleanup interface to delete it next frame when it is safe
BeginCleanup(OldVolumeData);
}
{
TArray<uint8> DerivedData;
// Save built distance field volume to DDC
FMemoryWriter Ar(DerivedData, /*bIsPersistent=*/ true);
Task->StaticMesh->GetRenderData()->LODResources[0].DistanceFieldData->Serialize(Ar, Task->StaticMesh);
GetDerivedDataCacheRef().Put(*Task->DDCKey, DerivedData, Task->StaticMesh->GetPathName());
COOK_STAT(Timer.AddMiss(DerivedData.Num()));
}
BeginCacheMeshCardRepresentation(Task->TargetPlatform, Task->StaticMesh, *Task->StaticMesh->GetRenderData(), Task->DDCKey, &Task->SourceMeshData);
}
delete Task;
}
#endif
}
void FDistanceFieldAsyncQueue::Shutdown()
{
CancelAllOutstandingBuilds();
UE_LOG(LogStaticMesh, Log, TEXT("Abandoning remaining async distance field tasks for shutdown"));
ThreadPool->Destroy();
}
FLandscapeTextureAtlas::FLandscapeTextureAtlas(ESubAllocType InSubAllocType)
: MaxDownSampleLevel(0)
, Generation(0)
, SubAllocType(InSubAllocType)
{}
void FLandscapeTextureAtlas::InitializeIfNeeded()
{
const bool bHeight = SubAllocType == SAT_Height;
const uint32 LocalTileSize = bHeight ? GHeightFieldAtlasTileSize : GHFVisibilityAtlasTileSize;
const uint32 LocalDimInTiles = bHeight ? GHeightFieldAtlasDimInTiles : GHFVisibilityAtlasDimInTiles;
const uint32 LocalDownSampleLevel = bHeight ? GHeightFieldAtlasDownSampleLevel : GHFVisibilityAtlasDownSampleLevel;
if (!AtlasTextureRHI
|| AddrSpaceAllocator.TileSize != LocalTileSize
|| AddrSpaceAllocator.DimInTiles != LocalDimInTiles
|| MaxDownSampleLevel != LocalDownSampleLevel)
{
AddrSpaceAllocator.Init(LocalTileSize, 1, LocalDimInTiles);
for (int32 Idx = 0; Idx < PendingStreamingTextures.Num(); ++Idx)
{
UTexture2D* Texture = PendingStreamingTextures[Idx];
Texture->bForceMiplevelsToBeResident = false;
}
PendingStreamingTextures.Empty();
for (TSet<FAllocation>::TConstIterator It(CurrentAllocations); It; ++It)
{
check(!PendingAllocations.Contains(*It));
PendingAllocations.Add(*It);
}
CurrentAllocations.Reset();
const uint32 SizeX = AddrSpaceAllocator.DimInTexels;
const uint32 SizeY = AddrSpaceAllocator.DimInTexels;
const ETextureCreateFlags Flags = TexCreate_ShaderResource | TexCreate_UAV;
const EPixelFormat Format = bHeight ? PF_R8G8 : PF_G8;
FRHIResourceCreateInfo CreateInfo(bHeight ? TEXT("HeightFieldAtlas") : TEXT("VisibilityAtlas"));
AtlasTextureRHI = RHICreateTexture2D(SizeX, SizeY, Format, 1, 1, Flags, CreateInfo);
AtlasUAVRHI = RHICreateUnorderedAccessView(AtlasTextureRHI, 0);
MaxDownSampleLevel = LocalDownSampleLevel;
++Generation;
}
}
void FLandscapeTextureAtlas::AddAllocation(UTexture2D* Texture, uint32 VisibilityChannel)
{
check(Texture);
FAllocation* Found = CurrentAllocations.Find(Texture);
if (Found)
{
++Found->RefCount;
return;
}
Found = FailedAllocations.Find(Texture);
if (Found)
{
++Found->RefCount;
return;
}
Found = PendingAllocations.Find(Texture);
if (Found)
{
++Found->RefCount;
}
else
{
PendingAllocations.Add(FAllocation(Texture, VisibilityChannel));
}
}
void FLandscapeTextureAtlas::RemoveAllocation(UTexture2D* Texture)
{
FSetElementId Id = PendingAllocations.FindId(Texture);
if (Id.IsValidId())
{
check(PendingAllocations[Id].RefCount);
if (!--PendingAllocations[Id].RefCount)
{
check(!PendingStreamingTextures.Contains(Texture));
PendingAllocations.Remove(Id);
}
return;
}
Id = FailedAllocations.FindId(Texture);
if (Id.IsValidId())
{
check(FailedAllocations[Id].RefCount);
if (!--FailedAllocations[Id].RefCount)
{
check(!PendingStreamingTextures.Contains(Texture));
FailedAllocations.Remove(Id);
}
return;
}
Id = CurrentAllocations.FindId(Texture);
if (Id.IsValidId())
{
FAllocation& Allocation = CurrentAllocations[Id];
check(Allocation.RefCount && Allocation.Handle != INDEX_NONE);
if (!--Allocation.RefCount)
{
AddrSpaceAllocator.Free(Allocation.Handle);
PendingStreamingTextures.Remove(Texture);
CurrentAllocations.Remove(Id);
}
}
}
class FUploadLandscapeTextureToAtlasCS : public FGlobalShader
{
public:
BEGIN_SHADER_PARAMETER_STRUCT(FSharedParameters, )
SHADER_PARAMETER(FUintVector4, UpdateRegionOffsetAndSize)
SHADER_PARAMETER(FVector4, SourceScaleBias)
SHADER_PARAMETER(uint32, SourceMipBias)
SHADER_PARAMETER_TEXTURE(Texture2D, SourceTexture)
SHADER_PARAMETER_SAMPLER(SamplerState, SourceTextureSampler)
END_SHADER_PARAMETER_STRUCT()
FUploadLandscapeTextureToAtlasCS() = default;
FUploadLandscapeTextureToAtlasCS(const ShaderMetaType::CompiledShaderInitializerType& Initializer)
: FGlobalShader(Initializer)
{}
static bool ShouldCompilePermutation(const FGlobalShaderPermutationParameters& Parameters)
{
return IsFeatureLevelSupported(Parameters.Platform, ERHIFeatureLevel::SM5) && DoesPlatformSupportDistanceFieldShadowing(Parameters.Platform);
}
static void ModifyCompilationEnvironment(const FGlobalShaderPermutationParameters& Parameters, FShaderCompilerEnvironment& OutEnvironment)
{
FGlobalShader::ModifyCompilationEnvironment(Parameters, OutEnvironment);
OutEnvironment.SetDefine(TEXT("THREADGROUP_SIZEX"), ThreadGroupSizeX);
OutEnvironment.SetDefine(TEXT("THREADGROUP_SIZEY"), ThreadGroupSizeY);
}
static constexpr uint32 ThreadGroupSizeX = 8;
static constexpr uint32 ThreadGroupSizeY = 8;
};
class FUploadHeightFieldToAtlasCS : public FUploadLandscapeTextureToAtlasCS
{
DECLARE_GLOBAL_SHADER(FUploadHeightFieldToAtlasCS);
SHADER_USE_PARAMETER_STRUCT(FUploadHeightFieldToAtlasCS, FUploadLandscapeTextureToAtlasCS);
using FPermutationDomain = FShaderPermutationNone;
BEGIN_SHADER_PARAMETER_STRUCT(FParameters,)
SHADER_PARAMETER_STRUCT_INCLUDE(FUploadLandscapeTextureToAtlasCS::FSharedParameters, SharedParams)
SHADER_PARAMETER_UAV(RWTexture2D<float2>, RWHeightFieldAtlas)
END_SHADER_PARAMETER_STRUCT()
};
IMPLEMENT_GLOBAL_SHADER(FUploadHeightFieldToAtlasCS, "/Engine/Private/HeightFieldAtlasManagement.usf", "UploadHeightFieldToAtlasCS", SF_Compute);
class FUploadVisibilityToAtlasCS : public FUploadLandscapeTextureToAtlasCS
{
DECLARE_GLOBAL_SHADER(FUploadVisibilityToAtlasCS);
SHADER_USE_PARAMETER_STRUCT(FUploadVisibilityToAtlasCS, FUploadLandscapeTextureToAtlasCS);
using FPermutationDomain = FShaderPermutationNone;
BEGIN_SHADER_PARAMETER_STRUCT(FParameters, )
SHADER_PARAMETER_STRUCT_INCLUDE(FUploadLandscapeTextureToAtlasCS::FSharedParameters, SharedParams)
SHADER_PARAMETER(FVector4, VisibilityChannelMask)
SHADER_PARAMETER_UAV(RWTexture2D<float>, RWVisibilityAtlas)
END_SHADER_PARAMETER_STRUCT()
};
IMPLEMENT_GLOBAL_SHADER(FUploadVisibilityToAtlasCS, "/Engine/Private/HeightFieldAtlasManagement.usf", "UploadVisibilityToAtlasCS", SF_Compute);
uint32 FLandscapeTextureAtlas::CalculateDownSampleLevel(uint32 SizeX, uint32 SizeY) const
{
const uint32 TileSize = AddrSpaceAllocator.TileSize;
for (uint32 CurLevel = 0; CurLevel <= MaxDownSampleLevel; ++CurLevel)
{
const uint32 DownSampledSizeX = SizeX >> CurLevel;
const uint32 DownSampledSizeY = SizeY >> CurLevel;
if (DownSampledSizeX <= TileSize && DownSampledSizeY <= TileSize)
{
return CurLevel;
}
}
return MaxDownSampleLevel;
}
void FLandscapeTextureAtlas::UpdateAllocations(FRDGBuilder& GraphBuilder, ERHIFeatureLevel::Type InFeatureLevel)
{
InitializeIfNeeded();
TArray<FPendingUpload, TInlineAllocator<8>> PendingUploads;
auto AllocSortPred = [](const FAllocation& A, const FAllocation& B)
{
const int32 SizeA = FMath::Max(A.SourceTexture->GetSizeX(), A.SourceTexture->GetSizeY());
const int32 SizeB = FMath::Max(B.SourceTexture->GetSizeX(), B.SourceTexture->GetSizeY());
return SizeA < SizeB;
};
for (int32 Idx = 0; Idx < PendingStreamingTextures.Num(); ++Idx)
{
UTexture2D* SourceTexture = PendingStreamingTextures[Idx];
const uint32 SizeX = SourceTexture->GetSizeX();
const uint32 SizeY = SourceTexture->GetSizeY();
const uint32 DownSampleLevel = CalculateDownSampleLevel(SizeX, SizeY);
const uint32 NumMissingMips = SourceTexture->GetNumMips() - SourceTexture->GetNumResidentMips();
if (NumMissingMips <= DownSampleLevel)
{
SourceTexture->bForceMiplevelsToBeResident = false;
const uint32 SourceMipBias = DownSampleLevel - NumMissingMips;
const FAllocation* Allocation = CurrentAllocations.Find(SourceTexture);
check(Allocation && Allocation->Handle != INDEX_NONE);
const uint32 VisibilityChannel = Allocation->VisibilityChannel;
PendingUploads.Emplace(SourceTexture, SizeX >> DownSampleLevel, SizeY >> DownSampleLevel, SourceMipBias, Allocation->Handle, VisibilityChannel);
PendingStreamingTextures.RemoveAtSwap(Idx--);
}
}
if (PendingAllocations.Num())
{
PendingAllocations.Sort(AllocSortPred);
bool bAllocFailed = false;
for (TSet<FAllocation>::TConstIterator It(PendingAllocations); It; ++It)
{
FAllocation TmpAllocation = *It;
if (!bAllocFailed)
{
UTexture2D* SourceTexture = TmpAllocation.SourceTexture;
const uint32 SizeX = SourceTexture->GetSizeX();
const uint32 SizeY = SourceTexture->GetSizeY();
const uint32 DownSampleLevel = CalculateDownSampleLevel(SizeX, SizeY);
const uint32 DownSampledSizeX = SizeX >> DownSampleLevel;
const uint32 DownSampledSizeY = SizeY >> DownSampleLevel;
const uint32 Handle = AddrSpaceAllocator.Alloc(DownSampledSizeX, DownSampledSizeY);
const uint32 VisibilityChannel = TmpAllocation.VisibilityChannel;
if (Handle == INDEX_NONE)
{
FailedAllocations.Add(TmpAllocation);
bAllocFailed = true;
continue;
}
const uint32 NumMissingMips = SourceTexture->GetNumMips() - SourceTexture->GetNumResidentMips();
const uint32 SourceMipBias = NumMissingMips > DownSampleLevel ? 0 : DownSampleLevel - NumMissingMips;
if (NumMissingMips > DownSampleLevel)
{
SourceTexture->bForceMiplevelsToBeResident = true;
check(!PendingStreamingTextures.Contains(SourceTexture));
PendingStreamingTextures.Add(SourceTexture);
}
TmpAllocation.Handle = Handle;
CurrentAllocations.Add(TmpAllocation);
PendingUploads.Emplace(SourceTexture, DownSampledSizeX, DownSampledSizeY, SourceMipBias, Handle, VisibilityChannel);
}
else
{
FailedAllocations.Add(TmpAllocation);
}
}
if (bAllocFailed)
{
FailedAllocations.Sort(AllocSortPred);
}
PendingAllocations.Empty();
}
if (FailedAllocations.Num())
{
for (TSet<FAllocation>::TIterator It(FailedAllocations); It; ++It)
{
FAllocation TmpAllocation = *It;
UTexture2D* SourceTexture = TmpAllocation.SourceTexture;
const uint32 SizeX = SourceTexture->GetSizeX();
const uint32 SizeY = SourceTexture->GetSizeY();
const uint32 DownSampleLevel = CalculateDownSampleLevel(SizeX, SizeY);
const uint32 DownSampledSizeX = SizeX >> DownSampleLevel;
const uint32 DownSampledSizeY = SizeY >> DownSampleLevel;
const uint32 Handle = AddrSpaceAllocator.Alloc(DownSampledSizeX, DownSampledSizeY);
const uint32 VisibilityChannel = TmpAllocation.VisibilityChannel;
if (Handle == INDEX_NONE)
{
break;
}
const uint32 NumMissingMips = SourceTexture->GetNumMips() - SourceTexture->GetNumResidentMips();
const uint32 SourceMipBias = NumMissingMips > DownSampleLevel ? 0 : DownSampleLevel - NumMissingMips;
if (NumMissingMips > DownSampleLevel)
{
SourceTexture->bForceMiplevelsToBeResident = true;
check(!PendingStreamingTextures.Contains(SourceTexture));
PendingStreamingTextures.Add(SourceTexture);
}
TmpAllocation.Handle = Handle;
CurrentAllocations.Add(TmpAllocation);
PendingUploads.Emplace(SourceTexture, DownSampledSizeX, DownSampledSizeY, SourceMipBias, Handle, VisibilityChannel);
It.RemoveCurrent();
}
}
if (PendingUploads.Num())
{
AddPass(GraphBuilder, [this](FRHICommandList& RHICmdList)
{
RHICmdList.Transition(FRHITransitionInfo(AtlasUAVRHI, ERHIAccess::Unknown, ERHIAccess::UAVCompute));
RHICmdList.BeginUAVOverlap(AtlasUAVRHI);
});
if (SubAllocType == SAT_Height)
{
TShaderMapRef<FUploadHeightFieldToAtlasCS> ComputeShader(GetGlobalShaderMap(InFeatureLevel));
for (int32 Idx = 0; Idx < PendingUploads.Num(); ++Idx)
{
typename FUploadHeightFieldToAtlasCS::FParameters* Parameters = GraphBuilder.AllocParameters<typename FUploadHeightFieldToAtlasCS::FParameters>();
const FIntPoint UpdateRegion = PendingUploads[Idx].SetShaderParameters(Parameters, *this);
GraphBuilder.AddPass(
RDG_EVENT_NAME("UploadHeightFieldToAtlas"),
Parameters,
ERDGPassFlags::Compute,
[Parameters, ComputeShader, UpdateRegion](FRHICommandList& CmdList)
{
FComputeShaderUtils::Dispatch(CmdList, ComputeShader, *Parameters, FIntVector(UpdateRegion.X, UpdateRegion.Y, 1));
});
}
}
else
{
TShaderMapRef<FUploadVisibilityToAtlasCS> ComputeShader(GetGlobalShaderMap(InFeatureLevel));
for (int32 Idx = 0; Idx < PendingUploads.Num(); ++Idx)
{
typename FUploadVisibilityToAtlasCS::FParameters* Parameters = GraphBuilder.AllocParameters<typename FUploadVisibilityToAtlasCS::FParameters>();
const FIntPoint UpdateRegion = PendingUploads[Idx].SetShaderParameters(Parameters, *this);
GraphBuilder.AddPass(
RDG_EVENT_NAME("UploadVisibilityToAtlas"),
Parameters,
ERDGPassFlags::Compute,
[Parameters, ComputeShader, UpdateRegion](FRHICommandList& CmdList)
{
FComputeShaderUtils::Dispatch(CmdList, ComputeShader, *Parameters, FIntVector(UpdateRegion.X, UpdateRegion.Y, 1));
});
}
}
AddPass(GraphBuilder, [this](FRHICommandList& RHICmdList)
{
RHICmdList.EndUAVOverlap(AtlasUAVRHI);
RHICmdList.Transition(FRHITransitionInfo(AtlasUAVRHI, ERHIAccess::UAVCompute, ERHIAccess::SRVGraphics));
});
}
}
void FLandscapeTextureAtlas::UpdateAllocations(FRHICommandListImmediate& RHICmdList, ERHIFeatureLevel::Type InFeatureLevel)
{
FMemMark Mark(FMemStack::Get());
FRDGBuilder GraphBuilder(RHICmdList);
UpdateAllocations(GraphBuilder, InFeatureLevel);
GraphBuilder.Execute();
}
uint32 FLandscapeTextureAtlas::GetAllocationHandle(UTexture2D* Texture) const
{
const FAllocation* Allocation = CurrentAllocations.Find(Texture);
return Allocation ? Allocation->Handle : INDEX_NONE;
}
FVector4 FLandscapeTextureAtlas::GetAllocationScaleBias(uint32 Handle) const
{
return AddrSpaceAllocator.GetScaleBias(Handle);
}
void FLandscapeTextureAtlas::FSubAllocator::Init(uint32 InTileSize, uint32 InBorderSize, uint32 InDimInTiles)
{
check(InDimInTiles && !(InDimInTiles & (InDimInTiles - 1)));
TileSize = InTileSize;
BorderSize = InBorderSize;
TileSizeWithBorder = InTileSize + 2 * InBorderSize;
DimInTiles = InDimInTiles;
DimInTilesShift = FMath::CountBits(InDimInTiles - 1);
DimInTilesMask = InDimInTiles - 1;
DimInTexels = InDimInTiles * TileSizeWithBorder;
MaxNumTiles = InDimInTiles * InDimInTiles;
TexelSize = 1.f / DimInTexels;
TileScale = TileSize * TexelSize;
LevelOffsets.Empty();
MarkerQuadTree.Empty();
SubAllocInfos.Empty();
uint32 NumBits = 0;
for (uint32 Level = 1; Level <= DimInTiles; Level <<= 1)
{
const uint32 NumQuadsInLevel = Level * Level;
LevelOffsets.Add(NumBits);
NumBits += NumQuadsInLevel;
}
MarkerQuadTree.Add(false, NumBits);
}
uint32 FLandscapeTextureAtlas::FSubAllocator::Alloc(uint32 SizeX, uint32 SizeY)
{
const uint32 NumTiles1D = FMath::DivideAndRoundUp(FMath::Max(SizeX, SizeY), TileSize);
check(NumTiles1D <= DimInTiles);
const uint32 NumLevels = LevelOffsets.Num();
const uint32 Level = NumLevels - FMath::CeilLogTwo(NumTiles1D) - 1;
const uint32 LevelOffset = LevelOffsets[Level];
const uint32 QuadsInLevel1D = 1u << Level;
const uint32 SearchEnd = LevelOffset + QuadsInLevel1D * QuadsInLevel1D;
uint32 QuadIdx = LevelOffset;
for (; QuadIdx < SearchEnd; ++QuadIdx)
{
if (!MarkerQuadTree[QuadIdx])
{
break;
}
}
if (QuadIdx != SearchEnd)
{
const uint32 QuadIdxInLevel = QuadIdx - LevelOffset;
uint32 ParentLevel = Level;
uint32 ParentQuadIdxInLevel = QuadIdxInLevel;
for (; ParentLevel != (uint32)-1; --ParentLevel)
{
const uint32 ParentLevelOffset = LevelOffsets[ParentLevel];
const uint32 ParentQuadIdx = ParentLevelOffset + ParentQuadIdxInLevel;
FBitReference Marker = MarkerQuadTree[ParentQuadIdx];
if (Marker)
{
break;
}
Marker = true;
ParentQuadIdxInLevel >>= 2;
}
uint32 ChildLevel = Level + 1;
uint32 ChildQuadIdxInLevel = QuadIdxInLevel << 2;
uint32 NumChildren = 4;
for (; ChildLevel < NumLevels; ++ChildLevel)
{
const uint32 ChildQuadIdx = ChildQuadIdxInLevel + LevelOffsets[ChildLevel];
for (uint32 Idx = 0; Idx < NumChildren; ++Idx)
{
check(!MarkerQuadTree[ChildQuadIdx + Idx]);
MarkerQuadTree[ChildQuadIdx + Idx] = true;
}
ChildQuadIdxInLevel <<= 2;
NumChildren <<= 2;
}
const uint32 QuadX = FMath::ReverseMortonCode2(QuadIdxInLevel);
const uint32 QuadY = FMath::ReverseMortonCode2(QuadIdxInLevel >> 1);
const uint32 QuadSizeInTiles1D = DimInTiles >> Level;
const uint32 TileX = QuadX * QuadSizeInTiles1D;
const uint32 TileY = QuadY * QuadSizeInTiles1D;
FSubAllocInfo SubAllocInfo;
SubAllocInfo.Level = Level;
SubAllocInfo.QuadIdx = QuadIdx;
SubAllocInfo.UVScaleBias.X = SizeX * TexelSize;
SubAllocInfo.UVScaleBias.Y = SizeY * TexelSize;
SubAllocInfo.UVScaleBias.Z = TileX / (float)DimInTiles + BorderSize * TexelSize;
SubAllocInfo.UVScaleBias.W = TileY / (float)DimInTiles + BorderSize * TexelSize;
return SubAllocInfos.Add(SubAllocInfo);
}
return INDEX_NONE;
}
void FLandscapeTextureAtlas::FSubAllocator::Free(uint32 Handle)
{
check(SubAllocInfos.IsValidIndex(Handle));
const FSubAllocInfo SubAllocInfo = SubAllocInfos[Handle];
SubAllocInfos.RemoveAt(Handle);
const uint32 Level = SubAllocInfo.Level;
const uint32 QuadIdx = SubAllocInfo.QuadIdx;
uint32 ChildLevel = Level;
uint32 ChildIdxInLevel = QuadIdx - LevelOffsets[Level];
uint32 NumChildren = 1;
const uint32 NumLevels = LevelOffsets.Num();
for (; ChildLevel < NumLevels; ++ChildLevel)
{
const uint32 ChildIdx = ChildIdxInLevel + LevelOffsets[ChildLevel];
for (uint32 Idx = 0; Idx < NumChildren; ++Idx)
{
check(MarkerQuadTree[ChildIdx + Idx]);
MarkerQuadTree[ChildIdx + Idx] = false;
}
ChildIdxInLevel <<= 2;
NumChildren <<= 2;
}
uint32 TestIdxInLevel = (QuadIdx - LevelOffsets[Level]) & ~3u;
uint32 ParentLevel = Level - 1;
for (; ParentLevel != (uint32)-1; --ParentLevel)
{
const uint32 TestIdx = TestIdxInLevel + LevelOffsets[ParentLevel + 1];
const bool bParentFree = !MarkerQuadTree[TestIdx] && !MarkerQuadTree[TestIdx + 1] && !MarkerQuadTree[TestIdx + 2] && !MarkerQuadTree[TestIdx + 3];
if (!bParentFree)
{
break;
}
const uint32 ParentIdxInLevel = TestIdxInLevel >> 2;
const uint32 ParentIdx = ParentIdxInLevel + LevelOffsets[ParentLevel];
MarkerQuadTree[ParentIdx] = false;
TestIdxInLevel = ParentIdxInLevel & ~3u;
}
}
FVector4 FLandscapeTextureAtlas::FSubAllocator::GetScaleBias(uint32 Handle) const
{
check(SubAllocInfos.IsValidIndex(Handle));
return SubAllocInfos[Handle].UVScaleBias;
}
FIntPoint FLandscapeTextureAtlas::FSubAllocator::GetStartOffset(uint32 Handle) const
{
check(SubAllocInfos.IsValidIndex(Handle));
const FSubAllocInfo& Info = SubAllocInfos[Handle];
const uint32 QuadIdxInLevel = Info.QuadIdx - LevelOffsets[Info.Level];
const uint32 QuadX = FMath::ReverseMortonCode2(QuadIdxInLevel);
const uint32 QuadY = FMath::ReverseMortonCode2(QuadIdxInLevel >> 1);
const uint32 QuadSizeInTexels1D = (DimInTiles >> Info.Level) * TileSizeWithBorder;
return FIntPoint(QuadX * QuadSizeInTexels1D, QuadY * QuadSizeInTexels1D);
}
FLandscapeTextureAtlas::FAllocation::FAllocation()
: SourceTexture(nullptr)
, Handle(INDEX_NONE)
, VisibilityChannel(0)
, RefCount(0)
{}
FLandscapeTextureAtlas::FAllocation::FAllocation(UTexture2D* InTexture, uint32 InVisibilityChannel)
: SourceTexture(InTexture)
, Handle(INDEX_NONE)
, VisibilityChannel(InVisibilityChannel)
, RefCount(1)
{}
FLandscapeTextureAtlas::FPendingUpload::FPendingUpload(UTexture2D* Texture, uint32 SizeX, uint32 SizeY, uint32 MipBias, uint32 InHandle, uint32 Channel)
: SourceTexture(Texture->Resource->TextureRHI)
, SizesAndMipBias(FIntVector(SizeX, SizeY, MipBias))
, VisibilityChannel(Channel)
, Handle(InHandle)
{}
FIntPoint FLandscapeTextureAtlas::FPendingUpload::SetShaderParameters(void* ParamsPtr, const FLandscapeTextureAtlas& Atlas) const
{
if (Atlas.SubAllocType == SAT_Height)
{
typename FUploadHeightFieldToAtlasCS::FParameters* Params = (typename FUploadHeightFieldToAtlasCS::FParameters*)ParamsPtr;
Params->RWHeightFieldAtlas = Atlas.AtlasUAVRHI;
return SetCommonShaderParameters(&Params->SharedParams, Atlas);
}
else
{
typename FUploadVisibilityToAtlasCS::FParameters* Params = (typename FUploadVisibilityToAtlasCS::FParameters*)ParamsPtr;
FVector4 ChannelMask(ForceInitToZero);
ChannelMask[VisibilityChannel] = 1.f;
Params->VisibilityChannelMask = ChannelMask;
Params->RWVisibilityAtlas = Atlas.AtlasUAVRHI;
return SetCommonShaderParameters(&Params->SharedParams, Atlas);
}
}
FIntPoint FLandscapeTextureAtlas::FPendingUpload::SetCommonShaderParameters(void* ParamsPtr, const FLandscapeTextureAtlas& Atlas) const
{
const uint32 DownSampledSizeX = SizesAndMipBias.X;
const uint32 DownSampledSizeY = SizesAndMipBias.Y;
const uint32 SourceMipBias = SizesAndMipBias.Z;
const float InvDownSampledSizeX = 1.f / DownSampledSizeX;
const float InvDownSampledSizeY = 1.f / DownSampledSizeY;
const uint32 BorderSize = Atlas.AddrSpaceAllocator.BorderSize;
const uint32 UpdateRegionSizeX = DownSampledSizeX + 2 * BorderSize;
const uint32 UpdateRegionSizeY = DownSampledSizeY + 2 * BorderSize;
const FIntPoint StartOffset = Atlas.AddrSpaceAllocator.GetStartOffset(Handle);
typename FUploadLandscapeTextureToAtlasCS::FSharedParameters* CommonParams = (typename FUploadLandscapeTextureToAtlasCS::FSharedParameters*)ParamsPtr;
CommonParams->UpdateRegionOffsetAndSize = FUintVector4(StartOffset.X, StartOffset.Y, UpdateRegionSizeX, UpdateRegionSizeY);
CommonParams->SourceScaleBias = FVector4(InvDownSampledSizeX, InvDownSampledSizeY, (.5f - BorderSize) * InvDownSampledSizeX, (.5f - BorderSize) * InvDownSampledSizeY);
CommonParams->SourceMipBias = SourceMipBias;
CommonParams->SourceTexture = SourceTexture;
CommonParams->SourceTextureSampler = TStaticSamplerState<SF_Bilinear>::GetRHI();
const uint32 NumGroupsX = FMath::DivideAndRoundUp(UpdateRegionSizeX, FUploadLandscapeTextureToAtlasCS::ThreadGroupSizeX);
const uint32 NumGroupsY = FMath::DivideAndRoundUp(UpdateRegionSizeY, FUploadLandscapeTextureToAtlasCS::ThreadGroupSizeY);
return FIntPoint(NumGroupsX, NumGroupsY);
}
| [
"ouczbs@qq.com"
] | ouczbs@qq.com |
1dd95f24cc0ff51b68eae4e3e2ee9492fc38068f | e7c6d9d0c1adb8701d9acc2447538107facb7dc5 | /LOCISFrameWork/core/src/stdafx.cpp | 949f76cdfb9f3f593a7a8399fa43ac646e3908c5 | [] | no_license | ArjunRamesh77/LOCIS | a93624cf31134c69b739fd8feea99de3fa7b0cab | 572b69c32953e6141d6276763ef1e7721630db0d | refs/heads/master | 2023-08-15T09:53:01.582827 | 2021-10-04T15:33:25 | 2021-10-04T15:33:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 295 | cpp | // stdafx.cpp : source file that includes just the standard includes
// Compiler.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| [
"arjun.ramesh77@gmail.com"
] | arjun.ramesh77@gmail.com |
a1020ac757417fa48659a45208c1561b07e83251 | b02d1872e54b9adbf054beea115b7cdacd148eca | /Week4/CMP105App/Cursor.h | 75cf45267a3b2671fb5452c73c1444d15b3a3f04 | [] | no_license | artishflora/CMP105_W4 | a4dcd1518bc69fdbbf71c40d4b67a157484a0091 | 8e4c318de5eff8b162af8de661d1ed90da5b0e2b | refs/heads/master | 2020-12-29T07:25:53.107114 | 2020-02-12T15:46:39 | 2020-02-12T15:46:39 | 238,512,703 | 0 | 0 | null | 2020-02-05T17:50:13 | 2020-02-05T17:50:12 | null | UTF-8 | C++ | false | false | 251 | h | #pragma once
#include "Framework/GameObject.h"
class Cursor :
public GameObject
{
Input* input;
sf::RenderWindow* window;
public:
Cursor();
~Cursor();
void update();
void setInput(Input* in);
void getWindow(sf::RenderWindow* win);
};
| [
"1903084@uad.ac.uk"
] | 1903084@uad.ac.uk |
fd6f50a8da6c4cefc9698bcd476e06b217680d6f | c1466e0815558818829d51326d445df6ffad9c17 | /cpp_xcode/FIrst_Project/FIrst_Project/QeueExample.cpp | af6090b0e50ecf47e8e9526e8d2a435688f7817c | [] | no_license | ojaster/first_project | 2177bc78d6a6000862a306ebce71d2cdeee8d475 | 0a09308acd6270085959251ca8892dc22d272cfb | refs/heads/master | 2021-07-07T13:04:51.200496 | 2020-06-25T10:52:08 | 2020-06-25T10:52:08 | 129,524,939 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,138 | cpp | ////
//// QeueExample.cpp
//// FIrst_Project
////
//// Created by Данил on 28/04/2019.
//// Copyright © 2019 Daniil. All rights reserved.
////
//
//#include "QeueExample.hpp"
//int QeueExample::qCount(){
// return items;
//}
//bool QeueExample::dnqueue(Item & item){
// if(front == NULL){
// return false;
// }
// item = front->item;
// items--;
// Node * temp = front;
// front = front->next;
// delete temp;
// if(items == 0){
// end = NULL;
// }
// return true;
//
//}
//bool QeueExample::enqueue(const Item & item){
// if(isFull()){
// return false;
// }
//
// Node * add = new Node;//bad
// add->item = item;
// add->next=NULL;
// items++;
//
// if(front == NULL){// если очередь пуста
// front = add;//элемент помещается в начало
// end = add;
// return true;
// }else{
// end -> next = add;//иначе помещается в конец
// end = add;//указатель конца указывает на новый узел
// return true;
// }
//}
//
//bool QeueExample::isEmpty()const{
// return items > 0 ? false : true;
//}
//bool QeueExample::isFull()const{
// if(items == Q_SZE){
// return true;
// }else{
// return false;
// }
//}
//
//;
//
//QeueExample::QeueExample(int qs) : qSize(qs),front(NULL),end(NULL), items(0){}//создание очереди с предельным размеров qs
//QeueExample::~QeueExample(){
// Node * temp;
// while(front!=NULL){//пока очередь не пуста
// temp = front;// сохранение адреса начального элемента
// front = front->next;//переустановка указателя на следующий элемент
// delete temp;//удаление предыдущего начального элемента
// }
//}
////int main(){
//// QeueExample nip;
//// QeueExample tuck;
//// //QeueExample line2(nip);//нельзя
//// //tuck = nip;//нельзя
////}
| [
"daniil.gusev@icloud.com"
] | daniil.gusev@icloud.com |
3269a0ef5c768893c24d663c69140ebf862d05a4 | 2cb2bc953975540de8dfe3aee256fb3daa852bfb | /yuki_hiroshi/tyama_codeiq171.cpp | 67dbdafb3e0ef6e4b87b62cf9371318994ecc714 | [] | no_license | cielavenir/codeiq_solutions | db0c2001f9a837716aee1effbd92071e4033d7e0 | 750a22c937db0a5d94bfa5b6ee5ae7f1a2c06d57 | refs/heads/master | 2023-04-27T14:20:09.251817 | 2023-04-17T03:22:57 | 2023-04-17T03:22:57 | 19,687,315 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 1,561 | cpp | #include <vector>
#include <map>
#include <set>
#include <algorithm>
#include <iostream>
#include <string>
#include <numeric>
using namespace std;
class union_find{
int *parent,n;
public:
int root(int a){return parent[a]==a?a:(parent[a]=root(parent[a]));}
union_find(int _n){n=_n;parent=new int[n+1];for(int i=1;i<=n;i++)parent[i]=i;}
~union_find(){delete []parent;}
int same(int a,int b){return root(a)==root(b);}
int unite(int a,int b){
int x=root(a),y=root(b);//if(x==y)return 0;
parent[x]=y;
return 1;
}
int size(){
set<int>s;
for(int i=1;i<=n;i++)s.insert(root(i));
return s.size();
}
};
int main(){
union_find uf(500);
map<string,int>m;
string s,t;
int n=0,i;
for(;cin>>s;){
i=s.find("=");
t=s.substr(i+1);
s=s.substr(0,i);
if(m.find(s)==m.end())m[s]=n++;
if(m.find(t)==m.end())m[t]=n++;
uf.unite(m[s],m[t]);
}
map<int,vector<string> >list;
auto mit=m.begin();
for(;mit!=m.end();mit++)list[uf.root(mit->second)].push_back(mit->first);
//puts list.values.map{|e|e.sort.join('=')}.sort.join("\n")
vector<string>result;
auto listit=list.begin();
for(;listit!=list.end();listit++){
sort(listit->second.begin(),listit->second.end());
//listit_val.reduce(''){|s,e|s+"="+e}, not listit_val.reduce{|s,e|s+"="+e}. so I need to strip first "=".
result.push_back(accumulate(listit->second.begin(),listit->second.end(),string(),[](string x,string y){return x+"="+y;}).substr(1));
}
sort(result.begin(),result.end());
auto resultit=result.begin();
for(;resultit!=result.end();resultit++)cout<<*resultit<<endl;
} | [
"cielartisan@gmail.com"
] | cielartisan@gmail.com |
e6cb8d0177526ed84733a960fbc238d8173226e9 | cfa65bb0d577efd427f4aa86b57f8f0dcd909aca | /AADC/src/adtfBase/AADC_ADTF_BaseFilters/src/arduino/AADC_ArduinoCommunication/cRawSerialDevice.cpp | 031533763472bbca8d2825d18b8845839ae400c6 | [
"BSD-2-Clause"
] | permissive | AADC-Fruit/AADC_2015_FRUIT | 33f61d87f75763b3e8c4c943715d93ba2e28f33c | 88bd18871228cb48c46a3bd803eded6f14dbac08 | refs/heads/master | 2021-01-18T13:51:33.907328 | 2015-10-05T10:32:31 | 2015-10-05T10:32:31 | 41,482,833 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,663 | cpp | /**
Copyright (c)
Audi Autonomous Driving Cup. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. 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.
3. All advertising materials mentioning features or use of this software must display the following acknowledgement: This product includes software developed by the Audi AG and its contributors for Audi Autonomous Driving Cup.
4. Neither the name of Audi 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 AUDI AG 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 AUDI AG 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.
**********************************************************************
* $Author:: spiesra $ $Date:: 2014-09-16 13:29:48#$ $Rev:: 26104 $
**********************************************************************/
#include "stdafx.h"
#include "cRawSerialDevice.h"
#ifndef WIN32
Serial::cRawSerialDevice::cRawSerialDevice()
{
memset (&m_old_options, 0, sizeof (m_old_options));
memset (&m_options, 0, sizeof (m_options));
}
Serial::cRawSerialDevice::~cRawSerialDevice()
{
tcsetattr(m_FileDescriptorSerial, TCSANOW, &m_old_options);
}
tResult Serial::cRawSerialDevice::Open(const tChar* strDeviceName, tInt nBaudRate, tInt nParity, tInt nDataBits, tInt nStopBits, tInt nRxQueue, tInt nTxQueue, tTimeStamp nReadTimeout)
{
// "/dev/ttyUSB0"
//m_FileDescriptorSerial = open( path, O_RDWR | O_NOCTTY );
if ( (m_FileDescriptorSerial = open( strDeviceName, O_RDWR | O_NOCTTY )) < 0 )
{
//std::cerr << "Could not open Serial Device specified..." << std::endl;
return m_FileDescriptorSerial;
//exit(-1);
}
tcgetattr ( m_FileDescriptorSerial, &m_old_options ) ;
bzero(&m_options, sizeof(m_options));
m_options.c_cflag = B115200 | CRTSCTS | CS8 | CLOCAL | CREAD;
m_options.c_iflag = IGNPAR;
m_options.c_oflag = OPOST;
m_options.c_lflag = 0;
m_options.c_cc[VTIME] = 0 ;
m_options.c_cc[VMIN] = 7; // blocking until 7 chars are received i.e. length of header of arduino frame
tcflush( m_FileDescriptorSerial, TCIFLUSH );
tcsetattr(m_FileDescriptorSerial, TCSANOW, &m_options);
//std::cout << "Open Serial Port with FileDesc: " << m_FileDescriptorSerial <<std::endl;
return m_FileDescriptorSerial;
}
tResult Serial::cRawSerialDevice::Close()
{
//std::cout << "Closing Serial Port with FileDesc: " << m_FileDescriptorSerial <<std::endl;
RETURN_IF_FAILED(close(m_FileDescriptorSerial));
RETURN_NOERROR;
}
tInt32 Serial::cRawSerialDevice::Write(unsigned char* frame, int bytesToWrite)
{
//std::cout << "Writing to Serial Port with FileDesc: " << m_FileDescriptorSerial << "\tBytes: " << bytesToWrite << std::endl;
return write( m_FileDescriptorSerial, frame, bytesToWrite);
}
tInt32 Serial::cRawSerialDevice::Read(unsigned char* frame, int bytesToRead)
{
//std::cout << "Reading from Serial Port with FileDesc: " << m_FileDescriptorSerial << "\tBytes: " << bytesToRead << std::endl;
return read(m_FileDescriptorSerial, frame , bytesToRead);
}
#endif
tInt32 Serial::cRawSerialDevice::BytesAvailable()
{
int bytesAvailable = 0;
#ifndef WIN32
ioctl(m_FileDescriptorSerial, FIONREAD, &bytesAvailable);
#else
DWORD status;
COMSTAT comStat;
ClearCommError((HWND)(m_hDevice),&status, &comStat);
bytesAvailable = (tInt32)comStat.cbInQue;
#endif
//std::cout << "Bytes available on FileDesc: " << FileDescriptorSerial << "\t Bytes: " << bytesAvailable << std::endl;
return bytesAvailable;
}
| [
"riestern@fp-10-126-42-205.eduroam-fp.privat"
] | riestern@fp-10-126-42-205.eduroam-fp.privat |
2957c057ba90aed5344319b7c5b12a8f2c57cd06 | 02c7b7c0fb4e03a639852cd18a44ce09a95db188 | /build/xpm/lib/Xpm-def.cpp | f7720aae3a5667427816376c821c1f0d5ffa8e3b | [] | no_license | luvfilpus/rxvt-native | c3727a1310fba963e380bc2d9fbb86195e4c1cfc | 8d31de59c9ae44f2355eb818879a4d79c99b1728 | refs/heads/master | 2016-09-06T13:51:04.189325 | 2014-05-13T05:15:27 | 2014-05-13T05:15:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 54 | cpp | /usr/src/rxvt-20050409-21/src/rxvt/xpm/lib/Xpm-def.cpp | [
"root@papa.(none)"
] | root@papa.(none) |
b553c99f48930ed7cd217074146eebb89fdfa94d | 8c7f65e1e9732889c166d9ff4e84a5d3b8c744e2 | /contests/icpc_2015/practice/zigzagtr.cpp | d6a078127bf9c43fc1812b71ed80bd9a9a1d3713 | [] | no_license | rushilpaul/competitive-programming | 045604e4b6782b9743426c7504364a932aa85f65 | 20f33b36f80fee490db0ab405048cdc12cd90364 | refs/heads/master | 2021-01-11T21:55:21.277372 | 2020-10-31T06:11:34 | 2020-10-31T06:11:34 | 78,875,026 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,413 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef long double LD;
typedef vector<int> VI;
typedef vector<LL> VLL;
typedef vector<double> VD;
#define EPS (std::numeric_limits<double>::epsilon())
#define max_buf_size 1024
#define rep(i,n) for(int i=0;i<(n);i++)
#define repab(i,a,b) for(int i=(a);i<=(b);i++)
#define all(v) v.begin(),v.end()
#define pb push_back
#define mp make_pair
#define sq(a) ((a)*(a))
#define PI 3.141592653589793238462643383279502884197
char _buf[max_buf_size];
int _bytes_read_ = max_buf_size-1;
char *_s = _buf + _bytes_read_;
inline char getc1() { if(_s >= _buf + _bytes_read_) { _bytes_read_ = fread(_buf,1,max_buf_size-1,stdin); _buf[_bytes_read_] = 0; _s = _buf; } return *(_s++); }
inline int readint()
{
char t=getc1(); int n=1,res=0;
while(t!='-' && !isdigit(t))
t=getc1();
if(t=='-')
{ n=-1; t=getc1(); }
while(isdigit(t))
{ res = 10*res + (t&15); t=getc1(); }
return res*n;
}
inline LL readLL()
{
char t=getc1(); int n=1; LL res=0;
while(t!='-' && !isdigit(t))
t=getc1();
if(t=='-')
{ n=-1; t=getc1(); }
while(isdigit(t))
{ res = (LL)10*res + (t&15); t=getc1(); }
return res*n;
}
inline char skipwhitespace() { char ch = getc1(); while(ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t') ch = getc1(); return ch; }
inline int readline(char *s)
{
char ch=skipwhitespace();
int n=0;
while( (ch != '\n' && ch != 0) )
{
s[n++] = ch;
ch = getc1();
}
s[n] = 0;
return n;
}
inline int readstr(char *s)
{
char ch=skipwhitespace();
int n=0;
while( (ch != '\n' && ch != ' ' && ch != '\t' && ch != 0) )
{
s[n++] = ch;
ch = getc1();
}
s[n] = 0;
return n;
}
inline string readstring(int n)
{
char buf[n+1];
readstr(buf);
string s(buf);
return s;
}
inline double readdouble()
{
char buf[40];
readstr(buf);
double d;
sscanf(buf,"%lf",&d);
return d;
}
inline LD readLD()
{
char buf[80];
readstr(buf);
LD d;
sscanf(buf,"%Lf",&d);
return d;
}
inline char readchar() { return skipwhitespace(); }
char outbuf[max_buf_size];
int outbuf_p;
inline void putc1(char ch) { if(outbuf_p >= max_buf_size) { fwrite(outbuf,1,max_buf_size,stdout); outbuf_p = 0; } outbuf[outbuf_p++] = ch; }
inline void flush() { fwrite(outbuf,1,outbuf_p,stdout); outbuf_p = 0; }
inline void writeint(int n)
{
int sign = n >= 0 ? 1 : -1;
n = n>0 ? n : -n;
char buf[10];
int i = 9;
if(!n) buf[i--] = 48;
while(n)
{
buf[i--] = n % 10 + 48;
n /= 10;
}
if(sign < 0) putc1('-');
while(++i < 10) putc1(buf[i]);
}
inline void writeLL(LL n)
{
int sign = n >= 0 ? 1 : -1;
n = n>0 ? n : -n;
char buf[25];
int i = 24;
if(!n) buf[i--] = 48;
while(n)
{
buf[i--] = n % 10 + 48;
n /= 10;
}
if(sign < 0) putc1('-');
while(++i < 25) putc1(buf[i]);
}
inline void writestr(char *s)
{
char *p = s;
while(*p)
{
putc1(*p);
p++;
}
}
inline void writedouble(double d, int p) { char buf[40]; sprintf(buf,"%.*f",p,d); writestr(buf); }
// END OF IO
double my_sqrt(double x, double delta = .00001)
{
double g = x / 2, ng;
while(fabs(g - (ng = (x / g + g) / 2)) > delta)
g = ng;
return g;
}
template<class T>
void print(vector<T> v)
{
for(T i : v)
cout << i << " ";
}
template<class T>
void fill(vector<T> v, T val = 0)
{
fill(v.begin(),v.end(),val);
}
vector<string> split(string S, string D)
{
vector<string> ar;
int pos = 0, last = 0;
while( (pos = S.find(D,last)) != string::npos)
{
string sub = S.substr(last,pos-last);
if(sub.length() > 0)
ar.push_back(sub);
last = pos + D.length();
}
string sub = S.substr(last);
if(sub.length() > 0)
ar.push_back(sub);
return ar;
}
inline LL pow(LL b, LL e)
{
LL ans=1;
while(e--) ans *= b;
return ans;
}
inline LL pow(LL b, LL e, LL mod)
{
LL ans=1;
while(e)
{
if(e & 1)
ans = ans * b % mod;
b = b * b % mod;
e >>= 1;
}
return ans;
}
template<class T>
T egcd(T a, T b, T &x, T &y)
{
if (a == 0)
{
x = 0;
y = 1;
return b;
}
T x1, y1;
T d = egcd(b%a, a, x1, y1);
x = y1 - x1* (b/a);
y = x1;
return d;
}
LL inv(LL a, LL m)
{
LL inv,y;
assert(egcd(a,m,inv,y) == 1);
if(inv < 0) inv += m;
return inv;
}
inline LL gcd(LL a, LL b)
{
while(b)
{
LL t = b;
b = a%b;
a = t;
}
return a;
}
int main()
{
int t = readint();
while(t--)
{
int n = readint();
int ar[n]; rep(a,n) ar[a] = readint();
printf("%d\n",n == 1 ? 1 : 2);
}
return 0;
}
| [
"rushilpaul@gmail.com"
] | rushilpaul@gmail.com |
a4e702605a376c168d83cfc751adead7f5dca25c | 685302288195200706c7287b294ef8bb8c994312 | /contrib/ssd/caffe/layers/detection_output_layer.hpp | 75c192ab8747aa44413de62e465fafb7dbf9c201 | [
"BSD-2-Clause",
"LicenseRef-scancode-generic-cla",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain"
] | permissive | IEC-lab/caffe | 9d48462281ccab614573bd6737227d266247bb29 | a29f1859265bd4249bb6e244406304e367d84d6f | refs/heads/master | 2020-04-16T11:18:22.363915 | 2019-01-27T04:19:33 | 2019-01-27T04:19:33 | 165,530,741 | 1 | 0 | NOASSERTION | 2019-01-27T04:19:34 | 2019-01-13T16:57:18 | C++ | UTF-8 | C++ | false | false | 3,579 | hpp | #ifndef CAFFE_DETECTION_OUTPUT_LAYER_HPP_
#define CAFFE_DETECTION_OUTPUT_LAYER_HPP_
#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/regex.hpp>
#include <map>
#include <string>
#include <utility>
#include <vector>
#include "caffe/blob.hpp"
#include "caffe/layer.hpp"
#include "caffe/proto/caffe.pb.h"
#include "caffe/util/bbox_util.hpp"
#include "caffe/util/ssd_transformer.hpp"
using namespace boost::property_tree; // NOLINT(build/namespaces)
namespace caffe {
/**
* @brief Generate the detection output based on location and confidence
* predictions by doing non maximum suppression.
*
* Intended for use with MultiBox detection method.
*
* NOTE: does not implement Backwards operation.
*/
template <typename Dtype>
class DetectionOutputLayer : public Layer<Dtype> {
public:
explicit DetectionOutputLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Reshape(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual inline const char* type() const { return "DetectionOutput"; }
virtual inline int MinBottomBlobs() const { return 3; }
virtual inline int MaxBottomBlobs() const { return 4; }
virtual inline int ExactNumTopBlobs() const { return 1; }
protected:
/**
* @brief Do non maximum suppression (nms) on prediction results.
*
* @param bottom input Blob vector (at least 2)
* -# @f$ (N \times C1 \times 1 \times 1) @f$
* the location predictions with C1 predictions.
* -# @f$ (N \times C2 \times 1 \times 1) @f$
* the confidence predictions with C2 predictions.
* -# @f$ (N \times 2 \times C3 \times 1) @f$
* the prior bounding boxes with C3 values.
* @param top output Blob vector (length 1)
* -# @f$ (1 \times 1 \times N \times 7) @f$
* N is the number of detections after nms, and each row is:
* [image_id, label, confidence, xmin, ymin, xmax, ymax]
*/
virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
/// @brief Not implemented
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {
NOT_IMPLEMENTED;
}
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {
NOT_IMPLEMENTED;
}
int num_classes_;
bool share_location_;
int num_loc_classes_;
int background_label_id_;
CodeType code_type_;
bool variance_encoded_in_target_;
int keep_top_k_;
float confidence_threshold_;
int num_;
int num_priors_;
float nms_threshold_;
int top_k_;
float eta_;
bool need_save_;
string output_directory_;
string output_name_prefix_;
string output_format_;
map<int, string> label_to_name_;
map<int, string> label_to_display_name_;
vector<string> names_;
vector<pair<int, int> > sizes_;
int num_test_image_;
int name_count_;
bool has_resize_;
ResizeParameter resize_param_;
ptree detections_;
bool visualize_;
float visualize_threshold_;
shared_ptr<SSDTransformer<Dtype> > data_transformer_;
string save_file_;
Blob<Dtype> bbox_preds_;
Blob<Dtype> bbox_permute_;
Blob<Dtype> conf_permute_;
};
} // namespace caffe
#endif // CAFFE_DETECTION_OUTPUT_LAYER_HPP_
| [
"yf.dl@qq.com"
] | yf.dl@qq.com |
e85c7f7c654b533cdb11042e153f30916bb41543 | e83e0820033f6dd66095ea89abf7b0c221fbebd7 | /examples/example0.cpp | e34f645208405c6f0d69c2abf59f8d11de291b57 | [
"MIT"
] | permissive | ameroueh/performance | e9ae34046435ac660ee3517a2f8310df79c30e63 | d393d3c826f04ef4379d6c686e46be483ba0bcd9 | refs/heads/master | 2020-04-29T07:13:33.667050 | 2019-04-13T15:03:56 | 2019-04-13T15:03:56 | 175,944,359 | 0 | 1 | MIT | 2019-04-11T22:13:56 | 2019-03-16T08:09:06 | Python | UTF-8 | C++ | false | false | 117 | cpp | #include <iostream>
int main() {
int a = 5;
int b = 8;
int c = 0;
c = a + b;
std::cout
<< c << std::endl;
}
| [
"ares.m@asidatascience.com"
] | ares.m@asidatascience.com |
246d6056485c9730d60ad9fee0d2f8490cc05752 | 32dc6d7b523d9144fd7b74ef44a832b170b26f1a | /hello/matrix_rgb_test/matrix_rgb_test/matrix_rgb_test.ino | 0460794a770b9269d27f75e000fafec3438d1773 | [] | no_license | autotel/thesis-prototype-zero | 56de5e58115606556a36ed2b39a73d3ced1ad1ac | d350d8eee3c207a066ac9a557ae8ad969977914d | refs/heads/master | 2021-07-07T06:36:35.714790 | 2017-09-29T17:57:39 | 2017-09-29T17:57:39 | 103,044,620 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,172 | ino |
void setup();
#define COMPENSATE_R 14
#define COMPENSATE_G 2
#define COMPENSATE_B 1
#define analogA A1
#define analogB A0
int _pin;
long lastchange;
char16_t gridImage [16] = {
0x800, 0x880, 0x008, 0x800,
0xff0, 0x0f0, 0x0ff, 0x0f0,
0xf0f, 0x0ff, 0x00f, 0x00f,
0xf00, 0x0f0, 0x00f, 0x000,
};
byte currentPixel = 0;
void setup() {
//the perfect pulldown is 2.5K ohms
pinMode(analogA, OUTPUT);
pinMode(analogB, OUTPUT);
//set all pins from 0 to 7 to output
DDRD = 0xFF;
}
long prevMillis=0;
void loop() {
float mills = (millis() % 2048) / 8.00;
/* for (byte a = 0; a < 16; a++) {
gridImage[a] |= a%4*0x4;
gridImage[a] |= (a%4)*0x4<<4;
gridImage[a] |= (a%4)*0x4<<8;
}*/
if (prevMillis > millis() + 10) {
prevMillis=millis();
for (byte a = 0; a < 16; a++) {
int m = 0;
for (byte b = 0; b < 3; b++) {
int sm = gridImage[a] >> b * 4;
sm++;
sm |= 0xf;
m |= sm << b * 4;
}
gridImage[a] = m;
}
}
//nibble A is connected to the mux address for the anodes / btn inputs
byte nibbleA = 0xF;
//nibble B is connected to the mux for the cathodes / btn outputs
byte nibbleB = 0xF;
byte currentLayer = currentPixel >> 4;
nibbleA &= (((currentPixel % 3) * 4) + (currentPixel % 12) / 3);
nibbleB &= (currentPixel / 12);
nibbleA += 4;
nibbleB += 8;
//mask out to get the current channel, in the gridimage that belongs to current puxel
byte currentIntensity = 0xF & (gridImage[(currentPixel / 3) % 16] >> ((currentPixel % 3) * 4));
if (currentIntensity > 0) {
analogWrite(analogA, currentIntensity << 4);
analogWrite(analogB, 0xf - currentIntensity);
PORTD = (nibbleB << 4) | (nibbleA);
switch (currentPixel % 3) {
case 1:
delayMicroseconds( COMPENSATE_B);
break;
case 2:
delayMicroseconds( COMPENSATE_G);
break;
case 3:
delayMicroseconds( COMPENSATE_R);
}
} else {
digitalWrite(analogA, LOW);
digitalWrite(analogB, HIGH);
}
// delay(300);
currentPixel++;
currentPixel = currentPixel % 48;
}
void updatePixel() {
}
void readButton() {}
| [
"joaquin@autotel.co"
] | joaquin@autotel.co |
d0d0a9b5d4d2db720f1694ec5042660dbbabc422 | dfe1f796a54143e5eb8661f3328ad29dbfa072d6 | /psx/_dump_/25/_dump_c_src_/diabpsx/psxsrc/async.cpp | a2be9747a4bbe1efb07e30c11b8dbf29301aa47e | [
"Unlicense"
] | permissive | diasurgical/scalpel | 0f73ad9be0750ce08eb747edc27aeff7931800cd | 8c631dff3236a70e6952b1f564d0dca8d2f4730f | refs/heads/master | 2021-06-10T18:07:03.533074 | 2020-04-16T04:08:35 | 2020-04-16T04:08:35 | 138,939,330 | 15 | 7 | Unlicense | 2019-08-27T08:45:36 | 2018-06-27T22:30:04 | C | UTF-8 | C++ | false | false | 1,089 | cpp | // C:\diabpsx\PSXSRC\ASYNC.CPP
#include "types.h"
// address: 0x80090394
// line start: 86
// line end: 87
void AS_CallBack0__Fi(int handle) {
}
// address: 0x800903A8
// line start: 91
// line end: 92
void AS_CallBack1__Fi(int handle) {
}
// address: 0x800903BC
// line start: 102
// line end: 125
void AS_WasLastBlock__FiP6STRHDRP6SFXHDR(int ah, struct STRHDR *sh, struct SFXHDR *sfh) {
// register: 16
register unsigned char *ptr;
}
// address: 0x80090498
// line start: 148
// line end: 164
int AS_OpenStream__FP6STRHDRP6SFXHDR(struct STRHDR *sh, struct SFXHDR *sfh) {
// register: 16
register int ah;
}
// address: 0x80090538
// line start: 174
// line end: 175
char AS_GetBlock__FP6SFXHDR(struct SFXHDR *sfh) {
}
// address: 0x80090544
// line start: 185
// line end: 189
void AS_CloseStream__FP6STRHDRP6SFXHDR(struct STRHDR *sh, struct SFXHDR *sfh) {
}
// address: 0x80090570
// line start: 200
// line end: 242
int AS_LoopStream__FiP6STRHDRP6SFXHDR(int ah, struct STRHDR *sh, struct SFXHDR *sfh) {
// register: 17
register unsigned char *ptr;
}
| [
"rnd0x00@gmail.com"
] | rnd0x00@gmail.com |
a385e7f6b4d6ef37940791f51b4c532b1097275b | f5d9684f87eab83a6375621716bd8e3ea59c00b1 | /src/acf.cpp | 7aae116f8880a79b1bf8eef8aa3320589b53455f | [
"MIT"
] | permissive | usefulcat/itoa-benchmark | f9d2f6fe5fed3107f1d2391d9bbd28cfe8067c4b | a8afc269382e1de1d9ce0f714eab84062e043a34 | refs/heads/master | 2020-05-16T01:26:29.016269 | 2019-04-22T02:04:28 | 2019-04-22T02:04:28 | 182,602,367 | 0 | 0 | null | 2019-04-22T01:30:01 | 2019-04-22T01:30:01 | null | UTF-8 | C++ | false | false | 12,530 | cpp | #include <stdint.h>
#include "test.h"
#include <string.h>
#define LIKELY(x) __builtin_expect(static_cast<bool>(x), 1)
#define UNLIKELY(x) __builtin_expect(static_cast<bool>(x), 0)
/*
* We only use functions for clarity here. Eyeballing -S output
* reveals GCC makes strange inlining decisions on this file,
* especially with LIKELY. Make sure our helpers are really
* inlined.
*/
#define INLINE inline __attribute__((always_inline)) static
typedef __uint128_t uint128_t;
/* Powers of 10. */
#define PO2 100ULL
#define PO4 10000ULL
#define PO8 100000000ULL
#define PO10 10000000000ULL
#define PO16 10000000000000000ULL
/* 64 bit's worth of '0' characters (i.e., 8 characters). */
#define ZERO_CHARS 0x3030303030303030ULL
/**
* encode_* functions unpack (pairs of) numbers into BCD: each byte
* contains exactly one decimal digit.
*
* The basic idea is to use SWAR (SIMD within a register) and perform
* low-precision arithmetic on several values in parallel.
*
* Most non-obviousness lies in the conversion of integer division
* constants to multiplication, shift and mask by hand. Decent
* compilers do it for scalars, but we can't easily express a SWAR
* integer division.
*
* The trick is to choose a low enough precision that the fixed point
* multiplication won't overflow into the next packed value (and high
* enough that the truncated division is exact for the relevant
* range), and to pack values so that the final result ends up in the
* byte we want. There are formulae to determine how little precision
* we need given an input range and a constant divisor, but for our
* cases, one can also check exhaustively (:
*
* The remainder is simple: given d = x / k, x % k = x - k * d.
*/
/**
* SWAR unpack [100 * hi + lo] to 4 decimal bytes, assuming hi and lo
* \in [0, 100)
*/
INLINE uint32_t
encode_hundreds(uint32_t hi, uint32_t lo)
{
/*
* Pack everything in a single 32 bit value.
*
* merged = [ hi 0 lo 0 ]
*/
uint32_t merged = hi | (lo << 16);
/*
* Fixed-point multiplication by 103/1024 ~= 1/10.
*/
uint32_t tens = (merged * 103UL) >> 10;
/*
* Mask away garbage bits between our digits.
*
* tens = [ hi/10 0 lo/10 0 ]
*
* On a platform with more restricted literals (ARM, for
* instance), it may make sense to and-not with the middle
* bits.
*/
tens &= (0xFUL << 16) | 0xFUL;
/*
* x mod 10 = x - 10 * (x div 10).
*
* (merged - 10 * tens) = [ hi%10 0 lo%10 0 ]
*
* Then insert these values between tens. Arithmetic instead
* of bitwise operation helps the compiler merge this with
* later increments by a constant (e.g., ZERO_CHARS).
*/
return tens + ((merged - 10UL * tens) << 8);
}
/**
* SWAR encode 10000 hi + lo to byte (unpacked) BCD.
*/
INLINE uint64_t
encode_ten_thousands(uint64_t hi, uint64_t lo)
{
uint64_t merged = hi | (lo << 32);
/* Truncate division by 100: 10486 / 2**20 ~= 1/100. */
uint64_t top = ((merged * 10486ULL) >> 20) & ((0x7FULL << 32) | 0x7FULL);
/* Trailing 2 digits in the 1e4 chunks. */
uint64_t bot = merged - 100ULL * top;
uint64_t hundreds;
uint64_t tens;
/*
* We now have 4 radix-100 digits in little-endian order, each
* in its own 16 bit area.
*/
hundreds = (bot << 16) + top;
/* Divide and mod by 10 all 4 radix-100 digits in parallel. */
tens = (hundreds * 103ULL) >> 10;
tens &= (0xFULL << 48) | (0xFULL << 32) | (0xFULL << 16) | 0xFULL;
tens += (hundreds - 10ULL * tens) << 8;
return tens;
}
/**
* Range-specialised version of itoa.
*
* We always convert to fixed-width BCD then shift away any leading
* zero. The slop will manifest as writing zero bytes after our
* encoded string, which is acceptable: we never write more than the
* maximal length (10 or 20 characters).
*/
/**
* itoa for x < 100.
*/
INLINE char*
itoa_hundred(char* out, unsigned int x)
{
/*
* -1 if x < 10, 0 otherwise. Tried to get an sbb, but ?:
* gets us branches.
*/
int small = (int)(x - 10) >> 8;
unsigned int base = (unsigned int)'0' | ((unsigned int)'0' << 8);
/*
* Probably not necessary, but why not abuse smaller constants?
* Also, see block comment above idiv_POx functions.
*/
unsigned int hi = (x * 103UL) >> 10;
unsigned int lo = x - 10UL * hi;
base += hi + (lo << 8);
/* Shift away the leading zero (shift by 8) if x < 10. */
base >>= small & 8;
memcpy(out, &base, 2);
/* 2 + small = 1 if x < 10, 2 otherwise. */
return out + 2 + small;
}
/**
* itoa for x < 10k.
*/
INLINE char*
itoa_ten_thousand(char* out, unsigned int x)
{
uint32_t buf;
unsigned int x_div_PO2, x_mod_PO2;
unsigned int zeros;
x_div_PO2 = (x * 10486UL) >> 20;
x_mod_PO2 = x - PO2 * x_div_PO2;
buf = encode_hundreds(x_div_PO2, x_mod_PO2);
/*
* Count leading (in memory, trailing in register: we're
* little endian) zero bytes: count leading zero bits and
* round down to 8.
*/
zeros = __builtin_ctz(buf) & -8U;
buf += ZERO_CHARS; /* BCD -> ASCII. */
buf >>= zeros; /* Shift away leading zero characters */
memcpy(out, &buf, 4);
/* zeros is in bits; convert to bytes to find actual length. */
return out + 4 - zeros / 8;
}
/**
* 32 bit helpers for truncation by constant.
*
* We only need them because GCC is stupid with likely/unlikely
* annotations: unlikely code is compiled with an extreme emphasis on
* size, up to compiling integer division by constants to actual div
* instructions. In turn, we want likely annotations because we only
* get a nice ladder of forward conditional jumps when there is no
* code between if blocks. We convince GCC that our "special" cases
* for shorter integers aren't slowpathed guards by marking each
* conditional as likely.
*
* The constants are easily proven correct (or compared with those
* generated by a reference compiler, e.g., GCC or clang). For
* example,
*
* 1/10000 ~= k = 3518437209 / 2**45 = 1/10000 + 73/21990232555520000.
*
* Let eps = 73/21990232555520000; for any 0 <= x < 2**32,
* floor(k * x) <= floor(x / 10000 + x * eps)
* <= floor(x / 10000 + 2**32 * eps)
* <= floor(x / 10000 + 2e-5).
*
* Given that x is unsigned, flooring the left and right -hand sides
* will yield the same value as long as the error term
* (x * eps <= 2e-5) is less than 1/10000, and 2e-5 < 10000. We finally
* conclude that 3518437209 / 2**45, our fixed point approximation of
* 1/10000, is always correct for truncated division of 32 bit
* unsigned ints.
*/
/**
* Divide a 32 bit int by 1e4.
*/
INLINE uint32_t
idiv_PO4(uint32_t x)
{
uint64_t wide = x;
uint64_t mul = 3518437209UL;
return (wide * mul) >> 45;
}
/**
* Divide a 32 bit int by 1e8.
*/
INLINE uint64_t
idiv_PO8(uint32_t x)
{
uint64_t wide = x;
uint64_t mul = 1441151881UL;
return (wide * mul) >> 57;
}
INLINE
char*
an_itoa(char* out, uint32_t x)
{
uint64_t buf;
uint32_t x_div_PO4;
uint32_t x_mod_PO4;
uint32_t x_div_PO8;
/*
* Smaller numbers can be encoded more quickly. Special
* casing them makes a significant difference compared to
* always going through 8-digit encoding.
*/
if (LIKELY(x < PO2)) {
return itoa_hundred(out, x);
}
if (LIKELY(x < PO4)) {
return itoa_ten_thousand(out, x);
}
/*
* Manual souped up common subexpression elimination.
*
* The sequel always needs x / PO4 and x % PO4. Compute them
* here, before branching. We may also need x / PO8 if
* x >= PO8. Benchmarking shows that performing this division
* by constant unconditionally doesn't hurt. If x >= PO8, we'll
* always want x_div_PO4 = (x % PO8) / PO4. We compute that
* in a roundabout manner to reduce the makespan, i.e., the
* length of the dependency chain for (x % PO8) % PO4 = x % PO4.
*/
x_div_PO4 = idiv_PO4(x);
x_mod_PO4 = x - x_div_PO4 * PO4;
x_div_PO8 = idiv_PO8(x);
/*
* We actually want x_div_PO4 = (x % PO8) / PO4.
* Subtract what would have been removed by (x % PO8) from
* x_div_PO4.
*/
x_div_PO4 -= x_div_PO8 * PO4;
/*
* Finally, we can unconditionally encode_ten_thousands the
* values we obtain after division by PO8 and fixup by
* x_div_PO8 * PO4.
*/
buf = encode_ten_thousands(x_div_PO4, x_mod_PO4);
if (LIKELY(x < PO8)) {
unsigned zeros;
zeros = __builtin_ctzll(buf) & -8U;
buf += ZERO_CHARS;
buf >>= zeros;
memcpy(out, &buf, 8);
return out + 8 - zeros / 8;
}
/* 32 bit integers are always below 1e10. */
buf += ZERO_CHARS;
out = itoa_hundred(out, x_div_PO8);
memcpy(out, &buf, 8);
return out + 8;
}
/**
* 64 bit helpers for truncation by constant.
*/
/**
* Divide a 64 bit int by 1e4.
*/
INLINE uint64_t
ldiv_PO4(uint64_t x)
{
uint128_t wide = x;
uint128_t mul = 3777893186295716171ULL;
return (wide * mul) >> 75;
}
/**
* Divide a 64 bit int by 1e8.
*/
INLINE uint64_t
ldiv_PO8(uint64_t x)
{
uint128_t wide = x;
uint128_t mul = 12379400392853802749ULL;
return (wide * mul) >> 90;
}
/**
* Divide a 64 bit int by 1e16.
*/
INLINE uint64_t
ldiv_PO16(uint64_t x)
{
uint128_t wide = x;
uint128_t mul = 4153837486827862103ULL;
return (wide * mul) >> 115;
}
INLINE
char*
an_ltoa(char* out, uint64_t x)
{
uint64_t x_div_PO4;
uint64_t x_mod_PO4;
uint64_t x_div_PO8;
uint64_t buf;
if (LIKELY(x < PO2)) {
return itoa_hundred(out, x);
}
if (LIKELY(x < PO4)) {
return itoa_ten_thousand(out, x);
}
x_div_PO4 = ldiv_PO4(x);
x_mod_PO4 = x - x_div_PO4 * PO4;
/*
* Benchmarking shows the long division by PO8 hurts
* performance for PO4 <= x < PO8. Keep encode_ten_thousands
* conditional for an_ltoa.
*/
if (LIKELY(x < PO8)) {
uint64_t buf;
unsigned zeros;
buf = encode_ten_thousands(x_div_PO4, x_mod_PO4);
zeros = __builtin_ctzll(buf) & -8U;
buf += ZERO_CHARS;
buf >>= zeros;
memcpy(out, &buf, 8);
return out + 8 - zeros / 8;
}
/* See block comment in an_itoa. */
x_div_PO8 = ldiv_PO8(x);
x_div_PO4 = x_div_PO4 - x_div_PO8 * PO4;
buf = encode_ten_thousands(x_div_PO4, x_mod_PO4) + ZERO_CHARS;
/*
* Add a case for PO8 <= x < PO10 because itoa_hundred is much
* quicker than a second call to encode_ten_thousands; the
* same isn't true of itoa_ten_thousand.
*/
if (LIKELY(x < PO10)) {
out = itoa_hundred(out, x_div_PO8);
memcpy(out, &buf, 8);
return out + 8;
}
/*
* Again, long division by PO16 hurts, so do the rest
* conditionally.
*/
if (LIKELY(x < PO16)) {
uint64_t buf_hi;
uint32_t hi_hi, hi_lo;
unsigned zeros;
/* x_div_PO8 < PO8 < 2**32, so idiv_PO4 is safe. */
hi_hi = idiv_PO4(x_div_PO8);
hi_lo = x_div_PO8 - hi_hi * PO4;
buf_hi = encode_ten_thousands(hi_hi, hi_lo);
zeros = __builtin_ctzll(buf_hi) & -8U;
buf_hi += ZERO_CHARS;
buf_hi >>= zeros;
memcpy(out, &buf_hi, 8);
out += 8 - zeros / 8;
memcpy(out, &buf, 8);
return out + 8;
} else {
uint64_t hi = ldiv_PO16(x);
uint64_t mid = x_div_PO8 - hi * PO8;
uint64_t buf_mid;
uint32_t mid_hi, mid_lo;
mid_hi = idiv_PO4(mid);
mid_lo = mid - mid_hi * PO4;
buf_mid = encode_ten_thousands(mid_hi, mid_lo) + ZERO_CHARS;
out = itoa_ten_thousand(out, hi);
memcpy(out, &buf_mid, 8);
memcpy(out + 8, &buf, 8);
return out + 16;
}
}
void u32toa_acf(uint32_t value, char* buffer) {
*an_itoa(buffer, value) = '\0';
}
void i32toa_acf(int32_t value, char* buffer) {
uint32_t u = static_cast<uint32_t>(value);
if (value < 0) {
*buffer++ = '-';
u = ~u + 1;
}
u32toa_acf(u, buffer);
}
void u64toa_acf(uint64_t value, char* buffer) {
*an_ltoa(buffer, value) = '\0';
}
void i64toa_acf(int64_t value, char* buffer) {
uint64_t u = static_cast<uint64_t>(value);
if (value < 0) {
*buffer++ = '-';
u = ~u + 1;
}
u64toa_acf(u, buffer);
}
REGISTER_TEST(acf);
| [
"scott@q240.com"
] | scott@q240.com |
0c2ddf58f253bb78ce03ba46d6a488cb9ba2d0a6 | 91a882547e393d4c4946a6c2c99186b5f72122dd | /Source/XPSP1/NT/inetsrv/iis/svcs/smtp/aqueue/advqueue/dcontext.h | 27cf0282df414e2946b542d531cf20c775244e44 | [] | no_license | IAmAnubhavSaini/cryptoAlgorithm-nt5src | 94f9b46f101b983954ac6e453d0cf8d02aa76fc7 | d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2 | refs/heads/master | 2023-09-02T10:14:14.795579 | 2021-11-20T13:47:06 | 2021-11-20T13:47:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,109 | h | //-----------------------------------------------------------------------------
//
//
// File: dcontext.h
//
// Description: Defines stucture referenced by delilvery context HANDLE
// (as returned by HrGetNextMessage). This should only be used inside
// the CMT.
//
// Author: mikeswa
//
// Copyright (C) 1997 Microsoft Corporation
//
//-----------------------------------------------------------------------------
#ifndef _DCONTEXT_H_
#define _DCONTEXT_H_
#include "bitmap.h"
#include "aqueue.h"
class CMsgRef;
class CDestMsgRetryQueue;
#define DELIVERY_CONTEXT_SIG 'txtC'
#define DELIVERY_CONTEXT_FREE 'txt!'
//---[ CDeliveryContext ]------------------------------------------------------
//
//
// Description:
// Context that is used to Ack message after local/remote delivery. The
// memory for this class is either allocated with the connection object
// or on the stack for local delivery.
// Hungarian:
//
//
//-----------------------------------------------------------------------------
class CDeliveryContext
{
public:
CDeliveryContext();
CDeliveryContext(CMsgRef *pmsgref, CMsgBitMap *pmbmap, DWORD cRecips,
DWORD *rgdwRecips, DWORD dwStartDomain, CDestMsgRetryQueue *pdmrq);
~CDeliveryContext();
HRESULT HrAckMessage(IN MessageAck *pMsgAck);
void Init(CMsgRef *pmsgref, CMsgBitMap *pmbmap, DWORD cRecips,
DWORD *rgdwRecips, DWORD dwStartDomain, CDestMsgRetryQueue *pdmrq);
void Recycle();
BOOL FVerifyHandle(IMailMsgProperties *pIMailMsgPropeties);
CDestMsgRetryQueue *pdmrqGetDMRQ() {return m_pdmrq;};
private:
friend class CMsgRef;
DWORD m_dwSignature;
CMsgRef *m_pmsgref; //MsgRef for this context
CMsgBitMap *m_pmbmap; //Bitmap of domains that delivery was attempted for
DWORD m_cRecips; //Number of recips to deliver to
DWORD *m_rgdwRecips; //Array of recip indexes
DWORD m_dwStartDomain; //First domain delivered to
//Retry interface for this delivey attempt
CDestMsgRetryQueue *m_pdmrq;
};
#endif //_DCONTEXT_H_ | [
"support@cryptoalgo.cf"
] | support@cryptoalgo.cf |
d3eaaddf9ab1bbe2e5ac028ccf2c4ab19b5962ac | 0d41ded3833c04ace259c69d59d7b2022a2c848f | /superBitstring.cpp | 4ced1f3c302e8042b8a150482904f1bf33c16a1d | [] | no_license | learnermaxRL/CompCodingSolutionsCPP | ab62b2770962a9dcfcfe1a9cf5739a45fda827ef | 45ea72bd03042bf55ddfbf819946a999848794a8 | refs/heads/master | 2020-06-02T05:25:08.764768 | 2019-06-09T20:24:59 | 2019-06-09T20:24:59 | 191,052,042 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,952 | cpp | #include <bits/stdc++.h>
using namespace std;
string ltrim(const string &);
string rtrim(const string &);
/*
* Complete the 'superBitstrings' function below.
*
* The function is expected to return an INTEGER.
* The function accepts following parameters:
* 1. INTEGER n
* 2. INTEGER_ARRAY bitStrings
*/
const int MAXBITS = 18;
int maxLen;
map<std::string, int> globalMap;
vector<string> split(const string &s, char delim)
{
vector<string> elems;
stringstream ss(s);
string item;
while (getline(ss, item, delim))
elems.push_back(item);
return elems;
}
int PowerSet(vector<int> arr,std::string bitStr)
{
vector<string> list;
int n = arr.size();
for (int i = 0; i < (int)pow(2, n); i++)
{
string subset = "";
for (int j = 0; j < n; j++)
{
if ((i & (1 << j)) != 0)
subset += to_string(arr[j]) + "|";
}
if (find(list.begin(), list.end(), subset) == list.end())
list.push_back(subset);
}
for (string subset : list)
{
string loc = bitStr;
vector<string> arr = split(subset, '|');
for (string str : arr){
loc[std::stoi( str )] = '1';
}
globalMap.insert({loc,0});
}
}
void Permute(int n)
{
bitset<MAXBITS> binN(n);
std::string str_bits = binN.to_string();
str_bits.erase(0, (MAXBITS - maxLen));
vector<int> zeroIndexes;
for (unsigned int i = 0; i < str_bits.length(); i++)
{
if (str_bits.at(i) == '0')
zeroIndexes.push_back(i);
}
PowerSet(zeroIndexes,str_bits);
}
int superBitstrings(int n, vector<int> bitStrings)
{
maxLen = n;
for (auto el:bitStrings){
Permute(el);
}
}
int main()
{
maxLen = 5;
std::vector<int> x{10,26};
superBitstrings(maxLen,x);
std::cout << globalMap.size()<<"\n";
}
| [
"sharma.mayankproacc@gmail.com"
] | sharma.mayankproacc@gmail.com |
cdc5e474c03175edcc3b67a0afb2f03a258fec1c | 8ae7a23f05805fd71d4be13686cf35d8994762ed | /mame150/src/emu/cpu/dsp56k/opcode.h | 5b8492e160193ffb184c361789d178047ac4f97d | [] | no_license | cyberkni/276in1JAMMA | fb06ccc6656fb4346808a24beed8977996da91b2 | d1a68172d4f3490cf7f6e7db25d5dfd4cde3bb22 | refs/heads/master | 2021-01-18T09:38:36.974037 | 2013-10-07T18:30:02 | 2013-10-07T18:30:02 | 13,152,960 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 820 | h | #ifndef __DSP56K_OPCODE_H__
#define __DSP56K_OPCODE_H__
#include "emu.h"
#include "inst.h"
#include "pmove.h"
#include "dsp56k.h"
//
// An Opcode contains an instruction and a parallel move operation.
//
namespace DSP56K
{
class Instruction;
class ParallelMove;
class Opcode
{
public:
Opcode(UINT16 w0, UINT16 w1);
virtual ~Opcode();
astring disassemble() const;
void evaluate(dsp56k_core* cpustate) const;
size_t size() const;
size_t evalSize() const;
// Peek through to the instruction
const reg_id& instSource() const;
const reg_id& instDestination() const;
const size_t instAccumulatorBitsModified() const;
private:
Instruction* m_instruction;
ParallelMove* m_parallelMove;
UINT16 m_word0;
//UINT16 m_word1;
astring dcString() const;
};
}
#endif
| [
"dan@van.derveer.com"
] | dan@van.derveer.com |
499f803f1df7bd3aee5163409547d54190a43384 | b67a780af96a1b70569f81def205f2adbe328292 | /Demo/Graph/UndirectedGraph/Graph/Graph.hpp | 88f788e169fc084b82a2c5fd84b7e9fd39077c4e | [] | no_license | doquanghuy/Algorithm | 8c27933c5c42b4324b39e061c43542adf4a6372b | 4dd63edd823bd0a158034e281c37ef1f6704ec9c | refs/heads/master | 2020-04-13T18:52:44.872226 | 2019-01-16T15:04:48 | 2019-01-16T15:04:48 | 163,387,254 | 0 | 0 | null | 2019-01-16T14:21:06 | 2018-12-28T08:36:31 | null | UTF-8 | C++ | false | false | 533 | hpp | //
// Graph.hpp
// Demo
//
// Created by Quang Huy on 12/18/18.
// Copyright © 2018 Techmaster. All rights reserved.
//
#ifndef Graph_hpp
#define Graph_hpp
#include <stdio.h>
#include <string>
#include "Iterator.hpp"
#include "Bag+LinkedList.hpp"
class StdIn;
class Graph {
public:
Graph(int v);
Graph(StdIn& in);
int V();
int E();
void addEdge(int v, int w);
Iterable<int>* adj(int v);
std:: string toString();
private:
int _V;
int _E;
LinkBag<int>* _adj;
};
#endif /* Graph_hpp */
| [
"sin.do@mobiclixgroup.com"
] | sin.do@mobiclixgroup.com |
55a9f1c1a59c750ece47277e505d01ad2d8b4965 | 90c117760d7ffadf3491f2e61926f8e00049c43c | /sources/supervisor/hal-x64-uefi/src/halmain.cc | 50309e75d91c795e339f0f899c7f1b2c2be15a5c | [] | no_license | twrl/conurbation | 7247897ef25485702f643895c5b3a3fd8a5f599f | af3df283f32050c7f6c67fcdfeb581064372a8ca | refs/heads/master | 2021-01-17T05:14:10.962925 | 2014-11-15T16:24:43 | 2014-11-15T16:24:43 | 24,960,165 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 448 | cc | #include "uefi/tables.h"
#include "stdlib.h"
#include "ConSup/mib.h"
char earlyDataArea[16 * 4096];
uintptr_t wkmib_hal_arch[3] = { 2UL, 1UL, 0UL };
extern "C" void halmain(efi_system_table_t* efiSystemTable) {
init_malloc(earlyDataArea, 16 * 4096);
set_external_alloc(NULL);
ConSup::kernel_root_mib = new ConSup::mib_c::mib_c();
chunk_t ch = {(void*)"x64-uefi", 9 };
ConSup::kernel_root_mib->set(wkmib_hal_arch, &ch);
}
| [
"tomrobbins@gmx.com"
] | tomrobbins@gmx.com |
6549de889c96346581264c81cfb81553a04082e2 | c5a2fdeaf3373d6ec145342c5a6eca327fcfa033 | /include/prnn/detail/matrix/atlas_library.h | da8b6342a069d9dc6de746d2232bdd319645ec7f | [
"Apache-2.0"
] | permissive | Shikherneo2/persistent-rnn | 0945ef7e646cac9bfe9b6f043e6eb8e6fea8de0c | 52a27d94ee51dca8b9270e842fd75b2fa98bd02e | refs/heads/master | 2022-11-29T06:37:13.307945 | 2020-08-14T16:33:00 | 2020-08-14T16:33:00 | 285,027,753 | 1 | 0 | Apache-2.0 | 2020-08-04T15:52:36 | 2020-08-04T15:52:36 | null | UTF-8 | C++ | false | false | 2,592 | h | /* \file AtlasLibrary.h
\date Thursday August 15, 2013
\author Gregory Diamos <solusstultus@gmail.com>
\brief The header file for the AtlasLibrary class.
*/
#pragma once
// Forward Declarations
namespace prnn
{
namespace matrix
{
class AtlasLibrary
{
public:
static const int CblasRowMajor = 101;
static const int CblasColMajor = 102;
static const int CblasNoTrans = 111;
static const int CblasTrans = 112;
static const int CblasConjTrans = 113;
static const int AtlasConj = 114;
static const int CblasUpper = 121;
static const int CblasLower = 122;
static const int CblasNonUnit = 131;
static const int CblasUnit = 132;
static const int CblasLeft = 141;
static const int CblasRight = 142;
public:
static void load();
static bool loaded();
public:
static void sgemm(const int Order, const int TransA,
const int TransB, const int M, const int N,
const int K, const float alpha, const float *A,
const int lda, const float *B, const int ldb,
const float beta, float *C, const int ldc);
static void dgemm(const int Order, const int TransA,
const int TransB, const int M, const int N,
const int K, const double alpha, const double* A,
const int lda, const double* B, const int ldb,
const double beta, double* C, const int ldc);
private:
static void _check();
private:
class Interface
{
public:
void (*cblas_sgemm)(const int Order, const int TransA,
const int TransB, const int M, const int N,
const int K, const float alpha, const float *A,
const int lda, const float *B, const int ldb,
const float beta, float *C, const int ldc);
void (*cblas_dgemm)(const int Order, const int TransA,
const int TransB, const int M, const int N,
const int K, const double alpha, const double *A,
const int lda, const double *B, const int ldb,
const double beta, double *C, const int ldc);
public:
/*! \brief The constructor zeros out all of the pointers */
Interface();
/*! \brief The destructor closes dlls */
~Interface();
/*! \brief Load the library */
void load();
/*! \brief Has the library been loaded? */
bool loaded() const;
/*! \brief unloads the library */
void unload();
private:
void* _library;
bool _failed;
};
private:
static Interface _interface;
};
}
}
| [
"gregory.diamos@gmail.com"
] | gregory.diamos@gmail.com |
72131bb551919056fb0337a827f44319376269c1 | e64da55b139d5747b03f59516c5d22bf9dfa6923 | /LicenseManagerAuthenticator/Authenticator.h | 168630ae9890451775da088c3276d99c5c0f5227 | [
"MIT"
] | permissive | johanlantz/headsetpresenter | b3a71d5a0b644eeb38e295fb5f356a8f69e98562 | 39c5e9740f58d66947e689670500fd0e8b7562c3 | refs/heads/master | 2021-01-23T00:33:58.233753 | 2017-05-30T12:37:02 | 2017-05-30T12:37:02 | 92,816,875 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 288 | h | #pragma once
#include "C:\Projects\LicenseManager\LicenseManager.h"
class Authenticator
{
public:
Authenticator(ILicenseHandler* imyLicenseHandler);
~Authenticator(void);
private:
ILicenseHandler* myLicenseHandler;
public:
bool AuthenticateComponent(void);
int CK;
};
| [
"johan@tid.es"
] | johan@tid.es |
8a435e0b18f7fc47f931f086c3a14169dfeb94a9 | 62addf266b04be24ec89c667a5ba0e3628f1bc50 | /SFML-GameFramework/SFML-GameFramework/Headers/game-state.h | 3573c0d672770bab65720559d5145f804fa02e17 | [] | no_license | JohnLoeffler/C-Projects | 7923a122bec9bbac851e0a2ada079e6a91577603 | a9eb2a7c2b46afbecd672a66b7985fbadf0aa643 | refs/heads/master | 2021-01-15T11:42:30.122056 | 2020-06-15T12:54:44 | 2020-06-15T12:54:44 | 99,633,768 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,238 | h | /*
* This program 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.
*
* Any source code included in this package written by myself, John Loeffler, is
* free to use as-is for any purpose, commercial and non-commercial alike, so
* long as the license & header documentation containing my contact info and
* link to the original source file on Github remains intact.
*
* Any source code included in this package that was written by others maintains
* its own licensing terms that must be followed, and this license in no way
* supersedes that license.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License v 3.0 for more details.
*
* see <https://www.gnu.org/licenses/gpl-3.0.en.html>.
*/
/**
* @file player.hpp
*
* @brief An abstract class from which different GameState Data Structures can be derived
*
* @ingroup game-framework
*
* @author John Loeffler
* <ul>contact:
* <li>John.Loeffler@gmail.com</li>
* <li>JohnLoeffler.com</li>
* <li>Github.com/JohnLoeffler</li>
* <li>LinkedIn.com/in/JohnLoeffler</li>
* </ul>
*/
#ifndef GAMESTATE_HPP
#define GAMESTATE_HPP
#include "../pch.h"
#include "../../SFML/include/SFML/System.hpp"
class GamePlayer;
/**
* @brief Defines the abstract GameState class for Game data objects
*
* While it defaults to just recording a winning player and a score, the GameState can
* be extended to contain all kinds of game data, even making it possible to save a game
* and come back to it later
*/
namespace GameFramework{
class GameState{
public:
/**
* @fn GameState()
* @brief Default Constructor
*/
GameState();
/**
* @fn ~GameState()
* @brief Destructor
*/
virtual ~GameState() = 0;
virtual void HandleEvents() = 0;
virtual void HandleLogic() = 0;
virtual void HandleRendering() = 0;
};
}
#endif // GAMESTATE_HPP
| [
"John.Loeffler@gmail.com"
] | John.Loeffler@gmail.com |
a76e4f2e3b3fde9409549491ee745592e7763323 | 4140d51ba6891469294307d12f18f2ef8121534b | /Kernel/Arch/aarch64/Kernel/irq.cpp | b00b32042cb14d34a13692e5e8321bb71c0a22a5 | [] | no_license | andreas-kleven/AndyOS | 8ff916c17c28dd0728de48b1041eca4e2945da5b | 9a1da06533700d8705f50c8f21622cabacbef0e3 | refs/heads/master | 2021-06-11T05:13:44.074799 | 2020-11-15T20:02:02 | 2020-11-15T20:02:02 | 128,439,100 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 132 | cpp | #include <Arch/irq.h>
namespace IRQ::Arch {
bool Install(int num, void (*handler)())
{
return false;
}
} // namespace IRQ::Arch | [
"andreas.kleven@live.no"
] | andreas.kleven@live.no |
2d9881ee536b02741b4a0b5d2877407ed88be5fd | 7a36a0652fe0704b4b27f644653e7b0f7e72060f | /TianShan/CPE/CPH_CDN/CPH_CDN.h | ef53c9ac614e1a5a8882ff18216c612ca98b0c43 | [] | no_license | darcyg/CXX | 1ee13c1765f1987e293c15b9cbc51ae625ac3a2e | ef288ad0e1624ed0582839f2a5a0ef66073d415e | refs/heads/master | 2020-04-06T04:27:11.940141 | 2016-12-29T03:49:56 | 2016-12-29T03:49:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,974 | h |
#ifndef _RDS_CPH_IMPL_
#define _RDS_CPH_IMPL_
#include "CPHInc.h"
#include "BaseCPH.h"
#include "FileIo.h"
#include "TianShanDefines.h"
#ifdef ZQ_OS_LINUX
#include "PacingInterface.h"
class PacedIndexFactory;
#endif
namespace ZQTianShan{
namespace ContentProvision{
class BaseGraph;
class PushSource;
class BaseTarget;
class FTPMSClientFactory;
class HTTPClientFactory;
}};
class CDNSess : public ZQTianShan::ContentProvision::BaseCPHSession, public ZQTianShan::ContentProvision::BaseGraph
{
public:
CDNSess(ZQTianShan::ContentProvision::BaseCPHelper& helper, const ::TianShanIce::ContentProvision::ProvisionSessionExPtr& pSess)
: BaseCPHSession(helper, pSess),
_filesize(0), _bQuit(false)
{
_bCleaned = false;
_pMainTarget = NULL;
_bStartEventSent = false;
_pRTFProc = NULL;
#ifdef ZQ_OS_LINUX
_bSuccessMount = false;
_sharePath = "";
#endif
}
virtual ~CDNSess();
public:
virtual bool preLoad();
virtual bool prime();
virtual void terminate(bool bProvisionSuccess=true);
virtual bool getProgress(::Ice::Long& offset, ::Ice::Long& total);
virtual void OnProgress(int64& prcvBytes);
virtual void OnStreamable(bool bStreamable);
virtual void OnMediaInfoParsed(ZQTianShan::ContentProvision::MediaInfo& mInfo);
protected:
// impl of ThreadRequest
virtual int run(void);
virtual void final(int retcode =0, bool bCancelled =false);
protected:
void cleanup();
bool _bPushTrigger;
int _bitrate;
bool _bStartEventSent;
std::string _strMethod;
int _nBandwidth;
::Ice::Long _filesize, _processed;
bool _bQuit;
bool _bCleaned;
ZQTianShan::ContentProvision::BaseTarget* _pMainTarget; //main target that will send streamable event
ZQTianShan::ContentProvision::BaseProcess* _pRTFProc; //the rtf process
public:
static std::auto_ptr<ZQTianShan::ContentProvision::FileIoFactory> _pFileIoFac;
static ZQTianShan::ContentProvision::FTPMSClientFactory* _pFTPClientFactory;
static ZQTianShan::ContentProvision::HTTPClientFactory* _pHttpClientFactory;
#ifdef ZQ_OS_LINUX
static PacedIndexFactory* _pPacedIndexFac;
static void* _pPacedIndexDll;
bool _bSuccessMount;
std::string _sharePath;
#endif
};
class MethodCostI : public ZQTianShan::ContentProvision::MethodCost
{
public:
/// evaluate the cost per given session count and total allocated bandwidth
///@param[in] bandwidthKbps to specify the allocated bandwidth in Kbps
///@param[in] sessions to specify the allocated session instances
///@return a cost in the range of [0, MAX_LOAD_VALUE] at the given load level:
/// 0 - fully available
/// MAX_LOAD_VALUE - completely unavailable
virtual unsigned int evaluateCost(unsigned int bandwidthKbps, unsigned int sessions)
{
if (sessions >_maxsessionNum)
return MAX_LOAD_VALUE + 1;
if(bandwidthKbps > _maxBandwidthKBps)
return MAX_LOAD_VALUE + 1;
int nCost1 = (int)(((float)bandwidthKbps)/_maxBandwidthKBps)*MAX_LOAD_VALUE;
int nCost2 = (int)(((float)sessions)/_maxsessionNum)*MAX_LOAD_VALUE;
return max(nCost1, nCost2);
}
MethodCostI(unsigned int maxBandwidthKBps, unsigned int maxsessionNum)
{
_maxsessionNum = maxsessionNum;
_maxBandwidthKBps = maxBandwidthKBps;
}
virtual std::string getCategory()
{
return "CPH_CDN";
}
protected:
unsigned int _maxsessionNum;
unsigned int _maxBandwidthKBps;
};
class CDNHelper : public ZQTianShan::ContentProvision::BaseCPHelper
{
public:
CDNHelper(ZQ::common::NativeThreadPool& pool, ZQTianShan::ContentProvision::ICPHManager* mgr);
virtual ~CDNHelper();
static ZQTianShan::ContentProvision::BaseCPHelper* _theHelper;
public: // impl of ICPHelper
///validate a potential ProvisionSession about to setup
///@param[in] sess access to the ProvisionSession about to setup
///@param[out] schema the collection of schema definition
///@return true if succeeded
virtual bool validateSetup(::TianShanIce::ContentProvision::ProvisionSessionExPtr sess)
throw (::TianShanIce::InvalidParameter, ::TianShanIce::SRM::InvalidResource);
virtual bool getBandwidthLoad(const char* methodType, long& bpsAllocated, long& bpsMax, long& initCost);
/// query the current load information of a method type
///@param[in] methodType to specify the method type to query
///@param[out] allocatedKbps the current allocated bandwidth in Kbps
///@param[out] maxKbps the maximal allowed bandwidth in Kbps, -1 if unlimited
///@param[out] sessions the current running session instances
///@param[out] maxSessins the maximal allowed session instances, -1 if unlimited
///@return true if the query succeeded
virtual bool getLoad(const char* methodType, uint32& allocatedKbps, uint32& maxKbps, uint& sessions, uint& maxSessins);
virtual ZQTianShan::ContentProvision::MethodCost* getMethodCost(const std::string& methodType)
{
MethodCostList::iterator it = _methodCostList.find(methodType);
if (it==_methodCostList.end())
return NULL;
return it->second;
}
virtual ZQTianShan::ContentProvision::ICPHSession* createHelperSession(const char* methodType, const ::TianShanIce::ContentProvision::ProvisionSessionExPtr& pSess)
{
if (NULL == methodType || (stricmp(METHODTYPE_CDN_FTPPropagation, methodType)&&
stricmp(METHODTYPE_CDN_FTPRTF, methodType)&&
stricmp(METHODTYPE_CDN_FTPRTFH264, methodType))&&
stricmp(METHODTYPE_CDN_NTFSRTF, methodType)&&
stricmp(METHODTYPE_CDN_NTFSRTFH264, methodType)&&
stricmp(METHODTYPE_CDN_C2Pull, methodType)&&
stricmp(METHODTYPE_CDN_C2PullH264, methodType)&&
stricmp(METHODTYPE_CDN_HTTPPropagation, methodType))
return NULL;
return new CDNSess(*this, pSess);
}
protected:
typedef std::map<std::string, MethodCostI*> MethodCostList;
MethodCostList _methodCostList;
};
#endif
| [
"jjz@example.com"
] | jjz@example.com |
c2ae72ca1e9aa4d9ac8e7705c43e33a41dd54b4a | b199446448f7f1f736a06d9097efb1e84375ee4c | /src/UI/Window.cpp | a6274b8ec2e50ef53128acacb416d06a927aa6bb | [] | no_license | leaker28/GoL-SDL | 2b60059fee8031ffcb9006288338e5db4bbd7df0 | 67f80af4240902b46fa9339f2fa0c1fd9038dab3 | refs/heads/master | 2022-10-12T15:36:41.705982 | 2018-11-23T17:57:25 | 2018-11-23T17:57:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 737 | cpp | //
// Window.cpp
// sdl test
//
// Created by Richard on 14/08/2018.
// Copyright © 2018 Richard. All rights reserved.
//
#include "Window.h"
Window::Window(int x, int y, int w, int h) : Control(x, y, w, h)
{
//printf("%dx%d - %d %d\n", x, y, w, h);
_bgColour = {0, 255, 255};
}
void Window::onDraw(SDL_Renderer* ren)
{
//printf("xdxdxdxd");
r = this->_bgColour.r;
g = this->_bgColour.g;
b = this->_bgColour.b;
SDL_SetRenderDrawColor(ren, r, g, b, 255);
SDL_RenderFillRect(ren, &box);
return;
}
/*
void Window::setBGColour(SDL_Color col)
{
_bgColour.r = col.r;
_bgColour.g = col.g;
_bgColour.b = col.b;
printf("%d %d %d\n", col.r, col.g, col.b);
}
*/
| [
"richard@hackintosh.local"
] | richard@hackintosh.local |
7cdb0c5264b82f359c9dd6877ee19bf2fda69983 | 7e61f0b1e32de858ec5e3cde3141d4f0eec10c1a | /Paranoia2.PreAlpha/src_main/mainui/menu_loadgame.cpp | 54f37e06d90024cc89b7c66c45ade915543263b5 | [] | no_license | HLSources/Paranoia2_ancient | adac519017b9da7dd7ae62ea4e841b3bfeb045dd | e3101e57c5c3eecfb13ad1d8597d5208487f98b4 | refs/heads/master | 2022-01-14T07:19:50.089119 | 2019-07-23T10:43:56 | 2019-07-23T10:43:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,026 | cpp | /*
Copyright (C) 1997-2001 Id Software, Inc.
This program 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 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "extdll.h"
#include "basemenu.h"
#include "utils.h"
#include "keydefs.h"
#include "menu_btnsbmp_table.h"
#define ART_BANNER "gfx/shell/head_load"
#define ID_BACKGROUND 0
#define ID_BANNER 1
#define ID_LOAD 2
#define ID_DELETE 3
#define ID_CANCEL 4
#define ID_SAVELIST 5
#define ID_TABLEHINT 6
#define ID_LEVELSHOT 7
#define ID_MSGBOX 8
#define ID_MSGTEXT 9
#define ID_YES 130
#define ID_NO 131
#define LEVELSHOT_X 72
#define LEVELSHOT_Y 400
#define LEVELSHOT_W 192
#define LEVELSHOT_H 160
#define TIME_LENGTH 20
#define NAME_LENGTH 32+TIME_LENGTH
#define GAMETIME_LENGTH 15+NAME_LENGTH
typedef struct
{
char saveName[UI_MAXGAMES][CS_SIZE];
char delName[UI_MAXGAMES][CS_SIZE];
char saveDescription[UI_MAXGAMES][95];
char *saveDescriptionPtr[UI_MAXGAMES];
menuFramework_s menu;
menuBitmap_s background;
menuBitmap_s banner;
menuPicButton_s load;
menuPicButton_s remove;
menuPicButton_s cancel;
menuScrollList_s savesList;
menuBitmap_s levelShot;
menuAction_s hintMessage;
char hintText[MAX_HINT_TEXT];
// prompt dialog
menuAction_s msgBox;
menuAction_s promptMessage;
menuPicButton_s yes;
menuPicButton_s no;
} uiLoadGame_t;
static uiLoadGame_t uiLoadGame;
/*
=================
UI_MsgBox_Ownerdraw
=================
*/
static void UI_MsgBox_Ownerdraw( void *self )
{
menuCommon_s *item = (menuCommon_s *)self;
UI_FillRect( item->x, item->y, item->width, item->height, uiPromptBgColor );
}
static void UI_DeleteDialog( void )
{
// toggle main menu between active\inactive
// show\hide remove dialog
uiLoadGame.load.generic.flags ^= QMF_INACTIVE;
uiLoadGame.remove.generic.flags ^= QMF_INACTIVE;
uiLoadGame.cancel.generic.flags ^= QMF_INACTIVE;
uiLoadGame.savesList.generic.flags ^= QMF_INACTIVE;
uiLoadGame.msgBox.generic.flags ^= QMF_HIDDEN;
uiLoadGame.promptMessage.generic.flags ^= QMF_HIDDEN;
uiLoadGame.no.generic.flags ^= QMF_HIDDEN;
uiLoadGame.yes.generic.flags ^= QMF_HIDDEN;
}
/*
=================
UI_LoadGame_KeyFunc
=================
*/
static const char *UI_LoadGame_KeyFunc( int key, int down )
{
if( down && key == K_ESCAPE && uiLoadGame.load.generic.flags & QMF_INACTIVE )
{
UI_DeleteDialog();
return uiSoundNull;
}
return UI_DefaultKey( &uiLoadGame.menu, key, down );
}
/*
=================
UI_LoadGame_GetGameList
=================
*/
static void UI_LoadGame_GetGameList( void )
{
char comment[256];
char **filenames;
int i, numFiles;
filenames = FS_SEARCH( "save/*.sav", &numFiles, TRUE );
// sort the saves in reverse order (oldest past at the end)
qsort( filenames, numFiles, sizeof( char* ), (cmpfunc)COM_CompareSaves );
for ( i = 0; i < numFiles; i++ )
{
if( i >= UI_MAXGAMES ) break;
if( !GET_SAVE_COMMENT( filenames[i], comment ))
{
if( strlen( comment ))
{
// get name string even if not found - SV_GetComment can be mark saves
// as <CORRUPTED> <OLD VERSION> etc
StringConcat( uiLoadGame.saveDescription[i], uiEmptyString, TIME_LENGTH );
StringConcat( uiLoadGame.saveDescription[i], comment, NAME_LENGTH );
StringConcat( uiLoadGame.saveDescription[i], uiEmptyString, NAME_LENGTH );
uiLoadGame.saveDescriptionPtr[i] = uiLoadGame.saveDescription[i];
COM_FileBase( filenames[i], uiLoadGame.delName[i] );
}
else uiLoadGame.saveDescriptionPtr[i] = NULL;
continue;
}
// strip path, leave only filename (empty slots doesn't have savename)
COM_FileBase( filenames[i], uiLoadGame.saveName[i] );
COM_FileBase( filenames[i], uiLoadGame.delName[i] );
// fill save desc
StringConcat( uiLoadGame.saveDescription[i], comment + CS_SIZE, TIME_LENGTH );
StringConcat( uiLoadGame.saveDescription[i], " ", TIME_LENGTH );
StringConcat( uiLoadGame.saveDescription[i], comment + CS_SIZE + CS_TIME, TIME_LENGTH );
StringConcat( uiLoadGame.saveDescription[i], uiEmptyString, TIME_LENGTH ); // fill remaining entries
StringConcat( uiLoadGame.saveDescription[i], comment, NAME_LENGTH );
StringConcat( uiLoadGame.saveDescription[i], uiEmptyString, NAME_LENGTH );
StringConcat( uiLoadGame.saveDescription[i], comment + CS_SIZE + (CS_TIME * 2), GAMETIME_LENGTH );
StringConcat( uiLoadGame.saveDescription[i], uiEmptyString, GAMETIME_LENGTH );
uiLoadGame.saveDescriptionPtr[i] = uiLoadGame.saveDescription[i];
}
for ( ; i < UI_MAXGAMES; i++ )
uiLoadGame.saveDescriptionPtr[i] = NULL;
uiLoadGame.savesList.itemNames = (const char **)uiLoadGame.saveDescriptionPtr;
if ( strlen( uiLoadGame.saveName[0] ) == 0 )
uiLoadGame.load.generic.flags |= QMF_GRAYED;
else uiLoadGame.load.generic.flags &= ~QMF_GRAYED;
if ( strlen( uiLoadGame.delName[0] ) == 0 )
uiLoadGame.remove.generic.flags |= QMF_GRAYED;
else uiLoadGame.remove.generic.flags &= ~QMF_GRAYED;
}
/*
=================
UI_LoadGame_Callback
=================
*/
static void UI_LoadGame_Callback( void *self, int event )
{
menuCommon_s *item = (menuCommon_s *)self;
if( event == QM_CHANGED )
{
if( strlen( uiLoadGame.saveName[uiLoadGame.savesList.curItem] ) == 0 )
uiLoadGame.load.generic.flags |= QMF_GRAYED;
else uiLoadGame.load.generic.flags &= ~QMF_GRAYED;
if( strlen( uiLoadGame.delName[uiLoadGame.savesList.curItem] ) == 0 )
uiLoadGame.remove.generic.flags |= QMF_GRAYED;
else uiLoadGame.remove.generic.flags &= ~QMF_GRAYED;
return;
}
if( event != QM_ACTIVATED )
return;
switch( item->id )
{
case ID_CANCEL:
UI_PopMenu();
break;
case ID_LOAD:
if( strlen( uiLoadGame.saveName[uiLoadGame.savesList.curItem] ))
{
char cmd[128];
sprintf( cmd, "load \"%s\"\n", uiLoadGame.saveName[uiLoadGame.savesList.curItem] );
CLIENT_COMMAND( FALSE, cmd );
}
break;
case ID_NO:
case ID_DELETE:
UI_DeleteDialog();
break;
case ID_YES:
if( strlen( uiLoadGame.delName[uiLoadGame.savesList.curItem] ))
{
char cmd[128];
sprintf( cmd, "killsave \"%s\"\n", uiLoadGame.delName[uiLoadGame.savesList.curItem] );
CLIENT_COMMAND( TRUE, cmd );
sprintf( cmd, "save/%s.bmp", uiLoadGame.delName[uiLoadGame.savesList.curItem] );
PIC_Free( cmd );
// restarts the menu
UI_PopMenu();
UI_LoadGame_Menu();
return;
}
UI_DeleteDialog();
break;
}
}
/*
=================
UI_LoadGame_Ownerdraw
=================
*/
static void UI_LoadGame_Ownerdraw( void *self )
{
menuCommon_s *item = (menuCommon_s *)self;
if( item->type != QMTYPE_ACTION && item->id == ID_LEVELSHOT )
{
int x, y, w, h;
// draw the levelshot
x = LEVELSHOT_X;
y = LEVELSHOT_Y;
w = LEVELSHOT_W;
h = LEVELSHOT_H;
UI_ScaleCoords( &x, &y, &w, &h );
if( strlen( uiLoadGame.saveName[uiLoadGame.savesList.curItem] ))
{
char saveshot[128];
sprintf( saveshot, "save/%s.bmp", uiLoadGame.saveName[uiLoadGame.savesList.curItem] );
if( !FILE_EXISTS( saveshot ))
UI_DrawPicAdditive( x, y, w, h, uiColorWhite, "gfx/empty.tga" );
else UI_DrawPic( x, y, w, h, uiColorWhite, saveshot );
}
else UI_DrawPicAdditive( x, y, w, h, uiColorWhite, "gfx/empty.tga" );
// draw the rectangle
UI_DrawRectangle( item->x, item->y, item->width, item->height, uiInputFgColor );
}
}
/*
=================
UI_LoadGame_Init
=================
*/
static void UI_LoadGame_Init( void )
{
memset( &uiLoadGame, 0, sizeof( uiLoadGame_t ));
uiLoadGame.menu.vidInitFunc = UI_LoadGame_Init;
uiLoadGame.menu.keyFunc = UI_LoadGame_KeyFunc;
StringConcat( uiLoadGame.hintText, "Time", TIME_LENGTH );
StringConcat( uiLoadGame.hintText, uiEmptyString, TIME_LENGTH );
StringConcat( uiLoadGame.hintText, "Game", NAME_LENGTH );
StringConcat( uiLoadGame.hintText, uiEmptyString, NAME_LENGTH );
StringConcat( uiLoadGame.hintText, "Elapsed time", GAMETIME_LENGTH );
StringConcat( uiLoadGame.hintText, uiEmptyString, GAMETIME_LENGTH );
uiLoadGame.background.generic.id = ID_BACKGROUND;
uiLoadGame.background.generic.type = QMTYPE_BITMAP;
uiLoadGame.background.generic.flags = QMF_INACTIVE;
uiLoadGame.background.generic.x = 0;
uiLoadGame.background.generic.y = 0;
uiLoadGame.background.generic.width = 1024;
uiLoadGame.background.generic.height = 768;
uiLoadGame.background.pic = ART_BACKGROUND;
uiLoadGame.banner.generic.id = ID_BANNER;
uiLoadGame.banner.generic.type = QMTYPE_BITMAP;
uiLoadGame.banner.generic.flags = QMF_INACTIVE|QMF_DRAW_ADDITIVE;
uiLoadGame.banner.generic.x = UI_BANNER_POSX;
uiLoadGame.banner.generic.y = UI_BANNER_POSY;
uiLoadGame.banner.generic.width = UI_BANNER_WIDTH;
uiLoadGame.banner.generic.height = UI_BANNER_HEIGHT;
uiLoadGame.banner.pic = ART_BANNER;
uiLoadGame.load.generic.id = ID_LOAD;
uiLoadGame.load.generic.type = QMTYPE_BM_BUTTON;
uiLoadGame.load.generic.flags = QMF_HIGHLIGHTIFFOCUS|QMF_DROPSHADOW;
uiLoadGame.load.generic.x = 72;
uiLoadGame.load.generic.y = 230;
uiLoadGame.load.generic.name = "Load";
uiLoadGame.load.generic.statusText = "Load saved game";
uiLoadGame.load.generic.callback = UI_LoadGame_Callback;
UI_UtilSetupPicButton( &uiLoadGame.load, PC_LOAD_GAME );
uiLoadGame.remove.generic.id = ID_DELETE;
uiLoadGame.remove.generic.type = QMTYPE_BM_BUTTON;
uiLoadGame.remove.generic.flags = QMF_HIGHLIGHTIFFOCUS|QMF_DROPSHADOW;
uiLoadGame.remove.generic.x = 72;
uiLoadGame.remove.generic.y = 280;
uiLoadGame.remove.generic.name = "Delete";
uiLoadGame.remove.generic.statusText = "Delete saved game";
uiLoadGame.remove.generic.callback = UI_LoadGame_Callback;
UI_UtilSetupPicButton( &uiLoadGame.remove, PC_DELETE );
uiLoadGame.cancel.generic.id = ID_CANCEL;
uiLoadGame.cancel.generic.type = QMTYPE_BM_BUTTON;
uiLoadGame.cancel.generic.flags = QMF_HIGHLIGHTIFFOCUS|QMF_DROPSHADOW;
uiLoadGame.cancel.generic.x = 72;
uiLoadGame.cancel.generic.y = 330;
uiLoadGame.cancel.generic.name = "Cancel";
uiLoadGame.cancel.generic.statusText = "Return back to main menu";
uiLoadGame.cancel.generic.callback = UI_LoadGame_Callback;
UI_UtilSetupPicButton( &uiLoadGame.cancel, PC_CANCEL );
uiLoadGame.hintMessage.generic.id = ID_TABLEHINT;
uiLoadGame.hintMessage.generic.type = QMTYPE_ACTION;
uiLoadGame.hintMessage.generic.flags = QMF_INACTIVE|QMF_SMALLFONT;
uiLoadGame.hintMessage.generic.color = uiColorHelp;
uiLoadGame.hintMessage.generic.name = uiLoadGame.hintText;
uiLoadGame.hintMessage.generic.x = 360;
uiLoadGame.hintMessage.generic.y = 225;
uiLoadGame.levelShot.generic.id = ID_LEVELSHOT;
uiLoadGame.levelShot.generic.type = QMTYPE_BITMAP;
uiLoadGame.levelShot.generic.flags = QMF_INACTIVE;
uiLoadGame.levelShot.generic.x = LEVELSHOT_X;
uiLoadGame.levelShot.generic.y = LEVELSHOT_Y;
uiLoadGame.levelShot.generic.width = LEVELSHOT_W;
uiLoadGame.levelShot.generic.height = LEVELSHOT_H;
uiLoadGame.levelShot.generic.ownerdraw = UI_LoadGame_Ownerdraw;
uiLoadGame.savesList.generic.id = ID_SAVELIST;
uiLoadGame.savesList.generic.type = QMTYPE_SCROLLLIST;
uiLoadGame.savesList.generic.flags = QMF_HIGHLIGHTIFFOCUS|QMF_DROPSHADOW|QMF_SMALLFONT;
uiLoadGame.savesList.generic.x = 360;
uiLoadGame.savesList.generic.y = 255;
uiLoadGame.savesList.generic.width = 640;
uiLoadGame.savesList.generic.height = 440;
uiLoadGame.savesList.generic.callback = UI_LoadGame_Callback;
uiLoadGame.msgBox.generic.id = ID_MSGBOX;
uiLoadGame.msgBox.generic.type = QMTYPE_ACTION;
uiLoadGame.msgBox.generic.flags = QMF_INACTIVE|QMF_HIDDEN;
uiLoadGame.msgBox.generic.ownerdraw = UI_MsgBox_Ownerdraw; // just a fill rectangle
uiLoadGame.msgBox.generic.x = 192;
uiLoadGame.msgBox.generic.y = 256;
uiLoadGame.msgBox.generic.width = 640;
uiLoadGame.msgBox.generic.height = 256;
uiLoadGame.promptMessage.generic.id = ID_MSGBOX;
uiLoadGame.promptMessage.generic.type = QMTYPE_ACTION;
uiLoadGame.promptMessage.generic.flags = QMF_INACTIVE|QMF_DROPSHADOW|QMF_HIDDEN;
uiLoadGame.promptMessage.generic.name = "Delete selected game?";
uiLoadGame.promptMessage.generic.x = 315;
uiLoadGame.promptMessage.generic.y = 280;
uiLoadGame.yes.generic.id = ID_YES;
uiLoadGame.yes.generic.type = QMTYPE_BM_BUTTON;
uiLoadGame.yes.generic.flags = QMF_HIGHLIGHTIFFOCUS|QMF_DROPSHADOW|QMF_HIDDEN;
uiLoadGame.yes.generic.name = "Ok";
uiLoadGame.yes.generic.x = 380;
uiLoadGame.yes.generic.y = 460;
uiLoadGame.yes.generic.callback = UI_LoadGame_Callback;
UI_UtilSetupPicButton( &uiLoadGame.yes, PC_OK );
uiLoadGame.no.generic.id = ID_NO;
uiLoadGame.no.generic.type = QMTYPE_BM_BUTTON;
uiLoadGame.no.generic.flags = QMF_HIGHLIGHTIFFOCUS|QMF_DROPSHADOW|QMF_HIDDEN;
uiLoadGame.no.generic.name = "Cancel";
uiLoadGame.no.generic.x = 530;
uiLoadGame.no.generic.y = 460;
uiLoadGame.no.generic.callback = UI_LoadGame_Callback;
UI_UtilSetupPicButton( &uiLoadGame.no, PC_CANCEL );
UI_LoadGame_GetGameList();
UI_AddItem( &uiLoadGame.menu, (void *)&uiLoadGame.background );
UI_AddItem( &uiLoadGame.menu, (void *)&uiLoadGame.banner );
UI_AddItem( &uiLoadGame.menu, (void *)&uiLoadGame.load );
UI_AddItem( &uiLoadGame.menu, (void *)&uiLoadGame.remove );
UI_AddItem( &uiLoadGame.menu, (void *)&uiLoadGame.cancel );
UI_AddItem( &uiLoadGame.menu, (void *)&uiLoadGame.hintMessage );
UI_AddItem( &uiLoadGame.menu, (void *)&uiLoadGame.levelShot );
UI_AddItem( &uiLoadGame.menu, (void *)&uiLoadGame.savesList );
UI_AddItem( &uiLoadGame.menu, (void *)&uiLoadGame.msgBox );
UI_AddItem( &uiLoadGame.menu, (void *)&uiLoadGame.promptMessage );
UI_AddItem( &uiLoadGame.menu, (void *)&uiLoadGame.no );
UI_AddItem( &uiLoadGame.menu, (void *)&uiLoadGame.yes );
}
/*
=================
UI_LoadGame_Precache
=================
*/
void UI_LoadGame_Precache( void )
{
PIC_Load( ART_BACKGROUND );
PIC_Load( ART_BANNER );
}
/*
=================
UI_LoadGame_Menu
=================
*/
void UI_LoadGame_Menu( void )
{
if( gMenu.m_gameinfo.gamemode == GAME_MULTIPLAYER_ONLY )
{
// completely ignore save\load menus for multiplayer_only
return;
}
if( !CheckGameDll( )) return;
UI_LoadGame_Precache();
UI_LoadGame_Init();
UI_PushMenu( &uiLoadGame.menu );
} | [
"a1ba.omarov@gmail.com"
] | a1ba.omarov@gmail.com |
7205183c46d7c80e37dd5253ab899e4e7eb43127 | 095d4ee0d2f80b6c1ee5629e15641d96d11ac92f | /LAB9/heap.cpp | 5779fdafcdcee27b50236f3014264690d90c796d | [] | no_license | RaghavMittal02/ADS | 580a48d9d0690c44be81756d6d4c860fcbe49139 | 43f820b13e4395558db074f576e09d03f9151b97 | refs/heads/master | 2023-02-06T10:32:05.271169 | 2020-12-29T13:40:33 | 2020-12-29T13:40:33 | 296,284,387 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,020 | cpp | #include<bits/stdc++.h>
using namespace std;
struct Node
{
int data, degree;
Node *child, *sibling, *parent;
};
Node* newNode(int key)
{
Node *temp = new Node;
temp->data = key;
temp->degree = 0;
temp->child = temp->parent = temp->sibling = NULL;
return temp;
}
Node* mergeBinomialTrees(Node *b1, Node *b2)
{
if (b1->data > b2->data)
swap(b1, b2);
b2->parent = b1;
b2->sibling = b1->child;
b1->child = b2;
b1->degree++;
return b1;
}
list<Node*> unionBionomialHeap(list<Node*> l1, list<Node*> l2)
{
list<Node*> _new;
list<Node*>::iterator it = l1.begin();
list<Node*>::iterator ot = l2.begin();
while (it!=l1.end() && ot!=l2.end())
{
if((*it)->degree <= (*ot)->degree)
{
_new.push_back(*it);
it++;
}
else
{
_new.push_back(*ot);
ot++;
}
}
while (it != l1.end())
{
_new.push_back(*it);
it++;
}
while (ot!=l2.end())
{
_new.push_back(*ot);
ot++;
}
return _new;
}
list<Node*> adjust(list<Node*> _heap)
{
if (_heap.size() <= 1)
return _heap;
list<Node*> new_heap;
list<Node*>::iterator it1,it2,it3;
it1 = it2 = it3 = _heap.begin();
if (_heap.size() == 2)
{
it2 = it1;
it2++;
it3 = _heap.end();
}
else
{
it2++;
it3=it2;
it3++;
}
while (it1 != _heap.end())
{
if (it2 == _heap.end())
it1++;
else if ((*it1)->degree < (*it2)->degree)
{
it1++;
it2++;
if(it3!=_heap.end())
it3++;
}
else if (it3!=_heap.end() &&
(*it1)->degree == (*it2)->degree &&
(*it1)->degree == (*it3)->degree)
{
it1++;
it2++;
it3++;
}
else if ((*it1)->degree == (*it2)->degree)
{
Node *temp;
*it1 = mergeBinomialTrees(*it1,*it2);
it2 = _heap.erase(it2);
if(it3 != _heap.end())
it3++;
}
}
return _heap;
}
list<Node*> insertATreeInHeap(list<Node*> _heap, Node *tree)
{
list<Node*> temp;
temp.push_back(tree);
temp = unionBionomialHeap(_heap,temp);
return adjust(temp);
}
list<Node*> removeMinFromTreeReturnBHeap(Node *tree)
{
list<Node*> heap;
Node *temp = tree->child;
Node *lo;
while (temp)
{
lo = temp;
temp = temp->sibling;
lo->sibling = NULL;
heap.push_front(lo);
}
return heap;
}
list<Node*> insert(list<Node*> _head, int key)
{
Node *temp = newNode(key);
return insertATreeInHeap(_head,temp);
}
Node* getMin(list<Node*> _heap)
{
list<Node*>::iterator it = _heap.begin();
Node *temp = *it;
while (it != _heap.end())
{
if ((*it)->data < temp->data)
temp = *it;
it++;
}
return temp;
}
list<Node*> extractMin(list<Node*> _heap)
{
list<Node*> new_heap,lo;
Node *temp;
temp = getMin(_heap);
list<Node*>::iterator it;
it = _heap.begin();
while (it != _heap.end())
{
if (*it != temp)
{
new_heap.push_back(*it);
}
it++;
}
lo = removeMinFromTreeReturnBHeap(temp);
new_heap = unionBionomialHeap(new_heap,lo);
new_heap = adjust(new_heap);
return new_heap;
}
void printTree(Node *h)
{
while (h)
{
cout << h->data << " ";
printTree(h->child);
h = h->sibling;
}
}
void printHeap(list<Node*> _heap)
{
list<Node*> ::iterator it;
it = _heap.begin();
while (it != _heap.end())
{
printTree(*it);
it++;
}
}
int main()
{
int key,n;
list<Node*> _heap;
cout<<"Enter number of elements: ";
cin>>n;
for(int i =0;i<n;i++){
cout<<"\nEnter key: ";
cin>>key;
_heap = insert(_heap,key);
}
cout << "\nHeap elements after insertion:\n";
printHeap(_heap);
Node *temp = getMin(_heap);
cout << "\n\nMinimum element of heap " << temp->data << "\n";
_heap = extractMin(_heap);
cout << "\nHeap after deletion of minimum element\n";
printHeap(_heap);
return 0;
} | [
"noreply@github.com"
] | noreply@github.com |
888a447b806f64f8482e878366456ea80e98c8fc | ea695b4b91bef72927df32421855b688a53f61bd | /grafy/scc.cc | b8d4c330615ddc3dc74b5f1d6dd005fa3af686cf | [] | no_license | Arthoom/algorithms | 15f6297c8c1ae5bcb49a4e8110717ca18805924d | c616df9478cfaf1f2bd6616f08143429b829fcc7 | refs/heads/master | 2021-07-24T16:45:07.608137 | 2018-02-20T18:41:16 | 2018-02-20T18:41:16 | 95,791,564 | 0 | 1 | null | 2022-08-01T17:59:31 | 2017-06-29T15:24:49 | C++ | UTF-8 | C++ | false | false | 1,168 | cc | class SCC {
VVI &G, rev_G;
int num_of_groups;
VB vis;
VI quit_order;
void quit_order_DFS(int v) {
vis[v] = 1;
for(int u : rev_G[v])
if(!vis[u])
quit_order_DFS(u);
quit_order.EB(v);
}
VI group;
void group_DFS(int v, int gr) {
vis[v] = 1;
group[v] = gr;
for(int u : G[v])
if(!vis[u])
group_DFS(u, gr);
}
public:
SCC(VVI &Graph) : G(Graph) {
int n = SZ(G);
rev_G.RS(n);
REP(v, n)
for(int u : G[v])
rev_G[u].EB(v);
DUMP(rev_G);
vis.RS(n);
REP(v, n)
if(!vis[v])
quit_order_DFS(v);
reverse(ALL(quit_order));
DUMP(quit_order);
fill(ALL(vis), 0);
group.RS(n);
int curr_gr = 0;
for(int v : quit_order)
if(!vis[v])
group_DFS(v, curr_gr++);
num_of_groups = curr_gr;
}
VI get_groups() { return group; }
int get_num_of_groups() { return num_of_groups; }
void set(VI &gr, int &num_gr) { gr = group; num_gr = num_of_groups; }
};
| [
"noreply@github.com"
] | noreply@github.com |
7c839c382b7d809fb94f9e27f3383c4b282a9794 | c9568c132fdffe264e93e9488d3881720f767024 | /src/ParallelRayTracer/macros.h | 0c14a15dc51cce5bba3b28d556e689fa40c9a8bf | [] | no_license | HenryPeacock/GCP | f12fb9bcc5133aafbdfc2fc932ec9b98e0214096 | 462e49c10543ba59494344b6c4bc1dd7a2590df3 | refs/heads/master | 2020-09-13T10:09:52.009303 | 2020-01-10T04:05:07 | 2020-01-10T04:05:07 | 222,736,950 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 174 | h | #pragma once
#ifndef MACROS_H
#define MACROS_H
#include <memory>
#define shared std::shared_ptr
#define weak std::weak_ptr
#define makesh std::make_shared
#endif | [
"henster23@hotmail.co.uk"
] | henster23@hotmail.co.uk |
eddb68d886f0591c45880a4e4c8f491677248c62 | f20c305c035034338052709c76a502e497ec66d8 | /iphdr.h | 9b6643ad5172e62b974c8793abe4d3448b24f4f0 | [] | no_license | jise8893/arp-spoofing-modified | 851b77e2c86109b88f4ea16dd8a65a67d66a615f | a8d9c694c7177d06192ba1cd4a964b8da103c72a | refs/heads/master | 2022-11-30T05:30:42.700631 | 2020-08-12T01:58:53 | 2020-08-12T01:58:53 | 286,890,534 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 437 | h | #include <cstdint>
#include <arpa/inet.h>
#ifndef IPHDR_H
#define IPHDR_H
#endif // IPHDR_H
struct IpHdr final {
uint8_t ip_hl:4,ip_v:4;
uint8_t tos;
uint16_t ip_len; /* total length */
uint16_t ip_id; /* identification */
uint16_t ip_off;
uint8_t ip_ttl; /* time to live */
uint8_t ip_p; /* protocol */
uint16_t ip_sum;
uint32_t ip_src;
uint32_t ip_dst;
};
| [
"js8893@naver.com"
] | js8893@naver.com |
3ce60eb1493e393f3466d1a986c22657bb4cd199 | 9ac21814f155794cb5a82d4d93bdef7d67a5158e | /StudyData/백준/17408(수열과 쿼리 24).cpp | 315bdf2cd85bc366aea74926131bff3c3b1fb0be | [] | no_license | MarbinSpectrum/Algorithm- | d71c69bbcc0b8c7573c75d25c3e0b31b6540309a | 5a06eadeaa771cbe70328b9f6d83e61bb4975053 | refs/heads/master | 2023-07-06T19:29:02.890491 | 2023-07-03T00:53:51 | 2023-07-03T00:53:51 | 188,868,476 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,471 | cpp | #include<iostream>
#include<math.h>
#include<algorithm>
#include<vector>
#include<queue>
#include<stack>
#include<string>
#include <string.h>
#include <set>
#pragma warning(disable:4996)
using namespace std;
vector<pair<int, long long>> TreeMax;
long long Arr[1000001];
int N, M;
pair<int, long long> InitMin(int node, int start, int end)
{
if (start == end)
TreeMax[node] = { start,Arr[start] };
else
{
pair<int, long long> a = InitMin(node * 2, start, (start + end) / 2);
pair<int, long long> b = InitMin(node * 2 + 1, (start + end) / 2 + 1, end);
if (a.second < b.second)
TreeMax[node] = b;
else
TreeMax[node] = a;
}
return TreeMax[node];
}
pair<int, long long> GetMax(int node, int start, int end, int left, int right)
{
if (left > end || right < start)
return { 0,0 };
if (left <= start && end <= right)
return TreeMax[node];
pair<int, long long> a = GetMax(node * 2, start, (start + end) / 2, left, right);
pair<int, long long> b = GetMax(node * 2 + 1, (start + end) / 2 + 1, end, left, right);
if (a.second < b.second)
return b;
else
return a;
}
pair<int, long long> Update(int node, int start, int end, int index, long long After)
{
if (start == end && end == index)
{
Arr[index] = After;
TreeMax[node].second = After;
return TreeMax[node];
}
if (start > index || end < index)
return TreeMax[node];
pair<int, long long> a = Update(node * 2, start, (start + end) / 2, index, After);
pair<int, long long> b = Update(node * 2 + 1, (start + end) / 2 + 1, end, index, After);
if (a.second < b.second)
TreeMax[node] = b;
else
TreeMax[node] = a;
return TreeMax[node];
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> N;
int H = ceil(log2f(N));
TreeMax.resize(pow(2, H + 1));
for (int i = 0; i < N; i++)
cin >> Arr[i];
InitMin(1, 0, N - 1);
cin >> M;
for (int i = 0; i < M; i++)
{
int a, b, c;
cin >> a >> b >> c;
if (a == 2)
{
int i, ja, jb;
i = GetMax(1, 0, N - 1, b - 1, c - 1).first;
ja = -1;
jb = -1;
if (b - 1 <= i - 1)
ja = GetMax(1, 0, N - 1, b - 1, i - 1).first;
if (i + 1 <= c - 1)
jb = GetMax(1, 0, N - 1, i + 1, c - 1).first;
if (ja != -1 && jb != -1)
cout << Arr[i] + max(Arr[ja], Arr[jb]) << "\n";
else if (ja == -1 && jb != -1)
cout << Arr[i] + Arr[jb] << "\n";
else if (ja != -1 && jb == -1)
cout << Arr[i] + Arr[ja] << "\n";
}
else
Update(1, 0, N - 1, b - 1, c);
}
} | [
"9507ym@naver.com"
] | 9507ym@naver.com |
150b8b0738c2c8cb9f135a61ec0bc0057223e5c9 | 040078fa17e66a74b30efd635328dfd1c37c41e2 | /1019.cc | 00df20c8b1d63c18dcb4f19662c914e898f34467 | [] | no_license | mosthandsomeman/PAT_A | 80d4ef654a796a5dc47db170529ff98d6b45b32a | e8fb5c3bc1df4013ba0e9bd70e01131794a339cd | refs/heads/master | 2020-04-14T20:17:48.373130 | 2019-01-07T10:08:13 | 2019-01-07T10:08:13 | 164,088,515 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 586 | cc | //#include<cstdio>
//#include<cstdlib>
//#include<algorithm>
//#include<vector>
//using namespace std;
//int n, b, num;
//vector<int> vec, revers;
//int main() {
// scanf("%d %d", &n, &b);
// num = n;
// if (n == 0) vec.push_back(0);
// else {
// while (num != 0) {
// vec.push_back(num % b);
// num /= b;
// }
// }
// revers = vec;
// reverse(vec.begin(), vec.end());
// if (revers == vec) printf("Yes\n");
// else printf("No\n");
// for (int i = 0;i < vec.size();++i) {
// printf("%d", vec[i]);
// if (i < vec.size() - 1) printf(" ");
// }
// system("pause");
// return 0;
//} | [
"fuzhichao@binghuoshan.com"
] | fuzhichao@binghuoshan.com |
5791c96c2c520701460db450de18db122869761b | 13f533846617b5d2614b8f9fcd21439839ebe1dd | /CF/1560C.cpp | 85c85bd9da1e103d18033bca86c6bdbc7ce35569 | [] | no_license | triphan2k3/CP_Train | ed0f444e82fdc36e0e14c6b7e8aacf55f3e77f86 | f03be185f7c6e3c5f3e44b50453d9ea0bebfe9fd | refs/heads/main | 2023-08-29T15:37:44.079594 | 2021-10-17T14:38:55 | 2021-10-17T14:38:55 | 418,120,655 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,082 | cpp | #include <bits/stdc++.h>
#define TASK ""
#define pb push_back
#define eb emplace_back
#define all(v) (v).begin(), (v).end()
#define ii pair<int,int>
#define iii pair<ii,int>
#define ll long long
#define F first
#define S second
#define sz(x) ((int) (x).size())
#define FOR(i, a, b) for (int i=a; i<=b; i++)
#define FOr(i, a, b) for (int i=a; i<b ; i++)
#define FOD(i, a, b) for (int i=a; i>=b; i--)
#define FOd(i, a, b) for (int i=a; i>b ; i--)
using namespace std;
const int N=1e6+7;
const int MOD=1e9+7;
const ll INF=(ll)1e18+7;
int main() {
#ifdef TriPhann
freopen("TEST.INP","r",stdin);
freopen("TEST.OUT","w",stdout);
#else
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
#endif
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
int loop = sqrt(n);
if (loop*loop == n) {
cout << loop << " 1\n";
continue;
}
int rem = n - loop*loop;
if (rem <= loop)
cout << rem << " " << loop+1 << "\n";
else
cout << loop+1 << " " << 2*loop - rem + 2 << "\n";
}
}
| [
"triphan2k3@gmail.com"
] | triphan2k3@gmail.com |
e0db1b79048c24af95c983ce3c05e5a989f4441d | 376a6f0bbc6c0eeb0ddf456c8db5cacd4aa00c89 | /randomForest.cpp | 6d97c611154dfe553af7788eccf397f00310fbbf | [] | no_license | eduard0167/Optical-Character-Recognition | 938c8d4c549402c483e22cce48442312bca760f4 | 2cbc1d0e61cece9a7f4754e29828fbcae43ffb82 | refs/heads/master | 2023-08-29T07:26:17.186920 | 2021-10-18T22:08:23 | 2021-10-18T22:08:23 | 382,789,152 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,149 | cpp | #include "randomForest.h"
#include <iostream>
#include <random>
#include <vector>
#include <string>
#include <set>
#include "decisionTree.h"
using std::vector;
using std::pair;
using std::string;
using std::mt19937;
vector<vector<int>> get_random_samples(const vector<vector<int>> &samples,
int num_to_return) {
// TODO(you)
// Intoarce un vector de marime num_to_return cu elemente random,
// diferite din samples
vector<vector<int>> ret;
int size = samples.size();
std::random_device rd;
mt19937 mt(rd());
std::set<int> rows;
while (rows.size() != num_to_return) {
rows.insert(mt() % size);
}
for (std::set<int>::iterator it = rows.begin(); it != rows.end(); ++it) {
ret.push_back(samples[*it]);
}
return ret;
}
RandomForest::RandomForest(int num_trees, const vector<vector<int>> &samples)
: num_trees(num_trees), images(samples) {}
void RandomForest::build() {
// Aloca pentru fiecare Tree cate n / num_trees
// Unde n e numarul total de teste de training
// Apoi antreneaza fiecare tree cu testele alese
assert(!images.empty());
vector<vector<int>> random_samples;
int data_size = images.size() / num_trees;
for (int i = 0; i < num_trees; i++) {
// cout << "Creating Tree nr: " << i << endl;
random_samples = get_random_samples(images, data_size);
// Construieste un Tree nou si il antreneaza
trees.push_back(Node());
trees[trees.size() - 1].train(random_samples);
}
}
int RandomForest::predict(const vector<int> &image) {
// TODO(you)
// Va intoarce cea mai probabila prezicere pentru testul din argument
// se va interoga fiecare Tree si se va considera raspunsul final ca
// fiind cel majoritar
int freq[10] = {0};
for (int i = 0; i < num_trees; i++) {
freq[trees[i].predict(image)]++;
}
int result = 0;
int max_freq = freq[0];
for (int i = 1; i < num_trees; i++) {
if (max_freq < freq[i]) {
max_freq = freq[i];
result = i;
}
}
return result;
}
| [
"eduard_ionut.mitroi@stud.acs.upb.ro"
] | eduard_ionut.mitroi@stud.acs.upb.ro |
1bedbe359c3e3f524c201e957d9e5a0ffd691d27 | a00215c8a20f3c9646005815a9e599b9aec14dff | /main.cpp | 08414ef229a2561d3d62ab4f43e6f0562c3ec68c | [] | no_license | copt/mobots | 2f600ceb1e8330e81655212065a7102da65eb04b | c8aa3665daeb7f604f5d56dee4164e4a5a2140a1 | refs/heads/master | 2021-01-19T16:51:43.011122 | 2013-04-23T03:17:51 | 2013-04-23T03:17:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,273 | cpp | #include <iostream>
#include <math.h>
#include <opencv2/opencv.hpp>
#include <highgui.h>
using namespace cv;
using namespace std;
#define LEFT 0
#define RIGHT 1
//#define LEFT_MIN_ANGLE (-90)
//#define LEFT_MAX_ANGLE (-20)
//#define RIGHT_MIN_ANGLE (20)
//#define RIGHT_MAX_ANGLE (90)
#define THRESHOLD 75
#define FADE_TIME 10
Vec4i linefilter(vector<Vec4i> lines, int side);
int findcenter(Vec4i leftline, Vec4i rightline, int imgwidth);
// Hough Transform parameters
int hough_threshold = 120;
int minLineLength = 50;
int maxLineGap = 220;
// Canny Edge Detection parameters
int threshold1 = 100;
int threshold2 = 200;
int blur_block_size = 0;
// Angle and searchspace parameters
int min_angle = 12;
int max_angle = 80;
int search_height = 25;
int main(int argc, char** argv)
{
Mat src, greyscale, dst, src2, src3;
Mat leftclone, rightclone, left, right;
vector<Vec4i> lines;
int fps = 15;
// Persistance variables
int counter_left = FADE_TIME+1, counter_right = FADE_TIME+1;
Vec4i leftline_old, rightline_old;
// Parameter window intitialization
namedWindow( "Hough Parameters", 0 );
cvResizeWindow( "Hough Parameters", 500, 40 );
createTrackbar( "Threshold", "Hough Parameters", &hough_threshold, 200, NULL);
createTrackbar( "Minimum Line Length", "Hough Parameters", &minLineLength, 150, NULL);
createTrackbar( "Maximum Line Gap", "Hough Parameters", &maxLineGap, 300, NULL);
// Parameter window intitialization
namedWindow( "Canny Parameters", 0 );
cvResizeWindow( "Canny Parameters", 500, 40 );
createTrackbar( "Blurring", "Canny Parameters", &blur_block_size, 4, NULL);
createTrackbar( "Threshold 1", "Canny Parameters", &threshold1, 300, NULL);
createTrackbar( "Threshold 2", "Canny Parameters", &threshold2, 300, NULL);
// Parameter window initialization
namedWindow( "Angle searchspace", 0 );
cvResizeWindow( "Angle searchspace", 500, 40 );
createTrackbar( "Min Angle", "Angle searchspace", &min_angle, 90, NULL);
createTrackbar( "Max Angle", "Angle searchspace", &max_angle, 90, NULL);
createTrackbar( "Search Height", "Angle searchspace", &search_height, 100, NULL);
// Statistics variables
double ratio_2line = 0.0;
double ratio_1line = 0.0;
double ratio_0line = 0.0;
double ratio_danger = 0.0;
// Display variables
int center = 0;
int center_old=0;
int distance_old = 0;
int distance = 0;
char distance_str[100];
char attention[100] = "DANGER!";
char filename[50] = "video.avi";
char hough_param_str[100];
char canny_param_str[100];
char angle_str[100];
Point distance_pt = cvPoint(50, 460);
Point attention_pt = cvPoint(450,460);
Point hough_param_pt = cvPoint(20, 10);
Point canny_param_pt = cvPoint(20, 25);
Point angle_pt = cvPoint(20, 40);
// Start video capture
VideoCapture capture(0);
if( !capture.isOpened() )
return -1;
VideoWriter writer("1.avi", CV_FOURCC('M','J','P','G'), fps, cvSize( 640, 480 ));
while(1){
// Get frame and convert to greyscale
capture >> src2;
resize(src2, src, Size(), 0.5, 0.5, INTER_LINEAR);
cvtColor( src, greyscale, CV_RGB2GRAY );
// Perform canny edge detection
// < Low threshold = not an edge
// > High threshold = edge
// between thresholds = edge if next to edge
if(blur_block_size != 0)
blur(greyscale, src3, Size(2*blur_block_size+1,2*blur_block_size+1));
else
src3 = greyscale;
Canny(src3, dst, threshold1, threshold2, 3);
// Afficher la ligne delimitant la zone de recherche
line(src, Point(0, search_height*src.rows/100), Point(src.cols, search_height*src.rows/100), Scalar(150,100,100), 1, CV_AA);
// Diviser l'image en deux (left and right)
leftclone = dst(Range(search_height*dst.rows/100,dst.rows),Range(0,0.5*dst.cols)); // Copies header
left = leftclone.clone(); // Copies data
rightclone = dst(Range(search_height*dst.rows/100,dst.rows),Range(0.5*dst.cols,dst.cols)); // Copies header
right = rightclone.clone(); // Copies data
// LEFT SIDE (Hough transform and linefilter)
HoughLinesP(left, lines, 1, CV_PI/180, hough_threshold, minLineLength, maxLineGap);
Vec4i leftline = linefilter(lines, LEFT);
if( leftline[0] != -1 ) // Check if line is detected
{
line( src, Point(leftline[0], leftline[1]+search_height*src.rows/100), Point(leftline[2], leftline[3]+search_height*src.rows/100), Scalar(0,255,0), 7, CV_AA); // draws best line to source
leftline_old = leftline;
counter_left = 0;
}
// If line is not detected, slowly fade the previously detected line away
else if( counter_left <= FADE_TIME )
{
counter_left++;
line( src, Point(leftline_old[0], leftline_old[1]+search_height*src.rows/100), Point(leftline_old[2], leftline_old[3]+search_height*src.rows/100), Scalar(0,255-counter_left*255/FADE_TIME,counter_left*255/FADE_TIME), 7, CV_AA); // draws best line to source
}
// RIGHT SIDE (Hough transform and linefilter)
HoughLinesP(right, lines, 1, CV_PI/180, hough_threshold, minLineLength, maxLineGap);
Vec4i rightline = linefilter(lines, RIGHT);
if( rightline[0] != -1 ) // Check if line is detected
{
line( src, Point(rightline[0]+0.5*src.cols, rightline[1]+search_height*src.rows/100), Point(rightline[2]+0.5*src.cols, rightline[3]+search_height*src.rows/100), Scalar(0,255,0), 7, CV_AA); // draws best line to source
rightline_old = rightline;
counter_right = 0;
}
// If line is not detected, slowly fade the previously detected line away
else if(counter_right <= FADE_TIME )
{
counter_right++;
line( src, Point(rightline_old[0]+0.5*src.cols, rightline_old[1]+search_height*src.rows/100), Point(rightline_old[2]+0.5*src.cols, rightline_old[3]+search_height*src.rows/100), Scalar(0,255-counter_right*255/FADE_TIME,counter_right*255/FADE_TIME), 7, CV_AA); // draws best line to source
}
// Add center lines
center = findcenter(leftline, rightline, src.cols);
distance = (center - 0.5*src.cols);
if( leftline[0] != -1 && rightline[0] != -1 ) // Check if both lines are detected
{
line( src, Point(center, search_height*src.rows/100), Point(center, src.rows), Scalar(255,0,0), 2, CV_AA);
center_old = center;
distance_old = distance;
}
else if(counter_left <= FADE_TIME && counter_right <= FADE_TIME)
{
line( src, Point(center_old, search_height*src.rows/100), Point(center_old, src.rows), Scalar(255,0,0), 2, CV_AA);
}
// Write text to image
sprintf(distance_str, "distance to center: %d", distance);
putText(src,distance_str,distance_pt,FONT_HERSHEY_SIMPLEX,0.5,CV_RGB(255,255,255));
if ( fabs(distance_old) > THRESHOLD || (counter_right > FADE_TIME) || (counter_left > FADE_TIME))
{
putText(src,attention,attention_pt,FONT_HERSHEY_SIMPLEX,1,CV_RGB(255,0,0));
ratio_danger += 1.0;
}
// Write Hough Transform parameters to image
sprintf(hough_param_str, "Hough params: T = %d Min Ln Lgth = %d Max Ln Gap = %d", hough_threshold, minLineLength, maxLineGap);
putText(src,hough_param_str,hough_param_pt,FONT_HERSHEY_SIMPLEX,0.3,CV_RGB(0,0,255));
// Write Canny Edge Detection parameters to image
sprintf(canny_param_str, "Canny params: T1 = %d T2 = %d Blur Matrix %dx%d", threshold1, threshold2, 2*blur_block_size+1, 2*blur_block_size+1);
putText(src,canny_param_str,canny_param_pt,FONT_HERSHEY_SIMPLEX,0.3,CV_RGB(0,0,255));
// Write angle searchspace to image
sprintf(angle_str, "Search angles: min = %d max = %d", min_angle, max_angle);
putText(src,angle_str,angle_pt,FONT_HERSHEY_SIMPLEX,0.3,CV_RGB(0,0,255));
// Write source to video file
writer << src;
imshow("src", src);
imshow("left", left);
imshow("right", right);
//imshow("rblurry", src3);
if( leftline[0] != -1 && rightline[0] != -1 )
ratio_2line += 1.0;
else if ( leftline[0] == -1 && rightline[0] == -1 )
ratio_0line += 1.0;
else
ratio_1line += 1.0;
if(waitKey(30) >= 0) break;
}
double total = ratio_0line + ratio_1line + ratio_2line;
ratio_0line *= 100.0/total;
ratio_1line *= 100.0/total;
ratio_2line *= 100.0/total;
ratio_danger *= 100.0/total;
printf("\n2 lines : %lf percent \n1 line : %lf percent \n0 lines : %lf percent\ndanger : %lf percent\ntotal sample : %lf\n\n\n", ratio_2line, ratio_1line, ratio_0line,ratio_danger,total);
return 0;
}
Vec4i linefilter(vector<Vec4i> lines, int side)
{
vector<Vec4i> candidateLines;
float angle, max_length, length;
int longest;
Vec4i error;
error[0] = error[1] = error[2] = error[3] = -1;
// Keep the lines that are in the angle acceptance window
// LEFT : 0 to 45 deg
// RIGHT : -45 to 0 deg
for( size_t i = 0; i < lines.size(); i++ ){
Vec4i l = lines[i];
// Calculate angle of vector (in degs), and convert it to keep it in the -PI/2 -to PI/2 range
angle = atan2( l[3]-l[1], l[2]-l[0] ) * 180/M_PI;
if( angle > 90 )
angle -= 180;
else if( angle < -90 )
angle += 180;
// If the angle is within the desired range, insert Vec4i in candidate vector
if( side == LEFT && angle >= -max_angle && angle <= -min_angle )
candidateLines.push_back(l);
else if( side == RIGHT && angle >= min_angle && angle <= max_angle )
candidateLines.push_back(l);
}
// If no lines were in the acceptance window, stop here
if( candidateLines.empty() )
return error;
// Compute length of first line of the candidateLines vector and set it as default maximum
max_length = pow(lines[0][3] - lines[0][1], 2.0) + pow(lines[0][2] - lines[0][0], 2.0);
longest = 0;
// Search among the candidate lines for the longest line
// The square of the euclidian distances is calculated in order to reduce the computional needs
for( size_t i = 0; i < candidateLines.size(); i++ )
{
Vec4i l = candidateLines[i];
length = pow(lines[i][3] - lines[i][1], 2.0) + pow(lines[i][2] - lines[i][0], 2.0);
if( length > max_length )
{
max_length = length;
longest = i;
}
}
return candidateLines[longest];
}
int findcenter(Vec4i lineleft, Vec4i lineright, int imgwidth)
{
return (lineleft[0] + lineleft[2] + lineright[0] + lineright[2] + imgwidth)/4;
}
| [
"flo.copt@hotmail.com"
] | flo.copt@hotmail.com |
3f70b82770a66a0eda5a7a171872d37186e26216 | 3d93f8fa5863716c5894084920cdc66dcd500f01 | /Programa Original/LoRaMasterSlaveMQTT2.4 Working SerialDebug (Slave Program = 22%)/LoRaMasterSlaveMQTT2.2_SerialDebug/Encryption.ino | 31511258b7476a27b227780922c77dac4718aa72 | [
"MIT"
] | permissive | bnossn/ESP32Lora | 60fdb01b7f01e428508f8976d79d94d13fa705ba | e6b87f15fab5bf27ddfcda62c55ac4fb42e9dd3e | refs/heads/master | 2020-05-24T13:36:37.026606 | 2019-05-18T00:58:28 | 2019-05-18T00:58:28 | 187,292,685 | 1 | 0 | MIT | 2019-05-18T00:45:25 | 2019-05-17T23:26:22 | C++ | UTF-8 | C++ | false | false | 8,099 | ino | /* Encryption Module*/
#include <AESLib.h>
#include <AES.h>
AESLib aesLib;
uint64_t chipid;
// AES Encryption Key
byte aes_key[] = { 0xC2, 0xE6, 0xCC, 0x86, 0x75, 0xED, 0x2B, 0xBF, 0xAF, 0x10, 0x34, 0x2B, 0x67, 0xA8, 0x11, 0x93 };
// General initialization vector (use your own)
byte aes_iv[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
char cleartext[256];
char ciphertext[1024];
bool bEncDebug = false;
// Generate IV (once)
void aes_init() {
char initText[256];
aesLib.gen_iv(aes_iv);
sprintf(initText, "AAA");
encrypt(initText, aes_iv); // workaround for incorrect B64 functionality on first run... initing b64 is not enough
}
// Serves for debug logging the case where IV changes after use...
void print_key_iv(byte iv[]) {
int i;
Serial_Println(bDebug, "AES IV: ");
for (i = 0; i < sizeof(aes_iv); i++) {
sprintf (Sbuffer, "%i", iv[i]);
Serial_Print(bDebug, Sbuffer);
if ((i + 1) < sizeof(aes_iv)) {
Serial_Print(bDebug, ",");
}
}
Serial_Println(bDebug, "");
}
String ivToString() {
String strIV;
int i;
for (i = 0; i < sizeof(aes_iv); i++) {
strIV = strIV + String(aes_iv[i]);
if ((i + 1) < sizeof(aes_iv)) {
strIV = strIV + ",";
}
}
return strIV;
}
void stringToIV (String strIV, byte iv[]) {
// !!!! Converte a String no array do vetor
for (int i = 0; i < 16; i++) {
int tempindex = strIV.indexOf(",");
if (tempindex > 0) {
iv[i] = strIV.substring(0, tempindex).toInt();
strIV = strIV.substring(tempindex + 1); // Retorna o Resto da Mensagem
} else if (strIV.length() > 0) { //Pega o ultimo valor
iv[i] = strIV.toInt();
break;
}
}
// !!!! \Converte a String no array do vetor
}
//char message[200] = {0};
String encode(String msg) {
char output[256] = {0};
char input[256] = {0};
sprintf(input, msg.c_str());
//int inputLen = strlen(input);
int enlen = base64_encode(output, input, msg.length());
sprintf (Sbuffer, "Encoded %i bytes to %s \n", enlen, output);
Serial_Println(bDebug, Sbuffer);
//sprintf(message, output);
return String(output);
}
String decode(String encoded) {
char output[256] = {0};
char input[256] = {0};
sprintf(input, encoded.c_str());
int msglen = base64_decode(output, input, encoded.length());
sprintf (Sbuffer, "Decoded %i bytes to %s \n", msglen, output);
Serial_Println(bDebug, Sbuffer);
return String(output);
}
String encrypt(char * msg, byte iv[]) {
unsigned long ms = micros();
int msgLen = strlen(msg);
char encrypted[4 * msgLen];
if (bEncDebug) Serial_Println(bDebug, "ANTES ENCRYPT: ");
aesLib.encrypt64(msg, encrypted, aes_key, iv);
if (bEncDebug) Serial_Println(bDebug, "APÓS ENCRYPT: ");
if (bEncDebug){
Serial_Print(bDebug, "Encryption took: ");
sprintf (Sbuffer, "%lu", (micros() - ms));
Serial_Print(bDebug, Sbuffer);
Serial_Println(bDebug, "us");
}
return String(encrypted);
}
String decrypt(char * msg, byte iv[]) {
unsigned long ms = micros();
int msgLen = strlen(msg);
char decrypted[msgLen]; // half may be enough
aesLib.decrypt64(msg, decrypted, aes_key, iv);
if (bEncDebug){
Serial_Print(bDebug, "Decryption [2] took: ");
sprintf (Sbuffer, "%lu", (micros() - ms));
Serial_Print(bDebug, Sbuffer);
Serial_Println(bDebug, "us");
}
return String(decrypted);
}
String decryptMessage (String msgToDecrypt, String deviceID) {
String msgRec;
msgRec = msgToDecrypt;
//Verifica se a string possui "&"
int index = msgRec.indexOf("&");
if (index >= 0) { //Primeira parte
// !!! Primeira parte da string (Tamanho da mensagem)
String msgRecLen = msgRec.substring(0, index); //Retorna Tamanho da Mensagem
msgRec = msgRec.substring(index + 1); // Retorna o Resto da Mensagem
if (bEncDebug){
Serial_Println(bDebug, "Primeira parte: ");
Serial_Print(bDebug, " Tamanho: ");
Serial_Println(bDebug, msgRecLen.c_str());
Serial_Print(bDebug, " Resto: ");
Serial_Println(bDebug, msgRec.c_str());
Serial_Println(bDebug, "\n" );
}
// !!! \Primeira parte da string
//Verifica se a string possui "&"
index = msgRec.indexOf("&");
if ((index >= 0) && (msgRec.length() == msgRecLen.toInt())) { //Segunda parte - Verifica se mensagem tem tamanho esperado.
// !!! Segunda parte da string (SlaveID)
String destID = msgRec.substring(0, index); //Retorna o ID de interesse.
msgRec = msgRec.substring(index + 1); // Retorna o Resto da Mensagem
if (bEncDebug){
Serial_Println(bDebug, "Segunda parte: ");
Serial_Print(bDebug, " deviceID: ");
Serial_Println(bDebug, destID.c_str());
Serial_Print(bDebug, " Resto: ");
Serial_Println(bDebug, msgRec.c_str());
Serial_Println(bDebug, "\n" );
}
// !!! \Segunda parte da string
//Verifica se a string possui "&"
index = msgRec.indexOf("&");
if ( (index >= 0) && (deviceID.equalsIgnoreCase(destID))) { //Terceira parte - Verifica o ID de interesse.
// !!! Terceira parte da string (initialization vector)
String str_iv = msgRec.substring(0, index); //Retorna o vetor
msgRec = msgRec.substring(index + 1); // Retorna o Resto da Mensagem
if (bEncDebug){
Serial_Println(bDebug, "Terceira parte: ");
Serial_Print(bDebug, " IV: ");
Serial_Println(bDebug, str_iv.c_str());
Serial_Print(bDebug, " Resto: ");
Serial_Println(bDebug, msgRec.c_str());
Serial_Println(bDebug, "\n" );
}
// !!! \Terceira parte da string
if (msgRec.length() > 0) { //Quarta parte
// !!! Quarta parte da string (Mensagem Criptografada
String encrypted = msgRec; //Retorna a mensagem criptografada
if (bEncDebug){
Serial_Println(bDebug, "Quarta parte: ");
Serial_Print(bDebug, " Mensagem Criptografada: ");
Serial_Println(bDebug, encrypted.c_str());
Serial_Println(bDebug, "\n" );
}
// !!! \Quarta parte da string
// !!!! Decodifica Mensagem
sprintf(ciphertext, "%s", encrypted.c_str()); //Converting to char[]
byte dec_iv[16]; // iv_block gets written to, requires always fresh copy
stringToIV(str_iv, dec_iv);
if (bEncDebug) print_key_iv(dec_iv);
String decrypted = decrypt(ciphertext, dec_iv);
if (bEncDebug){
Serial_Print(bDebug, "Decrypted Result: ");
Serial_Println(bDebug, decrypted.c_str());
Serial_Println(bDebug, "\n" );
}
return decrypted;
// !!!! \Decodifica Mensagem
}
}
}
}
return "";
}
String encryptMessage(String msgToEncrypt, String deviceID ) {
aesLib.gen_iv(aes_iv);
if (bEncDebug){
Serial_Println(bDebug, "IV Atual: ");
Serial_Println(bDebug, ivToString().c_str());
}
sprintf(cleartext, msgToEncrypt.c_str());
byte enc_iv[16]; // iv_block gets written to, reqires always fresh copy.
memcpy(enc_iv, aes_iv, sizeof(aes_iv));
if (bEncDebug) print_key_iv(enc_iv);
String encrypted = encrypt(cleartext, enc_iv);
if (bEncDebug){
Serial_Print(bDebug, "Encrypted Result: ");
Serial_Println(bDebug, encrypted.c_str());
Serial_Println(bDebug, "\n" );
}
/*
Mensagem codificada como:
TamanhoMsg & deviceID & initialization vector & mensagem criptografada
Slave envia mensgem com seu proprio ID
Master envia mensagem com ID de destino
*/
String msg;
msg = encrypted; //mensagem criptografa
msg = "&" + msg; //marcador 1
msg = ivToString() + msg; //initialization vector
msg = "&" + msg; // marcador 2
msg = deviceID + msg; // Device ID
uint16_t msglen = msg.length();
msg = "&" + msg; //marcador 3
msg = String(msglen) + msg; //Tamanha da mensagem
if (bEncDebug){
Serial_Print(bDebug, "Message Encrypted: ");
Serial_Println(bDebug, msg.c_str());
Serial_Println(bDebug, "\n" );
}
return msg;
}
| [
"bruno.nascimento@br.abb.com"
] | bruno.nascimento@br.abb.com |
9485d4eb3ef5daa133e357b3931338ffab5dea3c | 703227e62ae08496955d72ec9dde8096592832ae | /System Programing 20210528/Race/Race.h | 16987b2a81e5505de2580ae4a7c8648965ff20d7 | [] | no_license | hyuk02006/Jusung | 4c918cbf7cd634e50eaf7de32224346d110de1ce | c9d9717e85cb635deba5c74fcefd73f6f41e8431 | refs/heads/main | 2023-08-27T08:42:35.613344 | 2021-10-22T02:59:00 | 2021-10-22T02:59:00 | 365,973,186 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 599 | h |
// Race.h: Race 애플리케이션의 기본 헤더 파일
//
#pragma once
#ifndef __AFXWIN_H__
#error "PCH에 대해 이 파일을 포함하기 전에 'pch.h'를 포함합니다."
#endif
#include "resource.h" // 주 기호입니다.
// CRaceApp:
// 이 클래스의 구현에 대해서는 Race.cpp을(를) 참조하세요.
//
class CRaceApp : public CWinApp
{
public:
CRaceApp() noexcept;
// 재정의입니다.
public:
virtual BOOL InitInstance();
virtual int ExitInstance();
// 구현입니다.
afx_msg void OnAppAbout();
DECLARE_MESSAGE_MAP()
};
extern CRaceApp theApp;
| [
"hyuk02006@naver.com"
] | hyuk02006@naver.com |
6b0ad971c5ef9cc5fa8c79fc773ab2057ddc6e0f | 6d129ca82f911e031b2923c5aa4e2dc9862e1fef | /sketch_jul18a/sketch_jul18a.ino | 6ab40ccb940da023fe1e68aabc0b1294b66a0ae3 | [] | no_license | maikel112233/arduinopruebas | 56be4dbce727f219a2c546ada4c57dca92b93878 | dd4e4bdfa9544676f266e6b9cee0c78a54df5b07 | refs/heads/master | 2021-01-01T15:33:55.902308 | 2017-07-25T16:07:32 | 2017-07-25T16:07:32 | 97,645,175 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,312 | ino | /* TITULO: Reloj en tiempo real Tiny RTC I²C con LCD 2004.
AUTOR:
MARIANO DEL CAMPO GARCÍA (@2016) --> INGENIERO TÉCNICO INDUSTRIAL ESPECIALIDAD ELECTRÓNICA
- FACEBOOK: https://www.facebook.com/mariano.delcampogarcia
- TWITTER: https://twitter.com/MarianoCampoGa
- CORREO: marianodc83@gmail.com
DESCRIPCIÓN DEL PROGRAMA
Con este programa obtenemos un reloj en tiempo real gracias al Tiny RTC I²C que mostrará los valores
de hora y fecha a través de un display LCD 2004 que hemos conectado a nuestro Arduino mediante
comunicación I²C al igual que el RTC.
ESQUEMA DE CONEXION
+-----+
+----[PWR]-------------------| USB |--+
| +-----+ |
| GND/RST2 [ ][ ] |
| MOSI2/SCK2 [ ][ ] A5/SCL[ ] | SCL del LCD 2004 / SCL del Tiny RTC I²C
| 5V/MISO2 [ ][ ] A4/SDA[ ] | SDA del LCD 2004 / SDA del Tiny RTC I²C
| AREF[ ] |
| GND[ ] |
| [ ]N/C SCK/13[ ] |
| [ ]IOREF MISO/12[ ] |
| [ ]RST MOSI/11[ ]~|
| [ ]3V3 +---+ 10[ ]~|
| [ ]5v -| A |- 9[ ]~|
| [ ]GND -| R |- 8[ ] |
| [ ]GND -| D |- |
| [ ]Vin -| U |- 7[ ] |
| -| I |- 6[ ]~|
| [ ]A0 -| N |- 5[ ]~|
| [ ]A1 -| O |- 4[ ] |
| [ ]A2 +---+ INT1/3[ ]~|
| [ ]A3 INT0/2[ ] |
| [ ]A4/SDA RST SCK MISO TX>1[ ] |
| [ ]A5/SCL [ ] [ ] [ ] RX<0[ ] |
| [ ] [ ] [ ] |
| UNO_R3 GND MOSI 5V ____________/
\_______________________/
NOTAS:
- La alimentación y la masa del módulo LCM 2004 I²C V1 van directamente conectadas a +5V y GND
respectivamente.
- La alimentación y la masa del Tiny RTC I²C también van directamente conectadas a +5V y GND
respectivamente.
*/
// Importar librerías
#include <Wire.h> // Librería para la comunicación I²C
#include <LiquidCrystal_I2C.h> // Librería para el LCD I²C
#include "RTClib.h" // Librería para el RTC
// Declaración del objeto para el LCD 2004 I²C
// Poner la dirección del LCD a 0x20 para display 20x4 (A0=0, A1=0, A2=0)
// Terminales de conexión del LCD
// addr, en,rw,rs,d4,d5,d6,d7,bl,blpol
LiquidCrystal_I2C lcd(0x3f,16,2);
// Declaración del objeto para el RTC
DS1307 RTC;
void setup ()
{
lcd.begin(20,4); // Inicializamos el LCD para 20x4
Wire.begin(); // Inicializamos la comunicación I²C para el RTC
RTC.begin(); // Inicializamos el RTC
// Si quitamos el comentario de la línea siguiente, se ajusta la hora y la fecha con la del PC
// RTC.adjust(DateTime(__DATE__, __TIME__));
//lcd.display();
lcd.clear();
lcd.setCursor(0,0);
lcd.print("RELOJ EN TIEMPO REAL");
lcd.setCursor(0,1);
lcd.print("********************");
}
void loop ()
{
// Obtenemos la hora y la fecha del Tiny RTC I²C
DateTime now = RTC.now();
lcd.setCursor(0,2);
// Imprimimos la hora (HH:MM:SS)
lcd.print("> HORA: ");
// Imprimimos las HORAS
if(now.hour()<=9)
{
lcd.print("0");
}
lcd.print(now.hour(), DEC);
lcd.print(':');
// Imprimimos los MINUTOS
if(now.minute()<=9)
{
lcd.print("0");
}
lcd.print(now.minute(), DEC);
lcd.print(':');
// Imprimimos los SEGUNDOS
if(now.second()<=9)
{
lcd.print("0");
}
lcd.print(now.second(), DEC);
lcd.setCursor(0,3);
// Imprimimos la fecha (DÍA/MES/AÑO)
lcd.print("> FECHA: ");
// Imprimimos el DÍA
if(now.day()<=9)
{
lcd.print("0");
}
lcd.print(now.day(), DEC);
lcd.print('/');
// Imprimimos el MES
if(now.month()<=9)
{
lcd.print("0");
}
lcd.print(now.month(), DEC);
lcd.print('/');
// Imprimimos el AÑO
lcd.print(now.year(), DEC);
}
| [
"maikel112233@gmail.com"
] | maikel112233@gmail.com |
4885e416a67720097e7f4469d3b014f4f9544243 | 2beb2a0a0ab29fc4d8da630ffe8b82146299f3c7 | /Chapter003-particles/001-arrays/src/testApp.h | 2eb8f5e42e35bb9a3ee6880d9af40f9421b3f099 | [] | no_license | veev/CodeForArt | fd7e2159defc44aabf25134daa77dd4074750095 | 124dc5d2b6aef8ccc840e7ca5eeca03e2a3ea011 | refs/heads/master | 2021-01-18T10:26:09.943494 | 2012-11-30T18:00:09 | 2012-12-05T00:03:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 720 | h | #pragma once
#include "ofMain.h"
#define NUM_PARTICLES 100
class testApp : public ofBaseApp{
public:
void setup();
void update();
void draw();
void keyPressed (int key);
void keyReleased(int key);
void mouseMoved(int x, int y );
void mouseDragged(int x, int y, int button);
void mousePressed(int x, int y, int button);
void mouseReleased(int x, int y, int button);
void windowResized(int w, int h);
void dragEvent(ofDragInfo dragInfo);
void gotMessage(ofMessage msg);
float x_pos[NUM_PARTICLES];
float y_pos[NUM_PARTICLES];
float x_vel[NUM_PARTICLES];
float y_vel[NUM_PARTICLES];
float radius[NUM_PARTICLES];
int color[NUM_PARTICLES];
};
| [
"jefftimesten@gmail.com"
] | jefftimesten@gmail.com |
e725d479ee773a7994d37d9cc16d557c98830e8a | 7c717ba98f826f261f640c29065343968b786bb9 | /chatroom_server/src/server.cpp | 50f10aa7eb274b38825c6a3cf84d47bfff0ac46f | [] | no_license | vinimyls/COCUS | 71a87fab8d68473ecbc99355ed69febe4b067b3b | 48580940a4a5fc09945cf8e514c4198b4ab83e94 | refs/heads/main | 2023-07-13T11:55:01.841621 | 2021-08-24T15:09:04 | 2021-08-24T15:09:04 | 399,495,428 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,519 | cpp | #include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <pthread.h>
#include <sys/types.h>
#include <signal.h>
#include <atomic>
#include <sstream>
#include <redis-cpp/stream.h>
#include <redis-cpp/execute.h>
#define MAX_CLIENTS 100
#define BUFFER_SZ 2048
std::atomic<unsigned int > cli_count;
static int uid = 10;
int idActualMessage = 0;
auto redisConnection = rediscpp::make_stream("localhost", "6379");
int numberUsers =0;
/* Client structure */
typedef struct{
struct sockaddr_in address;
int sockfd;
int uid;
char name[32];
} client_t;
client_t *clients[MAX_CLIENTS];
pthread_mutex_t clients_mutex = PTHREAD_MUTEX_INITIALIZER;
void str_overwrite_stdout() {
printf("\r%s", "> ");
fflush(stdout);
}
void str_trim_lf (char* arr, int length) {
int i;
for (i = 0; i < length; i++) {
if (arr[i] == '\n') {
arr[i] = '\0';
break;
}
}
}
void print_client_addr(struct sockaddr_in addr){
printf("%d.%d.%d.%d",
addr.sin_addr.s_addr & 0xff,
(addr.sin_addr.s_addr & 0xff00) >> 8,
(addr.sin_addr.s_addr & 0xff0000) >> 16,
(addr.sin_addr.s_addr & 0xff000000) >> 24);
}
/* Add clients to queue */
void queue_add(client_t *cl){
pthread_mutex_lock(&clients_mutex);
for(int i=0; i < MAX_CLIENTS; ++i){
if(!clients[i]){
clients[i] = cl;
break;
}
}
pthread_mutex_unlock(&clients_mutex);
}
/* Remove clients to queue */
void queue_remove(int uid){
pthread_mutex_lock(&clients_mutex);
for(int i=0; i < MAX_CLIENTS; ++i){
if(clients[i]){
if(clients[i]->uid == uid){
clients[i] = NULL;
break;
}
}
}
pthread_mutex_unlock(&clients_mutex);
}
void broadcastMessage(const char* message){
for(int i=0; i<MAX_CLIENTS; ++i){
if(clients[i] && strlen(message)!= 0){
write(clients[i]->sockfd,message,strlen(message));
}
}
}
/* send last messages*/
void sendLastMessages(void){
pthread_mutex_lock(&clients_mutex);
int oldMessage = idActualMessage-20;
while(oldMessage < 0)
oldMessage++;
for(; oldMessage < idActualMessage; oldMessage++)
{
try{
// GET FROM REDIS
auto const oldMessageStr = std::to_string(oldMessage); // convert oldMessage to string
rediscpp::execute_no_flush(*redisConnection, "get", oldMessageStr); // get in redis
std::flush(*redisConnection);
rediscpp::value value{*redisConnection};
// CONVERSION TO SEND TO WRITE()
auto messageReturned = value.as<std::string>(); // move value returned to "messageReturned"
int n = messageReturned.size();
char messageReturnedChar[n+1]; // convert messageReturned to char
strcpy(messageReturnedChar, messageReturned.c_str());
char const *idChar = std::to_string(oldMessage).c_str();
broadcastMessage(idChar);
broadcastMessage(" -> ");
broadcastMessage(messageReturnedChar);
}
catch(std::exception const&){}
}
pthread_mutex_unlock(&clients_mutex);
}
void printHeader(void)
{
const char * header = "== COCUS CHAT ROOM ==\n\n";
broadcastMessage(header);
}
/* Clear users screen*/
void clearScreen(void){
pthread_mutex_lock(&clients_mutex);
const char* clearMessage = "system-clear";
broadcastMessage(clearMessage);
usleep(100000); // prevents no clear screen, but add delay
pthread_mutex_unlock(&clients_mutex);
}
/* Save em Redis*/
void setRedis(char * message){
std::string messageSet(message); // execute() needs all in string
auto const idActualMessageString = std::to_string(idActualMessage); // so lets convert int and char to string
static_cast<void>(rediscpp::execute(*redisConnection, "set", idActualMessageString, messageSet));
// delete oldest message "21"
if(idActualMessage >19){
auto const itemDel = std::to_string(idActualMessage-20);
static_cast<void>(rediscpp::execute(*redisConnection,"del", itemDel));
}
idActualMessage++;
clearScreen();
printHeader();
sendLastMessages();
}
/*get message's owner*/
std::string getMessageOwner(int idMessage){
// get message
static_cast<void>(rediscpp::execute_no_flush(*redisConnection, "get", std::to_string(idMessage)));
std::flush(*redisConnection);
rediscpp::value value{*redisConnection};
// separe user that sended the message
auto messageReturned = value.as<std::string>();
size_t operator_position = messageReturned.find_first_of(":");
std::string messageOwner = messageReturned.substr(0, operator_position);
// return message's owner
return messageOwner;
}
/* Remove message */
void remove_message(std::string user,std::string command)
{
std::string numberDeleted = command.substr(5);
// conversion to fix to fix problem with blank and garbed in spaces in "command"
std::stringstream intValue(numberDeleted);
int numberInt = 0;
intValue >> numberInt;
try {
// GET MESSAGE TO COMPARE
std::string messageOwner = getMessageOwner(numberInt);
if(messageOwner==user){
static_cast<void>(rediscpp::execute(*redisConnection,"del", std::to_string(numberInt))); // USE A "FOR AND DELETE"
std::cout << user << " removed message: " << numberInt << std::endl;
}
else{
std::cout <<
user << " tried to remove message: " <<
numberInt << " but this was write by "<<
messageOwner << std::endl;
}
}
catch (std::exception const&)
{
std::cout << "message doesn't exist" << std::endl;
}
clearScreen();
printHeader();
sendLastMessages();
}
/* Handle all communication with the client */
void *handle_client(void *arg){
char buff_out[BUFFER_SZ];
char name[32];
int leave_flag = 0;
cli_count++;
client_t *cli = (client_t *)arg;
// Name
if(recv(cli->sockfd, name, 32, 0) <= 0 || strlen(name) < 2 || strlen(name) >= 32-1){
printf("Didn't enter the name.\n");
leave_flag = 1;
} else{
strcpy(cli->name, name);
std::cout << name << " has joined" << std::endl;
sprintf(buff_out, "%s has joined\n", cli->name);
setRedis(buff_out);
numberUsers++;
}
bzero(buff_out, BUFFER_SZ);
while(1){
if (leave_flag) {
break;
}
int receive = recv(cli->sockfd, buff_out, BUFFER_SZ, 0);
if (receive > 0){
printf("%s",buff_out); // print buffer in this prompt
std::string bufferIn(buff_out),
name,
command;
// separe message to user
size_t operator_position = bufferIn.find_first_of(":");
name = bufferIn.substr(0, operator_position);
command = bufferIn.substr(operator_position+2);
// verify if the message is a delete message
if (command.find("--rm") != std::string::npos)
{
remove_message(name,command);
}
else{
if(strlen(buff_out) > 0){
setRedis(buff_out); // save message in redis
}
}
} else if (receive == 0 || strcmp(buff_out, "exit") == 0){
std::cout << name << " has left" << std::endl;
sprintf(buff_out, "%s has left\n", cli->name);
/////////////////////////
setRedis(buff_out);
numberUsers--;
if(numberUsers <1){
int idActual = idActualMessage-20;
while(idActual < 0)
idActual++;
for(; idActual < idActualMessage; idActual++) // CLEAR PREAVISLY MESSAGES
{ // FLUSHDB OR FLUSHALL
auto const itemDel = std::to_string(idActual); // DOESN'T WORK IN THIS LIBRARY
static_cast<void>(rediscpp::execute(*redisConnection,"del", itemDel)); // USE A "FOR AND DELETE"
}
idActualMessage = 0;
}
/////////////////////////
leave_flag = 1;
} else {
printf("ERROR: -1\n");
leave_flag = 1;
}
bzero(buff_out, BUFFER_SZ);
}
/* Delete client from queue and yield thread */
close(cli->sockfd);
queue_remove(cli->uid);
free(cli);
cli_count--;
pthread_detach(pthread_self());
return NULL;
}
int main(int argc, char **argv){
if(argc != 2){
printf("Usage: %s <port>\n", argv[0]);
return EXIT_FAILURE;
}
const char *ip = "127.0.0.1";
int port = atoi(argv[1]);
int option = 1;
int listenfd = 0, connfd = 0;
struct sockaddr_in serv_addr;
struct sockaddr_in cli_addr;
pthread_t tid;
/* Socket settings */
listenfd = socket(AF_INET, SOCK_STREAM, 0);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = inet_addr(ip);
serv_addr.sin_port = htons(port);
/* Ignore pipe signals */
signal(SIGPIPE, SIG_IGN);
if(setsockopt(listenfd, SOL_SOCKET,(SO_REUSEPORT | SO_REUSEADDR),(char*)&option,sizeof(option)) < 0){
perror("ERROR: setsockopt failed");
return EXIT_FAILURE;
}
/* Bind */
if(bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) {
perror("ERROR: Socket binding failed");
return EXIT_FAILURE;
}
/* Listen */
if (listen(listenfd, 10) < 0) {
perror("ERROR: Socket listening failed");
return EXIT_FAILURE;
}
printf("=== CHAT ROOM COCUS C++ ===\n");
while(1){
socklen_t clilen = sizeof(cli_addr);
connfd = accept(listenfd, (struct sockaddr*)&cli_addr, &clilen);
/* Check if max clients is reached */
if((cli_count + 1) == MAX_CLIENTS){
printf("Max clients reached. Rejected: ");
print_client_addr(cli_addr);
printf(":%d\n", cli_addr.sin_port);
close(connfd);
continue;
}
/* Client settings */
client_t *cli = (client_t *)malloc(sizeof(client_t));
cli->address = cli_addr;
cli->sockfd = connfd;
cli->uid = uid++;
/* Add client to the queue and fork thread */
queue_add(cli);
pthread_create(&tid, NULL, &handle_client, (void*)cli);
/* Reduce CPU usage */
sleep(1);
}
return EXIT_SUCCESS;
}
| [
"noreply@github.com"
] | noreply@github.com |
c0ce73e9aed41239c5565355a2be28e85c21da42 | 19d8265c7ba38d5277ae95fc7f0435c074571945 | /test/reg-test/fam-api-reg/fam_fence_reg_test.cpp | 2d49268b43b2f56f6219feab4dde0e12929684d4 | [
"BSD-3-Clause"
] | permissive | VrashiPonnappa/OpenFAM | 0b2fdbd17692a4e484e73c5a993eaafb9a177af8 | d5885fcf594504b46f0d2d4c9e95aa734e929e61 | refs/heads/master | 2020-08-12T06:58:40.826795 | 2019-10-12T21:15:19 | 2019-10-12T21:15:19 | 214,711,596 | 0 | 0 | BSD-3-Clause | 2019-10-12T20:33:18 | 2019-10-12T20:33:17 | null | UTF-8 | C++ | false | false | 3,842 | cpp | /*
* fam_fence_reg_test.cpp
* Copyright (c) 2019 Hewlett Packard Enterprise Development, LP. All rights
* reserved. Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. 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.
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* See https://spdx.org/licenses/BSD-3-Clause
*
*/
#include <fam/fam_exception.h>
#include <gtest/gtest.h>
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <fam/fam.h>
#include "common/fam_test_config.h"
using namespace std;
using namespace openfam;
fam *my_fam;
Fam_Options fam_opts;
// Test case 1 - put get test.
TEST(FamFence, FenceSuccess) {
Fam_Region_Descriptor *desc;
Fam_Descriptor *item;
const char *testRegion = get_uniq_str("test", my_fam);
const char *firstItem = get_uniq_str("first", my_fam);
EXPECT_NO_THROW(
desc = my_fam->fam_create_region(testRegion, 8192, 0777, RAID1));
EXPECT_NE((void *)NULL, desc);
// Allocating data items in the created region
EXPECT_NO_THROW(item = my_fam->fam_allocate(firstItem, 1024, 0777, desc));
EXPECT_NE((void *)NULL, item);
// allocate two integer array and initialize them
int oldLocal[50];
int newLocal[50];
for (int i = 0; i < 50; i++) {
oldLocal[i] = 1 + i;
}
for (int i = 0; i < 50; i++) {
newLocal[i] = 101 + i;
}
EXPECT_NO_THROW(
my_fam->fam_put_nonblocking(oldLocal, item, 0, sizeof(oldLocal)));
EXPECT_NO_THROW(my_fam->fam_fence());
// Replace the content on oldLocal with newLocal on FAM
EXPECT_NO_THROW(
my_fam->fam_put_nonblocking(newLocal, item, 0, sizeof(newLocal)));
EXPECT_NO_THROW(my_fam->fam_fence());
int *local = (int *)malloc(50 * sizeof(int));
EXPECT_NO_THROW(
my_fam->fam_get_nonblocking(local, item, 0, sizeof(newLocal)));
EXPECT_NO_THROW(my_fam->fam_quiet());
for (int i = 0; i < 50; i++) {
EXPECT_EQ(local[i], newLocal[i]);
}
EXPECT_NO_THROW(my_fam->fam_deallocate(item));
EXPECT_NO_THROW(my_fam->fam_destroy_region(desc));
delete item;
delete desc;
free((void *)testRegion);
free((void *)firstItem);
}
int main(int argc, char **argv) {
int ret;
::testing::InitGoogleTest(&argc, argv);
my_fam = new fam();
init_fam_options(&fam_opts);
EXPECT_NO_THROW(my_fam->fam_initialize("default", &fam_opts));
ret = RUN_ALL_TESTS();
EXPECT_NO_THROW(my_fam->fam_finalize("default"));
return ret;
}
| [
"sharad.singhal@hpe.com"
] | sharad.singhal@hpe.com |
759eeb178dd738c246eadab4000460fdf3396d41 | e4bf0948a50dd94ac14efd501f098413853f010d | /Arduino_part/lib/ESP8266WiFi/src/ESP8266WiFiMulti.cpp | db1857f73a0c2e6753239766dee87c02ea4e8dfd | [] | no_license | crazyggboom/fyp-Autonomous-model-car-based-on-arduino-and-Raspberry-Pi | ae27eff2a3dc5ec3a51dee03839f4a9e114217f0 | 2f0b19fd732eb01d2bff6e569ca6b1f443a00842 | refs/heads/master | 2020-05-19T12:41:48.584492 | 2019-05-08T08:41:06 | 2019-05-08T08:41:06 | 185,020,881 | 10 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,241 | cpp | /**
*
* @file ESP8266WiFiMulti.cpp
* @date 16.05.2015
* @author Markus Sattler
*
* Copyright (c) 2015 Markus Sattler. All rights reserved.
* This file is part of the esp8266 core for Arduino environment.
*
* 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 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include "ESP8266WiFiMulti.h"
#include <limits.h>
#include <string.h>
ESP8266WiFiMulti::ESP8266WiFiMulti() {
}
ESP8266WiFiMulti::~ESP8266WiFiMulti() {
APlistClean();
}
bool ESP8266WiFiMulti::addAP(const char* ssid, const char *passphrase) {
return APlistAdd(ssid, passphrase);
}
bool ESP8266WiFiMulti::existsAP(const char* ssid, const char *passphrase) {
return APlistExists(ssid, passphrase);
}
wl_status_t ESP8266WiFiMulti::run(void) {
wl_status_t status = WiFi.status();
if(status == WL_DISCONNECTED || status == WL_NO_SSID_AVAIL || status == WL_IDLE_STATUS || status == WL_CONNECT_FAILED) {
int8_t scanResult = WiFi.scanComplete();
if(scanResult == WIFI_SCAN_RUNNING) {
// scan is running, do nothing yet
status = WL_NO_SSID_AVAIL;
return status;
}
if(scanResult == 0) {
// scan done, no ssids found. Start another scan.
DEBUG_WIFI_MULTI("[WIFI] scan done\n");
DEBUG_WIFI_MULTI("[WIFI] no networks found\n");
WiFi.scanDelete();
DEBUG_WIFI_MULTI("\n\n");
delay(0);
WiFi.disconnect();
DEBUG_WIFI_MULTI("[WIFI] start scan\n");
// scan wifi async mode
WiFi.scanNetworks(true);
return status;
}
if(scanResult > 0) {
// scan done, analyze
WifiAPEntry bestNetwork { NULL, NULL };
int bestNetworkDb = INT_MIN;
uint8 bestBSSID[6];
int32_t bestChannel;
DEBUG_WIFI_MULTI("[WIFI] scan done\n");
delay(0);
DEBUG_WIFI_MULTI("[WIFI] %d networks found\n", scanResult);
for(int8_t i = 0; i < scanResult; ++i) {
String ssid_scan;
int32_t rssi_scan;
uint8_t sec_scan;
uint8_t* BSSID_scan;
int32_t chan_scan;
bool hidden_scan;
WiFi.getNetworkInfo(i, ssid_scan, sec_scan, rssi_scan, BSSID_scan, chan_scan, hidden_scan);
bool known = false;
for(auto entry : APlist) {
if(ssid_scan == entry.ssid) { // SSID match
known = true;
if(rssi_scan > bestNetworkDb) { // best network
if(sec_scan == ENC_TYPE_NONE || entry.passphrase) { // check for passphrase if not open wlan
bestNetworkDb = rssi_scan;
bestChannel = chan_scan;
bestNetwork = entry;
memcpy((void*) &bestBSSID, (void*) BSSID_scan, sizeof(bestBSSID));
}
}
break;
}
}
if(known) {
DEBUG_WIFI_MULTI(" ---> ");
} else {
DEBUG_WIFI_MULTI(" ");
}
DEBUG_WIFI_MULTI(" %d: [%d][%02X:%02X:%02X:%02X:%02X:%02X] %s (%d) %c\n", i, chan_scan, BSSID_scan[0], BSSID_scan[1], BSSID_scan[2], BSSID_scan[3], BSSID_scan[4], BSSID_scan[5], ssid_scan.c_str(), rssi_scan, (sec_scan == ENC_TYPE_NONE) ? ' ' : '*');
delay(0);
}
// clean up ram
WiFi.scanDelete();
DEBUG_WIFI_MULTI("\n\n");
delay(0);
if(bestNetwork.ssid) {
DEBUG_WIFI_MULTI("[WIFI] Connecting BSSID: %02X:%02X:%02X:%02X:%02X:%02X SSID: %s Channel: %d (%d)\n", bestBSSID[0], bestBSSID[1], bestBSSID[2], bestBSSID[3], bestBSSID[4], bestBSSID[5], bestNetwork.ssid, bestChannel, bestNetworkDb);
WiFi.begin(bestNetwork.ssid, bestNetwork.passphrase, bestChannel, bestBSSID);
status = WiFi.status();
static const uint32_t connectTimeout = 5000; //5s timeout
auto startTime = millis();
// wait for connection, fail, or timeout
while(status != WL_CONNECTED && status != WL_NO_SSID_AVAIL && status != WL_CONNECT_FAILED && (millis() - startTime) <= connectTimeout) {
delay(10);
status = WiFi.status();
}
#ifdef DEBUG_ESP_WIFI
IPAddress ip;
uint8_t * mac;
switch(status) {
case WL_CONNECTED:
ip = WiFi.localIP();
mac = WiFi.BSSID();
DEBUG_WIFI_MULTI("[WIFI] Connecting done.\n");
DEBUG_WIFI_MULTI("[WIFI] SSID: %s\n", WiFi.SSID().c_str());
DEBUG_WIFI_MULTI("[WIFI] IP: %d.%d.%d.%d\n", ip[0], ip[1], ip[2], ip[3]);
DEBUG_WIFI_MULTI("[WIFI] MAC: %02X:%02X:%02X:%02X:%02X:%02X\n", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
DEBUG_WIFI_MULTI("[WIFI] Channel: %d\n", WiFi.channel());
break;
case WL_NO_SSID_AVAIL:
DEBUG_WIFI_MULTI("[WIFI] Connecting Failed AP not found.\n");
break;
case WL_CONNECT_FAILED:
DEBUG_WIFI_MULTI("[WIFI] Connecting Failed.\n");
break;
default:
DEBUG_WIFI_MULTI("[WIFI] Connecting Failed (%d).\n", status);
break;
}
#endif
} else {
DEBUG_WIFI_MULTI("[WIFI] no matching wifi found!\n");
}
return status;
}
// scan failed, or some other condition not handled above. Start another scan.
DEBUG_WIFI_MULTI("[WIFI] delete old wifi config...\n");
WiFi.disconnect();
DEBUG_WIFI_MULTI("[WIFI] start scan\n");
// scan wifi async mode
WiFi.scanNetworks(true);
}
return status;
}
// ##################################################################################
bool ESP8266WiFiMulti::APlistAdd(const char* ssid, const char *passphrase) {
WifiAPEntry newAP;
if(!ssid || *ssid == 0x00 || strlen(ssid) > 32) {
// fail SSID too long or missing!
DEBUG_WIFI_MULTI("[WIFI][APlistAdd] no ssid or ssid too long\n");
return false;
}
//for passphrase, max is 63 ascii + null. For psk, 64hex + null.
if(passphrase && strlen(passphrase) > 64) {
// fail passphrase too long!
DEBUG_WIFI_MULTI("[WIFI][APlistAdd] passphrase too long\n");
return false;
}
if(APlistExists(ssid, passphrase)) {
DEBUG_WIFI_MULTI("[WIFI][APlistAdd] SSID: %s already exists\n", ssid);
return true;
}
newAP.ssid = strdup(ssid);
if(!newAP.ssid) {
DEBUG_WIFI_MULTI("[WIFI][APlistAdd] fail newAP.ssid == 0\n");
return false;
}
if(passphrase) {
newAP.passphrase = strdup(passphrase);
} else {
newAP.passphrase = strdup("");
}
if(!newAP.passphrase) {
DEBUG_WIFI_MULTI("[WIFI][APlistAdd] fail newAP.passphrase == 0\n");
free(newAP.ssid);
return false;
}
APlist.push_back(newAP);
DEBUG_WIFI_MULTI("[WIFI][APlistAdd] add SSID: %s\n", newAP.ssid);
return true;
}
bool ESP8266WiFiMulti::APlistExists(const char* ssid, const char *passphrase) {
if(!ssid || *ssid == 0x00 || strlen(ssid) > 32) {
// fail SSID too long or missing!
DEBUG_WIFI_MULTI("[WIFI][APlistExists] no ssid or ssid too long\n");
return false;
}
for(auto entry : APlist) {
if(!strcmp(entry.ssid, ssid)) {
if(!passphrase) {
if(!strcmp(entry.passphrase, "")) {
return true;
}
} else {
if(!strcmp(entry.passphrase, passphrase)) {
return true;
}
}
}
}
return false;
}
void ESP8266WiFiMulti::APlistClean(void) {
for(auto entry : APlist) {
if(entry.ssid) {
free(entry.ssid);
}
if(entry.passphrase) {
free(entry.passphrase);
}
}
APlist.clear();
}
| [
"240075880@qq.com"
] | 240075880@qq.com |
3f80ec7ff9a5e8770bd8dc767ee66acd15df57ee | 63d3fb9c756d99c3e10b6f57b2e5951e4e2d10d6 | /main.cpp | ac10cf4981b7d10dc1c89efbd72c587a6b71b0bf | [] | no_license | Alan-Baylis/dual_contouring_experiments | 5f105a83684f5f9e36944a991900ce1fbb7e509f | f05f107fcd58394df7777a5fd371bea078bf05cf | refs/heads/master | 2021-06-25T13:06:40.328097 | 2017-08-28T01:12:10 | 2017-08-28T01:12:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,002 | cpp | #include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
#include "Utils.h"
#include "Reconstruction.h"
#include "Contouring.h"
#include "Octree.h"
#include "json.hpp"
using namespace std;
using glm::vec3;
using json = nlohmann::json;
// ----------------------------------------------------------------------------
Real compute_boundingbox(DefaultMesh &mesh, DefaultMesh::Point &bb_min);
const string MESH_FILES = "mesh_files";
const string CAM_POS = "cam_pos";
string threshold_str(Real threshold){
std::stringstream ss;
ss << "simp";
while(threshold < 0){
ss<< "0";
threshold *= 10;
}
threshold = (int) threshold;
ss << std::to_string(threshold) ;
return ss.str();
}
int main(int argc, char** argv)
{
const int height = 6;
// int dist = 16;
string folder_name = "../";
string inputfilename, outputfilename;
//std::cout <<"Input File Name" << endl;
//std::cin >> inputfilename;
inputfilename = "cropped.json";
//inputfilename = "vase_antonina.json";
std::cout <<"Output File Name" << endl;
std::cin >> outputfilename;
std::ifstream descriptionStream(folder_name + inputfilename);
json object_json;
if (descriptionStream.is_open()) {
descriptionStream >> object_json;
}
std::vector<std::string> filenames = object_json[MESH_FILES];
std::vector<glm::vec3> cameras;
for (json::iterator j_it = object_json[CAM_POS].begin(); j_it != object_json[CAM_POS].end(); ++j_it) {
json cam_json = j_it.value();
std::cout << cam_json << std::endl;
cameras.push_back(glm::vec3(cam_json["x"], cam_json["y"], cam_json["z"]));
}
DefaultMesh myMesh;
//OpenMesh::IO::read_mesh(myMesh, "../models/analytic/sphere_lowpoly.off");
//OpenMesh::IO::read_mesh(myMesh, "../models/divided/vase_antonina.off");
OpenMesh::IO::read_mesh(myMesh, "../models/branca/k3branca1.off");
//OpenMesh::IO::read_mesh(myMesh, "../models/taoju/mechanic.off");
//OpenMesh::IO::read_mesh(myMesh, "../models/cow.off");
// compute bounding box
DefaultMesh::Point bb_min;
Real octreeSize = compute_boundingbox(myMesh, bb_min);
OctreeNode* root = Fusion::octree_from_samples(openmesh_to_glm(bb_min) - vec3(0.1), octreeSize * 1.1, height,
filenames, cameras);
Octree::classify_leaves_vertices(root);
VertexBuffer vertices;
IndexBuffer indices;
GenerateMeshFromOctree(/*sphere_octree.*/root, vertices, indices);
#ifdef DEBUG
std::cout << "Unoptimized points: " << Octree::unoptimized_points << std::endl;
std::cout << "Irregular cells " << Octree::irregular_cells << std::endl;
#endif
std::stringstream filepath;
filepath << folder_name << outputfilename << "full" << height << ".ply";
write_Ply(filepath.str(), vertices, indices);
//generates simplified version
Real simp_threshold = 1;
for (int i = 0; i < 3; ++i) {
simp_threshold *= 10;
root = Octree::SimplifyOctree(root, simp_threshold);
GenerateMeshFromOctree(root, vertices, indices);
std::stringstream simpfilepath;
simpfilepath << folder_name << threshold_str(simp_threshold) << outputfilename << "full" << height << ".ply";
write_Ply(simpfilepath.str(), vertices, indices);
}
return EXIT_SUCCESS;
}
// ----------------------------------------------------------------------------
Real compute_boundingbox(DefaultMesh &mesh, DefaultMesh::Point &bb_min)
{
auto v_it = mesh.vertices_begin();
DefaultMesh::Point bb_max = mesh.point(*v_it);
bb_min = bb_max;
for (; v_it != mesh.vertices_end(); ++v_it)
{
bb_min.minimize(mesh.point(*v_it));
bb_max.maximize(mesh.point(*v_it));
}
Real octreeSize = (bb_max - bb_min).max();
std::cout << "Min: (" << bb_min[0] << ", " << bb_min[1] << ", " << bb_min[2] << ") " << "Size: " << octreeSize << std::endl;
return octreeSize;
} | [
"hallpaaz@gmail.com"
] | hallpaaz@gmail.com |
c96e804f450f183ab8054a2a81e1565d3fc7de6e | 37d08c745caee39da991debb54635065df1a8e2a | /src/dorghr.cpp | 1aae70d21badc178959746081b093fe3cec46295 | [] | no_license | kjbartel/magma | c936cd4838523779f31df418303c6bebb063aecd | 3f0dd347d2e230c8474d1e22e05b550fa233c7a3 | refs/heads/master | 2020-06-06T18:12:56.286615 | 2015-06-04T17:20:40 | 2015-06-04T17:20:40 | 36,885,326 | 23 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 3,850 | cpp | /*
-- MAGMA (version 1.6.1) --
Univ. of Tennessee, Knoxville
Univ. of California, Berkeley
Univ. of Colorado, Denver
@date January 2015
@generated from zunghr.cpp normal z -> d, Fri Jan 30 19:00:18 2015
*/
#include "common_magma.h"
/**
Purpose
-------
DORGHR generates a DOUBLE_PRECISION unitary matrix Q which is defined as the
product of IHI-ILO elementary reflectors of order N, as returned by
DGEHRD:
Q = H(ilo) H(ilo+1) . . . H(ihi-1).
Arguments
---------
@param[in]
n INTEGER
The order of the matrix Q. N >= 0.
@param[in]
ilo INTEGER
@param[in]
ihi INTEGER
ILO and IHI must have the same values as in the previous call
of DGEHRD. Q is equal to the unit matrix except in the
submatrix Q(ilo+1:ihi,ilo+1:ihi).
1 <= ILO <= IHI <= N, if N > 0; ILO=1 and IHI=0, if N=0.
@param[in,out]
A DOUBLE_PRECISION array, dimension (LDA,N)
On entry, the vectors which define the elementary reflectors,
as returned by DGEHRD.
On exit, the N-by-N unitary matrix Q.
@param[in]
lda INTEGER
The leading dimension of the array A. LDA >= max(1,N).
@param[in]
tau DOUBLE_PRECISION array, dimension (N-1)
TAU(i) must contain the scalar factor of the elementary
reflector H(i), as returned by DGEHRD.
@param[in]
dT DOUBLE_PRECISION array on the GPU device.
DT contains the T matrices used in blocking the elementary
reflectors H(i), e.g., this can be the 9th argument of
magma_dgehrd.
@param[in]
nb INTEGER
This is the block size used in DGEHRD, and correspondingly
the size of the T matrices, used in the factorization, and
stored in DT.
@param[out]
info INTEGER
- = 0: successful exit
- < 0: if INFO = -i, the i-th argument had an illegal value
@ingroup magma_dgeev_comp
********************************************************************/
extern "C" magma_int_t
magma_dorghr(
magma_int_t n, magma_int_t ilo, magma_int_t ihi,
double *A, magma_int_t lda,
double *tau,
magmaDouble_ptr dT, magma_int_t nb,
magma_int_t *info)
{
#define A(i,j) (A + (j)*lda+ (i))
magma_int_t i, j, nh, iinfo;
*info = 0;
nh = ihi - ilo;
if (n < 0)
*info = -1;
else if (ilo < 1 || ilo > max(1,n))
*info = -2;
else if (ihi < min(ilo,n) || ihi > n)
*info = -3;
else if (lda < max(1,n))
*info = -5;
if (*info != 0) {
magma_xerbla( __func__, -(*info) );
return *info;
}
/* Quick return if possible */
if (n == 0)
return *info;
/* Shift the vectors which define the elementary reflectors one
column to the right, and set the first ilo and the last n-ihi
rows and columns to those of the unit matrix */
for (j = ihi-1; j >= ilo; --j) {
for (i = 0; i < j; ++i)
*A(i, j) = MAGMA_D_ZERO;
for (i = j+1; i < ihi; ++i)
*A(i, j) = *A(i, j - 1);
for (i = ihi; i < n; ++i)
*A(i, j) = MAGMA_D_ZERO;
}
for (j = 0; j < ilo; ++j) {
for (i = 0; i < n; ++i)
*A(i, j) = MAGMA_D_ZERO;
*A(j, j) = MAGMA_D_ONE;
}
for (j = ihi; j < n; ++j) {
for (i = 0; i < n; ++i)
*A(i, j) = MAGMA_D_ZERO;
*A(j, j) = MAGMA_D_ONE;
}
if (nh > 0) {
/* Generate Q(ilo+1:ihi,ilo+1:ihi) */
magma_dorgqr(nh, nh, nh,
A(ilo, ilo), lda,
tau+ilo-1, dT, nb, &iinfo);
}
return *info;
} /* magma_dorghr */
#undef A
| [
"kjbartel@users.noreply.github.com"
] | kjbartel@users.noreply.github.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.