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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f935506e289c9f8660fcfa3112670e5a02895f78 | e69198f43d3fd9d3272028ea253bcfe30e9698d6 | /cafe/cafe/RunController.hpp | 231406cdd4ac4e2207e8fe2f05ad42b84f91ff65 | [] | no_license | hengne/d0wmass | a8514dfb01db7d9a60aa517e49bb6bc980c8cd24 | f25d5ddb4616b00ca1e9ab83c02657844b778c3b | refs/heads/master | 2021-01-20T18:20:06.573869 | 2016-06-05T13:30:24 | 2016-06-05T13:30:24 | 60,460,795 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,504 | hpp | #ifndef CAFE_RUNCONTROLLER_HPP__
#define CAFE_RUNCONTROLLER_HPP__
#include <string>
#include <set>
#include "cafe/Controller.hpp"
class TTree;
class TFile;
namespace cafe {
class Processor;
/**
* A special version of a Controller.
*
* This opens the input files and loops over the events.
*
* Input specifications can be of the form:
*
* - file:pathname/to/file
* - listfile:pathname/to/listfile
* - sam:datadefinition
*
* and any other root prefix (rootd:, rootk:, http:, rfio:, dcache:)
*
* If '.Events' is greater than 0, only that many events will be processed.
*
* Configuration options:
*
* - .Input: InputSpecification (see above) [default: file:input.root]
* - .Events: MaxEvents [default: 0, i.e. no limit]
* - .Files: MaxFiles [default: 0, i.e. no limit]
* - .Skip: NumEvents [default: 0]
* - .SkipFiles: NumFiles [default: 0]
* - .Progress: Number (print progress after 'Number' events)
* - .EventList: Filename [ default: "", no event list ]
* - .PartialReads: false | true [ default: false, don't allow partial reads of objects]
* - .RootDebug: DebugLevel [ default: 0 ]
* - .TreeDebug: DebugLevel [ default: 0 ]
* - .TreeName: Name [ default: "TMBTree", use non-standard tree ]
* - .Friends: NameList [ default: "", list of friend trees to add ]
* - .LoadAll: 0|1 [ default: 0, force load of whole event ]
*
* @see Controller
*
* \ingroup cafe
*/
class RunController : public Controller {
public:
RunController(const char *name);
~RunController();
void processTree(TTree *tree, Event& event);
bool Run(unsigned int max_events = 0);
private:
std::string _input;
unsigned int _num_events;
unsigned int _max_events;
unsigned int _max_files;
unsigned int _num_files;
unsigned int _progress;
int _skip;
int _skip_files;
std::set<std::string> _friends;
bool _partialReads;
int _rootDebug;
int _treeDebug;
bool _loadAll;
TFile *_eventList;
std::string _treeName;
public:
ClassDef(RunController, 0);
};
}
#endif // CAFE_RUNCONTROLLER_HPP__
| [
"Hengne.Li@cern.ch"
] | Hengne.Li@cern.ch |
43fb6f314dd91ea9efc60064aa388716d3228fee | 560090526e32e009e2e9331e8a2b4f1e7861a5e8 | /Compiled/blaze-3.2/blazetest/src/mathtest/smatdmatmult/DCbSLDa.cpp | 7240c76abb95956963b102cda813066efd88d194 | [
"BSD-3-Clause"
] | permissive | jcd1994/MatlabTools | 9a4c1f8190b5ceda102201799cc6c483c0a7b6f7 | 2cc7eac920b8c066338b1a0ac495f0dbdb4c75c1 | refs/heads/master | 2021-01-18T03:05:19.351404 | 2018-02-14T02:17:07 | 2018-02-14T02:17:07 | 84,264,330 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,505 | cpp | //=================================================================================================
/*!
// \file src/mathtest/smatdmatmult/DCbSLDa.cpp
// \brief Source file for the DCbSLDa sparse matrix/dense matrix multiplication math test
//
// Copyright (C) 2012-2017 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. 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 names of the Blaze development group 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.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/CompressedMatrix.h>
#include <blaze/math/DiagonalMatrix.h>
#include <blaze/math/DynamicMatrix.h>
#include <blaze/math/StrictlyLowerMatrix.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/smatdmatmult/OperationTest.h>
#include <blazetest/system/MathTest.h>
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'DCbSLDa'..." << std::endl;
using blazetest::mathtest::TypeA;
using blazetest::mathtest::TypeB;
try
{
// Matrix type definitions
typedef blaze::DiagonalMatrix< blaze::CompressedMatrix<TypeB> > DCb;
typedef blaze::StrictlyLowerMatrix< blaze::DynamicMatrix<TypeA> > SLDa;
// Creator type definitions
typedef blazetest::Creator<DCb> CDCb;
typedef blazetest::Creator<SLDa> CSLDa;
// Running tests with small matrices
for( size_t i=0UL; i<=6UL; ++i ) {
for( size_t j=0UL; j<=i; ++j ) {
RUN_SMATDMATMULT_OPERATION_TEST( CDCb( i, j ), CSLDa( i ) );
}
}
// Running tests with large matrices
RUN_SMATDMATMULT_OPERATION_TEST( CDCb( 31UL, 7UL ), CSLDa( 31UL ) );
RUN_SMATDMATMULT_OPERATION_TEST( CDCb( 67UL, 7UL ), CSLDa( 67UL ) );
RUN_SMATDMATMULT_OPERATION_TEST( CDCb( 127UL, 13UL ), CSLDa( 127UL ) );
RUN_SMATDMATMULT_OPERATION_TEST( CDCb( 32UL, 8UL ), CSLDa( 32UL ) );
RUN_SMATDMATMULT_OPERATION_TEST( CDCb( 64UL, 8UL ), CSLDa( 64UL ) );
RUN_SMATDMATMULT_OPERATION_TEST( CDCb( 128UL, 16UL ), CSLDa( 128UL ) );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during sparse matrix/dense matrix multiplication:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
| [
"jonathan.doucette@alumni.ubc.ca"
] | jonathan.doucette@alumni.ubc.ca |
5419d13c511d1321b02f83081546f13f134858b1 | a73f24bf1302bebd56f5d376cb54e36fb284e43d | /Buffers/Buffer.h | 596e99f45fe7035496c8cc109321fa4f066dc94f | [] | no_license | harimohanraj89/Thesis | f04e25624e9dc50d33aaac97e62b6b9d4e8aea62 | 9ce4ce457d0ac5936969f5f253c10a18366a3c67 | refs/heads/master | 2021-01-18T13:58:31.849690 | 2013-09-24T17:44:11 | 2013-09-24T17:44:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,123 | h | //
// Buffer.h
// SoniScan_2_0
//
// Created by Hariharan Mohanraj on 12/6/12.
// Copyright (c) 2012 Hariharan Mohanraj. All rights reserved.
//
#ifndef __SoniScan_2_0__Buffer__
#define __SoniScan_2_0__Buffer__
#include <iostream>
#include "../Constants.h"
class Buffer
{
private:
sample* bufferContents;
int bufferSize;
public:
// Functions to get values from buffer
sample* Get();
void Get(sample[],int);
sample Get(int);
int Size();
// Functions to set values of buffer
void Set(sample[],int);
void Set(sample, int);
// Utility functions for buffer
void Clear();
void Clear(int);
void Copy(Buffer&);
void Copy(Buffer&, int);
void Add(Buffer&);
void Add(Buffer&, int);
void Add(Buffer&, float, int);
void Subtract(Buffer&);
void Multiply(Buffer&);
void Multiply(float);
void Reverse();
void Invert();
// Constructors and Destructors
Buffer();
Buffer(int);
Buffer(const Buffer&);
Buffer& operator=(Buffer);
~Buffer();
};
#endif /* defined(__SoniScan_2_0__Buffer__) */
| [
"hari.mohanraj89@gmail.com"
] | hari.mohanraj89@gmail.com |
9eb93a68692b89d489a7bf00a31efc62c79ec044 | 0f0238a2c2210fcd797f32a3a724a97ac5294e45 | /cheatBox/miscsetup.ino | 266cf4f7904065547eb9ab3e47f91bb65dc40422 | [] | no_license | underminedsk/kaleidoscope | 2a9a8a7ec7220a21afbcc933a9da9b4509ce3b35 | bffd72caf07479d020758abe7fa1d431657215d1 | refs/heads/master | 2020-04-06T07:02:21.902922 | 2016-08-21T00:43:02 | 2016-08-21T00:43:02 | 59,241,432 | 0 | 4 | null | 2016-06-14T06:23:39 | 2016-05-19T20:44:06 | Arduino | UTF-8 | C++ | false | false | 5,232 | ino | #include <Wire.h>
#include <LiquidCrystal_I2C.h>
// Addr: 0x3F, 20 chars & 4 lines. Sometimes display boards use address 0x27
LiquidCrystal_I2C lcd(0x3F, 16, 2); //Frentally display, use 0x3F if not working try 0x27
#include "pitches.h"
// notes in the melody:
int melody[] = {
NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
};
// note durations: 4 = quarter note, 8 = eighth note, etc.:
int noteDurations[] = {
4, 8, 8, 4, 4, 4, 4, 4
};
void playTone() {
// iterate over the notes of the melody:
for (int thisNote = 0; thisNote < 8; thisNote++) {
// to calculate the note duration, take one second
// divided by the note type.
//e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
int noteDuration = 1000 / noteDurations[thisNote];
tone(A2, melody[thisNote], noteDuration);
// to distinguish the notes, set a minimum time between them.
// the note's duration + 30% seems to work well:
int pauseBetweenNotes = noteDuration * 1.30;
delay(pauseBetweenNotes);
// stop the tone playing:
noTone(A2);
}
}
void lcdSetup()
{
lcd.clear();
lcd.init();
delay(100);
lcd.noBacklight();
lcd.setCursor(0, 0);
firstLine = "Hello";
secondLine = "What's your name?";
thirdLine = "";
fourthLine = "";
}
void lcdDisplayOn() {
lcd.backlight();
//lcd.blink();
}
boolean nameEntered() {
byte letter[1];
return false;
}
void updateLcd(byte val, byte &letterNum) {
switch (val) {
case 8: // Backspace
if (letterNum > 0) {
letterNum--;
playerName[letterNum] = 0;
thirdLine = (char*)playerName;
}
break;
case 13: // Enter
firstLine = "Your name is:";
secondLine = (char*)playerName;
thirdLine = "";
fourthLine = "Please retag card";
lcd.noBlink();
break;
default:
if (val >= 32 && val <= 122 && letterNum < 15) {
playerName[letterNum] = val;
letterNum++;
}
thirdLine = (char*)playerName;
}
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(firstLine);
lcd.setCursor(0, 1);
lcd.print(secondLine);
lcd.setCursor(0, 2);
lcd.print(thirdLine);
lcd.setCursor(0, 3);
lcd.print(fourthLine);
lcd.setCursor(letterNum, 2);
}
void lcdMessage(String first, String second) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(first);
lcd.setCursor(0, 1);
lcd.print(second);
}
#include <Keypad.h>
#define Password_Lenght 7 // Give enough room for six chars + NULL char
char Data[Password_Lenght]; // 6 is the number of chars it can hold + the null char = 7
char Master[Password_Lenght] = "123456";
byte data_count = 0, master_count = 0;
bool Pass_is_good;
char customKey;
const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
//define the cymbols on the buttons of the keypads
char hexaKeys[ROWS][COLS] = {
{'1','2','3','+'},
{'4','5','6','-'},
{'7','8','9','*'},
{'.','0','=','/'}
};
byte rowPins[ROWS] = {A1, 0, 9, 8}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {7, 6, 5, 4}; //connect to the column pinouts of the keypad
//initialize an instance of class NewKeypad
Keypad customKeypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);
void clearData()
{
while(data_count !=0)
{ // This can be used for any array size,
Data[data_count--] = 0; //clear array for new data
}
return;
}
void keypadSetup()
{
lcd.setCursor(0,0);
//lcd.print("Enter Password");
//lcdMessage(String((char*)playerUid), String((char*)playerData));
//lcd.clear();
/*
lcd.setCursor(0, 0);
for (int i=0; i < sizeof(playerUid); i++) {
lcd.print(playerUid[i], DEC);
}
lcd.setCursor(0, 1);
lcd.print(String((char*)playerName));
*/
lcd.setCursor(0, 0);
for (int i=0; i < sizeof(playerData); i++) {
lcd.print(playerData[i], HEX);
}
lcd.setCursor(0, 1);
lcd.print("past+ pres- done=");
//lcd.print(playerData[0], DEC);
customKey = customKeypad.getKey();
if (customKey) // makes sure a key is actually pressed, equal to (customKey != NO_KEY)
{
/*Data[data_count] = customKey; // store char into data array
lcd.setCursor(data_count,1); // move cursor to show each new char
lcd.print(Data[data_count]); // print char at said cursor
data_count++; // increment data array by 1 to store new char, also keep track of the number of chars entered
*/
switch (customKey)
{
case '1':
playerData[0]++;
playerData[1]++;
break;
case '2':
playerData[2]++;
playerData[3]++;
break;
case '3':
playerData[4]++;
playerData[5]++;
break;
case '4':
playerData[6]++;
playerData[7]++;
break;
case '5':
playerData[8]++;
playerData[9]++;
break;
case '6':
playerData[10]++;
playerData[11]++;
break;
case '7':
playerData[12]++;
playerData[13]++;
break;
case '+':
playerData[14]++;
break;
case '-':
playerData[15]++;
break;
case '=':
gameDone = true;
break;
default:
break;
}
}
}
| [
"noreply@github.com"
] | noreply@github.com |
2c7bc6d1844417368c29c4f6d747edaba3f6a84a | d08744a8cc972c39d2b9e039a922a032ef75f1ef | /src/rpcrawtransaction.cpp | f1da9e890a69adfb4375062be68ba746d2267b01 | [] | no_license | Geckoin/Giarcoin | ab1c0eb5da9e96a06ad6aa31d37335b985412a80 | a7c3b4a74965b68815479650267d435e6d4420d1 | refs/heads/master | 2020-06-02T09:30:32.427321 | 2014-04-04T13:33:55 | 2014-04-04T13:33:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,118 | cpp | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/assign/list_of.hpp>
#include "base58.h"
#include "bitcoinrpc.h"
#include "db.h"
#include "init.h"
#include "main.h"
#include "net.h"
#include "wallet.h"
using namespace std;
using namespace boost;
using namespace boost::assign;
using namespace json_spirit;
//
// Utilities: convert hex-encoded Values
// (throws error if not hex).
//
uint256 ParseHashV(const Value& v, string strName)
{
string strHex;
if (v.type() == str_type)
strHex = v.get_str();
if (!IsHex(strHex)) // Note: IsHex("") is false
throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')");
uint256 result;
result.SetHex(strHex);
return result;
}
uint256 ParseHashO(const Object& o, string strKey)
{
return ParseHashV(find_value(o, strKey), strKey);
}
vector<unsigned char> ParseHexV(const Value& v, string strName)
{
string strHex;
if (v.type() == str_type)
strHex = v.get_str();
if (!IsHex(strHex))
throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')");
return ParseHex(strHex);
}
vector<unsigned char> ParseHexO(const Object& o, string strKey)
{
return ParseHexV(find_value(o, strKey), strKey);
}
void ScriptPubKeyToJSON(const CScript& scriptPubKey, Object& out)
{
txnouttype type;
vector<CTxDestination> addresses;
int nRequired;
out.push_back(Pair("asm", scriptPubKey.ToString()));
out.push_back(Pair("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end())));
if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired))
{
out.push_back(Pair("type", GetTxnOutputType(TX_NONSTANDARD)));
return;
}
out.push_back(Pair("reqSigs", nRequired));
out.push_back(Pair("type", GetTxnOutputType(type)));
Array a;
BOOST_FOREACH(const CTxDestination& addr, addresses)
a.push_back(CBitcoinAddress(addr).ToString());
out.push_back(Pair("addresses", a));
}
void TxToJSON(const CTransaction& tx, const uint256 hashBlock, Object& entry)
{
entry.push_back(Pair("txid", tx.GetHash().GetHex()));
entry.push_back(Pair("version", tx.nVersion));
entry.push_back(Pair("locktime", (boost::int64_t)tx.nLockTime));
Array vin;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
Object in;
if (tx.IsCoinBase())
in.push_back(Pair("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
else
{
in.push_back(Pair("txid", txin.prevout.hash.GetHex()));
in.push_back(Pair("vout", (boost::int64_t)txin.prevout.n));
Object o;
o.push_back(Pair("asm", txin.scriptSig.ToString()));
o.push_back(Pair("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
in.push_back(Pair("scriptSig", o));
}
in.push_back(Pair("sequence", (boost::int64_t)txin.nSequence));
vin.push_back(in);
}
entry.push_back(Pair("vin", vin));
Array vout;
for (unsigned int i = 0; i < tx.vout.size(); i++)
{
const CTxOut& txout = tx.vout[i];
Object out;
out.push_back(Pair("value", ValueFromAmount(txout.nValue)));
out.push_back(Pair("n", (boost::int64_t)i));
Object o;
ScriptPubKeyToJSON(txout.scriptPubKey, o);
out.push_back(Pair("scriptPubKey", o));
vout.push_back(out);
}
entry.push_back(Pair("vout", vout));
if (hashBlock != 0)
{
entry.push_back(Pair("blockhash", hashBlock.GetHex()));
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end() && (*mi).second)
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain())
{
entry.push_back(Pair("confirmations", 1 + nBestHeight - pindex->nHeight));
entry.push_back(Pair("time", (boost::int64_t)pindex->nTime));
entry.push_back(Pair("blocktime", (boost::int64_t)pindex->nTime));
}
else
entry.push_back(Pair("confirmations", 0));
}
}
}
Value getrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getrawtransaction <txid> [verbose=0]\n"
"If verbose=0, returns a string that is\n"
"serialized, hex-encoded data for <txid>.\n"
"If verbose is non-zero, returns an Object\n"
"with information about <txid>.");
uint256 hash = ParseHashV(params[0], "parameter 1");
bool fVerbose = false;
if (params.size() > 1)
fVerbose = (params[1].get_int() != 0);
CTransaction tx;
uint256 hashBlock = 0;
if (!GetTransaction(hash, tx, hashBlock, true))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction");
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << tx;
string strHex = HexStr(ssTx.begin(), ssTx.end());
if (!fVerbose)
return strHex;
Object result;
result.push_back(Pair("hex", strHex));
TxToJSON(tx, hashBlock, result);
return result;
}
Value listunspent(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 3)
throw runtime_error(
"listunspent [minconf=1] [maxconf=9999999] [\"address\",...]\n"
"Returns array of unspent transaction outputs\n"
"with between minconf and maxconf (inclusive) confirmations.\n"
"Optionally filtered to only include txouts paid to specified addresses.\n"
"Results are an array of Objects, each of which has:\n"
"{txid, vout, scriptPubKey, amount, confirmations}");
RPCTypeCheck(params, list_of(int_type)(int_type)(array_type));
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
int nMaxDepth = 9999999;
if (params.size() > 1)
nMaxDepth = params[1].get_int();
set<CBitcoinAddress> setAddress;
if (params.size() > 2)
{
Array inputs = params[2].get_array();
BOOST_FOREACH(Value& input, inputs)
{
CBitcoinAddress address(input.get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Giarcoin address: ")+input.get_str());
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+input.get_str());
setAddress.insert(address);
}
}
Array results;
vector<COutput> vecOutputs;
assert(pwalletMain != NULL);
pwalletMain->AvailableCoins(vecOutputs, false);
BOOST_FOREACH(const COutput& out, vecOutputs)
{
if (out.nDepth < nMinDepth || out.nDepth > nMaxDepth)
continue;
if (setAddress.size())
{
CTxDestination address;
if (!ExtractDestination(out.tx->vout[out.i].scriptPubKey, address))
continue;
if (!setAddress.count(address))
continue;
}
int64 nValue = out.tx->vout[out.i].nValue;
const CScript& pk = out.tx->vout[out.i].scriptPubKey;
Object entry;
entry.push_back(Pair("txid", out.tx->GetHash().GetHex()));
entry.push_back(Pair("vout", out.i));
CTxDestination address;
if (ExtractDestination(out.tx->vout[out.i].scriptPubKey, address))
{
entry.push_back(Pair("address", CBitcoinAddress(address).ToString()));
if (pwalletMain->mapAddressBook.count(address))
entry.push_back(Pair("account", pwalletMain->mapAddressBook[address]));
}
entry.push_back(Pair("scriptPubKey", HexStr(pk.begin(), pk.end())));
if (pk.IsPayToScriptHash())
{
CTxDestination address;
if (ExtractDestination(pk, address))
{
const CScriptID& hash = boost::get<const CScriptID&>(address);
CScript redeemScript;
if (pwalletMain->GetCScript(hash, redeemScript))
entry.push_back(Pair("redeemScript", HexStr(redeemScript.begin(), redeemScript.end())));
}
}
entry.push_back(Pair("amount",ValueFromAmount(nValue)));
entry.push_back(Pair("confirmations",out.nDepth));
results.push_back(entry);
}
return results;
}
Value createrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 2)
throw runtime_error(
"createrawtransaction [{\"txid\":txid,\"vout\":n},...] {address:amount,...}\n"
"Create a transaction spending given inputs\n"
"(array of objects containing transaction id and output number),\n"
"sending to given address(es).\n"
"Returns hex-encoded raw transaction.\n"
"Note that the transaction's inputs are not signed, and\n"
"it is not stored in the wallet or transmitted to the network.");
RPCTypeCheck(params, list_of(array_type)(obj_type));
Array inputs = params[0].get_array();
Object sendTo = params[1].get_obj();
CTransaction rawTx;
BOOST_FOREACH(const Value& input, inputs)
{
const Object& o = input.get_obj();
uint256 txid = ParseHashO(o, "txid");
const Value& vout_v = find_value(o, "vout");
if (vout_v.type() != int_type)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key");
int nOutput = vout_v.get_int();
if (nOutput < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive");
CTxIn in(COutPoint(txid, nOutput));
rawTx.vin.push_back(in);
}
set<CBitcoinAddress> setAddress;
BOOST_FOREACH(const Pair& s, sendTo)
{
CBitcoinAddress address(s.name_);
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Giarcoin address: ")+s.name_);
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+s.name_);
setAddress.insert(address);
CScript scriptPubKey;
scriptPubKey.SetDestination(address.Get());
int64 nAmount = AmountFromValue(s.value_);
CTxOut out(nAmount, scriptPubKey);
rawTx.vout.push_back(out);
}
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << rawTx;
return HexStr(ss.begin(), ss.end());
}
Value decoderawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"decoderawtransaction <hex string>\n"
"Return a JSON object representing the serialized, hex-encoded transaction.");
vector<unsigned char> txData(ParseHexV(params[0], "argument"));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
CTransaction tx;
try {
ssData >> tx;
}
catch (std::exception &e) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
}
Object result;
TxToJSON(tx, 0, result);
return result;
}
Value signrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 4)
throw runtime_error(
"signrawtransaction <hex string> [{\"txid\":txid,\"vout\":n,\"scriptPubKey\":hex,\"redeemScript\":hex},...] [<privatekey1>,...] [sighashtype=\"ALL\"]\n"
"Sign inputs for raw transaction (serialized, hex-encoded).\n"
"Second optional argument (may be null) is an array of previous transaction outputs that\n"
"this transaction depends on but may not yet be in the block chain.\n"
"Third optional argument (may be null) is an array of base58-encoded private\n"
"keys that, if given, will be the only keys used to sign the transaction.\n"
"Fourth optional argument is a string that is one of six values; ALL, NONE, SINGLE or\n"
"ALL|ANYONECANPAY, NONE|ANYONECANPAY, SINGLE|ANYONECANPAY.\n"
"Returns json object with keys:\n"
" hex : raw transaction with signature(s) (hex-encoded string)\n"
" complete : 1 if transaction has a complete set of signature (0 if not)"
+ HelpRequiringPassphrase());
RPCTypeCheck(params, list_of(str_type)(array_type)(array_type)(str_type), true);
vector<unsigned char> txData(ParseHexV(params[0], "argument 1"));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
vector<CTransaction> txVariants;
while (!ssData.empty())
{
try {
CTransaction tx;
ssData >> tx;
txVariants.push_back(tx);
}
catch (std::exception &e) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
}
}
if (txVariants.empty())
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Missing transaction");
// mergedTx will end up with all the signatures; it
// starts as a clone of the rawtx:
CTransaction mergedTx(txVariants[0]);
bool fComplete = true;
// Fetch previous transactions (inputs):
CCoinsView viewDummy;
CCoinsViewCache view(viewDummy);
{
LOCK(mempool.cs);
CCoinsViewCache &viewChain = *pcoinsTip;
CCoinsViewMemPool viewMempool(viewChain, mempool);
view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view
BOOST_FOREACH(const CTxIn& txin, mergedTx.vin) {
const uint256& prevHash = txin.prevout.hash;
CCoins coins;
view.GetCoins(prevHash, coins); // this is certainly allowed to fail
}
view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long
}
bool fGivenKeys = false;
CBasicKeyStore tempKeystore;
if (params.size() > 2 && params[2].type() != null_type)
{
fGivenKeys = true;
Array keys = params[2].get_array();
BOOST_FOREACH(Value k, keys)
{
CBitcoinSecret vchSecret;
bool fGood = vchSecret.SetString(k.get_str());
if (!fGood)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
CKey key = vchSecret.GetKey();
tempKeystore.AddKey(key);
}
}
else
EnsureWalletIsUnlocked();
// Add previous txouts given in the RPC call:
if (params.size() > 1 && params[1].type() != null_type)
{
Array prevTxs = params[1].get_array();
BOOST_FOREACH(Value& p, prevTxs)
{
if (p.type() != obj_type)
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}");
Object prevOut = p.get_obj();
RPCTypeCheck(prevOut, map_list_of("txid", str_type)("vout", int_type)("scriptPubKey", str_type));
uint256 txid = ParseHashO(prevOut, "txid");
int nOut = find_value(prevOut, "vout").get_int();
if (nOut < 0)
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive");
vector<unsigned char> pkData(ParseHexO(prevOut, "scriptPubKey"));
CScript scriptPubKey(pkData.begin(), pkData.end());
CCoins coins;
if (view.GetCoins(txid, coins)) {
if (coins.IsAvailable(nOut) && coins.vout[nOut].scriptPubKey != scriptPubKey) {
string err("Previous output scriptPubKey mismatch:\n");
err = err + coins.vout[nOut].scriptPubKey.ToString() + "\nvs:\n"+
scriptPubKey.ToString();
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);
}
// what todo if txid is known, but the actual output isn't?
}
if ((unsigned int)nOut >= coins.vout.size())
coins.vout.resize(nOut+1);
coins.vout[nOut].scriptPubKey = scriptPubKey;
coins.vout[nOut].nValue = 0; // we don't know the actual output value
view.SetCoins(txid, coins);
// if redeemScript given and not using the local wallet (private keys
// given), add redeemScript to the tempKeystore so it can be signed:
if (fGivenKeys && scriptPubKey.IsPayToScriptHash())
{
RPCTypeCheck(prevOut, map_list_of("txid", str_type)("vout", int_type)("scriptPubKey", str_type)("redeemScript",str_type));
Value v = find_value(prevOut, "redeemScript");
if (!(v == Value::null))
{
vector<unsigned char> rsData(ParseHexV(v, "redeemScript"));
CScript redeemScript(rsData.begin(), rsData.end());
tempKeystore.AddCScript(redeemScript);
}
}
}
}
const CKeyStore& keystore = ((fGivenKeys || !pwalletMain) ? tempKeystore : *pwalletMain);
int nHashType = SIGHASH_ALL;
if (params.size() > 3 && params[3].type() != null_type)
{
static map<string, int> mapSigHashValues =
boost::assign::map_list_of
(string("ALL"), int(SIGHASH_ALL))
(string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY))
(string("NONE"), int(SIGHASH_NONE))
(string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY))
(string("SINGLE"), int(SIGHASH_SINGLE))
(string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY))
;
string strHashType = params[3].get_str();
if (mapSigHashValues.count(strHashType))
nHashType = mapSigHashValues[strHashType];
else
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid sighash param");
}
bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
// Sign what we can:
for (unsigned int i = 0; i < mergedTx.vin.size(); i++)
{
CTxIn& txin = mergedTx.vin[i];
CCoins coins;
if (!view.GetCoins(txin.prevout.hash, coins) || !coins.IsAvailable(txin.prevout.n))
{
fComplete = false;
continue;
}
const CScript& prevPubKey = coins.vout[txin.prevout.n].scriptPubKey;
txin.scriptSig.clear();
// Only sign SIGHASH_SINGLE if there's a corresponding output:
if (!fHashSingle || (i < mergedTx.vout.size()))
SignSignature(keystore, prevPubKey, mergedTx, i, nHashType);
// ... and merge in other signatures:
BOOST_FOREACH(const CTransaction& txv, txVariants)
{
txin.scriptSig = CombineSignatures(prevPubKey, mergedTx, i, txin.scriptSig, txv.vin[i].scriptSig);
}
if (!VerifyScript(txin.scriptSig, prevPubKey, mergedTx, i, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC, 0))
fComplete = false;
}
Object result;
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << mergedTx;
result.push_back(Pair("hex", HexStr(ssTx.begin(), ssTx.end())));
result.push_back(Pair("complete", fComplete));
return result;
}
Value sendrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 1)
throw runtime_error(
"sendrawtransaction <hex string>\n"
"Submits raw transaction (serialized, hex-encoded) to local node and network.");
// parse hex string from parameter
vector<unsigned char> txData(ParseHexV(params[0], "parameter"));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
CTransaction tx;
// deserialize binary data stream
try {
ssData >> tx;
}
catch (std::exception &e) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
}
uint256 hashTx = tx.GetHash();
bool fHave = false;
CCoinsViewCache &view = *pcoinsTip;
CCoins existingCoins;
{
fHave = view.GetCoins(hashTx, existingCoins);
if (!fHave) {
// push to local node
CValidationState state;
if (!tx.AcceptToMemoryPool(state, true, false))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX rejected"); // TODO: report validation state
}
}
if (fHave) {
if (existingCoins.nHeight < 1000000000)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "transaction already in block chain");
// Not in block, but already in the memory pool; will drop
// through to re-relay it.
} else {
SyncWithWallets(hashTx, tx, NULL, true);
}
RelayTransaction(tx, hashTx);
return hashTx.GetHex();
}
| [
"acunzomarco@live.it"
] | acunzomarco@live.it |
b36376c952f41e39ef7ed4cee7fc3218a70ddc34 | c01e34827cc944b1250418a083ce2c7162d81b63 | /Masters/Programming Parallel Computers/is4/is.cc | cfc7eb0361ca02c03989d7913f03ae80415c30d4 | [] | no_license | wessamKoraim/University-Projects | e49d088d9bef17248e262c83d096708b0894d38a | f40690e1b159835c72ce4b5766d81d9b099f4c12 | refs/heads/master | 2021-07-14T03:02:09.888294 | 2019-12-14T00:00:44 | 2019-12-14T00:00:44 | 137,661,115 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,441 | cc | #include "is.h"
#include <iostream>
#include <cstring>
#include <cstdint>
#include <omp.h>
using namespace std;
typedef double double4_t __attribute__ ((vector_size (4 * sizeof(double))));
typedef struct
{
double h;
Result r;
}HelperStruct;
Result segment(int ny, int nx, const float* data)
{
Result result { 0, 0, 0, 0, {0, 0, 0}, {0, 0, 0} };
int sum_nx = nx+1;
int sum_ny = ny+1;
double4_t s[ sum_nx * sum_ny ];
for(int x = 0; x < sum_nx; x++ )
{
s[x][0]=0;
s[x][1]=0;
s[x][2]=0;
}
for(int y = 0; y < sum_ny; y++ )
{
s[sum_nx*y][0]=0;
s[sum_nx*y][1]=0;
s[sum_nx*y][2]=0;
}
s[ 1 + sum_nx][0] = (double)data[0];
s[ 1 + sum_nx][1] = (double)data[1];
s[ 1 + sum_nx][2] = (double)data[2];
HelperStruct Helper[ ny ];
#pragma omp parallel for
for( int c = 0; c < 3; c++ )
{
for( int x = 3; x < 3 * nx; x += 3 )
{
s[ 1 + x/3 + sum_nx ][c] = (double)data[ c + x ] + s[1 + x/3 - 1 + sum_nx ][c];
}
for ( int y = 2; y < sum_ny; y++ )
{
for ( int x = 1; x < sum_nx; x++ )
{
int ind = x + sum_nx * y;
int ind3 = x + sum_nx * ( y - 1 );
if( x == 0 )
{
s[ ind ][ c ] = (double)data[ c + 3 * (x-1) + 3 * nx * (y-1) ] + s[ ind3 ][ c ];
}
else
{
int ind2 = ( x -1 ) + sum_nx * y;
int ind4 = ( x -1 ) + sum_nx * (y-1);
s[ ind ][ c ] = (double)data[ c + 3 * (x-1) + 3 * nx * (y-1) ] + s[ ind2 ][ c ] - s[ ind4 ][ c ] + s[ ind3 ][ c ];
}
}
}
}
double h = 0;
const double4_t sy = s[ ( sum_nx - 1 ) + sum_nx * ( sum_ny -1 ) ];
#pragma omp parallel for schedule (dynamic,1) num_threads( omp_get_max_threads())
for( int len_y = 1; len_y <= ny; len_y++ )
{
Result LoopResult;
double tmp = 0;
for( int len_x = 1; len_x <= nx; len_x++ )
{
double X = (double) (len_x * len_y);
double Y = (double) (nx * ny - X);
double tmp_X = 1/X;
double tmp_Y = 1/Y;
double4_t X_inv= {tmp_X,tmp_X,tmp_X,tmp_X};
double4_t Y_inv={tmp_Y,tmp_Y,tmp_Y,tmp_Y};
for( int pos_y = 1; pos_y <= sum_ny - len_y; pos_y++ )
{
for( int pos_x = 1; pos_x <= sum_nx - len_x; pos_x++ )
{
int x1 = pos_x + len_x - 1;
int y1 = pos_y + len_y - 1;
double4_t vx;
double4_t vy;
double h_loop = 0;
vx = s[ x1 + sum_nx * y1 ] -
s[ x1 + sum_nx * ( pos_y - 1 ) ] -
s[ ( pos_x - 1 ) + sum_nx * y1 ] +
s [ ( pos_x - 1 ) + sum_nx * ( pos_y - 1) ];
vy = sy - vx;
double4_t a = vx * vx / X;
double4_t b = vy * vy / Y;
for( int c = 0; c < 3; ++ c )
{
h_loop += ( a[c] + b[c] );
}
vx *= X_inv;
vy *= Y_inv;
if( h_loop > tmp )
{
LoopResult.x0 = pos_x - 1;
LoopResult.x1 = x1;
LoopResult.y0 = pos_y - 1;
LoopResult.y1 = y1;
LoopResult.outer[ 0 ] = (float)(vy[ 0 ]);
LoopResult.outer[ 1 ] = (float)(vy[ 1 ]);
LoopResult.outer[ 2 ] = (float)(vy[ 2 ]);
LoopResult.inner[ 0 ] = (float)(vx[ 0 ]);
LoopResult.inner[ 1 ] = (float)(vx[ 1 ]);
LoopResult.inner[ 2 ] = (float)(vx[ 2 ]);
tmp = h_loop;
}
}
}
}
Helper[len_y - 1].r = LoopResult;
Helper[len_y - 1].h = tmp;
}
for( int y = 0; y < ny; y++ )
{
if( Helper[y].h > h )
{
h = Helper[y].h;
result = Helper[y].r;
}
}
return result;
}
| [
"wesam.koraim@aalto.fi"
] | wesam.koraim@aalto.fi |
9c514bb35c1ac7a80e422ea5aa71cefd9395ee84 | db6472f1fb7f91aabf3dbc070ca102cd62819232 | /P126/ABCBank-0.3.2/ABCBank/BankServer/CMD/Transfer.cpp | 6f7cff0f38edab895ad447dbbe40bc6cab5d3dfe | [] | no_license | Jiwangreal/learn_cpp_with_me | 4d73c6948ab661a25e679fb28aa2fe23846a021b | 2aaf71899fbd1e1ea4bdc472133f7df41e8ab63b | refs/heads/main | 2023-05-05T22:46:13.528739 | 2021-05-30T10:49:31 | 2021-05-30T10:49:31 | 311,383,491 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,951 | cpp | #include "Transfer.h"
#include "../DAL/BankService.h"
#include "../../Public/Logging.h"
#include "../../Public/JUtil.h"
#include "../../Public/JInStream.h"
#include "../../Public/JOutStream.h"
using namespace PUBLIC;
using namespace CMD;
using namespace DAL;
void Transfer::Execute(BankSession& session)
{
JInStream jis(session.GetRequestPack()->buf, session.GetRequestPack()->head.len);
uint16 cmd = session.GetCmd();
// 帐号id
char account_id[7] = {0};
jis.ReadBytes(account_id, 6);
// 密码
char encryptedPass[16] = {0};
jis.ReadBytes(encryptedPass, 16);
unsigned char ideaKey[16];
unsigned char buf[2];
buf[0] = (cmd >> 8) & 0xff;
buf[1] = cmd & 0xff;
MD5 md5;
md5.MD5Make(ideaKey, buf, 2);
for (int i=0; i<8; ++i)
{
ideaKey[i] = ideaKey[i] ^ ideaKey[i+8];
ideaKey[i] = ideaKey[i] ^ ((cmd >> (i%2)) & 0xff);
ideaKey[i+8] = ideaKey[i] ^ ideaKey[i+8];
ideaKey[i+8] = ideaKey[i+8] ^ ((cmd >> (i%2)) & 0xff);
}
char pass[16];
Idea idea;
idea.Crypt(ideaKey, (const unsigned char*)encryptedPass, (unsigned char *)pass, 16, false); // 解密
Account acc;
acc.pass = pass;
// 金额
string money;
jis>>money;
// 对方帐号
char other_account_id[7] = {0};
jis.ReadBytes(other_account_id, 6);
// 以下转帐操作
BankService dao;
int16 error_code = 0;
char error_msg[31] = {0};
acc.account_id = Convert::StringToInt(account_id);
acc.balance = Convert::StringToDouble(money);
int ret = dao.Transfer(acc, other_account_id);
if (ret == 0)
{
LOG_INFO<<"转帐成功";
}
else if (ret == 2)
{
error_code = 2;
strcpy_s(error_msg, "帐户不存在");
LOG_INFO<<error_msg;
}
else if (ret == 3)
{
error_code = 3;
strcpy_s(error_msg, "密码错误");
LOG_INFO<<error_msg;
}
else if (ret == 4)
{
error_code = 4;
strcpy_s(error_msg, "余额不足");
LOG_INFO<<error_msg;
}
else if (ret == 5)
{
error_code = 5;
strcpy_s(error_msg, "对方帐号不存在");
LOG_INFO<<error_msg;
}
else if (ret == -1)
{
error_code = -1;
strcpy_s(error_msg, "数据库错误");
}
JOutStream jos;
// 包头cmd+len+cnt+seq+error_code+error_msg
jos<<cmd;
size_t lengthPos = jos.Length(); // len位置
jos.Skip(2); // 为len预留两个字节
uint16 cnt = 0;
uint16 seq = 0;
jos<<cnt<<seq<<error_code;
jos.WriteBytes(error_msg, 30);
// 包体
if (error_code == 0)
{
string balance = Convert::DoubleToString(acc.balance);
jos<<acc.name<<balance;
jos.WriteBytes(acc.op_date.c_str(), 19);
}
// 包头len字段
size_t tailPos = jos.Length();
jos.Reposition(lengthPos);
jos<<(uint16)(tailPos + 8 - sizeof(ResponseHead)); // 包体+包尾长度
// 包尾
jos.Reposition(tailPos);
unsigned char hash[16];
md5.MD5Make(hash, (unsigned char const*)jos.Data(), jos.Length());
for (int i=0; i<8; ++i)
{
hash[i] = hash[i] ^ hash[i+8];
hash[i] = hash[i] ^ ((cmd >> (i%2)) & 0xff);
}
jos.WriteBytes(hash, 8);
session.Send(jos.Data(), jos.Length());
}
| [
"jiwangreal@163.com"
] | jiwangreal@163.com |
96fd8c1e1a0934cfd3d18c277d6acc8db03fd468 | deff4e4c4cd5888b35e8994c6aeb37e3affa863b | /!!6439_cross.cc | 5c859a77ebb8a51cdcf721defbdc21d427689a04 | [] | no_license | sonyy789/algospot | e3748ddba5392fcd7b4c6da4c7fc5f4a2c1c5b7d | 8ab295e01d7b576141530a7bd44438e112697249 | refs/heads/master | 2020-05-21T23:41:39.542936 | 2019-04-16T07:44:54 | 2019-04-16T07:44:54 | 48,023,987 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,787 | cc | #include <cstdio>
#include <algorithm>
using namespace std;
struct POINT{
int x, y;
bool operator <(const POINT &A)const{
return x == A.x?y<A.y:x<A.x;
}
};
POINT A,B,R[4];
int ccw(POINT P1, POINT P2, POINT P3){
int t = P1.x*P2.y+P2.x*P3.y+P3.x*P1.y-P1.y*P2.x-P2.y*P3.x-P3.y*P1.x;
return t<0?-1:t>0;
}
bool isCross(int idx1, int idx2){
int ab = ccw(A,B,R[idx1])*ccw(A,B,R[idx2]);
int cd = ccw(R[idx1], R[idx2], A)*ccw(R[idx1],R[idx2], B);
if(ab == 0 && cd == 0){
pair<POINT, POINT> P1, P2;
if(A<B) P1 = {A,B};
else P1 = {B,A};
if(R[idx1]<R[idx2]) P2 = {R[idx1],R[idx2]};
else P2 = {R[idx2],R[idx1]};
if((P1.first < P2.first && P1.second < P2.first)||(P2.first < P1.first && P2.second < P1.first)) return false;
}
return ab<=0&&cd<=0;
}
void swap(POINT &P1, POINT &P2){
POINT T;
T.y = P1.y; T.x = P1.x;
P1.y = P2.y, P1.x = P2.x;
P2.y = T.y, P2.x = T.x;
}
int main(){
int t, minY, maxY, minX, maxX;
scanf("%d", &t);
while(t--){
scanf("%d%d%d%d%d%d%d%d",&A.x, &A.y,&B.x, &B.y, &R[0].x, &R[0].y,&R[2].x, &R[2].y);
if(R[0].y < R[2].y) swap(R[0], R[2]);
maxY = R[0].y; minY = R[2].y;
if(R[0].x > R[2].x){
maxX = R[0].x, minX = R[2].x;
R[1] = {maxX, minY}; R[3] = {minX, maxY};
}else{
maxX = R[2].x, minX = R[0].x;
R[1] = {maxX, maxY}; R[3] = {minX, minY};
}
if(A.y < maxY && B.y < maxY && A.y > minY && B.y > minY && A.x < maxX && B.x < maxX && A.x > minX && B.x > minX) {printf("T\n"); continue;}
int f = 1;
for(int i = 0; i < 4; i++)
if(isCross(i, (i+1)%4)) {f=0; break;}
if(f) printf("F\n");
else printf("T\n");
}
} | [
"sonyy453@naver.com"
] | sonyy453@naver.com |
da452681b3201885062a008d184e7a3b45c60e93 | 83716a38c589e8bfccd7046daebb0227118c846c | /sscom_test1/widget.h | 05ade34a3649aefcc8c54c08567f24da370b4daa | [] | no_license | misc-song/QTPro | e3a5474d2a5174be1cb963daea7284d285ff8e1f | f988c919e8f02cb7816eabded1eea14f278c625b | refs/heads/master | 2021-07-21T09:14:55.735709 | 2017-10-31T19:10:14 | 2017-10-31T19:10:14 | 109,042,004 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 484 | h | #ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QtSerialPort/QSerialPort>
#include <QtSerialPort/QSerialPortInfo>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
private slots:
void on_clearBtn_clicked();
void on_sendBtn_clicked();
void on_linkBtn_clicked();
void Read_Data();
private:
Ui::Widget *ui;
QSerialPort *serial;
};
#endif // WIDGET_H
| [
"wqshj@126.com"
] | wqshj@126.com |
c54c40581e3ae45b8c2e7b6e191dc9f2caf9694e | 07c61596c1fba2e2a7034fe5af9707794ea2e2c1 | /Leetcode/61/61.cpp | 012618d8279bb63ee47cfd9a48b09911241c1b32 | [] | no_license | H-Shen/Collection_of_my_coding_practice | 2fcb2f8fef9451ad4a3a9c063bbf6a34ea5966b4 | 6415552d38a756c9c89de0c774799654c73073a6 | refs/heads/master | 2023-08-24T21:19:08.886667 | 2023-08-22T03:47:39 | 2023-08-22T03:47:39 | 180,731,825 | 8 | 1 | null | 2021-08-13T18:25:25 | 2019-04-11T06:48:09 | C++ | UTF-8 | C++ | false | false | 957 | cpp | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if (!head || k == 0) {
return head;
}
int n = 0;
auto node(head);
while (node) {
++n;
node = node->next;
}
k %= n;
auto dummy = new ListNode();
dummy->next = head;
node = dummy;
for (int i = 0; i < n - k; ++i) {
node = node->next;
}
auto node2(head);
while (node2->next) {
node2 = node2->next;
}
node2->next = dummy->next;
dummy->next = node->next;
node->next = nullptr;
return dummy->next;
}
}; | [
"haohu3991@gmail.com"
] | haohu3991@gmail.com |
f35c1b8e60be1eeae8794d97b15857d777ff6886 | 043eb9b100070cef1a522ffea1c48f8f8d969ac7 | /ios_proj/wwj/Classes/Native/mscorlib_System_Array_InternalEnumerator_1_gen3404931059.h | b6f5e45343dd0f6009762d19d703a942b2fd0222 | [] | no_license | spidermandl/wawaji | 658076fcac0c0f5975eb332a52310a61a5396c25 | 209ef57c14f7ddd1b8309fc808501729dda58071 | refs/heads/master | 2021-01-18T16:38:07.528225 | 2017-10-19T09:57:00 | 2017-10-19T09:57:00 | 100,465,677 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,442 | h | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
#include "mscorlib_System_ValueType3507792607.h"
// System.Array
struct Il2CppArray;
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Array/InternalEnumerator`1<System.Text.EncodingInfo>
struct InternalEnumerator_1_t3404931059
{
public:
// System.Array System.Array/InternalEnumerator`1::array
Il2CppArray * ___array_0;
// System.Int32 System.Array/InternalEnumerator`1::idx
int32_t ___idx_1;
public:
inline static int32_t get_offset_of_array_0() { return static_cast<int32_t>(offsetof(InternalEnumerator_1_t3404931059, ___array_0)); }
inline Il2CppArray * get_array_0() const { return ___array_0; }
inline Il2CppArray ** get_address_of_array_0() { return &___array_0; }
inline void set_array_0(Il2CppArray * value)
{
___array_0 = value;
Il2CppCodeGenWriteBarrier(&___array_0, value);
}
inline static int32_t get_offset_of_idx_1() { return static_cast<int32_t>(offsetof(InternalEnumerator_1_t3404931059, ___idx_1)); }
inline int32_t get_idx_1() const { return ___idx_1; }
inline int32_t* get_address_of_idx_1() { return &___idx_1; }
inline void set_idx_1(int32_t value)
{
___idx_1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| [
"Desmond@Desmonds-MacBook-Pro.local"
] | Desmond@Desmonds-MacBook-Pro.local |
c90f08e74636a8e22679dadedecf5f028ce73e1d | d29a3d35c2484e84743f1557c209e934880d2e74 | /src/122BestTimeToBuyAndSellStockII/122BestTimeToBuyAndSellStockII.cpp | 72a83b29bb0412013e21638d5d2575eec82021e8 | [] | no_license | rainliu/leetcode | 2e68dd4839ac55b1f16f519c67b526c7b773874c | 5b31ebcbdbe0caffce0a9b4833170eb040396066 | refs/heads/master | 2022-07-21T05:41:23.838958 | 2022-07-15T20:39:59 | 2022-07-15T20:39:59 | 30,811,637 | 12 | 1 | null | 2022-07-15T20:40:00 | 2015-02-14T23:06:26 | C++ | UTF-8 | C++ | false | false | 1,516 | cpp | #include <sstream>
#include <iostream>
#include <string>
#include <vector>
#include <stack>
#include <unordered_map>
#include <algorithm>
#include <limits>
using namespace std;
/*
https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit.
You may complete as many transactions as you like
(ie, buy one and sell one share of the stock multiple times).
However, you may not engage in multiple transactions at the same time
(ie, you must sell the stock before you buy again).
E[i, j] = max(E[i, j-1]+diff(j-1, j), E[i, j-1], diff(i, j)), if diff(i, j)>=0
= max(E[i, j-1]+diff(j-1, j), E[i, j-1]), and update i, otherwise
*/
class Solution {
public:
int maxProfit(vector<int> &prices) {
int n = prices.size();
if(n<=1) return 0;
vector<int> E(n, 0);
int i = 0;
E[0] = 0;
for(int j=1; j<n; ++j){
if(prices[j]-prices[i]>=0){
E[j] = max(E[j-1], prices[j]-prices[i]);
}else{
E[j] = E[j-1];
i = j;
}
if(prices[j]-prices[j-1]>=0){
E[j] = max(E[j-1]+prices[j]-prices[j-1], E[j]);
}
}
return E[n-1];
}
};
int main(){
Solution s;
{
vector<int> prices1{6, 1, 3, 2, 4, 7};
cout<<s.maxProfit(prices1)<<endl;
vector<int> prices2{3, 4, 5, 7, 1, 6};
cout<<s.maxProfit(prices2)<<endl;
}
return 0;
} | [
"yliu@live.com"
] | yliu@live.com |
a5c808d01356be61495df2866776ef00ab77d6ed | 536656cd89e4fa3a92b5dcab28657d60d1d244bd | /third_party/blink/renderer/core/paint/inline_text_box_painter.cc | 97265da0b0ca358b3385c36c1fbc58489cf48947 | [
"LGPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-1.0-or-later",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | permissive | ECS-251-W2020/chromium | 79caebf50443f297557d9510620bf8d44a68399a | ac814e85cb870a6b569e184c7a60a70ff3cb19f9 | refs/heads/master | 2022-08-19T17:42:46.887573 | 2020-03-18T06:08:44 | 2020-03-18T06:08:44 | 248,141,336 | 7 | 8 | BSD-3-Clause | 2022-07-06T20:32:48 | 2020-03-18T04:52:18 | null | UTF-8 | C++ | false | false | 38,567 | cc | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/core/paint/inline_text_box_painter.h"
#include "base/optional.h"
#include "third_party/blink/renderer/core/content_capture/content_capture_manager.h"
#include "third_party/blink/renderer/core/editing/editor.h"
#include "third_party/blink/renderer/core/editing/markers/composition_marker.h"
#include "third_party/blink/renderer/core/editing/markers/document_marker_controller.h"
#include "third_party/blink/renderer/core/editing/markers/text_match_marker.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/layout/api/line_layout_api_shim.h"
#include "third_party/blink/renderer/core/layout/api/line_layout_box.h"
#include "third_party/blink/renderer/core/layout/layout_text_combine.h"
#include "third_party/blink/renderer/core/layout/layout_theme.h"
#include "third_party/blink/renderer/core/layout/line/inline_text_box.h"
#include "third_party/blink/renderer/core/layout/text_decoration_offset.h"
#include "third_party/blink/renderer/core/paint/applied_decoration_painter.h"
#include "third_party/blink/renderer/core/paint/decoration_info.h"
#include "third_party/blink/renderer/core/paint/document_marker_painter.h"
#include "third_party/blink/renderer/core/paint/paint_info.h"
#include "third_party/blink/renderer/core/paint/paint_timing_detector.h"
#include "third_party/blink/renderer/core/paint/selection_painting_utils.h"
#include "third_party/blink/renderer/core/paint/text_painter.h"
#include "third_party/blink/renderer/platform/graphics/dom_node_id.h"
#include "third_party/blink/renderer/platform/graphics/graphics_context_state_saver.h"
#include "third_party/blink/renderer/platform/graphics/paint/drawing_recorder.h"
#include "third_party/blink/renderer/platform/graphics/paint/paint_record.h"
#include "third_party/blink/renderer/platform/graphics/paint/paint_recorder.h"
#include "third_party/blink/renderer/platform/graphics/paint/paint_shader.h"
#include "third_party/skia/include/effects/SkGradientShader.h"
namespace blink {
namespace {
// If an inline text box is truncated by an ellipsis, text box markers paint
// over the ellipsis and other marker types don't. Other marker types that want
// the normal behavior should use MarkerPaintStartAndEnd().
std::pair<unsigned, unsigned> GetTextMatchMarkerPaintOffsets(
const DocumentMarker& marker,
const InlineTextBox& text_box) {
// text_box.Start() returns an offset relative to the start of the layout
// object. We add the LineLayoutItem's TextStartOffset() to get a DOM offset
// (which is what DocumentMarker uses). This is necessary to get proper
// behavior with the :first-letter psuedo element.
const unsigned text_box_start =
text_box.Start() + text_box.GetLineLayoutItem().TextStartOffset();
DCHECK(marker.GetType() == DocumentMarker::kTextMatch ||
marker.GetType() == DocumentMarker::kTextFragment);
const unsigned start_offset = marker.StartOffset() > text_box_start
? marker.StartOffset() - text_box_start
: 0U;
const unsigned end_offset =
std::min(marker.EndOffset() - text_box_start, text_box.Len());
return std::make_pair(start_offset, end_offset);
}
DOMNodeId GetNodeHolder(Node* node) {
if (node && node->GetLayoutObject()) {
DCHECK(node->GetLayoutObject()->IsText());
return (ToLayoutText(node->GetLayoutObject()))->EnsureNodeId();
}
return kInvalidDOMNodeId;
}
} // anonymous namespace
static LineLayoutItem EnclosingUnderlineObject(
const InlineTextBox* inline_text_box) {
bool first_line = inline_text_box->IsFirstLineStyle();
for (LineLayoutItem current = inline_text_box->Parent()->GetLineLayoutItem();
;) {
if (current.IsLayoutBlock())
return current;
if (!current.IsLayoutInline() || current.IsRubyText())
return nullptr;
const ComputedStyle& style_to_use = current.StyleRef(first_line);
if (EnumHasFlags(style_to_use.GetTextDecoration(),
TextDecoration::kUnderline))
return current;
current = current.Parent();
if (!current)
return current;
if (Node* node = current.GetNode()) {
if (IsA<HTMLAnchorElement>(node) ||
node->HasTagName(html_names::kFontTag))
return current;
}
}
}
LayoutObject& InlineTextBoxPainter::InlineLayoutObject() const {
return *LineLayoutAPIShim::LayoutObjectFrom(
inline_text_box_.GetLineLayoutItem());
}
static void ComputeOriginAndWidthForBox(const InlineTextBox& box,
LayoutPoint& local_origin,
LayoutUnit& width) {
if (box.Truncation() != kCNoTruncation) {
bool ltr = box.IsLeftToRightDirection();
bool flow_is_ltr =
box.GetLineLayoutItem().StyleRef().IsLeftToRightDirection();
width = LayoutUnit(box.GetLineLayoutItem().Width(
ltr == flow_is_ltr ? box.Start() : box.Start() + box.Truncation(),
ltr == flow_is_ltr ? box.Truncation() : box.Len() - box.Truncation(),
box.TextPos(),
flow_is_ltr ? base::i18n::TextDirection::LEFT_TO_RIGHT
: base::i18n::TextDirection::RIGHT_TO_LEFT,
box.IsFirstLineStyle()));
if (!flow_is_ltr) {
local_origin.Move(box.LogicalWidth() - width, LayoutUnit());
}
}
}
void InlineTextBoxPainter::Paint(const PaintInfo& paint_info,
const LayoutPoint& paint_offset) {
if (!ShouldPaintTextBox(paint_info))
return;
DCHECK(!ShouldPaintSelfOutline(paint_info.phase) &&
!ShouldPaintDescendantOutlines(paint_info.phase));
LayoutRect logical_visual_overflow = inline_text_box_.LogicalOverflowRect();
LayoutUnit logical_start =
logical_visual_overflow.X() +
(inline_text_box_.IsHorizontal() ? paint_offset.X() : paint_offset.Y());
LayoutUnit logical_extent = logical_visual_overflow.Width();
if (inline_text_box_.IsHorizontal()) {
if (!paint_info.GetCullRect().IntersectsHorizontalRange(
logical_start, logical_start + logical_extent))
return;
} else {
if (!paint_info.GetCullRect().IntersectsVerticalRange(
logical_start, logical_start + logical_extent))
return;
}
bool is_printing = paint_info.IsPrinting();
// Determine whether or not we're selected.
bool have_selection = !is_printing &&
paint_info.phase != PaintPhase::kTextClip &&
inline_text_box_.IsSelected();
if (!have_selection && paint_info.phase == PaintPhase::kSelection) {
// When only painting the selection, don't bother to paint if there is none.
return;
}
// The text clip phase already has a DrawingRecorder. Text clips are initiated
// only in BoxPainter::PaintFillLayer, which is already within a
// DrawingRecorder.
base::Optional<DrawingRecorder> recorder;
if (paint_info.phase != PaintPhase::kTextClip) {
if (DrawingRecorder::UseCachedDrawingIfPossible(
paint_info.context, inline_text_box_, paint_info.phase))
return;
recorder.emplace(paint_info.context, inline_text_box_, paint_info.phase);
}
GraphicsContext& context = paint_info.context;
const ComputedStyle& style_to_use =
inline_text_box_.GetLineLayoutItem().StyleRef(
inline_text_box_.IsFirstLineStyle());
LayoutPoint box_origin(inline_text_box_.PhysicalLocation().ToLayoutPoint() +
paint_offset);
// We round the y-axis to ensure consistent line heights.
if (inline_text_box_.IsHorizontal()) {
box_origin.SetY(LayoutUnit(box_origin.Y().Round()));
} else {
box_origin.SetX(LayoutUnit(box_origin.X().Round()));
}
LayoutRect box_rect(box_origin, LayoutSize(inline_text_box_.LogicalWidth(),
inline_text_box_.LogicalHeight()));
unsigned length = inline_text_box_.Len();
const String& layout_item_string =
inline_text_box_.GetLineLayoutItem().GetText();
String first_line_string;
if (inline_text_box_.IsFirstLineStyle()) {
first_line_string = layout_item_string;
const ComputedStyle& style = inline_text_box_.GetLineLayoutItem().StyleRef(
inline_text_box_.IsFirstLineStyle());
style.ApplyTextTransform(
&first_line_string,
inline_text_box_.GetLineLayoutItem().PreviousCharacter());
// TODO(crbug.com/795498): this is a hack. The root issue is that
// capitalizing letters can change the length of the backing string.
// That needs to be taken into account when computing the size of the box
// or its painting.
if (inline_text_box_.Start() >= first_line_string.length())
return;
length =
std::min(length, first_line_string.length() - inline_text_box_.Start());
// TODO(szager): Figure out why this CHECK sometimes fails, it shouldn't.
CHECK_LE(inline_text_box_.Start() + length, first_line_string.length());
} else {
// TODO(szager): Figure out why this CHECK sometimes fails, it shouldn't.
CHECK_LE(inline_text_box_.Start() + length, layout_item_string.length());
}
StringView string =
StringView(inline_text_box_.IsFirstLineStyle() ? first_line_string
: layout_item_string,
inline_text_box_.Start(), length);
int maximum_length = inline_text_box_.GetLineLayoutItem().TextLength() -
inline_text_box_.Start();
StringBuilder characters_with_hyphen;
TextRun text_run = inline_text_box_.ConstructTextRun(
style_to_use, string, maximum_length,
inline_text_box_.HasHyphen() ? &characters_with_hyphen : nullptr);
if (inline_text_box_.HasHyphen())
length = text_run.length();
bool should_rotate = false;
LayoutTextCombine* combined_text = nullptr;
if (!inline_text_box_.IsHorizontal()) {
if (style_to_use.HasTextCombine() &&
inline_text_box_.GetLineLayoutItem().IsCombineText()) {
combined_text = &ToLayoutTextCombine(InlineLayoutObject());
if (!combined_text->IsCombined())
combined_text = nullptr;
}
if (combined_text) {
box_rect.SetWidth(combined_text->InlineWidthForLayout());
// Justfication applies to before and after the combined text as if
// it is an ideographic character, and is prohibited inside the
// combined text.
if (float expansion = text_run.Expansion()) {
text_run.SetExpansion(0);
if (text_run.AllowsLeadingExpansion()) {
if (text_run.AllowsTrailingExpansion())
expansion /= 2;
LayoutSize offset =
LayoutSize(LayoutUnit(), LayoutUnit::FromFloatRound(expansion));
box_origin.Move(offset);
box_rect.Move(offset);
}
}
} else {
should_rotate = true;
context.ConcatCTM(TextPainterBase::Rotation(PhysicalRect(box_rect),
TextPainterBase::kClockwise));
}
}
// Determine text colors.
TextPaintStyle text_style = TextPainterBase::TextPaintingStyle(
inline_text_box_.GetLineLayoutItem().GetDocument(), style_to_use,
paint_info);
TextPaintStyle selection_style = TextPainterBase::SelectionPaintingStyle(
inline_text_box_.GetLineLayoutItem().GetDocument(), style_to_use,
inline_text_box_.GetLineLayoutItem().GetNode(), have_selection,
paint_info, text_style);
bool paint_selected_text_only = (paint_info.phase == PaintPhase::kSelection);
bool paint_selected_text_separately =
!paint_selected_text_only && text_style != selection_style;
// Set our font.
const Font& font = style_to_use.GetFont();
const SimpleFontData* font_data = font.PrimaryFont();
DCHECK(font_data);
int ascent = font_data ? font_data->GetFontMetrics().Ascent() : 0;
LayoutPoint text_origin(box_origin.X(), box_origin.Y() + ascent);
const DocumentMarkerVector& markers_to_paint = ComputeMarkersToPaint();
// 1. Paint backgrounds behind text if needed. Examples of such backgrounds
// include selection and composition highlights.
if (paint_info.phase != PaintPhase::kSelection &&
paint_info.phase != PaintPhase::kTextClip && !is_printing) {
PaintDocumentMarkers(markers_to_paint, paint_info, box_origin, style_to_use,
font, DocumentMarkerPaintPhase::kBackground);
if (have_selection) {
if (combined_text)
PaintSelection<InlineTextBoxPainter::PaintOptions::kCombinedText>(
context, box_rect, style_to_use, font, selection_style.fill_color,
combined_text);
else
PaintSelection<InlineTextBoxPainter::PaintOptions::kNormal>(
context, box_rect, style_to_use, font, selection_style.fill_color);
}
}
// 2. Now paint the foreground, including text and decorations.
int selection_start = 0;
int selection_end = 0;
if (paint_selected_text_only || paint_selected_text_separately)
inline_text_box_.SelectionStartEnd(selection_start, selection_end);
bool respect_hyphen =
selection_end == static_cast<int>(inline_text_box_.Len()) &&
inline_text_box_.HasHyphen();
if (respect_hyphen)
selection_end = text_run.length();
bool ltr = inline_text_box_.IsLeftToRightDirection();
bool flow_is_ltr = inline_text_box_.GetLineLayoutItem()
.ContainingBlock()
.StyleRef()
.IsLeftToRightDirection();
const PaintOffsets& selection_offsets =
ApplyTruncationToPaintOffsets({static_cast<unsigned>(selection_start),
static_cast<unsigned>(selection_end)});
selection_start = selection_offsets.start;
selection_end = selection_offsets.end;
if (have_selection) {
font.ExpandRangeToIncludePartialGlyphs(text_run, &selection_start,
&selection_end);
}
if (inline_text_box_.Truncation() != kCNoTruncation) {
// In a mixed-direction flow the ellipsis is at the start of the text
// rather than at the end of it.
length =
ltr == flow_is_ltr ? inline_text_box_.Truncation() : text_run.length();
}
TextPainter text_painter(context, font, text_run, text_origin, box_rect,
inline_text_box_.IsHorizontal());
TextEmphasisPosition emphasis_mark_position;
bool has_text_emphasis = inline_text_box_.GetEmphasisMarkPosition(
style_to_use, emphasis_mark_position);
if (has_text_emphasis)
text_painter.SetEmphasisMark(style_to_use.TextEmphasisMarkString(),
emphasis_mark_position);
if (combined_text)
text_painter.SetCombinedText(combined_text);
if (inline_text_box_.Truncation() != kCNoTruncation && ltr != flow_is_ltr)
text_painter.SetEllipsisOffset(inline_text_box_.Truncation());
DOMNodeId node_id = GetNodeHolder(
LineLayoutAPIShim::LayoutObjectFrom(inline_text_box_.GetLineLayoutItem())
->GetNode());
if (!paint_selected_text_only) {
// Paint text decorations except line-through.
DecorationInfo decoration_info;
bool has_line_through_decoration = false;
if (style_to_use.TextDecorationsInEffect() != TextDecoration::kNone &&
inline_text_box_.Truncation() != kCFullTruncation) {
LayoutPoint local_origin = LayoutPoint(box_origin);
LayoutUnit width = inline_text_box_.LogicalWidth();
ComputeOriginAndWidthForBox(inline_text_box_, local_origin, width);
const LineLayoutItem& decorating_box =
EnclosingUnderlineObject(&inline_text_box_);
const ComputedStyle* decorating_box_style =
decorating_box ? decorating_box.Style() : nullptr;
text_painter.ComputeDecorationInfo(
decoration_info, PhysicalOffsetToBeNoop(box_origin),
PhysicalOffsetToBeNoop(local_origin), width,
inline_text_box_.Root().BaselineType(), style_to_use,
decorating_box_style);
TextDecorationOffset decoration_offset(*decoration_info.style,
&inline_text_box_, decorating_box);
text_painter.PaintDecorationsExceptLineThrough(
decoration_offset, decoration_info, paint_info,
style_to_use.AppliedTextDecorations(), text_style,
&has_line_through_decoration);
}
int start_offset = 0;
int end_offset = length;
// Where the text and its flow have opposite directions then our offset into
// the text given by |truncation| is at the start of the part that will be
// visible.
if (inline_text_box_.Truncation() != kCNoTruncation && ltr != flow_is_ltr) {
start_offset = inline_text_box_.Truncation();
end_offset = text_run.length();
}
if (paint_selected_text_separately && selection_start < selection_end) {
start_offset = selection_end;
end_offset = selection_start;
}
text_painter.Paint(start_offset, end_offset, length, text_style, node_id);
// Paint line-through decoration if needed.
if (has_line_through_decoration) {
text_painter.PaintDecorationsOnlyLineThrough(
decoration_info, paint_info, style_to_use.AppliedTextDecorations(),
text_style);
}
}
if ((paint_selected_text_only || paint_selected_text_separately) &&
selection_start < selection_end) {
// paint only the text that is selected.
// Because only a part of the text glyph can be selected, we need to draw
// the selection twice:
LayoutRect selection_rect =
GetSelectionRect<InlineTextBoxPainter::PaintOptions::kNormal>(
context, box_rect, style_to_use, font);
// the first time, we draw the glyphs outside the selection area, with
// the original style.
{
GraphicsContextStateSaver state_saver(context);
context.ClipOut(FloatRect(selection_rect));
text_painter.Paint(selection_start, selection_end, length, text_style,
node_id);
}
// the second time, we draw the glyphs inside the selection area, with
// the selection style.
{
GraphicsContextStateSaver state_saver(context);
context.Clip(FloatRect(selection_rect));
text_painter.Paint(selection_start, selection_end, length,
selection_style, node_id);
}
}
if (paint_info.phase == PaintPhase::kForeground) {
PaintDocumentMarkers(markers_to_paint, paint_info, box_origin, style_to_use,
font, DocumentMarkerPaintPhase::kForeground);
}
if (should_rotate) {
context.ConcatCTM(TextPainterBase::Rotation(
PhysicalRectToBeNoop(box_rect), TextPainterBase::kCounterclockwise));
}
if (!font.ShouldSkipDrawing())
PaintTimingDetector::NotifyTextPaint(inline_text_box_.VisualRect());
}
bool InlineTextBoxPainter::ShouldPaintTextBox(const PaintInfo& paint_info) {
// We can skip painting if the text box (including selection) is invisible.
if (inline_text_box_.Truncation() == kCFullTruncation ||
!inline_text_box_.Len() || inline_text_box_.VisualRect().IsEmpty())
return false;
return true;
}
InlineTextBoxPainter::PaintOffsets
InlineTextBoxPainter::ApplyTruncationToPaintOffsets(
const InlineTextBoxPainter::PaintOffsets& offsets) {
const uint16_t truncation = inline_text_box_.Truncation();
if (truncation == kCNoTruncation)
return offsets;
// If we're in mixed-direction mode (LTR text in an RTL box or vice-versa),
// the truncation ellipsis is at the *start* of the text box rather than the
// end.
bool ltr = inline_text_box_.IsLeftToRightDirection();
bool flow_is_ltr = inline_text_box_.GetLineLayoutItem()
.ContainingBlock()
.StyleRef()
.IsLeftToRightDirection();
// truncation is relative to the start of the InlineTextBox, not the text
// node.
if (ltr == flow_is_ltr) {
return {std::min<unsigned>(offsets.start, truncation),
std::min<unsigned>(offsets.end, truncation)};
}
return {std::max<unsigned>(offsets.start, truncation),
std::max<unsigned>(offsets.end, truncation)};
}
InlineTextBoxPainter::PaintOffsets InlineTextBoxPainter::MarkerPaintStartAndEnd(
const DocumentMarker& marker) {
// Text match markers are painted differently (in an inline text box truncated
// by an ellipsis, they paint over the ellipsis) and so should not use this
// function.
DCHECK(marker.GetType() != DocumentMarker::kTextMatch &&
marker.GetType() != DocumentMarker::kTextFragment);
DCHECK(inline_text_box_.Truncation() != kCFullTruncation);
DCHECK(inline_text_box_.Len());
// inline_text_box_.Start() returns an offset relative to the start of the
// layout object. We add the LineLayoutItem's TextStartOffset() to get a DOM
// offset (which is what DocumentMarker uses). This is necessary to get proper
// behavior with the :first-letter psuedo element.
const unsigned inline_text_box_start =
inline_text_box_.Start() +
inline_text_box_.GetLineLayoutItem().TextStartOffset();
// Start painting at the beginning of the text or the specified underline
// start offset, whichever is greater.
unsigned paint_start = std::max(inline_text_box_start, marker.StartOffset());
// Cap the maximum paint start to the last character in the text box.
paint_start = std::min(paint_start, inline_text_box_.end());
// End painting just past the end of the text or the specified underline end
// offset, whichever is less.
unsigned paint_end = std::min(
inline_text_box_.end() + 1,
marker.EndOffset()); // end() points at the last char, not past it.
// paint_start and paint_end are currently relative to the start of the text
// node. Subtract to make them relative to the start of the InlineTextBox.
paint_start -= inline_text_box_start;
paint_end -= inline_text_box_start;
return ApplyTruncationToPaintOffsets({paint_start, paint_end});
}
void InlineTextBoxPainter::PaintSingleMarkerBackgroundRun(
GraphicsContext& context,
const LayoutPoint& box_origin,
const ComputedStyle& style,
const Font& font,
Color background_color,
int start_pos,
int end_pos) {
if (background_color == Color::kTransparent)
return;
int delta_y = (inline_text_box_.GetLineLayoutItem()
.StyleRef()
.IsFlippedLinesWritingMode()
? inline_text_box_.Root().SelectionBottom() -
inline_text_box_.LogicalBottom()
: inline_text_box_.LogicalTop() -
inline_text_box_.Root().SelectionTop())
.ToInt();
int sel_height = inline_text_box_.Root().SelectionHeight().ToInt();
FloatPoint local_origin(box_origin.X().ToFloat(),
box_origin.Y().ToFloat() - delta_y);
context.DrawHighlightForText(font, inline_text_box_.ConstructTextRun(style),
local_origin, sel_height, background_color,
start_pos, end_pos);
}
DocumentMarkerVector InlineTextBoxPainter::ComputeMarkersToPaint() const {
Node* const node = inline_text_box_.GetLineLayoutItem().GetNode();
auto* text_node = DynamicTo<Text>(node);
if (!text_node)
return DocumentMarkerVector();
DocumentMarkerController& document_marker_controller =
inline_text_box_.GetLineLayoutItem().GetDocument().Markers();
return document_marker_controller.ComputeMarkersToPaint(*text_node);
}
void InlineTextBoxPainter::PaintDocumentMarkers(
const DocumentMarkerVector& markers_to_paint,
const PaintInfo& paint_info,
const LayoutPoint& box_origin,
const ComputedStyle& style,
const Font& font,
DocumentMarkerPaintPhase marker_paint_phase) {
if (!inline_text_box_.GetLineLayoutItem().GetNode())
return;
DCHECK(inline_text_box_.Truncation() != kCFullTruncation);
DCHECK(inline_text_box_.Len());
DocumentMarkerVector::const_iterator marker_it = markers_to_paint.begin();
// Give any document markers that touch this run a chance to draw before the
// text has been drawn. Note end() points at the last char, not one past it
// like endOffset and ranges do.
for (; marker_it != markers_to_paint.end(); ++marker_it) {
DCHECK(*marker_it);
const DocumentMarker& marker = **marker_it;
if (marker.EndOffset() <= inline_text_box_.Start()) {
// marker is completely before this run. This might be a marker that sits
// before the first run we draw, or markers that were within runs we
// skipped due to truncation.
continue;
}
if (marker.StartOffset() > inline_text_box_.end()) {
// marker is completely after this run, bail. A later run will paint it.
continue;
}
// marker intersects this run. Paint it.
switch (marker.GetType()) {
case DocumentMarker::kSpelling:
if (marker_paint_phase == DocumentMarkerPaintPhase::kBackground)
continue;
inline_text_box_.PaintDocumentMarker(paint_info.context, box_origin,
marker, style, font, false);
break;
case DocumentMarker::kGrammar:
if (marker_paint_phase == DocumentMarkerPaintPhase::kBackground)
continue;
inline_text_box_.PaintDocumentMarker(paint_info.context, box_origin,
marker, style, font, true);
break;
case DocumentMarker::kTextFragment:
case DocumentMarker::kTextMatch:
if (marker_paint_phase == DocumentMarkerPaintPhase::kBackground) {
inline_text_box_.PaintTextMarkerBackground(
paint_info, box_origin, To<TextMarkerBase>(marker), style, font);
} else {
inline_text_box_.PaintTextMarkerForeground(
paint_info, box_origin, To<TextMarkerBase>(marker), style, font);
}
break;
case DocumentMarker::kComposition:
case DocumentMarker::kActiveSuggestion:
case DocumentMarker::kSuggestion: {
const auto& styleable_marker = To<StyleableMarker>(marker);
if (marker_paint_phase == DocumentMarkerPaintPhase::kBackground) {
const PaintOffsets marker_offsets =
MarkerPaintStartAndEnd(styleable_marker);
PaintSingleMarkerBackgroundRun(
paint_info.context, box_origin, style, font,
styleable_marker.BackgroundColor(), marker_offsets.start,
marker_offsets.end);
} else {
PaintStyleableMarkerUnderline(paint_info.context, box_origin,
styleable_marker, style, font);
}
} break;
default:
// Marker is not painted, or painting code has not been added yet
break;
}
}
}
void InlineTextBoxPainter::PaintDocumentMarker(GraphicsContext& context,
const LayoutPoint& box_origin,
const DocumentMarker& marker,
const ComputedStyle& style,
const Font& font,
bool grammar) {
if (inline_text_box_.GetLineLayoutItem().GetDocument().Printing())
return;
if (inline_text_box_.Truncation() == kCFullTruncation)
return;
LayoutUnit start; // start of line to draw, relative to tx
LayoutUnit width = inline_text_box_.LogicalWidth(); // how much line to draw
// Determine whether we need to measure text
bool marker_spans_whole_box = true;
if (inline_text_box_.Start() <= marker.StartOffset())
marker_spans_whole_box = false;
if ((inline_text_box_.end() + 1) !=
marker.EndOffset()) // end points at the last char, not past it
marker_spans_whole_box = false;
if (inline_text_box_.Truncation() != kCNoTruncation)
marker_spans_whole_box = false;
if (!marker_spans_whole_box || grammar) {
const PaintOffsets& marker_offsets = MarkerPaintStartAndEnd(marker);
// Calculate start & width
int delta_y = (inline_text_box_.GetLineLayoutItem()
.StyleRef()
.IsFlippedLinesWritingMode()
? inline_text_box_.Root().SelectionBottom() -
inline_text_box_.LogicalBottom()
: inline_text_box_.LogicalTop() -
inline_text_box_.Root().SelectionTop())
.ToInt();
int sel_height = inline_text_box_.Root().SelectionHeight().ToInt();
LayoutPoint start_point(box_origin.X(), box_origin.Y() - delta_y);
TextRun run = inline_text_box_.ConstructTextRun(style);
// FIXME: Convert the document markers to float rects.
IntRect marker_rect = EnclosingIntRect(
font.SelectionRectForText(run, FloatPoint(start_point), sel_height,
marker_offsets.start, marker_offsets.end));
start = marker_rect.X() - start_point.X();
width = LayoutUnit(marker_rect.Width());
}
DocumentMarkerPainter::PaintDocumentMarker(
context, PhysicalOffsetToBeNoop(box_origin), style, marker.GetType(),
PhysicalRect(start, LayoutUnit(), width,
inline_text_box_.LogicalHeight()));
}
template <InlineTextBoxPainter::PaintOptions options>
LayoutRect InlineTextBoxPainter::GetSelectionRect(
GraphicsContext& context,
const LayoutRect& box_rect,
const ComputedStyle& style,
const Font& font,
LayoutTextCombine* combined_text) {
// See if we have a selection to paint at all.
int start_pos, end_pos;
inline_text_box_.SelectionStartEnd(start_pos, end_pos);
if (start_pos >= end_pos)
return LayoutRect();
// If the text is truncated, let the thing being painted in the truncation
// draw its own highlight.
unsigned start = inline_text_box_.Start();
int length = inline_text_box_.Len();
bool ltr = inline_text_box_.IsLeftToRightDirection();
bool flow_is_ltr = inline_text_box_.GetLineLayoutItem()
.ContainingBlock()
.StyleRef()
.IsLeftToRightDirection();
if (inline_text_box_.Truncation() != kCNoTruncation) {
// In a mixed-direction flow the ellipsis is at the start of the text
// so we need to start after it. Otherwise we just need to make sure
// the end of the text is where the ellipsis starts.
if (ltr != flow_is_ltr)
start_pos = std::max<int>(start_pos, inline_text_box_.Truncation());
else
length = inline_text_box_.Truncation();
}
StringView string(inline_text_box_.GetLineLayoutItem().GetText(), start,
static_cast<unsigned>(length));
StringBuilder characters_with_hyphen;
bool respect_hyphen = end_pos == length && inline_text_box_.HasHyphen();
TextRun text_run = inline_text_box_.ConstructTextRun(
style, string,
inline_text_box_.GetLineLayoutItem().TextLength() -
inline_text_box_.Start(),
respect_hyphen ? &characters_with_hyphen : nullptr);
if (respect_hyphen)
end_pos = text_run.length();
if (options == InlineTextBoxPainter::PaintOptions::kCombinedText) {
DCHECK(combined_text);
// We can't use the height of m_inlineTextBox because LayoutTextCombine's
// inlineTextBox is horizontal within vertical flow
combined_text->TransformToInlineCoordinates(context, box_rect, true);
}
LayoutUnit selection_bottom = inline_text_box_.Root().SelectionBottom();
LayoutUnit selection_top = inline_text_box_.Root().SelectionTop();
int delta_y =
RoundToInt(inline_text_box_.GetLineLayoutItem()
.StyleRef()
.IsFlippedLinesWritingMode()
? selection_bottom - inline_text_box_.LogicalBottom()
: inline_text_box_.LogicalTop() - selection_top);
int sel_height = std::max(0, RoundToInt(selection_bottom - selection_top));
FloatPoint local_origin(box_rect.X().ToFloat(),
(box_rect.Y() - delta_y).ToFloat());
LayoutRect selection_rect = LayoutRect(font.SelectionRectForText(
text_run, local_origin, sel_height, start_pos, end_pos));
// For line breaks, just painting a selection where the line break itself
// is rendered is sufficient. Don't select it if there's an ellipsis
// there.
if (inline_text_box_.HasWrappedSelectionNewline() &&
inline_text_box_.Truncation() == kCNoTruncation &&
!inline_text_box_.IsLineBreak())
ExpandToIncludeNewlineForSelection(selection_rect);
// Line breaks report themselves as having zero width for layout purposes,
// and so will end up positioned at (0, 0), even though we paint their
// selection highlight with character width. For RTL then, we have to
// explicitly shift the selection rect over to paint in the right location.
if (!inline_text_box_.IsLeftToRightDirection() &&
inline_text_box_.IsLineBreak())
selection_rect.Move(-selection_rect.Width(), LayoutUnit());
if (!flow_is_ltr && !ltr && inline_text_box_.Truncation() != kCNoTruncation) {
selection_rect.Move(
inline_text_box_.LogicalWidth() - selection_rect.Width(), LayoutUnit());
}
return selection_rect;
}
template <InlineTextBoxPainter::PaintOptions options>
void InlineTextBoxPainter::PaintSelection(GraphicsContext& context,
const LayoutRect& box_rect,
const ComputedStyle& style,
const Font& font,
Color text_color,
LayoutTextCombine* combined_text) {
auto layout_item = inline_text_box_.GetLineLayoutItem();
Color c = SelectionPaintingUtils::SelectionBackgroundColor(
layout_item.GetDocument(), layout_item.StyleRef(), layout_item.GetNode());
if (!c.Alpha())
return;
LayoutRect selection_rect =
GetSelectionRect<options>(context, box_rect, style, font, combined_text);
// If the text color ends up being the same as the selection background,
// invert the selection background.
if (text_color == c)
c = Color(0xff - c.Red(), 0xff - c.Green(), 0xff - c.Blue());
GraphicsContextStateSaver state_saver(context);
context.FillRect(FloatRect(selection_rect), c);
}
void InlineTextBoxPainter::ExpandToIncludeNewlineForSelection(
LayoutRect& rect) {
FloatRectOutsets outsets = FloatRectOutsets();
float space_width = inline_text_box_.NewlineSpaceWidth();
if (inline_text_box_.IsLeftToRightDirection())
outsets.SetRight(space_width);
else
outsets.SetLeft(space_width);
rect.Expand(outsets);
}
void InlineTextBoxPainter::PaintStyleableMarkerUnderline(
GraphicsContext& context,
const LayoutPoint& box_origin,
const StyleableMarker& marker,
const ComputedStyle& style,
const Font& font) {
if (inline_text_box_.Truncation() == kCFullTruncation)
return;
const PaintOffsets marker_offsets = MarkerPaintStartAndEnd(marker);
const TextRun& run = inline_text_box_.ConstructTextRun(style);
// Pass 0 for height since we only care about the width
const FloatRect& marker_rect = font.SelectionRectForText(
run, FloatPoint(), 0, marker_offsets.start, marker_offsets.end);
DocumentMarkerPainter::PaintStyleableMarkerUnderline(
context, PhysicalOffsetToBeNoop(box_origin), marker, style, marker_rect,
inline_text_box_.LogicalHeight());
}
void InlineTextBoxPainter::PaintTextMarkerForeground(
const PaintInfo& paint_info,
const LayoutPoint& box_origin,
const TextMarkerBase& marker,
const ComputedStyle& style,
const Font& font) {
if (marker.GetType() == DocumentMarker::kTextMatch &&
!InlineLayoutObject()
.GetFrame()
->GetEditor()
.MarkedTextMatchesAreHighlighted())
return;
const auto paint_offsets =
GetTextMatchMarkerPaintOffsets(marker, inline_text_box_);
TextRun run = inline_text_box_.ConstructTextRun(style);
const SimpleFontData* font_data = font.PrimaryFont();
DCHECK(font_data);
if (!font_data)
return;
const TextPaintStyle text_style =
DocumentMarkerPainter::ComputeTextPaintStyleFrom(
style, marker,
inline_text_box_.GetLineLayoutItem()
.GetDocument()
.InForcedColorsMode());
if (text_style.current_color == Color::kTransparent)
return;
LayoutRect box_rect(box_origin, LayoutSize(inline_text_box_.LogicalWidth(),
inline_text_box_.LogicalHeight()));
LayoutPoint text_origin(
box_origin.X(), box_origin.Y() + font_data->GetFontMetrics().Ascent());
TextPainter text_painter(paint_info.context, font, run, text_origin, box_rect,
inline_text_box_.IsHorizontal());
text_painter.Paint(paint_offsets.first, paint_offsets.second,
inline_text_box_.Len(), text_style, kInvalidDOMNodeId);
}
void InlineTextBoxPainter::PaintTextMarkerBackground(
const PaintInfo& paint_info,
const LayoutPoint& box_origin,
const TextMarkerBase& marker,
const ComputedStyle& style,
const Font& font) {
if (marker.GetType() == DocumentMarker::kTextMatch &&
!LineLayoutAPIShim::LayoutObjectFrom(inline_text_box_.GetLineLayoutItem())
->GetFrame()
->GetEditor()
.MarkedTextMatchesAreHighlighted())
return;
const auto paint_offsets =
GetTextMatchMarkerPaintOffsets(marker, inline_text_box_);
TextRun run = inline_text_box_.ConstructTextRun(style);
Color color = LayoutTheme::GetTheme().PlatformTextSearchHighlightColor(
marker.IsActiveMatch(),
inline_text_box_.GetLineLayoutItem().GetDocument().InForcedColorsMode(),
style.UsedColorScheme());
GraphicsContext& context = paint_info.context;
GraphicsContextStateSaver state_saver(context);
LayoutRect box_rect(box_origin, LayoutSize(inline_text_box_.LogicalWidth(),
inline_text_box_.LogicalHeight()));
context.Clip(FloatRect(box_rect));
context.DrawHighlightForText(font, run, FloatPoint(box_origin),
box_rect.Height().ToInt(), color,
paint_offsets.first, paint_offsets.second);
}
} // namespace blink
| [
"pcding@ucdavis.edu"
] | pcding@ucdavis.edu |
29bae16ee555ea839c08d1f88108e184dfa0dfc3 | 1cf71a114fc68752034582a5d4ea9330cd9b7ace | /SP4 GDT Team 10/AI/Source/UIMessagePopup.h | 40a88ae1ecaedaad73d1dbf8424e378b15d257de | [] | no_license | Tynk3r/2019sp4gdt | 19af09673f1ab468331d1ebd93061b13cc1caeec | 8889a96d66a8cd4bfd7f3b34b0976bdb61d34830 | refs/heads/master | 2020-04-22T02:51:27.359357 | 2019-02-28T13:03:25 | 2019-02-28T13:03:25 | 170,065,462 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 389 | h | #include "UIBase.h"
class UIMessagePopup : public UIBase
{
public:
UIMessagePopup(const std::string& text, float duration = 4);
~UIMessagePopup();
float fElapsedTime;
float fDuration;
virtual void Update(float dt);
private:
//Order of ui components matter
enum UI_STARTBUTTON_COMPONENTS {
COMPONENT_OUTLINEBAR,
COMPONENT_GREYBAR,
COMPONENT_TEXT,
COMPONENT_TOTAL
};
}; | [
"valencoen222@gmail.com"
] | valencoen222@gmail.com |
031a9b7325446f441bf0c58299c1a2fd3b81748e | 44aa39e7b0bf6216a7bdcb77a652eaf23d2fb178 | /05. Trees and graphs/06. Find Repeat, Space Edition BEAST MODE/findRepeat01.cpp | e9b5a982e24f54c99299a8a239056ddf3079cb95 | [] | no_license | cesar-magana/Interview-Cake | 8df9fa7fb994f40ea550e237669d228f0d75f4c6 | 64fa403b99944fab6c15433e8fff0a2307192e63 | refs/heads/master | 2022-07-31T14:29:25.304800 | 2020-05-19T22:57:57 | 2020-05-19T22:57:57 | 263,289,977 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,662 | cpp | #include <iostream>
#include <vector>
#include <algorithm>
#include <unordered_set>
// C++11 lest unit testing framework
#include "lest.hpp"
using namespace std;
unsigned int findRepeat(const vector<unsigned int>& numbers)
{
// find a number that appears more than once
unordered_set<unsigned int> seen;
for ( size_t i = 0; i < numbers.size(); i++ ) {
if ( seen.find( numbers[i] ) != seen.end() ) {
return numbers[i];
}
else {
seen.insert( numbers[i] );
}
}
throw invalid_argument("No duplicate");
}
// tests
const lest::test tests[] = {
{CASE("just the repeated number") {
const vector<unsigned int> numbers {1, 1};
const unsigned int expected = 1;
const unsigned int actual = findRepeat(numbers);
EXPECT(actual == expected);
}},
{CASE("short vector") {
const vector<unsigned int> numbers {1, 2, 3, 2};
const unsigned int expected = 2;
const unsigned int actual = findRepeat(numbers);
EXPECT(actual == expected);
}},
{CASE("medium vector") {
const vector<unsigned int> numbers {1, 2, 5, 5, 5, 5};
const unsigned int expected = 5;
const unsigned int actual = findRepeat(numbers);
EXPECT(actual == expected);
}},
{CASE("long vector") {
const vector<unsigned int> numbers {4, 1, 4, 8, 3, 2, 7, 6, 5};
const unsigned int expected = 4;
const unsigned int actual = findRepeat(numbers);
EXPECT(actual == expected);
}}
};
int main(int argc, char** argv)
{
return lest::run(tests, argc, argv);
} | [
"cesar.cpp@gmail.com"
] | cesar.cpp@gmail.com |
1eb2c164285102abbbc22438e4d268f1b65795c2 | 04b1803adb6653ecb7cb827c4f4aa616afacf629 | /net/nqe/network_quality_observation.h | 9c5f954127996e034b1e0b1021658626ec59aa97 | [
"BSD-3-Clause"
] | permissive | Samsung/Castanets | 240d9338e097b75b3f669604315b06f7cf129d64 | 4896f732fc747dfdcfcbac3d442f2d2d42df264a | refs/heads/castanets_76_dev | 2023-08-31T09:01:04.744346 | 2021-07-30T04:56:25 | 2021-08-11T05:45:21 | 125,484,161 | 58 | 49 | BSD-3-Clause | 2022-10-16T19:31:26 | 2018-03-16T08:07:37 | null | UTF-8 | C++ | false | false | 2,614 | h | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef NET_NQE_NETWORK_QUALITY_OBSERVATION_H_
#define NET_NQE_NETWORK_QUALITY_OBSERVATION_H_
#include <stdint.h>
#include <vector>
#include "base/optional.h"
#include "base/time/time.h"
#include "net/base/net_export.h"
#include "net/nqe/network_quality_estimator_util.h"
#include "net/nqe/network_quality_observation_source.h"
namespace net {
namespace nqe {
namespace internal {
// Records observations of network quality metrics (such as round trip time
// or throughput), along with the time the observation was made. Observations
// can be made at several places in the network stack, thus the observation
// source is provided as well.
class NET_EXPORT_PRIVATE Observation {
public:
Observation(int32_t value,
base::TimeTicks timestamp,
int32_t signal_strength,
NetworkQualityObservationSource source);
Observation(int32_t value,
base::TimeTicks timestamp,
int32_t signal_strength,
NetworkQualityObservationSource source,
const base::Optional<IPHash>& host);
Observation(const Observation& other);
Observation& operator=(const Observation& other);
~Observation();
// Value of the observation.
int32_t value() const { return value_; }
// Time when the observation was taken.
base::TimeTicks timestamp() const { return timestamp_; }
// Signal strength when the observation was taken. Set to INT32_MIN when the
// value is unavailable. Otherwise, must be between 0 and 4 (both inclusive).
int32_t signal_strength() const { return signal_strength_; }
// The source of the observation.
NetworkQualityObservationSource source() const { return source_; }
// A unique identifier for the remote host which was used for the measurement.
base::Optional<IPHash> host() const { return host_; }
// Returns the observation categories to which this observation belongs to.
std::vector<ObservationCategory> GetObservationCategories() const;
private:
int32_t value_;
base::TimeTicks timestamp_;
// Signal strength of the network when the observation was taken. Set to
// INT32_MIN when the value is unavailable. Otherwise, must be between 0 and 4
// (both inclusive).
int32_t signal_strength_;
NetworkQualityObservationSource source_;
base::Optional<IPHash> host_;
};
} // namespace internal
} // namespace nqe
} // namespace net
#endif // NET_NQE_NETWORK_QUALITY_OBSERVATION_H_
| [
"sunny.nam@samsung.com"
] | sunny.nam@samsung.com |
9a11660a58fa9bec5299f6bb78cd6540f55a4305 | 6a63a3b241e161d1e69f1521077617ad86f31eab | /cpp/include/ray/api/function_manager.h | 324b6539277c68aab3065800fdbe6a69205ceb32 | [
"MIT",
"BSD-3-Clause",
"Apache-2.0"
] | permissive | jovany-wang/ray | 47a9df67e8ea26337517d625df50eb0b8b892135 | 227aef381a605cb1ebccbba4e84b840634196a35 | refs/heads/master | 2023-09-03T23:53:00.050619 | 2022-08-20T21:50:52 | 2022-08-20T21:50:52 | 240,190,407 | 1 | 1 | Apache-2.0 | 2023-03-04T08:57:04 | 2020-02-13T06:13:19 | Python | UTF-8 | C++ | false | false | 11,783 | h | // Copyright 2017 The Ray 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.
#pragma once
#include <ray/api/common_types.h>
#include <ray/api/serializer.h>
#include <ray/api/type_traits.h>
#include <boost/callable_traits.hpp>
#include <functional>
#include <map>
#include <memory>
#include <string>
#include <tuple>
#include <type_traits>
#include <unordered_map>
namespace ray {
namespace internal {
template <typename T>
inline static std::enable_if_t<!std::is_pointer<T>::value, msgpack::sbuffer>
PackReturnValue(T result) {
return Serializer::Serialize(std::move(result));
}
template <typename T>
inline static std::enable_if_t<std::is_pointer<T>::value, msgpack::sbuffer>
PackReturnValue(T result) {
return Serializer::Serialize((uint64_t)result);
}
inline static msgpack::sbuffer PackVoid() {
return Serializer::Serialize(msgpack::type::nil_t());
}
msgpack::sbuffer PackError(std::string error_msg);
using ArgsBuffer = msgpack::sbuffer;
using ArgsBufferList = std::vector<ArgsBuffer>;
using RemoteFunction = std::function<msgpack::sbuffer(const ArgsBufferList &)>;
using RemoteFunctionMap_t = std::unordered_map<std::string, RemoteFunction>;
using RemoteMemberFunction =
std::function<msgpack::sbuffer(msgpack::sbuffer *, const ArgsBufferList &)>;
using RemoteMemberFunctionMap_t = std::unordered_map<std::string, RemoteMemberFunction>;
/// It's help to invoke functions and member functions, the class Invoker<Function> help
/// do type erase.
template <typename Function>
struct Invoker {
/// Invoke functions by networking stream, at first deserialize the binary data to a
/// tuple, then call function with tuple.
static inline msgpack::sbuffer Apply(const Function &func,
const ArgsBufferList &args_buffer) {
using RetrunType = boost::callable_traits::return_type_t<Function>;
using ArgsTuple = RemoveReference_t<boost::callable_traits::args_t<Function>>;
if (std::tuple_size<ArgsTuple>::value != args_buffer.size()) {
throw std::invalid_argument("Arguments number not match");
}
msgpack::sbuffer result;
ArgsTuple tp{};
bool is_ok = GetArgsTuple(
tp, args_buffer, std::make_index_sequence<std::tuple_size<ArgsTuple>::value>{});
if (!is_ok) {
throw std::invalid_argument("Arguments error");
}
result = Invoker<Function>::Call<RetrunType>(func, std::move(tp));
return result;
}
static inline msgpack::sbuffer ApplyMember(const Function &func,
msgpack::sbuffer *ptr,
const ArgsBufferList &args_buffer) {
using RetrunType = boost::callable_traits::return_type_t<Function>;
using ArgsTuple =
RemoveReference_t<RemoveFirst_t<boost::callable_traits::args_t<Function>>>;
if (std::tuple_size<ArgsTuple>::value != args_buffer.size()) {
throw std::invalid_argument("Arguments number not match");
}
msgpack::sbuffer result;
ArgsTuple tp{};
bool is_ok = GetArgsTuple(
tp, args_buffer, std::make_index_sequence<std::tuple_size<ArgsTuple>::value>{});
if (!is_ok) {
throw std::invalid_argument("Arguments error");
}
uint64_t actor_ptr = Serializer::Deserialize<uint64_t>(ptr->data(), ptr->size());
using Self = boost::callable_traits::class_of_t<Function>;
Self *self = (Self *)actor_ptr;
result = Invoker<Function>::CallMember<RetrunType>(func, self, std::move(tp));
return result;
}
private:
template <typename T>
static inline T ParseArg(const ArgsBuffer &args_buffer, bool &is_ok) {
is_ok = true;
if constexpr (is_object_ref_v<T>) {
// Construct an ObjectRef<T> by id.
return T(std::string(args_buffer.data(), args_buffer.size()));
} else if constexpr (is_actor_handle_v<T>) {
auto actor_handle =
Serializer::Deserialize<std::string>(args_buffer.data(), args_buffer.size());
return T::FromBytes(actor_handle);
} else {
auto [success, value] =
Serializer::DeserializeWhenNil<T>(args_buffer.data(), args_buffer.size());
is_ok = success;
return value;
}
}
static inline bool GetArgsTuple(std::tuple<> &tup,
const ArgsBufferList &args_buffer,
std::index_sequence<>) {
return true;
}
template <size_t... I, typename... Args>
static inline bool GetArgsTuple(std::tuple<Args...> &tp,
const ArgsBufferList &args_buffer,
std::index_sequence<I...>) {
bool is_ok = true;
(void)std::initializer_list<int>{
(std::get<I>(tp) = ParseArg<Args>(args_buffer.at(I), is_ok), 0)...};
return is_ok;
}
template <typename R, typename F, typename... Args>
static std::enable_if_t<std::is_void<R>::value, msgpack::sbuffer> Call(
const F &f, std::tuple<Args...> args) {
CallInternal<R>(f, std::make_index_sequence<sizeof...(Args)>{}, std::move(args));
return PackVoid();
}
template <typename R, typename F, typename... Args>
static std::enable_if_t<!std::is_void<R>::value, msgpack::sbuffer> Call(
const F &f, std::tuple<Args...> args) {
auto r =
CallInternal<R>(f, std::make_index_sequence<sizeof...(Args)>{}, std::move(args));
return PackReturnValue(r);
}
template <typename R, typename F, size_t... I, typename... Args>
static R CallInternal(const F &f,
const std::index_sequence<I...> &,
std::tuple<Args...> args) {
(void)args;
using ArgsTuple = boost::callable_traits::args_t<F>;
return f(((typename std::tuple_element<I, ArgsTuple>::type)std::get<I>(args))...);
}
template <typename R, typename F, typename Self, typename... Args>
static std::enable_if_t<std::is_void<R>::value, msgpack::sbuffer> CallMember(
const F &f, Self *self, std::tuple<Args...> args) {
CallMemberInternal<R>(
f, self, std::make_index_sequence<sizeof...(Args)>{}, std::move(args));
return PackVoid();
}
template <typename R, typename F, typename Self, typename... Args>
static std::enable_if_t<!std::is_void<R>::value, msgpack::sbuffer> CallMember(
const F &f, Self *self, std::tuple<Args...> args) {
auto r = CallMemberInternal<R>(
f, self, std::make_index_sequence<sizeof...(Args)>{}, std::move(args));
return PackReturnValue(r);
}
template <typename R, typename F, typename Self, size_t... I, typename... Args>
static R CallMemberInternal(const F &f,
Self *self,
const std::index_sequence<I...> &,
std::tuple<Args...> args) {
(void)args;
using ArgsTuple = boost::callable_traits::args_t<F>;
return (self->*f)(
((typename std::tuple_element<I + 1, ArgsTuple>::type) std::get<I>(args))...);
}
};
/// Manage all ray remote functions, add remote functions by RAY_REMOTE, get functions by
/// TaskExecutionHandler.
class FunctionManager {
public:
static FunctionManager &Instance() {
static FunctionManager instance;
return instance;
}
std::pair<const RemoteFunctionMap_t &, const RemoteMemberFunctionMap_t &>
GetRemoteFunctions() {
return std::pair<const RemoteFunctionMap_t &, const RemoteMemberFunctionMap_t &>(
map_invokers_, map_mem_func_invokers_);
}
RemoteFunction *GetFunction(const std::string &func_name) {
auto it = map_invokers_.find(func_name);
if (it == map_invokers_.end()) {
return nullptr;
}
return &it->second;
}
template <typename Function>
std::enable_if_t<!std::is_member_function_pointer<Function>::value, bool>
RegisterRemoteFunction(std::string const &name, const Function &f) {
auto pair = func_ptr_to_key_map_.emplace(GetAddress(f), name);
if (!pair.second) {
throw RayException("Duplicate RAY_REMOTE function: " + name);
}
bool ok = RegisterNonMemberFunc(name, f);
if (!ok) {
throw RayException("Duplicate RAY_REMOTE function: " + name);
}
return true;
}
template <typename Function>
std::enable_if_t<std::is_member_function_pointer<Function>::value, bool>
RegisterRemoteFunction(std::string const &name, const Function &f) {
using Self = boost::callable_traits::class_of_t<Function>;
auto key = std::make_pair(typeid(Self).name(), GetAddress(f));
auto pair = mem_func_to_key_map_.emplace(std::move(key), name);
if (!pair.second) {
throw RayException("Duplicate RAY_REMOTE function: " + name);
}
bool ok = RegisterMemberFunc(name, f);
if (!ok) {
throw RayException("Duplicate RAY_REMOTE function: " + name);
}
return true;
}
template <typename Function>
std::enable_if_t<!std::is_member_function_pointer<Function>::value, std::string>
GetFunctionName(const Function &f) {
auto it = func_ptr_to_key_map_.find(GetAddress(f));
if (it == func_ptr_to_key_map_.end()) {
return "";
}
return it->second;
}
template <typename Function>
std::enable_if_t<std::is_member_function_pointer<Function>::value, std::string>
GetFunctionName(const Function &f) {
using Self = boost::callable_traits::class_of_t<Function>;
auto key = std::make_pair(typeid(Self).name(), GetAddress(f));
auto it = mem_func_to_key_map_.find(key);
if (it == mem_func_to_key_map_.end()) {
return "";
}
return it->second;
}
RemoteMemberFunction *GetMemberFunction(const std::string &func_name) {
auto it = map_mem_func_invokers_.find(func_name);
if (it == map_mem_func_invokers_.end()) {
return nullptr;
}
return &it->second;
}
private:
FunctionManager() = default;
~FunctionManager() = default;
FunctionManager(const FunctionManager &) = delete;
FunctionManager(FunctionManager &&) = delete;
template <typename Function>
bool RegisterNonMemberFunc(std::string const &name, Function f) {
return map_invokers_
.emplace(
name,
std::bind(&Invoker<Function>::Apply, std::move(f), std::placeholders::_1))
.second;
}
template <typename Function>
bool RegisterMemberFunc(std::string const &name, Function f) {
return map_mem_func_invokers_
.emplace(name,
std::bind(&Invoker<Function>::ApplyMember,
std::move(f),
std::placeholders::_1,
std::placeholders::_2))
.second;
}
template <class Dest, class Source>
Dest BitCast(const Source &source) {
static_assert(sizeof(Dest) == sizeof(Source),
"BitCast requires source and destination to be the same size");
Dest dest;
memcpy(&dest, &source, sizeof(dest));
return dest;
}
template <typename F>
std::string GetAddress(F f) {
auto arr = BitCast<std::array<char, sizeof(F)>>(f);
return std::string(arr.data(), arr.size());
}
RemoteFunctionMap_t map_invokers_;
RemoteMemberFunctionMap_t map_mem_func_invokers_;
std::unordered_map<std::string, std::string> func_ptr_to_key_map_;
std::map<std::pair<std::string, std::string>, std::string> mem_func_to_key_map_;
};
} // namespace internal
} // namespace ray | [
"noreply@github.com"
] | noreply@github.com |
394c280ca95ec8f792c1c515a275ceded5c43b27 | 6035e4b4bc25e5f87a2b5a44593b6fd7648a5794 | /ins_1.cpp | d1a6b8aebe85c8d6631b2515cca8d352d496638c | [] | no_license | pravgcet/progr_practice | 3e17ac08e08ce8ca2e47b2ed487bfd406ef56a5d | 5144514d1f14698f4f3d7bf1739d8760a896b530 | refs/heads/master | 2021-01-13T10:14:04.043798 | 2017-02-11T01:19:46 | 2017-02-11T01:19:46 | 81,659,326 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 870 | cpp | #include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <cstdio>
#include <vector>
#include <cstdlib>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
using namespace std;
void insertionSort(vector <int> ar)
{
vector <int> ::reverse_iterator i;
vector <int> ::iterator j;
int k,t=0;
k=ar[ar.size()-1];
for(i=ar.rbegin();i!=ar.rend();i++)
{
if(k<(*(i+1)))
{
*i=*(i+1);
}
else
{
*(i)=k;
t=1;
}
for(j=ar.begin();j!=ar.end();j++)
{
cout<<*j<<" ";
}
if(t==1)
{
break;
}
cout<<endl;
}
}
int main(void)
{
vector <int> _ar;
int _ar_size;
cin >> _ar_size;
for(int _ar_i=0; _ar_i<_ar_size; _ar_i++)
{
int _ar_tmp;
cin >> _ar_tmp;
_ar.push_back(_ar_tmp);
}
insertionSort(_ar);
return 0;
}
| [
"pravgcet@gmail.com"
] | pravgcet@gmail.com |
87cd86d12a64d2eb99ed8cc0d7e747ef5b562b62 | 9595d7ecb5422f0e5f3bb7c58f6ec39525484eda | /main.cpp | 45517a17205bd8d7481ee00ae0650ea6ecfabf1c | [] | no_license | flrl/basique | 2a2491778e91cbf76d7334675d5442f5116faeef | 939cd40b335592ce57d0d14418498cf52ca8989f | refs/heads/master | 2021-01-01T18:34:49.977836 | 2016-01-17T01:08:57 | 2016-01-17T01:08:57 | 955,656 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 392 | cpp | #include "interpreter.h"
basic::SymbolTable g_symbol_table;
int main (int argc, char * const argv[]) {
basic::Interpreter *interpreter = NULL;
if (argc > 1) {
// FIXME loop over input files
interpreter = new basic::Interpreter(argv[1]);
}
else {
interpreter = new basic::Interpreter(stdin);
}
interpreter->interpret();
return 0;
}
| [
"flrl@users.noreply.github.com"
] | flrl@users.noreply.github.com |
cd2b278a72cec4ef27ef2c8024159c474bbdfff5 | aa271b2ce9590aab3395b8a92c04af79519e34a3 | /src/test/writer/merlin_writer_unittest.cpp | af7cddfacb10d816206917df9030a9308d5f60aa | [] | no_license | comaniac/TheIR | 02244c51034662fe3e72be8a65e759a6b609d000 | 8023cce040193318395babb850bdd8e380b711f7 | refs/heads/master | 2021-01-19T07:57:32.152699 | 2017-04-10T06:16:51 | 2017-04-10T06:16:51 | 87,585,988 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,401 | cpp | #include <limits.h>
#include <fstream>
#include "../../../src/main/ds/DesignSpaceBase.h"
#include "../../../src/main/ds/DesignSpaceCont.h"
#include "../../../src/main/ir/schedule/Parallel.h"
#include "../../../src/main/writer/MerlinWriter.h"
#include "../../../src/main/writer/WriterBase.h"
#include "gtest/gtest.h"
using TheIR::WriterBase;
using TheIR::MerlinWriter;
using TheIR::DesignSpaceBase;
using TheIR::DesignSpaceCont;
using TheIR::Parallel;
void cleanStream(ostringstream &os) {
os.str("");
os.clear();
}
// Test pragmas
TEST(MerlinWriterTest, PragmaTest) {
std::ostringstream os;
MerlinWriter writer(os);
writer.writeParallelPragma();
EXPECT_EQ("#pragma ACCEL parallel ", os.str());
cleanStream(os);
DesignSpaceCont<int> ds(1, 10, DesignSpaceBase::SEQ);
writer.writeParallelPragma(ds);
EXPECT_EQ("#pragma ACCEL parallel factor=auto_i_1_10\n", os.str());
}
TEST(MerlinWriterTest, ParallelTest) {
std::ostringstream os;
MerlinWriter writer(os);
class PE : public Parallel {
public:
PE(int M) : Parallel("PE", 2048, M) { ; }
void func() { ; }
};
PE pe(7);
writer.write(pe);
std::string GOLDEN_RESULT =
std::string("for (int PE_task = 0; PE_task < 2048; PE_task ++) ") +
std::string("{\n#pragma ACCEL parallel factor=auto_i_1_7\n}\n");
EXPECT_EQ(GOLDEN_RESULT, os.str());
} | [
"comaniac0422@gmail.com"
] | comaniac0422@gmail.com |
525af3dd98bbf4422712a164e499a8bcc9412fbf | 817ffc7318bb6c2bc3e08b5035641fe168ccd8a7 | /src/LookatCommand.cpp | 27d4403fe92f0d1c488e694912556a1c461a9eb5 | [] | no_license | JChang10-bit/graphics | a69d54d48adbc50f8ae18b72413fcc839a1902ec | 58073495119152f21902c3f5f1bf51a5b26ae182 | refs/heads/master | 2021-06-20T00:26:12.276569 | 2017-04-26T20:22:24 | 2017-04-26T20:22:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,610 | cpp | #include "LookatCommand.h"
#include "Matrix44.h"
#include "global.h"
#include "Vector3.h"
#include "Matrix44.h"
#include <iostream>
#include <cmath>
LookatCommand::LookatCommand(float fX, float fY, float fZ, float atX, float atY, float atZ, float upX, float upY, float upZ, CLI& mainCLI):
name("lookat"), fx(fX), fy(fY), fz(fZ), atx(atX), aty(atY), atz(atZ), upx(upX), upy(upY), upz(upZ), cli(mainCLI) {}
void LookatCommand::execute() {
float dx, dy, dz ;
Vector3 slnv, rx, ry, rz, up;
Matrix44 ltrans, tmpsln, rfin, lookat;
//Vertex_unit v, sv;
//int i, j;
/* translation */
// ltrans default is I
// ltrans = I;
ltrans.set(0, 3, -fx);
ltrans.set(1, 3, -fy);
ltrans.set(2, 3, -fz);
up[0] = upx; up[1] = upy; up[3] = upz;
up = up.unit();
/* make P1P2 (rz) vector */
dx = atx - fx; dy = aty - fy; dz = atz - fz;
rz[0] = dx; rz[1] = dy; rz[2] = dz;
rz = rz.unit();
// default is I
// rfin = I;
/* make rx */
rx = rz.cross(up);
rx = rx.unit();
/* make ry */
ry = rx.cross(rz);
rfin.set(0, 0, rx[0]); rfin.set(0, 1, rx[1]); rfin.set(0, 2, rx[2]);
rfin.set(1, 0, ry[0]); rfin.set(1, 1, ry[1]); rfin.set(1, 2, ry[2]);
rfin.set(2, 0, -rz[0]); rfin.set(2, 1, -rz[1]); rfin.set(2, 2, -rz[2]);
rfin.set(3, 3, 0);
lookat = rfin * ltrans;
/* Multiply the lookat matrix by the matrix currently on the top
of the stack. This then becomes the new top of the stack. */
cli.currentMatrix *= lookat;
}
std::string LookatCommand::toString() const {
return name;
}
| [
"davidyangrocs@gmail.com"
] | davidyangrocs@gmail.com |
c8422828a6cdc18da8012b65d7b27f9dcc9b4f07 | 38e6ff2865a460887921b7a23e6807f571e3611d | /5.Concurrency/1.Intro/LamdasThread.cpp | dea6874e68b175f7b807134025e8e80cc172595c | [] | no_license | ChrisProgramming2018/cppCourse | 437582422d5ef50bafe352168a97f165c5ed7864 | 5e44416ba15c7d081a274ab90d2cf342bf4403da | refs/heads/master | 2020-12-26T06:12:09.882412 | 2020-03-24T09:18:14 | 2020-03-24T09:18:14 | 237,413,076 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 860 | cpp | // Copyright 2020
// cpp course
// Author: Christian Leininger <info2016frei@gmail.com>
#include <iostream>
#include <thread>
int main() {
int id = 0; // Define an integer variable
// starting a first thread (by reference)
auto f0 = [&id]() {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
std::cout << "a) ID in Thread (call-by-reference) = " << id << std::endl;
};
std::thread t1(f0);
// starting a second thread (by value)
std::thread t2([id]() mutable {
std::this_thread::sleep_for(std::chrono::milliseconds(50));
std::cout << "b) ID in Thread (call-by-value) = " << id << std::endl;
});
// increment and print id in main
++id;
std::cout << "c) ID in Main (call-by-value) = " << id << std::endl;
// wait for threads before returning
t1.join();
t2.join();
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
a5f227ae9ba37c80fd17662e003142b376420ca2 | 63c1ec9c41cf26122b79c7465d21c796d2497520 | /cpp/vector-example/examination.cpp | 8d5662fd3664a332cd6a068a9a9e75814dc0a72f | [] | no_license | xaratustrah/misc_code | 17870d70d8bcbdc568f6efb6e03752f83c58dc9b | ec2c3b8505543215e55dfc721be32a31943e46e0 | refs/heads/main | 2021-06-08T13:54:51.822401 | 2018-06-11T14:18:31 | 2018-06-11T14:18:31 | 25,710,112 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 544 | cpp | #include <string>
#include<iostream>
using namespace std;
#include "examination.h"
Examination::Examination()
{
title = "";
grade = 0;
}
Examination::Examination( string title )
{
this->title = title;
grade = 0;
}
string Examination::GetTitle()
{
return title;
}
void Examination::SetTitle( string title )
{
this->title = title;
}
float Examination::GetGrade()
{
cout << "getgrade examination" << endl;
return grade;
}
void Examination::SetGrade( float grade )
{
this->grade = grade;
} | [
"shahab@zamail.de"
] | shahab@zamail.de |
bebf7aab255bc92c5dec18c70b68a9525f5c50de | a88aabedcb08fbce60906343d4993f8d32dda49c | /src/rsafactorize.cc | 3b924ef708d3a81e88ba5d23cb44a783eb618e75 | [] | no_license | cran/bigIntegerAlgos | 982ef7ba8895caaca45a15dcf744144e81200a67 | 6c0a251452a017c2d1c30464fc0243e6ddc8f8b7 | refs/heads/master | 2020-03-10T03:12:50.400889 | 2018-04-30T16:09:30 | 2018-04-30T16:09:30 | 129,158,317 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 16,677 | cc | /*!
* \file rsafactorize.cc
*
* \version 1
*
* \date Created: 10/06/17
* \date Last modified: Time-stamp: <2018-04-07 12:30:00 EDT jwood000>
*
* \author Joseph Wood
*
* \note Licence: GPL (>=) 2
*/
#include "quadraticsieve.h"
#include "rsafactorize.h"
#include "importExportMPZ.h"
#include <vector>
#include "Rgmp.h"
#include <inttypes.h>
unsigned long int mpzChunkBig = 50;
static unsigned char primes_diff[] = {
#define P(a,b,c) a,
#include "primes.h"
#undef P
};
#define PRIMES_PTAB_ENTRIES (sizeof(primes_diff) / sizeof(primes_diff[0]))
/* Number of Miller-Rabin tests to run when not proving primality. */
#define MR_REPS 25
// Max number of iterations in the main loop
#define POLLARD_RHO_REPS 100000
unsigned long int getPower(mpz_t nmpz) {
mpz_t testRoot;
mpz_init(testRoot);
unsigned long int p = 2;
unsigned long int myPow = 1;
for (std::size_t i = 0; i < PRIMES_PTAB_ENTRIES; ) {
mpz_root(testRoot, nmpz, p);
mpz_pow_ui(testRoot, testRoot, p);
if (mpz_cmp(testRoot, nmpz) == 0) {
unsigned long int powPrime = p;
bool keepGoing = true;
// Determine if root is a power of a prime
while (keepGoing) {
powPrime *= p;
mpz_root(testRoot, nmpz, powPrime);
mpz_pow_ui(testRoot, testRoot, powPrime);
if (mpz_cmp(testRoot, nmpz) != 0)
keepGoing = false;
}
powPrime /= p;
myPow *= powPrime;
mpz_root(nmpz, nmpz, powPrime);
}
p += primes_diff[i++];
if (!mpz_perfect_power_p(nmpz))
break;
}
// This means the powers involved are very large
if (mpz_perfect_power_p(nmpz)) {
mpz_t myNextP;
mpz_init(myNextP);
mpz_init_set_ui(myNextP, p);
for (;;) {
mpz_root(testRoot, nmpz, p);
mpz_pow_ui(testRoot, testRoot, p);
if (mpz_cmp(testRoot, nmpz) == 0) {
unsigned long int powPrime = p;
bool keepGoing = true;
// Determine if root is a power of a prime
while (keepGoing) {
powPrime *= p;
mpz_root(testRoot, nmpz, powPrime);
mpz_pow_ui(testRoot, testRoot, powPrime);
if (mpz_cmp(testRoot, nmpz) != 0)
keepGoing = false;
}
powPrime /= p;
myPow *= powPrime;
mpz_root(nmpz, nmpz, powPrime);
}
mpz_nextprime(myNextP, myNextP);
p = mpz_get_ui(myNextP);
if (!mpz_perfect_power_p(nmpz))
break;
}
}
return myPow;
}
int trialDivision (mpz_t t, int numPrimes,
mpz_t factors[], unsigned long int& numPs,
std::vector<unsigned long int>& myLens,
unsigned long int arrayMax) {
mpz_t q;
unsigned long int p;
int i;
mpz_init (q);
p = mpz_scan1 (t, 0);
mpz_div_2exp (t, t, p);
if (p) {
mpz_set_ui(factors[numPs], 2);
myLens.push_back(p);
numPs++;
}
p = 3;
for (i = 1; i < numPrimes;) {
if (!mpz_divisible_ui_p(t, p)) {
p += primes_diff[i++];
if (mpz_cmp_ui (t, p * p) < 0)
break;
} else {
mpz_tdiv_q_ui (t, t, p);
mpz_set_ui(factors[numPs], p);
myLens.push_back(1);
while (mpz_divisible_ui_p(t, p)) {
mpz_tdiv_q_ui(t, t, p);
myLens[numPs]++;
}
numPs++;
if (numPs == arrayMax)
return 1;
p += primes_diff[i++];
if (mpz_cmp_ui (t, p * p) < 0)
break;
}
}
mpz_clear (q);
return 0;
}
int pollardRhoWithConstraint (mpz_t n, unsigned long int a,
mpz_t factors[], unsigned long int& numPs,
std::vector<unsigned long int>& myLens,
unsigned long int myLimit,
unsigned long int powMultiplier,
unsigned long int arrayMax,
std::vector<unsigned long int>& extraRecursionFacs) {
mpz_t x, z, y, P;
mpz_t t, t2;
unsigned long int k, l, i;
int returnVal = 0;
mpz_init (t);
mpz_init (t2);
mpz_init_set_si (y, 2);
mpz_init_set_si (x, 2);
mpz_init_set_si (z, 2);
mpz_init_set_ui (P, 1);
k = 1;
l = 1;
unsigned long int count = 0;
while (mpz_cmp_ui (n, 1) != 0) {
for (;;) {
do {
mpz_mul (t, x, x);
mpz_mod (x, t, n);
mpz_add_ui (x, x, a);
mpz_sub (t, z, x);
mpz_mul (t2, P, t);
mpz_mod (P, t2, n);
if (k % 32 == 1) {
mpz_gcd (t, P, n);
if (mpz_cmp_ui (t, 1) != 0)
goto factor_found;
mpz_set (y, x);
}
count++;
}
while (--k != 0 && count < myLimit);
if (count == myLimit)
goto myReturn;
mpz_set (z, x);
k = l;
l = 2 * l;
for (i = 0; i < k; i++) {
mpz_mul (t, x, x);
mpz_mod (x, t, n);
mpz_add_ui (x, x, a);
}
mpz_set (y, x);
}
factor_found:
do {
mpz_mul (t, y, y);
mpz_mod (y, t, n);
mpz_add_ui (y, y, a);
mpz_sub (t, z, y);
mpz_gcd (t, t, n);
}
while (mpz_cmp_ui (t, 1) == 0);
mpz_divexact (n, n, t); /* divide by t, before t is overwritten */
if (mpz_probab_prime_p (t, MR_REPS) == 0) {
returnVal = pollardRhoWithConstraint (t, a + 1, factors, numPs,
myLens, myLimit, powMultiplier,
arrayMax, extraRecursionFacs);
if (returnVal == 1) {
int ind = numPs - 1;
while (mpz_probab_prime_p (factors[ind], MR_REPS) == 0) {ind--;}
extraRecursionFacs.push_back(ind);
mpz_mul(factors[ind], factors[ind], t);
goto myReturn;
}
} else {
mpz_set(factors[numPs], t);
myLens.push_back(powMultiplier);
while (mpz_divisible_p (n, t)) {
mpz_divexact (n, n, t);
myLens[numPs] += powMultiplier;
}
numPs++;
if (numPs == arrayMax) {
returnVal = 1;
goto myReturn;
}
}
if (mpz_probab_prime_p (n, MR_REPS) != 0) {
mpz_set(factors[numPs], n);
mpz_set_ui(n, 1);
myLens.push_back(powMultiplier);
numPs++;
if (numPs == arrayMax)
returnVal = 1;
break;
}
mpz_mod (x, x, n);
mpz_mod (z, z, n);
mpz_mod (y, y, n);
}
myReturn:
mpz_clear (P);
mpz_clear (t2);
mpz_clear (t);
mpz_clear (z);
mpz_clear (x);
mpz_clear (y);
return returnVal;
}
void getBigPrimeFacs(mpz_t n, mpz_t factors[],
mpz_t result[], unsigned long int& numPs,
std::vector<unsigned long int>& myLens,
unsigned long int powMaster,
unsigned long int arrayMax,
std::vector<unsigned long int>& extraRecursionFacs) {
if (mpz_sizeinbase(n, 10) < 24) {
pollardRhoWithConstraint(n, 1, factors, numPs, myLens, 10000000,
powMaster, arrayMax, extraRecursionFacs);
} else {
quadraticSieve (n, 0.0, 0.0, (int64_t) 0, result);
for (std::size_t i = 0; i < 2; i++) {
unsigned long int myPow = 1;
if (mpz_perfect_power_p(result[i]))
myPow = getPower(result[i]);
myPow *= powMaster;
if (mpz_probab_prime_p(result[i], MR_REPS) == 0) {
mpz_t recurseTemp[2];
mpz_init(recurseTemp[0]); mpz_init(recurseTemp[1]);
getBigPrimeFacs(result[i], factors, recurseTemp,
numPs, myLens, myPow, arrayMax, extraRecursionFacs);
mpz_clear(recurseTemp[0]); mpz_clear(recurseTemp[1]);
} else {
mpz_divexact(n, n, result[i]);
mpz_set(factors[numPs], result[i]);
myLens.push_back(myPow);
while (mpz_divisible_p (n, result[i]))
mpz_divexact (n, n, result[i]);
numPs++;
// This should not happen
if (numPs == arrayMax)
error("Too many prime factors!!");
}
}
}
}
SEXP QuadraticSieveContainer (SEXP Rn) {
unsigned long int vSize;
switch (TYPEOF(Rn)) {
case RAWSXP: {
const char* raw = (char*)RAW(Rn);
vSize = ((int*)raw)[0];
break;
}
default:
vSize = LENGTH(Rn);
}
mpz_t myVec[1];
mpz_init(myVec[0]);
if (vSize > 1)
error(_("Can only factor one number at a time"));
// This is from the importExportMPZ header
createMPZArray(Rn, myVec, 1);
mpz_t nmpz;
mpz_init_set(nmpz, myVec[0]);
int sgn = mpz_sgn(nmpz);
if (sgn <= 0)
error(_("Can only factor positive numbers"));
mpz_t *result;
result = (mpz_t *) malloc(2 * sizeof(mpz_t));
mpz_init(result[0]); mpz_init(result[1]);
std::vector<unsigned long int> lengths, extraRecursionFacs;
unsigned long int arrayMax = mpzChunkBig, numUni = 0;
unsigned long int myPow = 1;
mpz_t *factors;
factors = (mpz_t *) malloc(mpzChunkBig * sizeof(mpz_t));
for (std::size_t i = 0; i < mpzChunkBig; i++)
mpz_init(factors[i]);
// First we test for small factors.
int increaseSize = trialDivision(nmpz, PRIMES_PTAB_ENTRIES,
factors, numUni, lengths, arrayMax);
while (increaseSize) {
arrayMax += mpzChunkBig;
factors = (mpz_t *) realloc(factors, arrayMax * sizeof factors[0]);
for (std::size_t i = (arrayMax - mpzChunkBig); i < arrayMax; i++)
mpz_init(factors[i]);
increaseSize = trialDivision(nmpz, PRIMES_PTAB_ENTRIES,
factors, numUni, lengths, arrayMax);
}
if (mpz_cmp_ui(nmpz, 1) != 0) {
// We now test for larger primes using pollard's rho
// algorithm, but constrain it to a limited number of checks
increaseSize = pollardRhoWithConstraint(nmpz, 1, factors, numUni,
lengths, POLLARD_RHO_REPS,
1, arrayMax, extraRecursionFacs);
while (increaseSize) {
arrayMax += mpzChunkBig;
factors = (mpz_t *) realloc(factors, arrayMax * sizeof factors[0]);
for (std::size_t i = (arrayMax - mpzChunkBig); i < arrayMax; i++)
mpz_init(factors[i]);
increaseSize = pollardRhoWithConstraint(nmpz, 1, factors, numUni,
lengths, POLLARD_RHO_REPS,
1, arrayMax, extraRecursionFacs);
}
// extraRecursionFacs are factors that are a result of the pollarRho algo
// terminating early because of the limitations on the size of the factors
// array. As a result, we are left with an extra factor, say f, that can't
// be placed anywhere in the current array. To remedy this, we find an index
// of the factors array that contains a prime factor, say pj, and set this
// index to the product (pj * f). We also take note of the index by pushing
// it to the extraRecursionFacs vector. Below, we take this info and fully
// factorize these partially factored numbers and add them to our final array.
unsigned long int eRFSize = extraRecursionFacs.size();
if (eRFSize > 0) {
arrayMax += (eRFSize * mpzChunkBig);
factors = (mpz_t *) realloc(factors, arrayMax * sizeof factors[0]);
for (std::size_t i = (arrayMax - (eRFSize * mpzChunkBig)); i < arrayMax; i++)
mpz_init(factors[i]);
mpz_t tempNum;
mpz_t *tempFacs;
tempFacs = (mpz_t *) malloc(mpzChunkBig * sizeof(mpz_t));
for (std::size_t i = 0; i < mpzChunkBig; i++)
mpz_init(tempFacs[i]);
mpz_init(tempNum);
std::vector<unsigned long int>::iterator it, itEnd = extraRecursionFacs.end();
for (it = extraRecursionFacs.begin(); it < itEnd; it++) {
mpz_set(tempNum, factors[*it]);
unsigned long int tempUni = 0;
std::vector<unsigned long int> tempLens, dummyVec;
int temp = pollardRhoWithConstraint(tempNum, 1, tempFacs, tempUni,
tempLens, 10000000, 1,
100000, dummyVec);
if (temp == 0) {
mpz_set(factors[*it], tempFacs[0]);
for (std::size_t i = 1; i < tempUni; i++) {
mpz_set(factors[numUni], tempFacs[i]);
lengths.push_back(tempLens[i]);
numUni++;
}
} else {
error("Too many prime factors!!");
}
}
}
// If there is less than 60% of mpzChunkBig, then increase array
// size to ensure that the functions below have enough space
if ((100 * (arrayMax - numUni) / mpzChunkBig) < 60) {
arrayMax += mpzChunkBig;
factors = (mpz_t *) realloc(factors, arrayMax * sizeof factors[0]);
for (std::size_t i = arrayMax - mpzChunkBig; i < arrayMax; i++)
mpz_init(factors[i]);
}
if (mpz_cmp_ui(nmpz, 1) != 0) {
// Protect quadratic sieve from perfect powers
if (mpz_perfect_power_p(nmpz))
myPow = getPower(nmpz);
if (mpz_probab_prime_p (nmpz, MR_REPS) != 0) {
mpz_set(factors[numUni], nmpz);
lengths.push_back(1);
numUni++;
} else {
getBigPrimeFacs(nmpz, factors, result, numUni,
lengths, myPow, arrayMax, extraRecursionFacs);
}
}
}
// Sort the prime factors as well as order the
// lengths vector by the order of the factors array
quickSort(factors, 0, numUni - 1, lengths);
unsigned long int totalNum = 0;
for (std::size_t i = 0; i < numUni; i++)
totalNum += lengths[i];
unsigned long int intSize = sizeof(int); // starting with vector-size-header
unsigned long int numb = 8 * intSize;
unsigned long int tempSize, size = intSize;
std::vector<unsigned long int> mySizes(totalNum);
unsigned long int count = 0;
for (std::size_t i = 0; i < numUni; i++) { // adding each bigint's needed size
for (std::size_t j = 0; j < lengths[i]; j++, count++) {
tempSize = intSize * (2 + (mpz_sizeinbase(factors[i], 2) + numb - 1) / numb);
size += tempSize;
mySizes[count] = tempSize;
}
}
SEXP ans = PROTECT(Rf_allocVector(RAWSXP, size));
char* r = (char*)(RAW(ans));
((int*)(r))[0] = totalNum; // first int is vector-size-header
// current position in pos[] (starting after vector-size-header)
unsigned long int pos = intSize;
count = 0;
for (std::size_t i = 0; i < numUni; i++)
for (std::size_t j = 0; j < lengths[i]; j++, count++)
pos += myRaw(&r[pos], factors[i], mySizes[count]);
Rf_setAttrib(ans, R_ClassSymbol, Rf_mkString("bigz"));
UNPROTECT(1);
return(ans);
}
| [
"csardi.gabor+cran@gmail.com"
] | csardi.gabor+cran@gmail.com |
b06c22ae3f34d4e0bfc34e8a5cd9a42b378aa7bf | d09945668f19bb4bc17087c0cb8ccbab2b2dd688 | /leetcode/biweekly/081-120/100/2594.cpp | 0003ac89a893582a08474963b94559f4bc464712 | [] | no_license | kmjp/procon | 27270f605f3ae5d80fbdb28708318a6557273a57 | 8083028ece4be1460150aa3f0e69bdb57e510b53 | refs/heads/master | 2023-09-04T11:01:09.452170 | 2023-09-03T15:25:21 | 2023-09-03T15:25:21 | 30,825,508 | 23 | 2 | null | 2023-08-18T14:02:07 | 2015-02-15T11:25:23 | C++ | UTF-8 | C++ | false | false | 1,007 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef signed long long ll;
#undef _P
#define _P(...) (void)printf(__VA_ARGS__)
#define FOR(x,to) for(x=0;x<(to);x++)
#define FORR(x,arr) for(auto& x:arr)
#define FORR2(x,y,arr) for(auto& [x,y]:arr)
#define ALL(a) (a.begin()),(a.end())
#define ZERO(a) memset(a,0,sizeof(a))
#define MINUS(a) memset(a,0xff,sizeof(a))
template<class T> bool chmax(T &a, const T &b) { if(a<b){a=b;return 1;}return 0;}
template<class T> bool chmin(T &a, const T &b) { if(a>b){a=b;return 1;}return 0;}
//-------------------------------------------------------
int num[100000];
ll S[101010];
class Solution {
public:
long long repairCars(vector<int>& ranks, int cars) {
int N=ranks.size();
ll ret=1LL<<60;
int i,j;
for(i=59;i>=0;i--) {
ll tmp=ret-(1LL<<i);
ll sum=0;
FOR(j,N) {
ll a=tmp/ranks[j];
sum+=sqrt(a+0.11);
if(sum>=cars) break;
}
if(sum>=cars) ret=tmp;
}
return ret;
}
};
| [
"kmjp@users.noreply.github.com"
] | kmjp@users.noreply.github.com |
c950689bef05d8bde2aaa9303ade469d134e88f3 | ec8c4f8494f2248141daa3bdc59b657919907da8 | /Src/EBAMRElliptic/AMReX_NeumannConductivityDomainBC.H | 541e0ca7cf183ff8fa32a89dcc11dad7cfeb6eb4 | [
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | shashankNREL/amrex | a16cc19349115312b87c6a6af224b606fa2a352e | b50104b6c9e184129ddce1186266ba811da379b3 | refs/heads/master | 2021-04-15T03:53:24.704414 | 2018-03-01T16:45:32 | 2018-03-01T16:45:32 | 126,224,399 | 0 | 0 | null | 2018-03-21T18:36:41 | 2018-03-21T18:36:40 | null | UTF-8 | C++ | false | false | 2,365 | h | /*
* {_ {__ {__{_______ {__ {__
* {_ __ {_ {__ {___{__ {__ {__ {__
* {_ {__ {__ {__ { {__{__ {__ {__ {__ {__
* {__ {__ {__ {__ {__{_ {__ {_ {__ {__
* {______ {__ {__ {_ {__{__ {__ {_____ {__ {__ {__
* {__ {__ {__ {__{__ {__ {_ {__ {__
* {__ {__{__ {__{__ {__ {____ {__ {__
*
*/
#ifndef _NEUMANNCONDUCTIVITYDOMAINBC_H___
#define _NEUMANNCONDUCTIVITYDOMAINBC_H___
#include "AMReX_ConductivityBaseDomainBC.H"
namespace amrex
{
///
/**
Class to do Dirichlet boundary conditions on the domain for the conductivity operator.
*/
class NeumannConductivityDomainBC: public ConductivityBaseDomainBC
{
public:
NeumannConductivityDomainBC();
virtual ~NeumannConductivityDomainBC();
///
virtual void
fillPhiGhost(FArrayBox& a_state,
const Box& a_valid,
bool a_homogeneous);
///this is for when the EB and the domain intersect
virtual void getFaceFlux(Real& a_faceFlux,
const VolIndex& a_vof,
const MFIter & a_mfi,
const EBCellFAB& a_phi,
const int& a_idir,
const Side::LoHiSide& a_side,
const bool& a_useHomogeneous);
///
void
getFaceGradPhi(Real& a_faceGradPhi,
const FaceIndex& a_face,
const MFIter & a_mfi,
const EBCellFAB& a_phi,
const int& a_idir,
const Side::LoHiSide& a_side,
const bool& a_useHomogeneous);
private:
};
class NeumannConductivityDomainBCFactory: public ConductivityBaseDomainBCFactory
{
public:
NeumannConductivityDomainBCFactory()
{
}
virtual ~NeumannConductivityDomainBCFactory()
{
}
ConductivityBaseDomainBC* new_object_ptr()
{
NeumannConductivityDomainBC* newBC = new NeumannConductivityDomainBC();
return static_cast<ConductivityBaseDomainBC*>(newBC);
}
};
}
#endif
| [
"dtgraves@lbl.gov"
] | dtgraves@lbl.gov |
ecd92db1b6d49f890e55b2d9d23c6cf761887dfa | 9d86667eb14bc51cc67f7747a1e6eab557f7f7d1 | /NMP/SegmentTree/2357_find_maxvalue_minvalue.cpp | 296b83ffe41a777b61db761886e69fa4f040830e | [] | no_license | kyc113212/BOJ | d84fbdf04a6412478cd10524828b4cc0b48a6c12 | 1aba37d08723c217049360ff3a6507a240624f68 | refs/heads/master | 2023-08-16T10:23:59.872869 | 2023-08-16T09:28:05 | 2023-08-16T09:28:05 | 198,989,751 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,650 | cpp | #include <iostream>
#include <cmath>
#include <vector>
#include <algorithm>
using namespace std;
int N, M;
vector<int> v;
vector<int> min_t, max_t;
void init_t(int start, int end, int node) {
if (start == end) {
min_t[node] = max_t[node] = v[start];
return;
}
int mid = (start + end) / 2;
init_t(start, mid, node * 2);
init_t(mid + 1, end, node * 2 + 1);
min_t[node] = min(min_t[node * 2], min_t[node * 2 + 1]);
max_t[node] = max(max_t[node * 2], max_t[node * 2 + 1]);
return;
}
int find_min(int node, int start, int end, int left, int right) {
if (start > right || end < left)
return 1000000001;
if (start >= left && end <= right) {
return min_t[node];
}
int mid = (start + end) / 2;
return min(find_min(node * 2, start, mid, left, right), find_min(node * 2 + 1, mid + 1, end, left, right));
}
int find_max(int node, int start, int end, int left, int right) {
if (start > right || end < left)
return 0;
if (start >= left && end <= right) {
return max_t[node];
}
int mid = (start + end) / 2;
return max(find_max(node * 2, start, mid, left, right), find_max(node * 2 + 1, mid + 1, end, left, right));
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> N >> M;
v.resize(N);
for (int i = 0; i < N; i++) {
cin >> v[i];
}
int h = (int)ceil(log2(N));
int tree_size = (1 << (h + 1));
min_t.resize(tree_size,1000000001);
max_t.resize(tree_size,0);
init_t(0, N-1, 1);
for (int i = 0; i < M; i++) {
int a, b;
cin >> a >> b;
int minV = find_min(1, 1, N, a, b);
int maxV = find_max(1, 1, N, a, b);
cout << minV << " " << maxV << '\n';
}
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
87aa657334b721b7bbd49ad700c037f5a2110bed | 01310f3f4d3dfb427108c7582ee5288c30ca7da8 | /src/raspicam_test.cpp | d1a9a77c5c11e79a3216856f30c2a2e8afa01751 | [] | no_license | biswesh/planogram-integrity | 2517a335ff27478f8c7b132f63616da3252ce80f | d8add0c7d48ea7ea0eb0f6e4cf14fd32186e719c | refs/heads/master | 2021-01-19T23:24:55.644988 | 2017-04-18T15:46:34 | 2017-04-18T15:46:34 | 88,976,054 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,218 | cpp | #include <ctime>
#include <iostream>
#include <raspicam/raspicam_cv.h>
using namespace std;
int main ( int argc,char **argv ) {
time_t timer_begin,timer_end;
raspicam::RaspiCam_Cv Camera;
cv::Mat image;
int nCount=1;
//set camera params
Camera.set( CV_CAP_PROP_FORMAT, CV_8UC1 );
//Open camera
cout<<"Opening Camera..."<<endl;
if (!Camera.open()) {cerr<<"Error opening the camera"<<endl;return -1;}
//Start capture
cout<<"Capturing "<<nCount<<" frames ...."<<endl;
time ( &timer_begin );
for ( int i=0; i<nCount; i++ ) {
Camera.grab();
Camera.retrieve ( image);
if ( i%5==0 ) cout<<"\r captured "<<i<<" images"<<std::flush;
}
cout<<"Stop camera..."<<endl;
Camera.release();
//show time statistics
time ( &timer_end ); /* get current time; same as: timer = time(NULL) */
double secondsElapsed = difftime ( timer_end,timer_begin );
cout<< secondsElapsed<<" seconds for "<< nCount<<" frames : FPS = "<< ( float ) ( ( float ) ( nCount ) /secondsElapsed ) <<endl;
//save image
cv::imwrite("../testing/raspicam_results/raspicam_cv_image.jpg",image);
cout<<"Image saved at testing folder"<<endl;
} | [
"biswesh@aimonk.com"
] | biswesh@aimonk.com |
711053ecc5a63722afd483f22443e3d855af444d | 54b66f71a0a9031ac9b09ae4d92fe3767e175f07 | /src/VertexBuffer.cpp | 600e6c64aeb16ad51c2b62379c643be12b16e9ca | [] | no_license | bindingofisaac/pix | fd63d32c22473a061153bd7b0f99a1badf298827 | 32896ed7bde980560d8136691ddd05fa5c40c135 | refs/heads/master | 2016-09-05T22:11:23.704876 | 2015-07-30T20:39:59 | 2015-07-30T20:39:59 | 38,706,922 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 583 | cpp | #include <VertexBuffer.hpp>
namespace Pix{
VertexBuffer::VertexBuffer(GLfloat *data, GLsizei count, GLuint componentCount) : m_ComponentCount(componentCount){
glGenBuffers(1, &m_VBO);
bind();
glBufferData(GL_ARRAY_BUFFER, count * sizeof(GLfloat), data, GL_STATIC_DRAW);
unbind();
}
VertexBuffer::~VertexBuffer(){
glDeleteBuffers(1, &m_VBO);
}
void VertexBuffer::bind() const {
glBindBuffer(GL_ARRAY_BUFFER, m_VBO);
}
void VertexBuffer::unbind() const {
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
}
| [
"bindingofisaacs@gmail.com"
] | bindingofisaacs@gmail.com |
947260e515d87fcb55f529bf1ae377df38243e66 | d2361a5dddb1f5a4332ffc13eef6bed4f6b66ca1 | /cpp_piscine/day06/ex01/main.cpp | c05fe5bfc9c7b27b769bcf687253893967fd528e | [] | no_license | costae/42_first_projects | b00fee7a684a247628671ce412f18c405c04eb2c | 309460972822582f5606190412650a34735fcc28 | refs/heads/master | 2021-03-22T00:11:51.018365 | 2017-12-12T16:23:09 | 2017-12-12T16:23:09 | 114,004,753 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 809 | cpp | #include <iostream>
#include <ctime>
#include <cstdlib>
#include <string>
struct Data
{
std::string s1;
int n;
std::string s2;
};
void *serialize(void)
{
static char list[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
Data *ret = new Data();
for(int i=0; i<8; i++)
ret->s1 += list[rand() % sizeof(list)];
ret->n = rand() % 100;
for(int i=0; i<8; i++)
ret->s2 += list[rand() % sizeof(list)];
return ret;
}
Data *deserialize(void *raw)
{
Data *ret = reinterpret_cast<Data*>(raw);
return ret;
}
int main()
{
srand(time(NULL));
void *raw = serialize();
Data *data = deserialize(raw);
std::cout << "String s1: " << data->s1 << std::endl;
std::cout << "Int: " << data->n << std::endl;
std::cout << "String s2: " << data->s2 << std::endl;
delete data;
return 0;
} | [
"cmiron@e1p47.chisinau.42.fr"
] | cmiron@e1p47.chisinau.42.fr |
f8516547d88ea461430a1a267d8e86c7feac96b4 | ed86c63aa8bad7ebc2eb39da851b013617683edc | /Code/Warrior.hpp | 570d05a98f3b208c7b846f96977a35e5dbd35d0b | [] | no_license | emilysteiner71/character_build | 04808e787bb1c0ff7d1aa6bf090a221eaf4bf594 | f0cb406b9a4d5c0196aa34cc688ae3aa7193fa3d | refs/heads/master | 2023-01-19T15:29:09.138330 | 2020-11-28T01:49:00 | 2020-11-28T01:49:00 | 296,502,994 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 444 | hpp | #ifndef WARRIOR_HPP_
#define WARRIOR_HPP_
#include "Person.hpp"
#include <string>
#include <vector>
class Warrior: public Person {
private:
int warriorScore;
public:
Warrior(const std::string &name, int age);
virtual characterBuild getCharacterBuild() const;
void setWarriorDefaultScore();
void calculateWarriorScore();
int getWarriorScore() const;
virtual ~Warrior();
};
#endif | [
"emilysteiner@Bert-The-Turtles-macbook-pro.local"
] | emilysteiner@Bert-The-Turtles-macbook-pro.local |
c0804e7d8ad6ad85827bafca2d44d20267def98b | 7198abd2110f631653dc1ac3ed569b0d8136fe2e | /video_player/videowidget.h | aeb45f5ec522d9dc110cb08a51049d2c000263d3 | [] | no_license | xuqingjia1/audio_video | f5a5945959fec5c60b8b5a2080b41404ebca64bb | 85486d5ce46ad158720979e6ebd660ec26e5d380 | refs/heads/main | 2023-07-29T14:43:34.608090 | 2021-09-19T14:49:17 | 2021-09-19T14:49:17 | 368,381,795 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 575 | h | #ifndef VIDEOWIDGET_H
#define VIDEOWIDGET_H
#include <QWidget>
#include <QImage>
#include "videoplayer.h"
class VideoWidget : public QWidget
{
Q_OBJECT
public:
explicit VideoWidget(QWidget *parent = nullptr);
~VideoWidget();
public slots:
void onPlayerFrameDecoded(VideoPlayer *player,uint8_t *data,VideoPlayer::VideoSwsSpec &spec);
void onPlayerStateChanged(VideoPlayer *player);
private:
QImage *_image = nullptr;
QRect _rect;
void paintEvent(QPaintEvent *event) override;
void freeImage();
signals:
};
#endif // VIDEOWIDGET_H
| [
"xuqingjia@xuqingjiadeMacBook-Pro.local"
] | xuqingjia@xuqingjiadeMacBook-Pro.local |
21932d07b899137bda86e07a8307683135495678 | 4c6fd789ede23abb32f4aa3a59a1c8b87f3a3511 | /BojaySFIS/BojaySFISDlg.cpp | e2238f2c0b9daff7958d75f87d68d714b9cffb7f | [] | no_license | HanoiGuo/BoJay-SFIS | b8db03303ce37ce43ecc3a81cee572325656ff50 | e36776347b604cecc2df8657f1cd0d0d4588224c | refs/heads/master | 2021-01-17T06:12:17.941445 | 2016-04-05T01:41:19 | 2016-04-05T01:41:19 | 49,415,307 | 0 | 0 | null | 2016-04-05T01:41:20 | 2016-01-11T09:23:10 | C++ | GB18030 | C++ | false | false | 9,288 | cpp |
// BojaySFISDlg.cpp : implementation file
//
#include "stdafx.h"
#include "Resource.h"
#include "BojaySFIS.h"
#include "BojaySFISDlg.h"
#include "afxdialogex.h"
#include <fstream>
#include "DBAdo.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
CDBAdo m_dbDemo;
string itemName[32];
vector<CString>customer;
vector<string>dataBase;
bool isBindAutoTestTool = false;
// CAboutDlg dialog used for App About
using namespace std;
class CAboutDlg : public CDialogEx
{
public:
CAboutDlg();
// Dialog Data
enum { IDD = IDD_ABOUTBOX };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()
// CBojaySFISDlg dialog
CBojaySFISDlg::CBojaySFISDlg(CWnd* pParent /*=NULL*/)
: CDialogEx(CBojaySFISDlg::IDD, pParent)
{
//m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
m_hIcon = AfxGetApp()->LoadIcon(IDI_ICON_LOG);
}
void CBojaySFISDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Control(pDX, IDC_STATIC_MAINTITLE, m_mainTitle);
DDX_Control(pDX, IDC_TAB_SHEET, m_sheet);
}
BEGIN_MESSAGE_MAP(CBojaySFISDlg, CDialogEx)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_WM_CTLCOLOR()
ON_WM_CLOSE()
END_MESSAGE_MAP()
// CBojaySFISDlg message handlers
BOOL CBojaySFISDlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
// Add "About..." menu item to system menu.
// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
BOOL bNameValid;
CString strAboutMenu;
bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
ASSERT(bNameValid);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
// TODO: Add extra initialization here
m_mainTitle.SetTransparent(TRUE);
m_mainTitle.SetBkClr(RGB(159,227,251));
m_mainTitle.SetTextClr(RGB(0,0,255));
m_mainTitle.SetWindowText(_T("博杰生产管理软件 V1.9临时版本"));
m_mainTitle.SetTextFont(40, 1, 0, _T("宋体") );//设置字体
//设置字体
CFont* m_editFont = new CFont();
CFont *ptf = m_mainTitle.GetFont();//获取原来的字体
LOGFONT lf; //LOGFONT是windows内部的逻辑结构,主要用于设置字体格式
ptf->GetLogFont(&lf);
lf.lfHeight = 30;//设置字体高度
lf.lfWidth = 20;//设置字体宽度
wcscpy(lf.lfFaceName,L"隶书");
m_editFont->CreateFontIndirectW(&lf);
m_mainTitle.SetFont(m_editFont);
m_brsush.CreateSolidBrush(RGB(0,128,255));
CString cEoorMessage;
bool res = operateFileClass.GetTestItem("\\\\172.20.0.8\\1.公司会议资料\\博杰生产管理软件\\配置文件\\SFCItem.txt",itemName,cEoorMessage);
if (!res)
{
AfxMessageBox(L"连接服务器失败\n");
return TRUE;
}
//读取客户对象文件
if(!operateFileClass.CheckCustomer("\\\\172.20.0.8\\1.公司会议资料\\博杰生产管理软件\\配置文件\\customer.txt",customer))
{
AfxMessageBox(L"获取客户对象文件失败");
return FALSE;
}
//读取数据库文件
if(!operateFileClass.GetAllDataBaseName("\\\\172.20.0.8\\1.公司会议资料\\博杰生产管理软件\\数据库",dataBase))
{
AfxMessageBox(L"获取数据名称失败");
return FALSE;
}
//读取是否关联隔音自动软体
string data;
if (!operateFileClass.CheckIsBindSoundTestTool("\\\\172.20.0.8\\1.公司会议资料\\博杰生产管理软件\\配置文件\\isBindTestTool.txt",data))
{
AfxMessageBox(L"获取绑定文件失败");
return FALSE;
}
CString csData;
csData = data.c_str();
csData.MakeUpper();
if (_tcsstr(csData,L"TRUE"))
{
isBindAutoTestTool = TRUE;
}
bool isShowAll = false;
fstream pageFile("page.txt",ios::in);
if (pageFile.is_open())
{
string temp;
string SumTemp;
while(getline(pageFile,temp))
{
SumTemp += temp;
}
if (strstr(SumTemp.c_str(),"all"))
{
isShowAll = true;
}
}
fstream readFile("local.txt",ios::in);
string strPage;
if (readFile.is_open())
{
string temp;
string SumTemp;
while(getline(readFile,temp))
{
SumTemp += temp;
}
strPage = SumTemp;
}
if (isShowAll)
{
for (int i=0; i<32; i++)
{
if (strstr(itemName[i].c_str(),"激活"))
{
m_sheet.AddPage(L"激活界面", &m_activeWindowPage, IDD_DIALOG_ACTIVEWINDOW);
}
else if (strstr(itemName[i].c_str(),"条码"))
{
m_sheet.AddPage(L"打印条码界面", &m_printQRCodePage, IDD_DIALOG_PRINTQRCODE);
}
else if (strstr(itemName[i].c_str(),"功能"))
{
m_sheet.AddPage(L"功能测试界面", &m_soundInsulationPage, IDD_DIALOG_SOUNDINSULATION);
}
else if (strstr(itemName[i].c_str(),"OQC"))
{
m_sheet.AddPage(L"OQC界面", &m_OQCPage, IDD_DIALOG_OQC);
}
else if (strstr(itemName[i].c_str(),"PalletID"))
{
m_sheet.AddPage(L"PalletID界面", &m_PalletIDPage, IDD_DIALOG_PALLETID);
}
else if (strstr(itemName[i].c_str(),"出货"))
{
m_sheet.AddPage(L"出货界面", &m_ShipmentPage, IDD_DIALOG_SHIP);
}
else if (strstr(itemName[i].c_str(),"PCBA"))
{
m_sheet.AddPage(L"PCBA界面", &m_PCBA, IDD_DIALOG_PCBA);
}
}
m_sheet.AddPage(L"查询界面", &m_search, IDD_DIALOG_SEARCH);
m_sheet.Show(0);
}
else
{
if (strstr(strPage.c_str(),"激活"))
{
m_sheet.AddPage(L"激活界面", &m_activeWindowPage, IDD_DIALOG_ACTIVEWINDOW);
}
else if (strstr(strPage.c_str(),"功能"))
{
m_sheet.AddPage(L"功能测试界面", &m_soundInsulationPage, IDD_DIALOG_SOUNDINSULATION);
}
else if (strstr(strPage.c_str(),"OQC"))
{
m_sheet.AddPage(L"OQC界面", &m_OQCPage, IDD_DIALOG_OQC);
}
else if (strstr(strPage.c_str(),"出货"))
{
m_sheet.AddPage(L"出货界面", &m_ShipmentPage, IDD_DIALOG_SHIP);
}
else if (strstr(strPage.c_str(),"PCBA"))
{
m_sheet.AddPage(L"PCBA界面", &m_PCBA, IDD_DIALOG_PCBA);
}
m_sheet.AddPage(L"查询界面", &m_search, IDD_DIALOG_SEARCH);
m_sheet.Show(0);
}
return TRUE; // return TRUE unless you set the focus to a control
}
void CBojaySFISDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialogEx::OnSysCommand(nID, lParam);
}
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CBojaySFISDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialogEx::OnPaint();
DrawBK(IDB_BITMAP_BK,IDC_STATIC_MAINTITLE);
}
}
// The system calls this function to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CBojaySFISDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
HBRUSH CBojaySFISDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
HBRUSH hbr = CDialogEx::OnCtlColor(pDC, pWnd, nCtlColor);
/*
if (pWnd->GetDlgCtrlID() == IDC_STATIC_MAINTITLE)
{
//由于控件文本本身也有背景颜色,解决办法是讲文本控件本身设置为透明色
pDC->SetBkMode(TRANSPARENT);
return m_brsush;
}
*/
// TODO: Change any attributes of the DC here
// TODO: Return a different brush if the default is not desired
return hbr;
}
void CBojaySFISDlg::DrawBK(UINT bmpID,UINT id)
{
CPaintDC dc(GetDlgItem(id));
CRect rect;
GetDlgItem(id)->GetClientRect(&rect);
CDC dcMem;
dcMem.CreateCompatibleDC(&dc);
CBitmap bmpBackground;
bmpBackground.LoadBitmap(bmpID);
BITMAP bitmap;
bmpBackground.GetBitmap(&bitmap);
CBitmap *pbmpOld=dcMem.SelectObject(&bmpBackground);
dc.SetStretchBltMode(HALFTONE);
dc.StretchBlt(0,0,rect.Width(),rect.Height(),&dcMem,0,0,bitmap.bmWidth,bitmap.bmHeight,SRCCOPY);
if (IDC_STATIC_MAINTITLE == id)
{
m_mainTitle.SetTransparent(TRUE);
}
}
void CBojaySFISDlg::GetMyCurrentTime(CString &time)
{
CTime tm;
tm=CTime::GetCurrentTime();
time.Format(L"%d-%d-%d-%d-%d-%d",tm.GetYear(),tm.GetMonth(),tm.GetDay(),tm.GetHour(),tm.GetMinute(),tm.GetSecond());
}
void CBojaySFISDlg::OnClose()
{
// TODO: Add your message handler code here and/or call default
//DeleteFile(L"\\\\172.20.0.8\\1.公司会议资料\\博杰生产管理软件\\Debug\\busy.txt");
m_dbDemo.ClearAllParameters();
m_dbDemo.CloseConnection();
CDialogEx::OnClose();
}
| [
"guoruishigood@163.com"
] | guoruishigood@163.com |
b7ea5a51819d0bf80c513745e3f2b345295468d0 | 65549d29e1595c26a57b2137c0c1c77ac4ae142b | /B-BOS Backup/backup/OSV 8/OSV/kernel.cpp | d1b753f35b29bca7a8536ee495a0a0ccb34e2035 | [] | no_license | Bradon-Barfuss/B-BOS-Bradon-Barfuss-Operating-System | 05bfb42ad044ca4a30b45a4478d8d7f883c5f6cf | 9556266fd85782bbc64fa4a05dae30f9b9a9aa26 | refs/heads/master | 2023-03-05T18:12:25.656689 | 2023-02-24T19:10:55 | 2023-02-24T19:10:55 | 262,191,622 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,293 | cpp | #include "types.h"
#include "gdt.h"
#include "std/print.h"
#include "std/len.h"
#include "Interrupts/interrupt.h"
#include "drivers/driver.h"
#include "drivers/keyboard.h"
#include "drivers/mouse.h"
void printf(char* str){ // This is a printf function, taking the pointer or position of the current char
uint16_t* VideoMemory = (uint16_t*)0xb8000;//the memory location of where the computer will start printing char to the screen is 0xb8000
static uint8_t x = 0, y = 0;
for(int i = 0; str[i] != '\0'; ++i){ //Going to loop through the string until it finds a '\0'
VideoMemory[(80*y)+x] = (VideoMemory[(80*y)+x] & 0xFF00) | str[i]; //it will set the videoMemory var to current char of the string
/*If we just set it to str[i], it will override the high byte where the color information is stored
So we need to combine the current High byte (VideoMemory[i] & 0xBB00) This work as comparing VideoMemory[i] with the bitwise symbole & (AND bitwise symbole) So 0xBB-- will stay the same and ox--00 will change by str[i] text colors */
switch (str[i]){
case '\n':
y++;
x = 0;
break;
default:
VideoMemory[(80*y)+x] = (VideoMemory[(80*y)+x] & 0xFF00) | str[i];
x++;
break;
}
if(x >= 80){
y++;
x = 0;
}
if(y >= 25){
clearScreen();
x = 0;
y = 0;
}
}
}
void printfposition(char* str, uint8_t x, uint8_t y){ // This is a printf function, taking the pointer or position of the current char
uint16_t* VideoMemory = (uint16_t*)0xb8000;//the memory location of where the computer will start printing char to the screen is 0xb8000
for(int i = 0; str[i] != '\0'; ++i){ //Going to loop through the string until it finds a '\0'
VideoMemory[(80*y)+x] = (VideoMemory[(80*y)+x] & 0xFF00) | str[i]; //it will set the videoMemory var to current char of the string
/*If we just set it to str[i], it will override the high byte where the color information is stored
So we need to combine the current High byte (VideoMemory[i] & 0xBB00) This work as comparing VideoMemory[i] with the bitwise symbole & (AND bitwise symbole) So 0xBB-- will stay the same and ox--00 will change by str[i] text colors */
switch (str[i]){
case '\n':
y++;
x = 0;
break;
default:
VideoMemory[(80*y)+x] = (VideoMemory[(80*y)+x] & 0xFF00) | str[i];
x++;
break;
}
if(x >= 80){
y++;
x = 0;
}
if(y >= 25){
clearScreen();
x = 0;
y = 0;
}
}
}
void printfHex(uint8_t key){
char* foo = "00";
char* hex = "0123456789ABCDEF";
foo[0] = hex[(key >> 4) & 0xF];
foo[1] = hex[(key) & 0x0F];
printf(foo);
}
//hard ware
//keyboard
class PrintfKeyboardEventHandler : public KeyboardEventHandler{
public:
void OnKeyDown(char c){
char* foo = " ";
foo[0] = c;
printf(foo);
}
};
//mouse
class MouseToConsole : public MouseEventHandler{
int8_t x, y;//the orginal x and y postions
public:
MouseToConsole(){}
virtual void OnMouseDown(int button){
}
virtual void OnActivate(){
uint16_t* VideoMemory = (uint16_t*)0xb8000;
x = 40;
y = 12;
VideoMemory[80*y+x] = ((VideoMemory[80*y+x] & 0xF000) >> 4)
| ((VideoMemory[80*y+x] & 0x0F00) << 4)
| ((VideoMemory[80*y+x] & 0x00FF));
}
virtual void OnMouseMove(int xoffset, int yoffset){
static uint16_t* VideoMemory = (uint16_t*)0xb8000;
VideoMemory[80*y+x] = ((VideoMemory[80*y+x] & 0xF000) >> 4)
| ((VideoMemory[80*y+x] & 0x0F00) << 4)
| ((VideoMemory[80*y+x] & 0x00FF));
x += xoffset;
if(x < 0){x = 0;}//keeps the mouce leaving the screen
if(x > 80){x=79;}
y += yoffset;//y offset is negitive, so you would add it.
if(y < 0){y = 0;}//keeps the mouce leaving the screen
if(y >= 25){y=24;}
VideoMemory[80*y+x] = ((VideoMemory[80*y+x] & 0xF000) >> 4)
| ((VideoMemory[80*y+x] & 0x0F00) << 4)
| ((VideoMemory[80*y+x] & 0x00FF));
}
};
void startUp(){
uint16_t* VideoMemory = (uint16_t*)0xb8000;//the memory location of where the computer will start printing char to the screen is 0xb8000
char* welcome = "Welcome to Bradons OS";
printfposition(welcome, 25, 4);
char* copyright = "This is the property of bradon barfuss";
printfposition(copyright, 15, 7);
char* instructions = "Please Wait";
printfposition(instructions, 30, 12);
}
//the normal start of kernal
extern "C" void kernelMain(void* multiboot_structure, uint32_t magicnumber){//start of the kernel and the "extern C" is used for c++ to work with gcc
len l;
printf("1\0");//the space, '\f' and '\0' count as one char
//char len = l.length("abcdefghijklmnopqrstuvwxyz\0");
GlobalDescriptorTable gdt;
InterruptManager interrupts(&gdt);//happens here
clearScreen();
printf("HERE 1\n");
DriverManager drvManager;
PrintfKeyboardEventHandler kbhandler;
KeyboardDrive keyboard(&interrupts, &kbhandler);
drvManager.AddDrivers(&keyboard);
MouseToConsole mousehandler;
MouseDriver mouse(&interrupts, &mousehandler);//start the keyboard interupts
drvManager.AddDrivers(&mouse);
printf("HERE 2\n");
drvManager.ActivateAll();
printf("HERE 3\n");
interrupts.Activate();
//clearScreen();
startUp();
while(1);//infinit loop
}
| [
"bradonbarfuss@gmail.com"
] | bradonbarfuss@gmail.com |
c62ec5041980430cd3c6b4ac7d1d64dc2932dff6 | 8a6f96f2c86292699109db3b624f38e29953d69f | /src/masternodeman.h | 94f4a9a9252e0a185731962e98fddabec2b88469 | [
"MIT"
] | permissive | Dgikar/MN-Browsing-Coin | 485cace82b2fe80b8827033d245d4325edc47106 | a7b5a647c34481ff15a37eaede44a2c463b6d189 | refs/heads/master | 2020-04-28T17:01:42.221304 | 2019-02-07T15:56:34 | 2019-02-07T15:56:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,669 | h | // Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Copyright (c) 2017-2018 The MN Browsing Coin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef MASTERNODEMAN_H
#define MASTERNODEMAN_H
#include "base58.h"
#include "key.h"
#include "main.h"
#include "masternode.h"
#include "net.h"
#include "sync.h"
#include "util.h"
#define MASTERNODES_DUMP_SECONDS (15 * 60)
#define MASTERNODES_DSEG_SECONDS (3 * 60 * 60)
using namespace std;
class CMasternodeMan;
extern CMasternodeMan mnodeman;
void DumpMasternodes();
/** Access to the MN database (mncache.dat)
*/
class CMasternodeDB
{
private:
boost::filesystem::path pathMN;
std::string strMagicMessage;
public:
enum ReadResult {
Ok,
FileError,
HashReadError,
IncorrectHash,
IncorrectMagicMessage,
IncorrectMagicNumber,
IncorrectFormat
};
CMasternodeDB();
bool Write(const CMasternodeMan& mnodemanToSave);
ReadResult Read(CMasternodeMan& mnodemanToLoad, bool fDryRun = false);
};
class CMasternodeMan
{
private:
// critical section to protect the inner data structures
mutable CCriticalSection cs;
// critical section to protect the inner data structures specifically on messaging
mutable CCriticalSection cs_process_message;
// map to hold all MNs
std::vector<CMasternode> vMasternodes;
// who's asked for the Masternode list and the last time
std::map<CNetAddr, int64_t> mAskedUsForMasternodeList;
// who we asked for the Masternode list and the last time
std::map<CNetAddr, int64_t> mWeAskedForMasternodeList;
// which Masternodes we've asked for
std::map<COutPoint, int64_t> mWeAskedForMasternodeListEntry;
public:
// Keep track of all broadcasts I've seen
map<uint256, CMasternodeBroadcast> mapSeenMasternodeBroadcast;
// Keep track of all pings I've seen
map<uint256, CMasternodePing> mapSeenMasternodePing;
// keep track of dsq count to prevent masternodes from gaming obfuscation queue
int64_t nDsqCount;
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
{
LOCK(cs);
READWRITE(vMasternodes);
READWRITE(mAskedUsForMasternodeList);
READWRITE(mWeAskedForMasternodeList);
READWRITE(mWeAskedForMasternodeListEntry);
READWRITE(nDsqCount);
READWRITE(mapSeenMasternodeBroadcast);
READWRITE(mapSeenMasternodePing);
}
CMasternodeMan();
CMasternodeMan(CMasternodeMan& other);
/// Add an entry
bool Add(CMasternode& mn);
/// Ask (source) node for mnb
void AskForMN(CNode* pnode, CTxIn& vin);
/// Check all Masternodes
void Check();
/// Check all Masternodes and remove inactive
void CheckAndRemove(bool forceExpiredRemoval = false);
/// Clear Masternode vector
void Clear();
int CountEnabled(int protocolVersion = -1);
void DsegUpdate(CNode* pnode);
/// Find an entry
CMasternode* Find(const CScript& payee);
CMasternode* Find(const CTxIn& vin);
CMasternode* Find(const CPubKey& pubKeyMasternode);
/// Find an entry in the masternode list that is next to be paid
CMasternode* GetNextMasternodeInQueueForPayment(int nBlockHeight, bool fFilterSigTime, int& nCount);
/// Find a random entry
CMasternode* FindRandomNotInVec(std::vector<CTxIn>& vecToExclude, int protocolVersion = -1);
/// Get the current winner for this block
CMasternode* GetCurrentMasterNode(int mod = 1, int64_t nBlockHeight = 0, int minProtocol = 0);
std::vector<CMasternode> GetFullMasternodeVector()
{
Check();
return vMasternodes;
}
std::vector<pair<int, CMasternode> > GetMasternodeRanks(int64_t nBlockHeight, int minProtocol = 0);
int GetMasternodeRank(const CTxIn& vin, int64_t nBlockHeight, int minProtocol = 0, bool fOnlyActive = true);
CMasternode* GetMasternodeByRank(int nRank, int64_t nBlockHeight, int minProtocol = 0, bool fOnlyActive = true);
void ProcessMasternodeConnections();
void ProcessMessage(CNode* pfrom, std::string& strCommand, CDataStream& vRecv);
/// Return the number of (unique) Masternodes
int size() { return vMasternodes.size(); }
std::string ToString() const;
void Remove(CTxIn vin);
/// Update masternode list and maps using provided CMasternodeBroadcast
void UpdateMasternodeList(CMasternodeBroadcast mnb);
};
#endif
| [
"46704511+MNBrowsing@users.noreply.github.com"
] | 46704511+MNBrowsing@users.noreply.github.com |
92eaceec6b4ca2de078e59a68780741c2fb75817 | dd80a584130ef1a0333429ba76c1cee0eb40df73 | /external/chromium_org/third_party/WebKit/Source/web/default/WebRenderTheme.cpp | 0ffd2c9249f772a83adeac4d0c266e56c182f55d | [
"MIT",
"GPL-1.0-or-later",
"LGPL-2.0-or-later",
"Apache-2.0",
"BSD-3-Clause"
] | permissive | karunmatharu/Android-4.4-Pay-by-Data | 466f4e169ede13c5835424c78e8c30ce58f885c1 | fcb778e92d4aad525ef7a995660580f948d40bc9 | refs/heads/master | 2021-03-24T13:33:01.721868 | 2017-02-18T17:48:49 | 2017-02-18T17:48:49 | 81,847,777 | 0 | 2 | MIT | 2020-03-09T00:02:12 | 2017-02-13T16:47:00 | null | UTF-8 | C++ | false | false | 1,918 | cpp | /*
* Copyright (C) 2010 Joel Stanley. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "WebRenderTheme.h"
#include "WebView.h"
#include "core/rendering/RenderThemeChromiumDefault.h"
using WebCore::RenderTheme;
using WebCore::RenderThemeChromiumDefault;
namespace blink {
void setCaretBlinkInterval(double interval)
{
RenderThemeChromiumDefault::setCaretBlinkInterval(interval);
}
} // namespace blink
| [
"karun.matharu@gmail.com"
] | karun.matharu@gmail.com |
446e131658cd545fe11e81bc992dae99b2647c0a | 86609148aee683f1a2f92f9ab5c073b4c29380e4 | /utils/dnp3_src/cpp/libs/src/opendnp3/app/IINValue.h | cf85bc094fd7ce9b903583e570920d60f6404773 | [
"Apache-2.0"
] | permissive | thiagoralves/OpenPLC_v3 | 16ba73585ab6b4aff7fb3e0f6388cf31f7aa2fce | cf139121bc15cb960a8fad62c02f34532b36a7c7 | refs/heads/master | 2023-08-07T06:55:19.533734 | 2023-07-19T15:33:35 | 2023-07-19T15:33:35 | 137,387,519 | 817 | 370 | null | 2023-09-14T03:09:01 | 2018-06-14T17:15:49 | C++ | UTF-8 | C++ | false | false | 1,283 | h | /*
* Licensed to Green Energy Corp (www.greenenergycorp.com) under one or
* more contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright ownership.
* Green Energy Corp 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.
*
* This project was forked on 01/01/2013 by Automatak, LLC and modifications
* may have been made to this file. Automatak, LLC licenses these modifications
* to you under the terms of the License.
*/
#ifndef OPENDNP3_IINVALUE_H
#define OPENDNP3_IINVALUE_H
namespace opendnp3
{
// a simple wrapper type to differentiate an IIN from a bool
class IINValue
{
public:
IINValue() : value(false)
{}
IINValue(bool value_) : value(value_)
{}
bool value;
};
}
#endif
| [
"thiagoralves@gmail.com"
] | thiagoralves@gmail.com |
a517936c4df615a69dd766bfdc660f1955bc4f39 | f626dbd0d37ea81a703830ab406e8e6a5abd4b0a | /Gunz/ZGameInput.cpp | 1fe44a5eea8c368ff4c92869f9665812fdb10be4 | [] | no_license | celestialkey/SRC | 074be88320324b6b799a7b1af19f7a89e7708d90 | c286d588604e6d987e22a302cc02dd2293fa7a2f | refs/heads/main | 2023-04-30T09:40:28.430868 | 2021-05-28T10:16:23 | 2021-05-28T10:16:23 | null | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 23,640 | cpp | #include "stdafx.h"
#include "ZGameInput.h"
#include "ZApplication.h"
#include "ZGameInterface.h"
#include "ZGame.h"
#include "ZConfiguration.h"
#include "ZActionDef.h"
#include "Mint.h"
#include "MEvent.h"
#include "MWidget.h"
#include "ZGameClient.h"
#include "ZCombatInterface.h"
#include "ZConsole.h"
//#include "MActionKey.h"
#include "ZPost.h"
#include "ZScreenEffectManager.h"
#include "ZMyInfo.h"
#include "ZMinimap.h"
#include "ZInput.h"
#include "ZBandiCapturer.h" // 동영상 캡쳐
#undef _DONOTUSE_DINPUT_MOUSE
ZGameInput* ZGameInput::m_pInstance = NULL;
ZGameInput::ZGameInput()
{
m_pInstance = this;
m_bCTOff = false;
// 이것들은 실행되는 내내 m_SequenceActions안에 참조되므로 static 으로 선언되어 있다.
static ZKEYSEQUENCEITEM action_ftumble[]= { {true,ZACTION_FORWARD}, {false,ZACTION_FORWARD} , {true,ZACTION_FORWARD} }; // 앞 앞
static ZKEYSEQUENCEITEM action_btumble[]= { {true,ZACTION_BACK}, {false,ZACTION_BACK} , {true,ZACTION_BACK} }; // 뒤 뒤
static ZKEYSEQUENCEITEM action_rtumble[]= { {true,ZACTION_RIGHT}, {false,ZACTION_RIGHT} , {true,ZACTION_RIGHT} };
static ZKEYSEQUENCEITEM action_ltumble[]= { {true,ZACTION_LEFT}, {false,ZACTION_LEFT} , {true,ZACTION_LEFT} };
#define ADDKEYSEQUENCE(time,x) m_SequenceActions.push_back(ZKEYSEQUENCEACTION(time,sizeof(x)/sizeof(ZKEYSEQUENCEITEM),x));
const float DASH_SEQUENCE_TIME = 0.2f;
ADDKEYSEQUENCE(DASH_SEQUENCE_TIME,action_ftumble);
ADDKEYSEQUENCE(DASH_SEQUENCE_TIME,action_btumble);
ADDKEYSEQUENCE(DASH_SEQUENCE_TIME,action_rtumble);
ADDKEYSEQUENCE(DASH_SEQUENCE_TIME,action_ltumble);
}
ZGameInput::~ZGameInput()
{
m_pInstance = NULL;
}
bool ZGameInput::OnEvent(MEvent* pEvent)
{
int sel = 0;
if ((ZGetGameInterface()->GetState() != GUNZ_GAME)) return false;
if ( ZGetGameInterface()->GetGame() == NULL ) return false;
MWidget* pMenuWidget = ZGetGameInterface()->GetIDLResource()->FindWidget("CombatMenuFrame");
if ((pMenuWidget) && (pMenuWidget->IsVisible())) return false;
MWidget* pChatWidget = ZGetGameInterface()->GetIDLResource()->FindWidget("CombatChatInput");
if ((pChatWidget) && (pChatWidget->IsVisible())) return false;
MWidget* p112ConfirmWidget = ZGetGameInterface()->GetIDLResource()->FindWidget("112Confirm");
if (p112ConfirmWidget->IsVisible()) return false;
#ifndef _PUBLISH
if (m_pInstance) {
if (m_pInstance->OnDebugEvent(pEvent) == true)
return true;
}
#endif
ZMyCharacter* pMyCharacter = ZGetGameInterface()->GetGame()->m_pMyCharacter;
if ((!pMyCharacter) || (!pMyCharacter->GetInitialized())) return false;
////////////////////////////////////////////////////////////////////////////
switch(pEvent->nMessage){
case MWM_HOTKEY:
{
int nKey = pEvent->nKey;
ZHOTKEY *hk=ZGetConfiguration()->GetHotkey(nKey);
//if(ProcessLowLevelCommand(hk->command.c_str())==false)
char buffer[256];
strcpy(buffer,hk->command.c_str());
ZApplication::GetGameInterface()->GetChat()->Input(buffer);
// ConsoleInputEvent(hk->command.c_str());
}break;
case MWM_LBUTTONDOWN:
{
ZCombatInterface* pCombatInterface = ZGetGameInterface()->GetCombatInterface();
if ( ZGetCombatInterface()->IsShowResult())
{
if ( ((ZGetCombatInterface()->m_nReservedOutTime - timeGetTime()) / 1000) < 13)
{
if(ZGetGameClient()->IsLadderGame() || ZGetGameClient()->IsDuelTournamentGame())
ZChangeGameState(GUNZ_LOBBY);
else
ZChangeGameState(GUNZ_STAGE);
return true;
}
}
if (pCombatInterface->IsChat())
{
pCombatInterface->EnableInputChat(false);
}
if (pCombatInterface->GetObserver()->IsVisible())
{
pCombatInterface->GetObserver()->ChangeToNextTarget();
return true;
}
/* if ((pMyCharacter) && (pMyCharacter->IsDie())) //// 실서비스에서 스폰안되는 버그유발. 원인불명(_PUBLISH누락) 영구봉쇄.
{
// 혼자테스트할때 되살아나기
if(g_pGame->m_CharacterManager.size()==1)
{
#ifndef _PUBLISH
ZGetGameInterface()->RespawnMyCharacter();
return true;
#endif
}
}*/
if (ZGetGameInterface()->IsCursorEnable())
return false;
}
return true;
case MWM_RBUTTONDOWN:
{
if (ZGetGameInterface()->GetCombatInterface()->IsChat())
{
ZGetGameInterface()->GetCombatInterface()->EnableInputChat(false);
}
ZCombatInterface* pCombatInterface = ZGetGameInterface()->GetCombatInterface();
if (pCombatInterface->GetObserver()->IsVisible())
{
pCombatInterface->GetObserver()->NextLookMode();
}
}
return true;
case MWM_MBUTTONDOWN:
if (ZGetGameInterface()->GetCombatInterface()->IsChat())
{
ZGetGameInterface()->GetCombatInterface()->EnableInputChat(false);
}
return true;
case MWM_ACTIONRELEASED:
{
switch(pEvent->nKey){
case ZACTION_FORWARD:
case ZACTION_BACK:
case ZACTION_LEFT:
case ZACTION_RIGHT:
if (m_pInstance)
m_pInstance->m_ActionKeyHistory.push_back(ZACTIONKEYITEM(ZGetGame()->GetTime(),false,pEvent->nKey));
return true;
case ZACTION_DEFENCE:
{
if(ZGetGame()->m_pMyCharacter)
ZGetGame()->m_pMyCharacter->m_statusFlags.Ref().m_bGuardKey = false;
}
return true;
}
}break;
case MWM_ACTIONPRESSED:
if ( !ZGetGame()->IsReservedSuicide()) // 자살 예정인 경우 대쉬를 할수없게 막는다
{
switch(pEvent->nKey){
case ZACTION_FORWARD:
case ZACTION_BACK:
case ZACTION_LEFT:
case ZACTION_RIGHT:
case ZACTION_JUMP:
if (m_pInstance)
m_pInstance->m_ActionKeyHistory.push_back(ZACTIONKEYITEM(ZGetGame()->GetTime(),true,pEvent->nKey));
return true;
case ZACTION_MELEE_WEAPON:
{
if ( !ZGetGame()->IsReplay())
ZGetGameInterface()->ChangeWeapon(ZCWT_MELEE);
}
return true;
case ZACTION_PRIMARY_WEAPON:
{
if ( !ZGetGame()->IsReplay())
ZGetGameInterface()->ChangeWeapon(ZCWT_PRIMARY);
}
return true;
case ZACTION_SECONDARY_WEAPON:
{
if ( !ZGetGame()->IsReplay())
ZGetGameInterface()->ChangeWeapon(ZCWT_SECONDARY);
}
return true;
case ZACTION_ITEM1:
case ZACTION_ITEM2:
{
int nIndex = pEvent->nKey - ZACTION_ITEM1 + ZCWT_CUSTOM1;
if ( !ZGetGame()->IsReplay()) {
ZGetGameInterface()->ChangeWeapon(ZChangeWeaponType(nIndex));
}
}
return true;
case ZACTION_COMMUNITYITEM1: mlog("Community Item1 Selected!\n"); return true;
case ZACTION_COMMUNITYITEM2: mlog("Community Item2 Selected!\n"); return true;
case ZACTION_PREV_WEAPON:
{
if ( !ZGetGame()->IsReplay())
ZGetGameInterface()->ChangeWeapon(ZCWT_PREV);
}
return true;
case ZACTION_NEXT_WEAPON:
{
if ( !ZGetGame()->IsReplay())
ZGetGameInterface()->ChangeWeapon(ZCWT_NEXT);
}
return true;
case ZACTION_RELOAD:
{
if ( !ZGetGame()->IsReplay())
ZGetGameInterface()->Reload();
}
return true;
case ZACTION_DEFENCE:
{
if ( ZGetGame()->m_pMyCharacter && !ZGetGame()->IsReplay())
ZGetGame()->m_pMyCharacter->m_statusFlags.Ref().m_bGuardKey = true;
}
return true;
case ZACTION_TAUNT: // 틸다키
case ZACTION_BOW:
case ZACTION_WAVE:
case ZACTION_LAUGH:
case ZACTION_CRY:
case ZACTION_DANCE:
{
if ( ZGetGame()->IsReplay())
break;
if ( MEvent::GetShiftState())
break;
if(ZGetGameInterface()->GetCombatInterface()->GetObserverMode())
break;
ZC_SPMOTION_TYPE mtype;
if(pEvent->nKey == ZACTION_TAUNT) mtype = ZC_SPMOTION_TAUNT;
else if(pEvent->nKey == ZACTION_BOW ) mtype = ZC_SPMOTION_BOW;
else if(pEvent->nKey == ZACTION_WAVE ) mtype = ZC_SPMOTION_WAVE;
else if(pEvent->nKey == ZACTION_LAUGH) mtype = ZC_SPMOTION_LAUGH;
else if(pEvent->nKey == ZACTION_CRY ) mtype = ZC_SPMOTION_CRY;
else if(pEvent->nKey == ZACTION_DANCE) mtype = ZC_SPMOTION_DANCE;
else
return true;
if(ZGetGame())
ZGetGame()->PostSpMotion( mtype ); // ZPostSpMotion(mtype);
}
return true;
case ZACTION_RECORD:
{
if ( ZGetGame() && !ZGetGame()->IsReplay())
ZGetGame()->ToggleRecording();
}
return true;
case ZACTION_MOVING_PICTURE:
{ // 동영상 캡쳐...2008.10.02
if (ZGetGameInterface()->GetBandiCapturer() != NULL)
ZGetGameInterface()->GetBandiCapturer()->ToggleStart();
}
return true;
case ZACTION_TOGGLE_CHAT:
{
if(ZGetCombatInterface()->IsShowUI())
{ // UI토글이 켜져 있을때만 채팅토글을 처리해준다.
if (ZGetGame())
{
ZCombatInterface* pCombatInterface = ZGetGameInterface()->GetCombatInterface();
ZGetSoundEngine()->PlaySound("if_error");
pCombatInterface->ShowChatOutput(!ZGetConfiguration()->GetViewGameChat());
}
}
}
return true;
case ZACTION_USE_WEAPON:
case ZACTION_USE_WEAPON2:
{
return true;
}
case ZACTION_SENSITIVITY_INC:
case ZACTION_SENSITIVITY_DEC:
{
int nPrev = ZGetConfiguration()->GetMouseSensitivityInInt();
float senstivity = Z_MOUSE_SENSITIVITY;
if (pEvent->nKey == ZACTION_SENSITIVITY_INC)
senstivity += 0.01f;
else
senstivity -= 0.01f;
ZGetConfiguration()->SetMouseSensitivityInFloat(senstivity);
int nNew = ZGetConfiguration()->GetMouseSensitivityInInt();
ZGetConfiguration()->ReserveSave();
ZChatOutputMouseSensitivityChanged(nPrev, nNew);
return true;
}
} // switch
}
break;
case MWM_KEYDOWN:
{
ZCombatInterface* pCombatInterface = ZGetGameInterface()->GetCombatInterface();
switch (pEvent->nKey)
{
case VK_F1:
case VK_F2:
case VK_F3:
case VK_F4:
case VK_F5:
case VK_F6:
case VK_F7:
case VK_F8:
if( pEvent->nKey == VK_F1 ) sel = 0;
else if( pEvent->nKey == VK_F2 ) sel = 1;
else if( pEvent->nKey == VK_F3 ) sel = 2;
else if( pEvent->nKey == VK_F4 ) sel = 3;
else if( pEvent->nKey == VK_F5 ) sel = 4;
else if( pEvent->nKey == VK_F6 ) sel = 5;
else if( pEvent->nKey == VK_F7 ) sel = 6;
else if( pEvent->nKey == VK_F8 ) sel = 7;
if(ZGetConfiguration()) {
char* str = ZGetConfiguration()->GetMacro()->GetString( sel );
if(str) {
if(ZApplication::GetGameInterface())
if(ZApplication::GetGameInterface()->GetChat())
ZApplication::GetGameInterface()->GetChat()->Input(str);
}
}
return true;
case VK_F9:
case VK_RETURN:
case VK_OEM_2:
{
if (!ShowCombatInputChat()) return false;
}
return true;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'Y':
case 'N':
if (pCombatInterface->GetObserver()->IsVisible())
pCombatInterface->GetObserver()->OnKeyEvent(pEvent->bCtrl, pEvent->nKey);
if (ZGetGameClient()->CanVote() ||
ZGetGameInterface()->GetCombatInterface()->GetVoteInterface()->GetShowTargetList() )
{
ZGetGameInterface()->GetCombatInterface()->GetVoteInterface()->VoteInput(pEvent->nKey);
}
break;
case VK_ESCAPE: // 메뉴를 부르거나 kick player를 취소한다
if (ZGetGameInterface()->GetCombatInterface()->GetVoteInterface()->GetShowTargetList()) {
ZGetGameInterface()->GetCombatInterface()->GetVoteInterface()->CancelVote();
} else {
ZGetGameInterface()->ShowMenu(!ZGetGameInterface()->IsMenuVisible());
ZGetGameInterface()->Show112Dialog(false);
}
return true;
case 'M' :
if ( ZGetGame()->IsReplay() && pCombatInterface->GetObserver()->IsVisible())
{
if(ZGetGameInterface()->GetCamera()->GetLookMode()==ZCAMERA_FREELOOK)
ZGetGameInterface()->GetCamera()->SetLookMode(ZCAMERA_MINIMAP);
else
ZGetGameInterface()->GetCamera()->SetLookMode(ZCAMERA_FREELOOK);
}
break;
case 'T' :
if(ZGetGame()->m_pMyCharacter->GetTeamID()==MMT_SPECTATOR &&
ZGetGame()->GetMatch()->IsTeamPlay() &&
pCombatInterface->GetObserver()->IsVisible()) {
ZObserver *pObserver = pCombatInterface->GetObserver();
pObserver->SetType(pObserver->GetType()==ZOM_BLUE ? ZOM_RED : ZOM_BLUE);
pObserver->ChangeToNextTarget();
}
case 'H':
if ( ZGetGame()->IsReplay() && pCombatInterface->GetObserver()->IsVisible())
{
if ( ZGetGame()->IsShowReplayInfo())
ZGetGame()->ShowReplayInfo( false);
else
ZGetGame()->ShowReplayInfo( true);
}
break;
case 'J':
{
#ifdef _CMD_PROFILE
if ((pEvent->bCtrl) && (ZIsLaunchDevelop()))
{
#ifndef _PUBLISH
ZGetGameClient()->m_CommandProfiler.Analysis();
#endif
}
#endif
}
break;
#ifdef _DEBUG
case 'K':
{
rvector pos = ZGetGame()->m_pMyCharacter->GetPosition();
pos.x+=1;
ZGetGame()->m_pMyCharacter->SetPosition(pos);
}
break;
case 'L':
{
rvector pos = ZGetGame()->m_pMyCharacter->GetPosition();
pos.x-=1;
ZGetGame()->m_pMyCharacter->SetPosition(pos);
}
break;
//case 'J':
// {
// ZGetGame()->m_pMyCharacter->GetPosition().z = ZGetGame()->m_pMyCharacter->GetPosition().z+1;
// }
// break;
//case 'M':
// {
// ZGetGame()->m_pMyCharacter->GetPosition().z = ZGetGame()->m_pMyCharacter->GetPosition().z-1;
// }
// break;
case 'U':
{
rvector pos = ZGetGame()->m_pMyCharacter->GetPosition();
pos.x = -3809;
pos.y = -1330;
pos.z = 100;
ZGetGame()->m_pMyCharacter->SetPosition(pos);
//ZGetGame()->m_pMyCharacter->GetPosition().x = -3809;
//ZGetGame()->m_pMyCharacter->GetPosition().y = -1337.5;
//ZGetGame()->m_pMyCharacter->GetPosition().z = 461;
}
break;
#endif
}
}
break;
case MWM_CHAR:
{
ZMatch* pMatch = ZGetGame()->GetMatch();
if (pMatch->IsTeamPlay()) {
switch(pEvent->nKey) {
case '\'':
case '\"':
{
ZCombatInterface* pCombatInterface = ZGetGameInterface()->GetCombatInterface();
pCombatInterface->EnableInputChat(true, true);
}
return true;
};
}
// for deutsch, spanish keyboard
if (pEvent->nKey == '/') {
if (!ShowCombatInputChat()) return false;
}
}
break;
case MWM_SYSKEYDOWN:
{
// alt+a ~ z(65~90)
if(pEvent->nKey==90){ // Alt+'Z' // 모든 UI 감추기... by kammir 20081020
ZGetCombatInterface()->SetIsShowUI(!ZGetCombatInterface()->IsShowUI());
if (ZGetGame())
{
ZCombatInterface* pCombatInterface = ZGetGameInterface()->GetCombatInterface();
ZGetSoundEngine()->PlaySound("if_error");
pCombatInterface->ShowChatOutput(ZGetCombatInterface()->IsShowUI());
}
}
}
break;
case MWM_MOUSEWHEEL:
{
if ( ZGetGame()->IsReplay())
break;
int nDelta = pEvent->nDelta;
/* Fix Removes scroll option for admins to change camera distance while spectating
if ( (ZGetMyInfo()->IsAdminGrade() && ZGetCombatInterface()->GetObserver()->IsVisible()) ||
(ZGetGameInterface()->GetScreenDebugger()->IsVisible()) ||
(!ZGetGameInterface()->m_bViewUI))
{
ZCamera* pCamera = ZGetGameInterface()->GetCamera();
pCamera->m_fDist+=-(float)nDelta;
pCamera->m_fDist=max(CAMERA_DIST_MIN,pCamera->m_fDist);
pCamera->m_fDist=min(CAMERA_DIST_MAX,pCamera->m_fDist);
break;
} */
// if (nDelta > 0) ZGetGameInterface()->ChangeWeapon(ZCWT_PREV);
// else if (nDelta < 0) ZGetGameInterface()->ChangeWeapon(ZCWT_NEXT);
}break;
case MWM_MOUSEMOVE:
{
if(ZGetGameInterface()->IsCursorEnable()==false)
{
return true;
}
}
break;
} // switch (message)
return false;
}
bool ZGameInput::ShowCombatInputChat()
{
if( ZGetCombatInterface()->IsShowUI() && !ZGetCombatInterface()->IsShowResult() )
{ // UI토글이 켜져 있을때만 채팅토글을 처리해준다.
ZCombatInterface* pCombatInterface = ZGetGameInterface()->GetCombatInterface();
if ((pCombatInterface) && (!pCombatInterface->IsChat()) && !ZGetGame()->IsReplay())
{
MWidget* pWidget = ZGetGameInterface()->GetIDLResource()->FindWidget("112Confirm");
if (pWidget && pWidget->IsVisible()) return false;
pCombatInterface->EnableInputChat(true);
}
}
return true;
}
#include "MTextArea.h"
void ZGameInput::Update(float fElapsed)
{
/*
{
static DWORD dwLastTime = timeGetTime();
if(timeGetTime()-dwLastTime > 10 )
{
dwLastTime = timeGetTime();
{
MTextArea *pTextArea = (MTextArea*)ZGetGameInterface()->GetIDLResource()->FindWidget("CombatChatOutputTest");
if(pTextArea)
{
char szbuffer[256];
for(int i=0;i<100;i++)
{
szbuffer[i]=rand()%255+1;
}
szbuffer[100]=0;
pTextArea->AddText(szbuffer);
if(pTextArea->GetLineCount()>10) pTextArea->DeleteFirstLine();
}
}
{
MTextArea *pTextArea = (MTextArea*)ZGetGameInterface()->GetIDLResource()->FindWidget("CombatChatOutput");
if(pTextArea)
{
char szbuffer[256];
for(int i=0;i<100;i++)
{
szbuffer[i]=rand()%255+1;
}
szbuffer[100]=0;
pTextArea->AddText(szbuffer);
if(pTextArea->GetLineCount()>10) pTextArea->DeleteFirstLine();
}
}
}
}//*/
// if(RIsActive() && !g_pGame->IsReplay())
//jintriple3 메모리 프록시...비트 패킹..
const ZCharaterStatusBitPacking &uStatus = ZGetGame()->m_pMyCharacter->m_dwStatusBitPackingValue.Ref();
ZMyCharaterStatusBitPacking & zStatus = ZGetGame()->m_pMyCharacter->m_statusFlags.Ref();
if(RIsActive())
{
ZCamera* pCamera = ZGetGameInterface()->GetCamera();
ZMyCharacter* pMyCharacter = ZGetGame()->m_pMyCharacter;
if ((!pMyCharacter) || (!pMyCharacter->GetInitialized())) return;
// 커서가 없는 상태에서만 카메라및 게임입력을 받는다
if(!ZGetGameInterface()->IsCursorEnable())
{
{
float fRotateX = 0;
float fRotateY = 0;
#ifdef _DONOTUSE_DINPUT_MOUSE
// DINPUT 을 사용하지 않는경우
int iDeltaX, iDeltaY;
POINT pt;
GetCursorPos(&pt);
ScreenToClient(g_hWnd,&pt);
iDeltaX = pt.x-RGetScreenWidth()/2;
iDeltaY = pt.y-RGetScreenHeight()/2;
float fRotateStep = 0.0005f * Z_MOUSE_SENSITIVITY*10.0f;
fRotateX = (iDeltaX * fRotateStep);
fRotateY = (iDeltaY * fRotateStep);
#else
// 마우스 입력 dinput 처리
ZGetInput()->GetRotation(&fRotateX,&fRotateY);
#endif
bool bRotateEnable=false;
// TODO : 칼로 벽에 꽂았을때 프리카메라로 바꾸자
if( !zStatus.m_bSkill && !uStatus.m_bWallJump && !uStatus.m_bWallJump2 && !zStatus.m_bWallHang &&
!uStatus.m_bTumble && !uStatus.m_bBlast && !uStatus.m_bBlastStand && !uStatus.m_bBlastDrop )
bRotateEnable=true;
if (pMyCharacter->IsDie()) bRotateEnable = true;
if (RIsActive())
{
ZCamera *pCamera = ZGetGameInterface()->GetCamera();
pCamera->m_fAngleX += fRotateY;
pCamera->m_fAngleZ += fRotateX;
if(pCamera->GetLookMode()==ZCAMERA_MINIMAP) {
pCamera->m_fAngleX=max(pi/2+.1f,pCamera->m_fAngleX);
pCamera->m_fAngleX=min(pi-0.1f,pCamera->m_fAngleX);
}else {
static float lastanglex,lastanglez;
if(bRotateEnable)
{
// 정밀도 유지를 위해 0~2pi 로 유지
pCamera->m_fAngleZ = fmod(pCamera->m_fAngleZ,2*PI);
pCamera->m_fAngleX = fmod(pCamera->m_fAngleX,2*PI);
pCamera->m_fAngleX=max(CAMERA_ANGLEX_MIN,pCamera->m_fAngleX);
pCamera->m_fAngleX=min(CAMERA_ANGLEX_MAX,pCamera->m_fAngleX);
lastanglex=pCamera->m_fAngleX;
lastanglez=pCamera->m_fAngleZ;
}else
{
// 각도제한이 필요하다
pCamera->m_fAngleX=max(CAMERA_ANGLEX_MIN,pCamera->m_fAngleX);
pCamera->m_fAngleX=min(CAMERA_ANGLEX_MAX,pCamera->m_fAngleX);
pCamera->m_fAngleX=max(lastanglex-pi/4.f,pCamera->m_fAngleX);
pCamera->m_fAngleX=min(lastanglex+pi/4.f,pCamera->m_fAngleX);
pCamera->m_fAngleZ=max(lastanglez-pi/4.f,pCamera->m_fAngleZ);
pCamera->m_fAngleZ=min(lastanglez+pi/4.f,pCamera->m_fAngleZ);
}
}
ZCombatInterface* pCombatInterface = ZGetGameInterface()->GetCombatInterface();
if (pCombatInterface && !pCombatInterface->IsChat() &&
(pCamera->GetLookMode()==ZCAMERA_FREELOOK || pCamera->GetLookMode()==ZCAMERA_MINIMAP))
{
rvector right;
rvector forward=RCameraDirection;
CrossProduct(&right,rvector(0,0,1),forward);
Normalize(right);
const rvector up = rvector(0,0,1);
rvector accel = rvector(0,0,0);
if(ZIsActionKeyPressed(ZACTION_FORWARD)==true) accel+=forward;
if(ZIsActionKeyPressed(ZACTION_BACK)==true) accel-=forward;
if(ZIsActionKeyPressed(ZACTION_LEFT)==true) accel-=right;
if(ZIsActionKeyPressed(ZACTION_RIGHT)==true) accel+=right;
if(ZIsActionKeyPressed(ZACTION_JUMP)==true) accel+=up;
if(ZIsActionKeyPressed(ZACTION_USE_WEAPON)==true) accel-=up;
rvector cameraMove =
(pCamera->GetLookMode()==ZCAMERA_FREELOOK ? 1000.f : 10000.f ) // 미니맵모드는 빨리 움직임
* fElapsed*accel;
rvector targetPos = pCamera->GetPosition()+cameraMove;
// 프리룩은 충돌체크를 한다
if(pCamera->GetLookMode()==ZCAMERA_FREELOOK)
ZGetGame()->GetWorld()->GetBsp()->CheckWall(pCamera->GetPosition(),targetPos,ZFREEOBSERVER_RADIUS,0.f,RCW_SPHERE);
else
// 미니맵은 범위내에 있는지 체크한다
{
rboundingbox *pbb = &ZGetGame()->GetWorld()->GetBsp()->GetRootNode()->bbTree;
targetPos.x = max(min(targetPos.x,pbb->maxx),pbb->minx);
targetPos.y = max(min(targetPos.y,pbb->maxy),pbb->miny);
ZMiniMap *pMinimap = ZGetGameInterface()->GetMiniMap();
if(pMinimap)
targetPos.z = max(min(targetPos.z,pMinimap->GetHeightMax()),pMinimap->GetHeightMin());
else
targetPos.z = max(min(targetPos.z,7000),2000);
}
pCamera->SetPosition(targetPos);
}
else if ( !ZGetGame()->IsReplay())
{
pMyCharacter->ProcessInput( fElapsed);
}
}
}
POINT pt={RGetScreenWidth()/2,RGetScreenHeight()/2};
ClientToScreen(g_hWnd,&pt);
SetCursorPos(pt.x,pt.y);
// 대쉬 키 입력 검사
GameCheckSequenceKeyCommand();
}else
pMyCharacter->ReleaseButtonState(); // 메뉴가 나왔을때는 버튼이 눌리지 않은상태로 돌려놓는다
}
}
#define MAX_KEY_SEQUENCE_TIME 2.f
void ZGameInput::GameCheckSequenceKeyCommand()
{
// 철지난 키 입력은 일단 제거한다.
while(m_ActionKeyHistory.size()>0 && (ZGetGame()->GetTime()-(*m_ActionKeyHistory.begin()).fTime>MAX_KEY_SEQUENCE_TIME))
{
m_ActionKeyHistory.erase(m_ActionKeyHistory.begin());
}
if(m_ActionKeyHistory.size())
{
for(int ai=0;ai<(int)m_SequenceActions.size();ai++)
{
ZKEYSEQUENCEACTION action=m_SequenceActions.at(ai);
list<ZACTIONKEYITEM>::iterator itr=m_ActionKeyHistory.end();
itr--;
bool bAction=true;
for(int i=action.nKeyCount-1;i>=0;i--)
{
ZACTIONKEYITEM itm=*itr;
if(i==0)
{
if(ZGetGame()->GetTime()-itm.fTime>action.fTotalTime)
{
bAction=false;
break;
}
}
if(itm.nActionKey!=action.pKeys[i].nActionKey || itm.bPressed!=action.pKeys[i].bPressed)
{
bAction=false;
break;
}
if(i!=0 && itr==m_ActionKeyHistory.begin())
{
bAction=false;
break;
}
itr--;
}
if(bAction)
{
while(m_ActionKeyHistory.size())
{
m_ActionKeyHistory.erase(m_ActionKeyHistory.begin());
}
if(ai>=0 && ai<=3) // 덤블링
ZGetGame()->m_pMyCharacter->OnTumble(ai);
}
}
}
}
| [
"justintinblake@gmail.com"
] | justintinblake@gmail.com |
b283ca8e36979536fa2cdbee7b0ac2b68226c1ab | 6c1d7976b43be4de8b3fe472fea8ef50f461ce44 | /aieBootstrap-master/PhysicsProject/Box.h | 8376b90a60f1b607d4bc0bce562478ce945c40ec | [
"MIT"
] | permissive | JustinKatic/PhysicsProject | 4b1ed92429522c3949899e91512eb2aadb9c993a | 29c84a07adcb90ad538b5b141cd8c5088bc7c6e1 | refs/heads/main | 2023-03-04T01:31:00.589052 | 2021-02-17T01:43:48 | 2021-02-17T01:43:48 | 335,802,354 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 936 | h | #pragma once
#include "RigidBody.h"
class Box : public RigidBody
{
public:
Box(glm::vec2 a_position, glm::vec2 a_velocity, float a_rotation, float a_mass, float a_width, float a_height);
Box(glm::vec2 a_position, glm::vec2 a_velocity, float a_rotation, float a_mass, float a_width, float a_height, glm::vec4 a_color);
~Box();
virtual void FixedUpdate(glm::vec2 a_gravity, float a_timestep);
virtual void MakeGizmo();
virtual bool IsInside(glm::vec2 a_point) { return false; }
bool CheckBoxCorners(const Box& a_box, glm::vec2& a_contact, int& a_numOfContacts, float& a_pen, glm::vec2& a_edgeNode);
float GetWidth() { return m_extents.x * 2; }
float GetHeight() { return m_extents.y * 2; }
glm::vec2 GetExtents() const { return m_extents; }
glm::vec2 GetLocalX() { return m_localX; }
glm::vec2 GetLocalY() { return m_localY; }
protected:
glm::vec2 m_extents; //the half length of the box
glm::vec4 m_color;
};
| [
"justinkatic4@gmail.com"
] | justinkatic4@gmail.com |
05bf6b96d230704fa18dc5306cf2dbf61a56109c | 3c8cf4de6c08e21b2c10094ef20488e93d7a34be | /TktkUtilityLib/Tktk3dCollisionLib/inc/Tktk3dCollision/BoundingSphere.h | 19db665b287e8f24b33a26514b67074d10987bb3 | [] | no_license | tktk2104/TktkLib | 07762028c8a3a7378d7e82be8f1ed8c6a0cdc97c | 2af549bfb8448ace9f9fee6c2225ea7d2e6329b8 | refs/heads/master | 2022-11-30T12:26:33.290941 | 2020-08-11T17:50:14 | 2020-08-11T17:50:14 | 213,307,835 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 675 | h | #ifndef BOUNDING_SPHERE_H_
#define BOUNDING_SPHERE_H_
#include "Body3dBase/Body3dBase.h"
class AxisAlignedBoundingBox;
// 球体
// ※楕円体ではない
class BoundingSphere
: public Body3dBase
{
public:
BoundingSphere(
float radius,
const Vector3 & localPosition = Vector3::zero
);
// 衝突判定
bool isCollide(const Body3dBase& other, HitInfo3D* hitinfo) const override;
public:
// ※行列のスケールの値はx要素だけが使用される
float calculateRadius() const;
// ※行列のスケールの値はx要素だけが使用される
float calculateLocalRadius() const;
private:
float m_radius;
};
#endif // !BOUNDING_SPHERE_H_ | [
"taka.lalpedhuez@2104.gmail.com"
] | taka.lalpedhuez@2104.gmail.com |
61bfc9963ace444872b5b648f563c172d164123f | ca9cac516d14f27ecbdeffd23f7d6fbd581558b9 | /Blackjack/Dealer.cpp | 40dfa781de156d85c0be1a1a39f36363f8b321e7 | [] | no_license | srepper/Blackjack | 7e2f75df7d7dee82a7381d4c182f1dcfeb52fc2d | bc6e14a1d6c1466119fa2f190a7feab9626b8093 | refs/heads/master | 2020-04-02T19:43:30.451776 | 2016-07-03T03:50:45 | 2016-07-03T03:50:45 | 62,480,386 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,005 | cpp | #include "Dealer.h"
Dealer::Dealer(SDL_Surface *surface)
{
pot = 0;
score = 0;
handPos = 0;
busted = false;
dealerLabel = new MyLabel("Dealer:", 20, 130);
lblScore = new MyLabel("", 105, 130);
lblPot = new MyLabel("", SCREEN_WIDTH/2 - 50, 185);
lblBust = new MyLabel("BUST", 25, 50);
lblBust->setColorRed();
hand[0] = new Card();
hand[0]->setPos(20, 20);
hand[0]->setSurface(surface);
for(int i = 1; i < 11; i++)
{
SDL_Rect tempPos = hand[i-1]->getPos();
hand[i] = new Card();
hand[i]->setPos(tempPos.x + 15, tempPos.y + 4);
hand[i]->setSurface(surface);
}
}
Dealer::~Dealer()
{
delete dealerLabel;
delete lblScore;
delete lblPot;
delete lblBust;
delete[] hand;
}
void Dealer::clearPot()
{
pot = 0;
}
void Dealer::updatePot(int bet)
{
pot += bet;
}
int Dealer::getPot()
{
return pot;
}
int Dealer::checkBlackjack()
{
return score + hand[0]->getValue();
}
int Dealer::getScore()
{
return score;
}
std::string Dealer::getPotString()
{
std::string retString;
std::stringstream ss;
ss << pot;
retString = "$" + ss.str();
return retString;
}
std::string Dealer::getScoreString()
{
if(score == 0)
return "-";
std::string retString;
std::stringstream ss;
ss << score;
retString = ss.str();
return retString;
}
void Dealer::setCardBack(SDL_Surface *blueCard)
{
cardBack = blueCard;
}
void Dealer::dealCard(Card *newCard)
{
if(handPos != 0)
{
hand[handPos]->setClip(newCard->getClip()->x, newCard->getClip()->y);
hand[handPos]->setRank(newCard->getRank());
hand[handPos]->setValue(newCard->getValue());
score += hand[handPos]->getValue();
}
else
{
tempClip = newCard->getClip();
hand[handPos]->setSurface(cardBack);
hand[handPos]->setClip(0, 0);
hand[handPos]->setRank(newCard->getRank());
hand[handPos]->setValue(newCard->getValue());
}
if(score > 21)
reduceAce();
handPos++;
}
void Dealer::clearHand()
{
for(int i = 0; i < 11; i++)
{
hand[i]->setValue(0);
}
handPos = 0;
score = 0;
}
/* Checks for and reduces one Ace from 11 to 1 value within hand */
void Dealer::reduceAce()
{
for(int i = 0; i < 11; i++)
{
if(hand[i]->getRank() == ACE && hand[i]->getValue() != 1)
{
hand[i]->setValue(1);
score -= 10;
break;
}
else if(hand[i]->getRank() == 0)
break;
}
}
void Dealer::bust()
{
busted = true;
}
void Dealer::clearBust()
{
busted = false;
}
/* "Flip" the dealer's hidden card */
void Dealer::showHidden(SDL_Surface *cards)
{
hand[0]->setSurface(cards);
hand[0]->setClip(*tempClip);
score += hand[0]->getValue();
}
/* Updates all screen information for dealer */
void Dealer::update(SDL_Surface *screen)
{
dealerLabel->applySurface(screen, NULL);
lblScore->setMessage(getScoreString());
lblScore->applySurface(screen, NULL);
lblPot->setMessage("Pot: " + getPotString());
lblPot->applySurface(screen, NULL);
for(int i = 0; i < 11; i++)
{
if(hand[i]->getValue() != 0)
{
hand[i]->applySurface(screen);
}
}
if(busted)
lblBust->applySurface(screen, NULL);
} | [
"s.repper@yahoo.com"
] | s.repper@yahoo.com |
6a99b2d8f4e9bfef9969b914b2e87f102c55b6e5 | 6cabb3a28013758e71c3cfab530762d49b89785b | /Offline contest (36)/river/river.cpp | 4fcec536502ab7b9b0dcee09372608a236f0c216 | [] | no_license | TreeYD/Code | 2caeccbebd1330fd51373fc46aafd6804c9446bf | 1e16ccc80cf36af3728f3ca172e4ab86402e4d8e | refs/heads/master | 2020-04-01T22:47:06.318221 | 2018-10-31T11:37:19 | 2018-10-31T11:37:19 | 153,726,191 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 823 | cpp | #include<bits/stdc++.h>
using namespace std;
#define MaxL 10003005
int A[105],m;
bool mark[MaxL];
int S,T,Len;
template<typename T>void Min(T &x,T y){if(x>y)x=y;}
struct P70{
int dp[MaxL],Q[MaxL];
void solve(){
int L=0,R=0;
Q[++R]=0;
memset(dp,63,sizeof(dp));
dp[0]=0;
for(int i=1;i<=m;i++)
mark[A[i]]=1;
for(int i=S;i<Len+T;i++){
if(L<=R&&i-Q[L]>T)L++;
while(L<=R&&dp[i-S]<=dp[Q[L]])L++;
Q[++R]=i-S;
Min(dp[i],dp[Q[L]]+mark[i]);
}
int ans=2e9;
for(int i=Len;i<Len+T;i++)
Min(ans,dp[i]);
printf("%d\n",ans);
}
}p70;
int main(){//name memory long long * mod -
// freopen("river.in","r",stdin);
// freopen("river.out","w",stdout);
scanf("%d",&Len);
scanf("%d%d%d",&S,&T,&m);
for(int i=1;i<=m;i++){
scanf("%d",&A[i]);
mark[A[i]]=1;
}
// p30.solve();
p70.solve();
return 0;
}
| [
"672713702@qq.com"
] | 672713702@qq.com |
34f9e7bad711e916565e932653f8ae0ef3a0e922 | 45a8ea04a90c26b93df3d7b6af5b2b67ad09bfac | /wrappers/lazy_ptr.hpp | 9410c4208c6f33b86f7e1b8ea75623e3da3478b8 | [] | no_license | runouw-dev/util.wrapperscpp | 9ec6741c43ef0ea6aab1b92eec1706310845c8f1 | f4bd66faa7f6658a40257975375d8f5532c715c5 | refs/heads/master | 2021-01-23T10:56:20.230468 | 2017-06-02T00:31:42 | 2017-06-02T00:31:42 | 93,111,051 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,178 | hpp | #pragma once
#include <functional>
#include <memory>
namespace wrappers {
template <class T>
class lazy_ptr {
private:
std::unique_ptr<T> _instance;
std::function<T()> _constructor;
bool _init;
public:
lazy_ptr(const std::function<T()>& constructor) :
_instance(nullptr),
_constructor(constructor),
_init(false) {}
lazy_ptr(lazy_ptr<T>&) = delete;
lazy_ptr(lazy_ptr<T>&&) = default;
~lazy_ptr() = default;
lazy_ptr<T>& operator=(lazy_ptr<T>&) = delete;
lazy_ptr<T>& operator=(lazy_ptr<T>&&) = default;
T * get();
T& operator*();
T * operator->();
T * restore();
bool isInitialized() const;
};
template<class T>
bool lazy_ptr<T>::isInitialized() const {
return _init;
}
template<class T>
T * lazy_ptr<T>::get() {
if (_init) {
return _instance.get();
} else {
return restore();
}
}
template<class T>
T * lazy_ptr<T>::restore() {
auto newPtr = std::make_unique<T> (_constructor());
_instance.swap(newPtr);
_init = true;
return _instance.get();
}
template<class T>
T& lazy_ptr<T>::operator*() {
return *get();
}
template<class T>
T * lazy_ptr<T>::operator->() {
return get();
}
}
| [
"zmichaels11@gmail.com"
] | zmichaels11@gmail.com |
b210d2b50bcca30d7ff01e7af6114c6999af0b1e | c0ea9dfd2ac29b9756bbc78679c5a90b469a6d7e | /pwnable_kr/uaf/my_uaf.cpp | a6707e39fb97491810deda7b4c4e65989e306ce1 | [] | no_license | ssdemajia/writeup | a6c98a926ffdfa31193e4e31c1ee9563dbff6f31 | c574a38c69fd10f90bbd02f80134c91730a37e3f | refs/heads/master | 2020-08-12T17:41:34.802823 | 2019-10-18T06:21:37 | 2019-10-18T06:21:37 | 214,811,593 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 216 | cpp | #include <stdio.h>
#include <string>
class Test {
int age;
std::string name;
};
int main() {
Test* t = new Test();
delete t;
Test* t2 = new Test();
printf("%p - %p\n", t, t2);
delete t2;
} | [
"2chashao@gmail.com"
] | 2chashao@gmail.com |
7beb760c4a1d54d9f041383a3f941a6047b1310a | eac24fbc91fcd353c8996346972639f27bc3197c | /rei/rei_recognition_nodes/include/rei_recognition_nodes/filter/filter_block.hpp | 8d02b7c88ecd321681eb066012e12f73961ba63a | [
"BSD-3-Clause"
] | permissive | Forrest-Z/hotaru_planner | 3e05ae864d6dc6f46b5b23b3441a4de4dcbdd149 | 04070d58e72bd9d94c50c15ef3447ffdb40ce383 | refs/heads/master | 2023-01-10T01:43:29.113939 | 2020-10-01T14:22:11 | 2020-10-01T14:22:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 287 | hpp | /*
* filter_block.hpp
*
* Created on: Sep 9, 2020
* Author: kyberszittya
*/
#ifndef INCLUDE_REI_RECOGNITION_NODES_FILTER_FILTER_BLOCK_HPP_
#define INCLUDE_REI_RECOGNITION_NODES_FILTER_FILTER_BLOCK_HPP_
#endif /* INCLUDE_REI_RECOGNITION_NODES_FILTER_FILTER_BLOCK_HPP_ */
| [
"noreply@github.com"
] | noreply@github.com |
665c0d7ec2ca15197e415acf46855aedd201ceed | 2cfc8e8694e2115995e259151e320ad8bc64ed08 | /Robot_ws/devel/include/more_custom_msgs/Hve_Write_Params.h | 94c370a64d2f62db9ad69ef4d9f2d18901c7580c | [] | no_license | thilina-thilakarathna/robot_ws | d31e6ea82758b91dbf3a8045faedcf0e8a283ca1 | 094854a54b88eb3690f77710739dc2fe7d22b6f8 | refs/heads/master | 2023-01-10T15:17:51.400625 | 2019-08-28T18:59:21 | 2019-08-28T18:59:21 | 187,395,119 | 0 | 0 | null | 2023-01-07T09:10:06 | 2019-05-18T19:00:30 | Makefile | UTF-8 | C++ | false | false | 7,049 | h | // Generated by gencpp from file more_custom_msgs/Hve_Write_Params.msg
// DO NOT EDIT!
#ifndef MORE_CUSTOM_MSGS_MESSAGE_HVE_WRITE_PARAMS_H
#define MORE_CUSTOM_MSGS_MESSAGE_HVE_WRITE_PARAMS_H
#include <string>
#include <vector>
#include <map>
#include <ros/types.h>
#include <ros/serialization.h>
#include <ros/builtin_message_traits.h>
#include <ros/message_operations.h>
#include <std_msgs/Header.h>
#include <more_custom_msgs/Hve_Conf_Param.h>
namespace more_custom_msgs
{
template <class ContainerAllocator>
struct Hve_Write_Params_
{
typedef Hve_Write_Params_<ContainerAllocator> Type;
Hve_Write_Params_()
: header()
, parameters() {
}
Hve_Write_Params_(const ContainerAllocator& _alloc)
: header(_alloc)
, parameters(_alloc) {
(void)_alloc;
}
typedef ::std_msgs::Header_<ContainerAllocator> _header_type;
_header_type header;
typedef std::vector< ::more_custom_msgs::Hve_Conf_Param_<ContainerAllocator> , typename ContainerAllocator::template rebind< ::more_custom_msgs::Hve_Conf_Param_<ContainerAllocator> >::other > _parameters_type;
_parameters_type parameters;
typedef boost::shared_ptr< ::more_custom_msgs::Hve_Write_Params_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::more_custom_msgs::Hve_Write_Params_<ContainerAllocator> const> ConstPtr;
}; // struct Hve_Write_Params_
typedef ::more_custom_msgs::Hve_Write_Params_<std::allocator<void> > Hve_Write_Params;
typedef boost::shared_ptr< ::more_custom_msgs::Hve_Write_Params > Hve_Write_ParamsPtr;
typedef boost::shared_ptr< ::more_custom_msgs::Hve_Write_Params const> Hve_Write_ParamsConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::more_custom_msgs::Hve_Write_Params_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::more_custom_msgs::Hve_Write_Params_<ContainerAllocator> >::stream(s, "", v);
return s;
}
} // namespace more_custom_msgs
namespace ros
{
namespace message_traits
{
// BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': True}
// {'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg'], 'geometry_msgs': ['/opt/ros/kinetic/share/geometry_msgs/cmake/../msg'], 'more_custom_msgs': ['/home/thilina/development/robot_ws/Robot_ws/src/more_custom_msgs/msg']}
// !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types']
template <class ContainerAllocator>
struct IsFixedSize< ::more_custom_msgs::Hve_Write_Params_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::more_custom_msgs::Hve_Write_Params_<ContainerAllocator> const>
: FalseType
{ };
template <class ContainerAllocator>
struct IsMessage< ::more_custom_msgs::Hve_Write_Params_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::more_custom_msgs::Hve_Write_Params_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::more_custom_msgs::Hve_Write_Params_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::more_custom_msgs::Hve_Write_Params_<ContainerAllocator> const>
: TrueType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::more_custom_msgs::Hve_Write_Params_<ContainerAllocator> >
{
static const char* value()
{
return "165f347965c3c8e1065a41586476c3d4";
}
static const char* value(const ::more_custom_msgs::Hve_Write_Params_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0x165f347965c3c8e1ULL;
static const uint64_t static_value2 = 0x065a41586476c3d4ULL;
};
template<class ContainerAllocator>
struct DataType< ::more_custom_msgs::Hve_Write_Params_<ContainerAllocator> >
{
static const char* value()
{
return "more_custom_msgs/Hve_Write_Params";
}
static const char* value(const ::more_custom_msgs::Hve_Write_Params_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::more_custom_msgs::Hve_Write_Params_<ContainerAllocator> >
{
static const char* value()
{
return "std_msgs/Header header\n\
Hve_Conf_Param[] parameters\n\
================================================================================\n\
MSG: std_msgs/Header\n\
# Standard metadata for higher-level stamped data types.\n\
# This is generally used to communicate timestamped data \n\
# in a particular coordinate frame.\n\
# \n\
# sequence ID: consecutively increasing ID \n\
uint32 seq\n\
#Two-integer timestamp that is expressed as:\n\
# * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')\n\
# * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')\n\
# time-handling sugar is provided by the client library\n\
time stamp\n\
#Frame this data is associated with\n\
# 0: no frame\n\
# 1: global frame\n\
string frame_id\n\
\n\
================================================================================\n\
MSG: more_custom_msgs/Hve_Conf_Param\n\
string full_parameter_path\n\
string parameter_value\n\
";
}
static const char* value(const ::more_custom_msgs::Hve_Write_Params_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::more_custom_msgs::Hve_Write_Params_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)
{
stream.next(m.header);
stream.next(m.parameters);
}
ROS_DECLARE_ALLINONE_SERIALIZER
}; // struct Hve_Write_Params_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::more_custom_msgs::Hve_Write_Params_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::more_custom_msgs::Hve_Write_Params_<ContainerAllocator>& v)
{
s << indent << "header: ";
s << std::endl;
Printer< ::std_msgs::Header_<ContainerAllocator> >::stream(s, indent + " ", v.header);
s << indent << "parameters[]" << std::endl;
for (size_t i = 0; i < v.parameters.size(); ++i)
{
s << indent << " parameters[" << i << "]: ";
s << std::endl;
s << indent;
Printer< ::more_custom_msgs::Hve_Conf_Param_<ContainerAllocator> >::stream(s, indent + " ", v.parameters[i]);
}
}
};
} // namespace message_operations
} // namespace ros
#endif // MORE_CUSTOM_MSGS_MESSAGE_HVE_WRITE_PARAMS_H
| [
"ltjt.thilina@gmail.com"
] | ltjt.thilina@gmail.com |
3c992e9ff8c157a396b4707c68f16752ce1e2a36 | 06988b0d37e030b91b13b24774017a12ac8f09fb | /MQWeb/include/MQ/Web/Dictionary.h | 7b60cc811547546b04952895aba220adf36c3a68 | [
"MIT"
] | permissive | fbraem/mqweb | d28b7b2791054217087a7625e77b108e31985673 | a8aefb129ec08b3e408b6bd93a871c2a8bf36169 | refs/heads/master | 2021-12-24T18:51:22.154241 | 2019-03-25T09:08:32 | 2019-03-25T09:08:32 | 6,764,663 | 19 | 8 | null | 2013-11-27T13:30:16 | 2012-11-19T17:54:14 | C++ | UTF-8 | C++ | false | false | 5,203 | h | /*
* Copyright 2017 - KBC Group NV - Franky Braem - 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.
*/
#ifndef _MQWeb_Dictionary
#define _MQWeb_Dictionary
#include <cmqc.h>
#include <map>
#include <string>
#include "Poco/JSON/Object.h"
#include "MQ/PCF.h"
#include "MQ/Web/MapInitializer.h"
namespace MQ {
namespace Web {
typedef std::map<MQLONG, std::string> TextMap;
typedef MapInitializer<MQLONG, std::string> TextMapInitializer;
class Dictionary
/// Class for holding all names, ids and values for Websphere MQ fields.
/// It can be used to get the field name for a given Websphere MQ field constant
/// or to get a String representation of a value of a field.
/// It's used by PCFCommand to translate the values, ids, ...:
/// getName(MQCA_ALTERATION_DATE) will return "AlterationDate",
/// while getId("AlterationDate") will return MQCA_ALTERATION_DATE.
/// getDisplayValue(MQIA_PLATFORM, MQPL_UNIX) will return "UNIX".
{
public:
Dictionary();
/// Constructor
virtual ~Dictionary();
/// Destructor
Dictionary& operator()(MQLONG id, const std::string& name = "");
/// Adds the name for the given id.
Dictionary& operator()(MQLONG id, const std::string& name, const TextMap& textMap);
/// Adds the name and value for the given id.
const TextMap& getTextMap(MQLONG id) const;
/// Returns all values for the given id.
std::string getTextForValue(MQLONG id, MQLONG value) const;
/// Returns the display string for the given value of the given id.
/// For example: in PCFCommand getDisplayValue(MQIA_PLATFORM, MQPL_UNIX) will return "UNIX".
MQLONG getIdForText(MQLONG id, const std::string& value) const;
/// Returns the id for the given value and id.
/// For example: in PCFCommand getDisplayId(MQIA_PLATFORM, "UNIX") will return MQPL_UNIX.
MQLONG getIdForName(const std::string& name) const;
/// Returns the id for the given name.
/// For example: in PCFCommand getId("Platform") will return MQIA_PLATFORM.
std::string getNameForId(MQLONG id) const;
/// Returns the name for the given id
/// For example: in PCFCommand getName(MQIA_PLATFORM) will return "Platform".
bool hasTextMap(MQLONG id) const;
/// Returns true when the id has a corresponding map with display values.
void mapToJSON(const PCFParameters& parameters, Poco::JSON::Object::Ptr& json, bool alwaysCreate = true) const;
void mapToPCF(Poco::JSON::Object::Ptr json, PCF &pcf) const;
std::map<MQLONG, std::string>::const_iterator begin() const;
/// Returns the begin iterator of the id map
std::map<MQLONG, std::string>::const_iterator end() const;
/// Returns the end iterator of the id map
void set(MQLONG id, const std::string& name);
void set(MQLONG id, const std::string& name, const TextMap& textMap);
private:
std::map<MQLONG, std::string> _idMap;
std::map<std::string, MQLONG> _nameMap;
std::map<MQLONG, TextMap> _textMaps;
};
inline std::string Dictionary::getNameForId(MQLONG id) const
{
std::string name;
std::map<MQLONG, std::string>::const_iterator it = _idMap.find(id);
if ( it != _idMap.end() )
name = it->second;
return name;
}
inline MQLONG Dictionary::getIdForName(const std::string& name) const
{
MQLONG id = -1;
std::map<std::string, MQLONG>::const_iterator it =_nameMap.find(name);
if ( it != _nameMap.end() )
id = it->second;
return id;
}
inline const TextMap& Dictionary::getTextMap(MQLONG id) const
{
static TextMap emptyMap;
std::map<MQLONG, TextMap>::const_iterator it = _textMaps.find(id);
if ( it == _textMaps.end() )
return emptyMap;
return it->second;
}
inline bool Dictionary::hasTextMap(MQLONG id) const
{
return _textMaps.find(id) != _textMaps.end();
}
inline std::map<MQLONG, std::string>::const_iterator Dictionary::begin() const
{
return _idMap.begin();
}
inline std::map<MQLONG, std::string>::const_iterator Dictionary::end() const
{
return _idMap.end();
}
inline void Dictionary::set(MQLONG id, const std::string& name)
{
_idMap[id] = name;
_nameMap[name] = id;
}
inline void Dictionary::set(MQLONG id, const std::string& name, const TextMap& textMap)
{
set(id, name);
_textMaps[id] = textMap;
}
}} // Namespace MQWeb
#endif // _MQWeb_Dictionary
| [
"franky.braem@gmail.com"
] | franky.braem@gmail.com |
867ec01915736b4db56183e0ed25014eb5a66340 | c3e9f2f91b2c02cee249aa5948ea0f6ef899db7c | /libraries/AdaDHT11/DHT.cpp | 4e5582e42bf7dc7171dfe060599fa057c2219964 | [] | no_license | VincentGijsen/all_energia_stuff | 42fae3efded2e76caf6ebc743d871698debc15d0 | a4a0154663259aff437fdca3ede1b01a3c2f9ddf | refs/heads/master | 2021-01-15T18:09:11.498451 | 2013-08-08T17:51:48 | 2013-08-08T17:51:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,174 | cpp | /* DHT library
MIT license
written by Adafruit Industries
*/
#include "DHT.h"
DHT::DHT(uint8_t pin, uint8_t type) {
_pin = pin;
_type = type;
firstreading = true;
}
void DHT::begin(void) {
// set up the pins!
pinMode(_pin, INPUT);
digitalWrite(_pin, HIGH);
_lastreadtime = 0;
}
//boolean S == Scale. True == Farenheit; False == Celcius
float DHT::readTemperature(bool S) {
float f;
if (read()) {
switch (_type) {
case DHT11:
f = data[2];
if(S)
f = convertCtoF(f);
return f;
case DHT22:
case DHT21:
f = data[2] & 0x7F;
f *= 256;
f += data[3];
f /= 10;
if (data[2] & 0x80)
f *= -1;
if(S)
f = convertCtoF(f);
return f;
}
}
//Serial.print("Read fail");
return 0;
}
float DHT::convertCtoF(float c) {
return c * 9 / 5 + 32;
}
float DHT::readHumidity(void) {
float f;
if (read()) {
switch (_type) {
case DHT11:
f = data[0];
return f;
case DHT22:
case DHT21:
f = data[0];
f *= 256;
f += data[1];
f /= 10;
return f;
}
}
//Serial.print("Read fail");
return 0;
}
boolean DHT::read(void) {
uint8_t laststate = HIGH;
uint8_t counter = 0;
uint8_t j = 0, i;
unsigned long currenttime;
// pull the pin high and wait 250 milliseconds
digitalWrite(_pin, HIGH);
delay(250);
currenttime = millis();
if (currenttime < _lastreadtime) {
// ie there was a rollover
_lastreadtime = 0;
}
if (!firstreading && ((currenttime - _lastreadtime) < 2000)) {
return true; // return last correct measurement
//delay(2000 - (currenttime - _lastreadtime));
}
firstreading = false;
/*
Serial.print("Currtime: "); Serial.print(currenttime);
Serial.print(" Lasttime: "); Serial.print(_lastreadtime);
*/
_lastreadtime = millis();
data[0] = data[1] = data[2] = data[3] = data[4] = 0;
// now pull it low for ~20 milliseconds
pinMode(_pin, OUTPUT);
digitalWrite(_pin, LOW);
delay(20);
noInterrupts();
digitalWrite(_pin, HIGH);
delayMicroseconds(40);
pinMode(_pin, INPUT);
// read in timings
for ( i=0; i< MAXTIMINGS; i++) {
counter = 0;
while (digitalRead(_pin) == laststate) {
counter++;
delayMicroseconds(3);
if (counter == 255) {
break;
}
}
laststate = digitalRead(_pin);
if (counter == 255) break;
// ignore first 3 transitions
if ((i >= 4) && (i%2 == 0)) {
// shove each bit into the storage bytes
data[j/8] <<= 1;
if (counter > 6)
data[j/8] |= 1;
j++;
}
}
interrupts();
/*
Serial.println(j, DEC);
Serial.print(data[0], HEX); Serial.print(", ");
Serial.print(data[1], HEX); Serial.print(", ");
Serial.print(data[2], HEX); Serial.print(", ");
Serial.print(data[3], HEX); Serial.print(", ");
Serial.print(data[4], HEX); Serial.print(" =? ");
Serial.println(data[0] + data[1] + data[2] + data[3], HEX);
*/
// check we read 40 bits and that the checksum matches
if ((j >= 40) &&
(data[4] == ((data[0] + data[1] + data[2] + data[3]) & 0xFF)) ) {
return true;
}
return false;
}
| [
"vincent@sciencerockstars.com"
] | vincent@sciencerockstars.com |
f36914dd174cd826aba3ea29c13da5e6df3beb7f | 31b6a4c30aa02652658a8499c0202ddb226cf36d | /main_resize.cpp | 9829047a767efed31112545a7056ba8d2752252b | [] | no_license | myxxxsquared/totalpreprocess | c59c36ee32ed91356e165d29663118aafa5a9687 | 18ae41af01f52e60a9730c1257687a40221ba176 | refs/heads/master | 2021-05-06T13:55:21.776141 | 2018-01-13T12:57:09 | 2018-01-13T12:57:09 | 113,293,752 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 550 | cpp |
#include "data.hpp"
#include "process.hpp"
#include "resize.hpp"
int main_resize(int argc, char* argv[])
{
if(argc != 7)
throw "useage: totalpreprocess resize size image polygon output beginid";
int size = atoi(argv[2]);
const char* imagefile = argv[3];
const char* polyfile = argv[4];
const char* outputfile = argv[5];
int beginid = atoi(argv[6]);
Resize r;
r.target_height = r.target_width = size;
r.current = beginid;
r.loadfile(polyfile, imagefile);
r.generate(outputfile);
return 0;
}
| [
"zhang_a_a_a@outlook.com"
] | zhang_a_a_a@outlook.com |
d472b9ed24ac43c2da35a8d097249aedbd235e8a | bc6da89a05bacaae60d951379452c9f987bb47ba | /plugins/Dfusion/src/OutFile.cpp | 5617175f8257b6b043c12d4f7db2230ba0195235 | [
"Zlib",
"MIT",
"BSD-2-Clause",
"LicenseRef-scancode-public-domain"
] | permissive | quietust/dfhack-23a | fb351d05515c6e6d0542fb04759d2af2aaa68119 | dcd03430fb3b3beba4b7ffd8ae6ae35f4bf0ec9a | refs/heads/master | 2023-01-31T03:54:23.314605 | 2023-01-10T02:54:36 | 2023-01-10T02:54:36 | 6,946,231 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,484 | cpp | #include "OutFile.h"
#include <stdexcept>
using namespace OutFile;
File::File(std::string path)
{
//mystream.exceptions ( std::fstream::eofbit | std::fstream::failbit | std::fstream::badbit );
mystream.open(path.c_str(),std::fstream::binary|std::ios::in|std::ios::out);
if(mystream)
{
mystream.read((char*)&myhead,sizeof(myhead));
for(unsigned i=0;i<myhead.sectioncount;i++)
{
Section x;
mystream.read((char*)&x,sizeof(Section));
sections[x.name]=x;
}
//std::cout<<"Sizeof:"<<sizeof(Section)<<"\n";
/*myhead.PrintData();
for(auto it=sections.begin();it!=sections.end();it++)
{
it->second.PrintData();
}*/
}
else
{
throw std::runtime_error("Error opening file!");
}
}
Section &File::GetSection(std::string name)
{
return sections[name];
}
void File::GetText(char *ptr)
{
Section &s=GetSection(".text");
mystream.seekg(s.start);
mystream.read(ptr,s.size);
}
size_t File::GetTextSize()
{
Section &s=GetSection(".text");
return s.size;
}
void File::PrintRelocations()
{
for(auto it=sections.begin();it!=sections.end();it++)
{
std::cout<<it->first<<":\n";
for(unsigned i=0;i<it->second.numRel;i++)
{
Relocation r;
mystream.seekg(it->second.ptrRel+10*i);
mystream.read((char*)&r,10);
std::cout<<r.ptr<<" -- "<<r.tblIndex<<":"<</*symbols[r.tblIndex].name<<*/" type:"<<r.type<<"\n";
}
}
}
void File::PrintSymbols()
{
std::cout<<"Sizeof symbol:"<<sizeof(Symbol)<<std::endl;
std::cout<<"Symbol count:"<<myhead.symbolcount<<std::endl;
for(unsigned i=0;i<myhead.symbolcount;i++)
{
mystream.seekg(myhead.symbolptr+i*18);
Symbol s;
std::cout<<i<<"\t";
s.Read(mystream,myhead.symbolptr+18*myhead.symbolcount);
//mystream.read((char*)&s,sizeof(Symbol));
s.PrintData();
symbols.push_back(s);
if(s.auxsymbs>0)
{
i+=s.auxsymbs;
}
}
}
void File::LoadSymbols()
{
symbols.clear();
for(unsigned i=0;i<myhead.symbolcount;i++)
{
mystream.seekg(myhead.symbolptr+i*18);
Symbol s;
s.Read(mystream,myhead.symbolptr+18*myhead.symbolcount);
symbols.push_back(s);
if(s.auxsymbs>0)
{
i+=s.auxsymbs;
}
}
}
File::~File()
{
}
| [
"Warmist@gmail.com"
] | Warmist@gmail.com |
887ee36f90cc486f27b3088e2ea62da4047689b8 | 22624712561a9e4d687f46368af83ab70b3c4584 | /glGame2/TexturedModle.cpp | d503ec0b94df221d21152792478313bf740637bc | [] | no_license | JakeI/PlaneteSimulator | 6554325b66fff44765c999a50d59f40a8ff49ec6 | 5a5cafe7a76fd575e4dadc6cc8a9088982561c04 | refs/heads/master | 2020-12-13T22:36:27.724900 | 2016-09-27T17:41:26 | 2016-09-27T17:41:26 | 68,303,422 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,769 | cpp | #include "TexturedModle.h"
void TexturedShaderProg::LoadUniformID() {
matrixID = glGetUniformLocation(ProgrammID, "MVP");
}
void TexturedShaderProg::start(GLuint vao, GLuint vboXYZ, GLuint vboUV, GLuint tbo) {
glBindTexture(GL_TEXTURE_2D, tbo);
glBindVertexArray(vao);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vboXYZ);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, vboUV);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, (void*)0);
}
void TexturedShaderProg::stop() {
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
}
void TexturedShaderProg::draw(GLuint vao, GLuint vboXYZ, GLuint vboUV, GLuint tbo,
int length, GLenum mode, glm::mat4 mvp) {
use(true);
drawPrestarted(vao, vboXYZ, vboUV, tbo, length, mode, mvp);
use(false);
}
void TexturedShaderProg::uploadMatrix(glm::mat4 matrix) {
glUniformMatrix4fv(matrixID, 1, GL_FALSE, &matrix[0][0]);
}
void TexturedShaderProg::drawPrestarted(GLuint vao, GLuint vboXYZ, GLuint vboUV,
GLuint tbo, int length, GLenum mode, glm::mat4 mvp) {
start(vao, vboXYZ, vboUV, tbo);
uploadMatrix(mvp);
glDrawArrays(mode, 0, length);
stop();
}
TexturedShaderProg* TexturedModle::shader;
bool TexturedModle::wasInitialised = false;
void TexturedModle::init() {
if (wasInitialised)
return;
shader = new TexturedShaderProg();
wasInitialised = true;
}
void TexturedModle::close() {
if (!wasInitialised)
return;
delete shader;
wasInitialised = false;
}
TexturedModle::TexturedModle() {
vao = 0;
vboXYZ = 0;
vboUV = 0;
tbo = 0;
length = 0;
}
TexturedModle::~TexturedModle() {}
void TexturedModle::draw(glm::mat4 mvp) {
shader->draw(vao, vboXYZ, vboUV, tbo, length, GL_QUADS, mvp);
} | [
"j.illerhaus@live.de"
] | j.illerhaus@live.de |
65c89dfb43775d13cf7144df41f0d8353dab0e92 | 610dfa590d5863e9465cc5a07a2045c9ee0c9385 | /src/Externals/tinyxml/tinystr.h | 275e76a9a18f0b28075c0a619d84da749b12dd14 | [
"Zlib"
] | permissive | SCI-ElVis/ElVis | f275322dea593ed39c4771b072399573819624c0 | 7978b5898ef7d0a0f7711c77dda0e69167716efa | refs/heads/master | 2021-01-01T06:18:45.390678 | 2015-10-19T09:00:23 | 2015-10-19T09:00:23 | 8,036,991 | 14 | 4 | null | 2020-10-13T00:43:47 | 2013-02-05T20:11:59 | C++ | UTF-8 | C++ | false | false | 8,776 | h | /*
www.sourceforge.net/projects/tinyxml
Original file by Yves Berquin.
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product documentation
would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
/*
* THIS FILE WAS ALTERED BY Tyge Lovset, 7. April 2005.
*
* - completely rewritten. compact, clean, and fast implementation.
* - sizeof(TiXmlString) = pointer size (4 bytes on 32-bit systems)
* - fixed reserve() to work as per specification.
* - fixed buggy compares operator==(), operator<(), and operator>()
* - fixed operator+=() to take a const ref argument, following spec.
* - added "copy" constructor with length, and most compare operators.
* - added swap(), clear(), size(), capacity(), operator+().
*/
#ifndef TIXML_USE_STL
#ifndef TIXML_STRING_INCLUDED
#define TIXML_STRING_INCLUDED
#include <assert.h>
#include <string.h>
/* The support for explicit isn't that universal, and it isn't really
required - it is used to check that the TiXmlString class isn't incorrectly
used. Be nice to old compilers and macro it here:
*/
#if defined(_MSC_VER) && (_MSC_VER >= 1200 )
// Microsoft visual studio, version 6 and higher.
#define TIXML_EXPLICIT explicit
#elif defined(__GNUC__) && (__GNUC__ >= 3 )
// GCC version 3 and higher.s
#define TIXML_EXPLICIT explicit
#else
#define TIXML_EXPLICIT
#endif
namespace tinyxml
{
/*
TiXmlString is an emulation of a subset of the std::string template.
Its purpose is to allow compiling TinyXML on compilers with no or poor STL support.
Only the member functions relevant to the TinyXML project have been implemented.
The buffer allocation is made by a simplistic power of 2 like mechanism : if we increase
a string and there's no more room, we allocate a buffer twice as big as we need.
*/
class TiXmlString
{
public :
// The size type used
typedef size_t size_type;
// Error value for find primitive
static const size_type npos; // = -1;
// TiXmlString empty constructor
TiXmlString () : rep_(&nullrep_)
{
}
// TiXmlString copy constructor
TiXmlString ( const TiXmlString & copy)
{
init(copy.length());
memcpy(start(), copy.data(), length());
}
// TiXmlString constructor, based on a string
TIXML_EXPLICIT TiXmlString ( const char * copy)
{
init( static_cast<size_type>( strlen(copy) ));
memcpy(start(), copy, length());
}
// TiXmlString constructor, based on a string
TIXML_EXPLICIT TiXmlString ( const char * str, size_type len)
{
init(len);
memcpy(start(), str, len);
}
// TiXmlString destructor
~TiXmlString ()
{
quit();
}
// = operator
TiXmlString& operator = (const char * copy)
{
return assign( copy, (size_type)strlen(copy));
}
// = operator
TiXmlString& operator = (const TiXmlString & copy)
{
return assign(copy.start(), copy.length());
}
// += operator. Maps to append
TiXmlString& operator += (const char * suffix)
{
return append(suffix, static_cast<size_type>( strlen(suffix) ));
}
// += operator. Maps to append
TiXmlString& operator += (char single)
{
return append(&single, 1);
}
// += operator. Maps to append
TiXmlString& operator += (const TiXmlString & suffix)
{
return append(suffix.data(), suffix.length());
}
// Convert a TiXmlString into a null-terminated char *
const char * c_str () const { return rep_->str; }
// Convert a TiXmlString into a char * (need not be null terminated).
const char * data () const { return rep_->str; }
// Return the length of a TiXmlString
size_type length () const { return rep_->size; }
// Alias for length()
size_type size () const { return rep_->size; }
// Checks if a TiXmlString is empty
bool empty () const { return rep_->size == 0; }
// Return capacity of string
size_type capacity () const { return rep_->capacity; }
// single char extraction
const char& at (size_type index) const
{
assert( index < length() );
return rep_->str[ index ];
}
// [] operator
char& operator [] (size_type index) const
{
assert( index < length() );
return rep_->str[ index ];
}
// find a char in a string. Return TiXmlString::npos if not found
size_type find (char lookup) const
{
return find(lookup, 0);
}
// find a char in a string from an offset. Return TiXmlString::npos if not found
size_type find (char tofind, size_type offset) const
{
if (offset >= length()) return npos;
for (const char* p = c_str() + offset; *p != '\0'; ++p)
{
if (*p == tofind) return static_cast< size_type >( p - c_str() );
}
return npos;
}
void clear ()
{
//Lee:
//The original was just too strange, though correct:
// TiXmlString().swap(*this);
//Instead use the quit & re-init:
quit();
init(0,0);
}
/* Function to reserve a big amount of data when we know we'll need it. Be aware that this
function DOES NOT clear the content of the TiXmlString if any exists.
*/
void reserve (size_type cap);
TiXmlString& assign (const char* str, size_type len);
TiXmlString& append (const char* str, size_type len);
void swap (TiXmlString& other)
{
Rep* r = rep_;
rep_ = other.rep_;
other.rep_ = r;
}
private:
void init(size_type sz) { init(sz, sz); }
void set_size(size_type sz) { rep_->str[ rep_->size = sz ] = '\0'; }
char* start() const { return rep_->str; }
char* finish() const { return rep_->str + rep_->size; }
struct Rep
{
size_type size, capacity;
char str[1];
};
void init(size_type sz, size_type cap)
{
if (cap)
{
// Lee: the original form:
// rep_ = static_cast<Rep*>(operator new(sizeof(Rep) + cap));
// doesn't work in some cases of new being overloaded. Switching
// to the normal allocation, although use an 'int' for systems
// that are overly picky about structure alignment.
const size_type bytesNeeded = sizeof(Rep) + cap;
const size_type intsNeeded = ( bytesNeeded + sizeof(int) - 1 ) / sizeof( int );
rep_ = reinterpret_cast<Rep*>( new int[ intsNeeded ] );
rep_->str[ rep_->size = sz ] = '\0';
rep_->capacity = cap;
}
else
{
rep_ = &nullrep_;
}
}
void quit()
{
if (rep_ != &nullrep_)
{
// The rep_ is really an array of ints. (see the allocator, above).
// Cast it back before delete, so the compiler won't incorrectly call destructors.
delete [] ( reinterpret_cast<int*>( rep_ ) );
}
}
Rep * rep_;
static Rep nullrep_;
} ;
inline bool operator == (const TiXmlString & a, const TiXmlString & b)
{
return ( a.length() == b.length() ) // optimization on some platforms
&& ( strcmp(a.c_str(), b.c_str()) == 0 ); // actual compare
}
inline bool operator < (const TiXmlString & a, const TiXmlString & b)
{
return strcmp(a.c_str(), b.c_str()) < 0;
}
inline bool operator != (const TiXmlString & a, const TiXmlString & b) { return !(a == b); }
inline bool operator > (const TiXmlString & a, const TiXmlString & b) { return b < a; }
inline bool operator <= (const TiXmlString & a, const TiXmlString & b) { return !(b < a); }
inline bool operator >= (const TiXmlString & a, const TiXmlString & b) { return !(a < b); }
inline bool operator == (const TiXmlString & a, const char* b) { return strcmp(a.c_str(), b) == 0; }
inline bool operator == (const char* a, const TiXmlString & b) { return b == a; }
inline bool operator != (const TiXmlString & a, const char* b) { return !(a == b); }
inline bool operator != (const char* a, const TiXmlString & b) { return !(b == a); }
TiXmlString operator + (const TiXmlString & a, const TiXmlString & b);
TiXmlString operator + (const TiXmlString & a, const char* b);
TiXmlString operator + (const char* a, const TiXmlString & b);
/*
TiXmlOutStream is an emulation of std::ostream. It is based on TiXmlString.
Only the operators that we need for TinyXML have been developped.
*/
class TiXmlOutStream : public TiXmlString
{
public :
// TiXmlOutStream << operator.
TiXmlOutStream & operator << (const TiXmlString & in)
{
*this += in;
return *this;
}
// TiXmlOutStream << operator.
TiXmlOutStream & operator << (const char * in)
{
*this += in;
return *this;
}
} ;
}
#endif // TIXML_STRING_INCLUDED
#endif // TIXML_USE_STL
| [
"dillonl@sdcenter.utah.edu"
] | dillonl@sdcenter.utah.edu |
dbd6a5695ca2a9dd0263978438258c109c6d8cd7 | 9da899bf6541c6a0514219377fea97df9907f0ae | /Developer/MaterialUtilities/Private/MeshRendering.cpp | 2c49156abafe86552f145835a1343bc889cdad9d | [] | 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 | 30,014 | cpp | // Copyright Epic Games, Inc. All Rights Reserved.
/*=============================================================================
MeshRendering.cpp: Mesh rendering implementation.
=============================================================================*/
#include "MeshRendering.h"
#include "EngineDefines.h"
#include "ShowFlags.h"
#include "RHI.h"
#include "RenderResource.h"
#include "HitProxies.h"
#include "RenderingThread.h"
#include "VertexFactory.h"
#include "TextureResource.h"
#include "PackedNormal.h"
#include "Engine/TextureRenderTarget2D.h"
#include "Misc/App.h"
#include "MaterialUtilities.h"
#include "Misc/FileHelper.h"
#include "StaticMeshAttributes.h"
#include "SceneView.h"
#include "MeshBatch.h"
#include "CanvasItem.h"
#include "CanvasRender.h"
#include "LocalVertexFactory.h"
#include "Rendering/SkeletalMeshLODRenderData.h"
#include "MeshPassProcessor.h"
#include "RendererInterface.h"
#include "EngineModule.h"
#include "LightMapHelpers.h"
#include "Async/ParallelFor.h"
#include "DynamicMeshBuilder.h"
#include "MaterialBakingHelpers.h"
#define SHOW_WIREFRAME_MESH 0
#define SAVE_INTERMEDIATE_TEXTURES 0
class FMeshRenderInfo : public FLightCacheInterface
{
public:
FMeshRenderInfo(const FLightMap* InLightMap, const FShadowMap* InShadowMap, FUniformBufferRHIRef Buffer)
: FLightCacheInterface()
{
SetLightMap(InLightMap);
SetShadowMap(InShadowMap);
SetPrecomputedLightingBuffer(Buffer);
}
virtual FLightInteraction GetInteraction(const class FLightSceneProxy* LightSceneProxy) const override
{
return LIT_CachedLightMap;
}
};
/**
* Canvas render item enqueued into renderer command list.
*/
class FMeshMaterialRenderItem2 : public FCanvasBaseRenderItem
{
public:
FMeshMaterialRenderItem2(FSceneViewFamily* InViewFamily, const FMeshDescription* InMesh, const FSkeletalMeshLODRenderData* InLODData, int32 LightMapIndex, int32 InMaterialIndex, const FBox2D& InTexcoordBounds, const TArray<FVector2D>& InTexCoords, const FVector2D& InSize, const FMaterialRenderProxy* InMaterialRenderProxy, const FCanvas::FTransformEntry& InTransform /*= FCanvas::FTransformEntry(FMatrix::Identity)*/, FLightMapRef LightMap, FShadowMapRef ShadowMap, FUniformBufferRHIRef Buffer) : Data(new FRenderData(
InViewFamily,
InMesh,
InLODData,
LightMapIndex,
InMaterialIndex,
InTexcoordBounds,
InTexCoords,
InSize,
InMaterialRenderProxy,
InTransform,
new FMeshRenderInfo(LightMap, ShadowMap, Buffer)))
{
}
~FMeshMaterialRenderItem2()
{
}
private:
class FRenderData
{
public:
FRenderData(
FSceneViewFamily* InViewFamily,
const FMeshDescription* InMesh,
const FSkeletalMeshLODRenderData* InLODData,
int32 InLightMapIndex,
int32 InMaterialIndex,
const FBox2D& InTexcoordBounds,
const TArray<FVector2D>& InTexCoords,
const FVector2D& InSize,
const FMaterialRenderProxy* InMaterialRenderProxy = nullptr,
const FCanvas::FTransformEntry& InTransform = FCanvas::FTransformEntry(FMatrix::Identity),
FLightCacheInterface* InLCI = nullptr)
: ViewFamily(InViewFamily)
, StaticMesh(InMesh)
, SkeletalMesh(InLODData)
, LightMapIndex(InLightMapIndex)
, MaterialIndex(InMaterialIndex)
, TexcoordBounds(InTexcoordBounds)
, TexCoords(InTexCoords)
, Size(InSize)
, MaterialRenderProxy(InMaterialRenderProxy)
, Transform(InTransform)
, LCI(InLCI)
{}
FSceneViewFamily* ViewFamily;
const FMeshDescription* StaticMesh;
const FSkeletalMeshLODRenderData* SkeletalMesh;
int32 LightMapIndex;
int32 MaterialIndex;
FBox2D TexcoordBounds;
const TArray<FVector2D>& TexCoords;
FVector2D Size;
const FMaterialRenderProxy* MaterialRenderProxy;
FCanvas::FTransformEntry Transform;
FLightCacheInterface* LCI;
};
FRenderData* Data;
public:
static void EnqueueMaterialRender(class FCanvas* InCanvas, FSceneViewFamily* InViewFamily, const FMeshDescription* InMesh, const FSkeletalMeshLODRenderData* InLODRenderData, int32 LightMapIndex, int32 InMaterialIndex, const FBox2D& InTexcoordBounds, const TArray<FVector2D>& InTexCoords, const FVector2D& InSize, const FMaterialRenderProxy* InMaterialRenderProxy, FLightMapRef LightMap, FShadowMapRef ShadowMap, FUniformBufferRHIRef Buffer)
{
// get sort element based on the current sort key from top of sort key stack
FCanvas::FCanvasSortElement& SortElement = InCanvas->GetSortElement(InCanvas->TopDepthSortKey());
// get the current transform entry from top of transform stack
const FCanvas::FTransformEntry& TopTransformEntry = InCanvas->GetTransformStack().Top();
// create a render batch
FMeshMaterialRenderItem2* RenderBatch = new FMeshMaterialRenderItem2(
InViewFamily,
InMesh,
InLODRenderData,
LightMapIndex,
InMaterialIndex,
InTexcoordBounds,
InTexCoords,
InSize,
InMaterialRenderProxy,
TopTransformEntry,
LightMap,
ShadowMap,
Buffer);
SortElement.RenderBatchArray.Add(RenderBatch);
}
static int32 FillStaticMeshData(bool bDuplicateTris, const FMeshDescription& RawMesh, FRenderData& Data, TArray<FDynamicMeshVertex>& OutVerts, TArray<uint32>& OutIndices)
{
// count triangles for selected material
int32 NumTris = 0;
for (const FTriangleID TriangleID : RawMesh.Triangles().GetElementIDs())
{
const FPolygonGroupID PolygonGroupID = RawMesh.GetTrianglePolygonGroup(TriangleID);
if (PolygonGroupID.GetValue() == Data.MaterialIndex)
{
NumTris++;
}
}
if (NumTris == 0)
{
// there's nothing to do here
return 0;
}
FStaticMeshConstAttributes Attributes(RawMesh);
TVertexAttributesConstRef<FVector> VertexPositions = Attributes.GetVertexPositions();
TVertexInstanceAttributesConstRef<FVector> VertexInstanceNormals = Attributes.GetVertexInstanceNormals();
TVertexInstanceAttributesConstRef<FVector> VertexInstanceTangents = Attributes.GetVertexInstanceTangents();
TVertexInstanceAttributesConstRef<float> VertexInstanceBinormalSigns = Attributes.GetVertexInstanceBinormalSigns();
TVertexInstanceAttributesConstRef<FVector2D> VertexInstanceUVs = Attributes.GetVertexInstanceUVs();
TVertexInstanceAttributesConstRef<FVector4> VertexInstanceColors = Attributes.GetVertexInstanceColors();
int32 NumVerts = NumTris * 3;
// reserve renderer data
OutVerts.Empty(NumVerts);
OutIndices.Empty(bDuplicateTris ? NumVerts * 2 : NumVerts);
float U = Data.TexcoordBounds.Min.X;
float V = Data.TexcoordBounds.Min.Y;
float SizeU = Data.TexcoordBounds.Max.X - Data.TexcoordBounds.Min.X;
float SizeV = Data.TexcoordBounds.Max.Y - Data.TexcoordBounds.Min.Y;
float ScaleX = (SizeU != 0) ? Data.Size.X / SizeU : 1.0;
float ScaleY = (SizeV != 0) ? Data.Size.Y / SizeV : 1.0;
// count number of texture coordinates for this mesh
int32 NumTexcoords = FMath::Min(VertexInstanceUVs.GetNumChannels(), (int32)MAX_STATIC_TEXCOORDS);
// check if we should use NewUVs or original UV set
bool bUseNewUVs = Data.TexCoords.Num() > 0;
if (bUseNewUVs)
{
check(Data.TexCoords.Num() == VertexInstanceUVs.GetNumElements());
ScaleX = Data.Size.X;
ScaleY = Data.Size.Y;
}
// add vertices
int32 VertIndex = 0;
int32 FaceIndex = 0;
for (const FTriangleID TriangleID : RawMesh.Triangles().GetElementIDs())
{
const FPolygonGroupID PolygonGroupID = RawMesh.GetTrianglePolygonGroup(TriangleID);
if (PolygonGroupID.GetValue() == Data.MaterialIndex)
{
for (int32 Corner = 0; Corner < 3; Corner++)
{
const int32 SrcVertIndex = FaceIndex * 3 + Corner;
const FVertexInstanceID SrcVertexInstanceID = RawMesh.GetTriangleVertexInstance(TriangleID, Corner);
const FVertexID SrcVertexID = RawMesh.GetVertexInstanceVertex(SrcVertexInstanceID);
// add vertex
FDynamicMeshVertex* Vert = new(OutVerts)FDynamicMeshVertex();
if (!bUseNewUVs)
{
// compute vertex position from original UV
const FVector2D& UV = VertexInstanceUVs.Get(SrcVertexInstanceID, 0);
Vert->Position.Set((UV.X - U) * ScaleX, (UV.Y - V) * ScaleY, 0);
}
else
{
const FVector2D& UV = Data.TexCoords[SrcVertIndex];
Vert->Position.Set(UV.X * ScaleX, UV.Y * ScaleY, 0);
}
FVector TangentX = VertexInstanceTangents[SrcVertexInstanceID];
FVector TangentZ = VertexInstanceNormals[SrcVertexInstanceID];
FVector TangentY = FVector::CrossProduct(TangentZ, TangentX).GetSafeNormal() * VertexInstanceBinormalSigns[SrcVertexInstanceID];
Vert->SetTangents(TangentX, TangentY, TangentZ);
for (int32 TexcoordIndex = 0; TexcoordIndex < NumTexcoords; TexcoordIndex++)
{
Vert->TextureCoordinate[TexcoordIndex] = VertexInstanceUVs.Get(SrcVertexInstanceID, TexcoordIndex);
}
// Store original vertex positions in texture coordinate data
Vert->TextureCoordinate[6].X = VertexPositions[SrcVertexID].X;
Vert->TextureCoordinate[6].Y = VertexPositions[SrcVertexID].Y;
Vert->TextureCoordinate[7].X = VertexPositions[SrcVertexID].Z;
Vert->Color = FLinearColor(VertexInstanceColors[SrcVertexInstanceID]).ToFColor(true);
// add index
OutIndices.Add(VertIndex);
VertIndex++;
}
if (bDuplicateTris)
{
// add the same triangle with opposite vertex order
OutIndices.Add(VertIndex - 3);
OutIndices.Add(VertIndex - 1);
OutIndices.Add(VertIndex - 2);
}
}
FaceIndex++;
}
return NumTris;
}
static int32 FillSkeletalMeshData(bool bDuplicateTris, const FSkeletalMeshLODRenderData& LODData, FRenderData& Data, TArray<FDynamicMeshVertex>& OutVerts, TArray<uint32>& OutIndices)
{
TArray<uint32> IndexData;
LODData.MultiSizeIndexContainer.GetIndexBuffer(IndexData);
int32 NumTris = 0;
int32 NumVerts = 0;
const int32 SectionCount = LODData.NumNonClothingSections();
// count triangles and vertices for selected material
for (int32 SectionIndex = 0; SectionIndex < SectionCount; SectionIndex++)
{
const FSkelMeshRenderSection& Section = LODData.RenderSections[SectionIndex];
if (Section.MaterialIndex == Data.MaterialIndex)
{
NumTris += Section.NumTriangles;
NumVerts += Section.NumVertices;
}
}
if (NumTris == 0)
{
// there's nothing to do here
return 0;
}
bool bUseNewUVs = Data.TexCoords.Num() > 0;
if (bUseNewUVs)
{
// we should split all merged vertices because UVs are prepared per-corner, i.e. has
// (NumTris * 3) vertices
NumVerts = NumTris * 3;
}
// reserve renderer data
OutVerts.Empty(NumVerts);
OutIndices.Empty(bDuplicateTris ? NumVerts * 2 : NumVerts);
float U = Data.TexcoordBounds.Min.X;
float V = Data.TexcoordBounds.Min.Y;
float SizeU = Data.TexcoordBounds.Max.X - Data.TexcoordBounds.Min.X;
float SizeV = Data.TexcoordBounds.Max.Y - Data.TexcoordBounds.Min.Y;
float ScaleX = (SizeU != 0) ? Data.Size.X / SizeU : 1.0;
float ScaleY = (SizeV != 0) ? Data.Size.Y / SizeV : 1.0;
uint32 DefaultColor = FColor::White.DWColor();
int32 NumTexcoords = LODData.GetNumTexCoords();
// check if we should use NewUVs or original UV set
if (bUseNewUVs)
{
ScaleX = Data.Size.X;
ScaleY = Data.Size.Y;
}
// add vertices
if (!bUseNewUVs)
{
// Use original UV from mesh, render indexed mesh as indexed mesh.
uint32 FirstVertex = 0;
uint32 OutVertexIndex = 0;
for (int32 SectionIndex = 0; SectionIndex < SectionCount; SectionIndex++)
{
const FSkelMeshRenderSection& Section = LODData.RenderSections[SectionIndex];
const int32 NumVertsInSection = Section.NumVertices;
if (Section.MaterialIndex == Data.MaterialIndex)
{
// offset to remap source mesh vertex index to destination vertex index
int32 IndexOffset = FirstVertex - OutVertexIndex;
// copy vertices
int32 SrcVertIndex = FirstVertex;
for (int32 VertIndex = 0; VertIndex < NumVertsInSection; VertIndex++)
{
FDynamicMeshVertex* DstVert = new(OutVerts)FDynamicMeshVertex();
// compute vertex position from original UV
const FVector2D UV = LODData.StaticVertexBuffers.StaticMeshVertexBuffer.GetVertexUV(SrcVertIndex, 0);
DstVert->Position.Set((UV.X - U) * ScaleX, (UV.Y - V) * ScaleY, 0);
DstVert->TangentX = LODData.StaticVertexBuffers.StaticMeshVertexBuffer.VertexTangentX(SrcVertIndex);
DstVert->TangentZ = LODData.StaticVertexBuffers.StaticMeshVertexBuffer.VertexTangentZ(SrcVertIndex);
for (int32 TexcoordIndex = 0; TexcoordIndex < NumTexcoords; TexcoordIndex++)
{
DstVert->TextureCoordinate[TexcoordIndex] = LODData.StaticVertexBuffers.StaticMeshVertexBuffer.GetVertexUV(SrcVertIndex, TexcoordIndex);
}
DstVert->Color = LODData.StaticVertexBuffers.ColorVertexBuffer.VertexColor(SrcVertIndex);
SrcVertIndex++;
OutVertexIndex++;
}
// copy indices
int32 Index = Section.BaseIndex;
for (uint32 TriIndex = 0; TriIndex < Section.NumTriangles; TriIndex++)
{
uint32 Index0 = IndexData[Index++] - IndexOffset;
uint32 Index1 = IndexData[Index++] - IndexOffset;
uint32 Index2 = IndexData[Index++] - IndexOffset;
OutIndices.Add(Index0);
OutIndices.Add(Index1);
OutIndices.Add(Index2);
if (bDuplicateTris)
{
// add the same triangle with opposite vertex order
OutIndices.Add(Index0);
OutIndices.Add(Index2);
OutIndices.Add(Index1);
}
}
}
FirstVertex += NumVertsInSection;
}
}
else // bUseNewUVs
{
// Use external UVs. These UVs are prepared per-corner, so we should convert indexed mesh to non-indexed, without
// sharing of vertices between triangles.
uint32 OutVertexIndex = 0;
for (int32 SectionIndex = 0; SectionIndex < SectionCount; SectionIndex++)
{
const FSkelMeshRenderSection& Section = LODData.RenderSections[SectionIndex];
if (Section.MaterialIndex == Data.MaterialIndex)
{
// copy vertices
int32 LastIndex = Section.BaseIndex + Section.NumTriangles * 3;
for (int32 Index = Section.BaseIndex; Index < LastIndex; Index += 3)
{
for (int32 Corner = 0; Corner < 3; Corner++)
{
int32 CornerIndex = Index + Corner;
int32 SrcVertIndex = IndexData[CornerIndex];
FDynamicMeshVertex* DstVert = new(OutVerts)FDynamicMeshVertex();
const FVector2D UV = LODData.StaticVertexBuffers.StaticMeshVertexBuffer.GetVertexUV(SrcVertIndex, 0);
DstVert->Position.Set(UV.X * ScaleX, UV.Y * ScaleY, 0);
DstVert->TangentX = LODData.StaticVertexBuffers.StaticMeshVertexBuffer.VertexTangentX(SrcVertIndex);
DstVert->TangentZ = LODData.StaticVertexBuffers.StaticMeshVertexBuffer.VertexTangentZ(SrcVertIndex);
for (int32 TexcoordIndex = 0; TexcoordIndex < NumTexcoords; TexcoordIndex++)
{
DstVert->TextureCoordinate[TexcoordIndex] = LODData.StaticVertexBuffers.StaticMeshVertexBuffer.GetVertexUV(SrcVertIndex, TexcoordIndex);
}
DstVert->Color = LODData.StaticVertexBuffers.ColorVertexBuffer.VertexColor(SrcVertIndex);
OutIndices.Add(OutVertexIndex);
OutVertexIndex++;
}
if (bDuplicateTris)
{
// add the same triangle with opposite vertex order
OutIndices.Add(OutVertexIndex - 3);
OutIndices.Add(OutVertexIndex - 1);
OutIndices.Add(OutVertexIndex - 2);
}
}
}
}
}
return NumTris;
}
static int32 FillQuadData(FRenderData& Data, TArray<FDynamicMeshVertex>& OutVerts, TArray<uint32>& OutIndices)
{
OutVerts.Empty(4);
OutIndices.Empty(6);
float U = Data.TexcoordBounds.Min.X;
float V = Data.TexcoordBounds.Min.Y;
float SizeU = Data.TexcoordBounds.Max.X - Data.TexcoordBounds.Min.X;
float SizeV = Data.TexcoordBounds.Max.Y - Data.TexcoordBounds.Min.Y;
float ScaleX = (SizeU != 0) ? Data.Size.X / SizeU : 1.0;
float ScaleY = (SizeV != 0) ? Data.Size.Y / SizeV : 1.0;
// add vertices
for (int32 VertIndex = 0; VertIndex < 4; VertIndex++)
{
FDynamicMeshVertex* Vert = new(OutVerts)FDynamicMeshVertex();
int X = VertIndex & 1;
int Y = (VertIndex >> 1) & 1;
Vert->Position.Set(ScaleX * X, ScaleY * Y, 0);
Vert->SetTangents(FVector(1, 0, 0), FVector(0, 1, 0), FVector(0, 0, 1));
FMemory::Memzero(&Vert->TextureCoordinate, sizeof(Vert->TextureCoordinate));
Vert->TextureCoordinate[0].Set(U + SizeU * X, V + SizeV * Y);
Vert->Color = FColor::White;
}
// add indices
static const uint32 Indices[6] = { 0, 2, 1, 2, 3, 1 };
OutIndices.Append(Indices, 6);
return 2;
}
static void RenderMaterial(FCanvasRenderContext& RenderContext, FMeshPassProcessorRenderState& DrawRenderState, const class FSceneView& View, FRenderData& Data)
{
// Check if material is TwoSided - single-sided materials should be rendered with normal and reverse
// triangle corner orders, to avoid problems with inside-out meshes or mesh parts. Note:
// FExportMaterialProxy::GetMaterial() (which is really called here) ignores 'InFeatureLevel' parameter.
const bool bIsMaterialTwoSided = Data.MaterialRenderProxy->GetIncompleteMaterialWithFallback(GMaxRHIFeatureLevel).IsTwoSided();
TArray<FDynamicMeshVertex> Verts;
TArray<uint32> Indices;
int32 NumTris = 0;
if (Data.StaticMesh != nullptr)
{
check(Data.SkeletalMesh == nullptr)
NumTris = FillStaticMeshData(!bIsMaterialTwoSided, *Data.StaticMesh, Data, Verts, Indices);
}
else if (Data.SkeletalMesh != nullptr)
{
NumTris = FillSkeletalMeshData(!bIsMaterialTwoSided, *Data.SkeletalMesh, Data, Verts, Indices);
}
else
{
// both are null, use simple rectangle
NumTris = FillQuadData(Data, Verts, Indices);
}
if (NumTris == 0)
{
// there's nothing to do here
return;
}
uint32 LightMapCoordinateIndex = (uint32)Data.LightMapIndex;
LightMapCoordinateIndex = LightMapCoordinateIndex < MAX_STATIC_TEXCOORDS ? LightMapCoordinateIndex : MAX_STATIC_TEXCOORDS - 1;
FDynamicMeshBuilder DynamicMeshBuilder(View.GetFeatureLevel(), MAX_STATIC_TEXCOORDS, LightMapCoordinateIndex);
DynamicMeshBuilder.AddVertices(Verts);
DynamicMeshBuilder.AddTriangles(Indices);
FMeshBatch& MeshElement = *RenderContext.Alloc<FMeshBatch>();
FMeshBuilderOneFrameResources& OneFrameResource = *RenderContext.Alloc<FMeshBuilderOneFrameResources>();
DynamicMeshBuilder.GetMeshElement(FMatrix::Identity, Data.MaterialRenderProxy, SDPG_Foreground, true, false, 0, OneFrameResource, MeshElement);
check(OneFrameResource.IsValidForRendering());
Data.LCI->CreatePrecomputedLightingUniformBuffer_RenderingThread(View.GetFeatureLevel());
MeshElement.LCI = Data.LCI;
MeshElement.ReverseCulling = false;
#if SHOW_WIREFRAME_MESH
MeshElement.bWireframe = true;
#endif
GetRendererModule().DrawTileMesh(RenderContext, DrawRenderState, View, MeshElement, false /*bIsHitTesting*/, FHitProxyId());
}
virtual bool Render_RenderThread(FCanvasRenderContext& RenderContext, FMeshPassProcessorRenderState& DrawRenderState, const FCanvas* Canvas)
{
checkSlow(Data);
// current render target set for the canvas
const FRenderTarget* CanvasRenderTarget = Canvas->GetRenderTarget();
FIntRect ViewRect(FIntPoint(0, 0), CanvasRenderTarget->GetSizeXY());
// make a temporary view
FSceneViewInitOptions ViewInitOptions;
ViewInitOptions.ViewFamily = Data->ViewFamily;
ViewInitOptions.SetViewRectangle(ViewRect);
ViewInitOptions.ViewOrigin = FVector::ZeroVector;
ViewInitOptions.ViewRotationMatrix = FMatrix::Identity;
ViewInitOptions.ProjectionMatrix = Data->Transform.GetMatrix();
ViewInitOptions.BackgroundColor = FLinearColor::Black;
ViewInitOptions.OverlayColor = FLinearColor::White;
bool bNeedsToSwitchVerticalAxis = RHINeedsToSwitchVerticalAxis(Canvas->GetShaderPlatform()) && !Canvas->GetAllowSwitchVerticalAxis();
check(bNeedsToSwitchVerticalAxis == false);
FSceneView* View = new FSceneView(ViewInitOptions);
RenderMaterial(RenderContext, DrawRenderState, *View, *Data);
RenderContext.DeferredDelete(View);
if (Canvas->GetAllowedModes() & FCanvas::Allow_DeleteOnRender)
{
RenderContext.DeferredDelete(Data);
Data = nullptr;
}
return true;
}
virtual bool Render_GameThread(const FCanvas* Canvas, FCanvasRenderThreadScope& RenderScope)
{
checkSlow(Data);
// current render target set for the canvas
const FRenderTarget* CanvasRenderTarget = Canvas->GetRenderTarget();
FIntRect ViewRect(FIntPoint(0, 0), CanvasRenderTarget->GetSizeXY());
// make a temporary view
FSceneViewInitOptions ViewInitOptions;
ViewInitOptions.ViewFamily = Data->ViewFamily;
ViewInitOptions.SetViewRectangle(ViewRect);
ViewInitOptions.ViewOrigin = FVector::ZeroVector;
ViewInitOptions.ViewRotationMatrix = FMatrix::Identity;
ViewInitOptions.ProjectionMatrix = Data->Transform.GetMatrix();
ViewInitOptions.BackgroundColor = FLinearColor::Black;
ViewInitOptions.OverlayColor = FLinearColor::White;
FSceneView* View = new FSceneView(ViewInitOptions);
bool bNeedsToSwitchVerticalAxis = RHINeedsToSwitchVerticalAxis(Canvas->GetShaderPlatform()) && !Canvas->GetAllowSwitchVerticalAxis();
check(bNeedsToSwitchVerticalAxis == false);
struct FDrawMaterialParameters
{
FSceneView* View;
FRenderData* RenderData;
uint32 AllowedCanvasModes;
};
FDrawMaterialParameters DrawMaterialParameters =
{
View,
Data,
Canvas->GetAllowedModes()
};
FDrawMaterialParameters Parameters = DrawMaterialParameters;
RenderScope.EnqueueRenderCommand(
[Parameters](FCanvasRenderContext& RenderContext)
{
FMeshPassProcessorRenderState DrawRenderState;
// disable depth test & writes
DrawRenderState.SetDepthStencilState(TStaticDepthStencilState<false, CF_Always>::GetRHI());
RenderMaterial(RenderContext, DrawRenderState, *Parameters.View, *Parameters.RenderData);
RenderContext.DeferredDelete(Parameters.View);
if (Parameters.AllowedCanvasModes & FCanvas::Allow_DeleteOnRender)
{
RenderContext.DeferredDelete(Parameters.RenderData);
}
});
if (Canvas->GetAllowedModes() & FCanvas::Allow_DeleteOnRender)
{
Data = nullptr;
}
return true;
}
};
bool FMeshRenderer::RenderMaterial(struct FMaterialMergeData& InMaterialData, FMaterialRenderProxy* InMaterialProxy, EMaterialProperty InMaterialProperty, UTextureRenderTarget2D* InRenderTarget, TArray<FColor>& OutBMP)
{
check(IsInGameThread());
check(InRenderTarget);
FTextureRenderTargetResource* RTResource = InRenderTarget->GameThread_GetRenderTargetResource();
{
// Create a canvas for the render target and clear it to black
FCanvas Canvas(RTResource, NULL, FApp::GetCurrentTime() - GStartTime, FApp::GetDeltaTime(), FApp::GetCurrentTime() - GStartTime, GMaxRHIFeatureLevel);
#if 0 // original FFlattenMaterial code - kept here for comparison
#if !SHOW_WIREFRAME_MESH
Canvas.Clear(InRenderTarget->ClearColor);
#else
Canvas.Clear(FLinearColor::Yellow);
#endif
FVector2D UV0(InMaterialData.TexcoordBounds.Min.X, InMaterialData.TexcoordBounds.Min.Y);
FVector2D UV1(InMaterialData.TexcoordBounds.Max.X, InMaterialData.TexcoordBounds.Max.Y);
FCanvasTileItem TileItem(FVector2D(0.0f, 0.0f), InMaterialProxy, FVector2D(InRenderTarget->SizeX, InRenderTarget->SizeY), UV0, UV1);
TileItem.bFreezeTime = true;
Canvas.DrawItem(TileItem);
Canvas.Flush_GameThread();
#else
// create ViewFamily
float CurrentRealTime = 0.f;
float CurrentWorldTime = 0.f;
float DeltaWorldTime = 0.f;
const FRenderTarget* CanvasRenderTarget = Canvas.GetRenderTarget();
FSceneViewFamily ViewFamily(FSceneViewFamily::ConstructionValues(
CanvasRenderTarget,
NULL,
FEngineShowFlags(ESFIM_Game))
.SetWorldTimes(CurrentWorldTime, DeltaWorldTime, CurrentRealTime)
.SetGammaCorrection(CanvasRenderTarget->GetDisplayGamma()));
#if !SHOW_WIREFRAME_MESH
Canvas.Clear(InRenderTarget->ClearColor);
#else
Canvas.Clear(FLinearColor::Yellow);
#endif
// add item for rendering
FMeshMaterialRenderItem2::EnqueueMaterialRender(
&Canvas,
&ViewFamily,
InMaterialData.Mesh,
InMaterialData.LODData,
InMaterialData.LightMapIndex,
InMaterialData.MaterialIndex,
InMaterialData.TexcoordBounds,
InMaterialData.TexCoords,
FVector2D(InRenderTarget->SizeX, InRenderTarget->SizeY),
InMaterialProxy,
InMaterialData.LightMap,
InMaterialData.ShadowMap,
InMaterialData.Buffer
);
// In case of running commandlet the RHI is not fully set up on first flush so do it twice TODO
static bool TempForce = true;
if (IsRunningCommandlet() && TempForce)
{
Canvas.Flush_GameThread();
TempForce = false;
}
// rendering is performed here
Canvas.Flush_GameThread();
#endif
FlushRenderingCommands();
Canvas.SetRenderTarget_GameThread(NULL);
FlushRenderingCommands();
}
bool bNormalmap = (InMaterialProperty == MP_Normal);
FReadSurfaceDataFlags ReadPixelFlags(bNormalmap ? RCM_SNorm : RCM_UNorm);
ReadPixelFlags.SetLinearToGamma(false);
bool result = false;
if (InMaterialProperty != MP_EmissiveColor)
{
// Read normal color image
result = RTResource->ReadPixels(OutBMP, ReadPixelFlags);
}
else
{
// Read HDR emissive image
TArray<FFloat16Color> Color16;
result = RTResource->ReadFloat16Pixels(Color16);
// Find color scale value
float MaxValue = 0;
for (int32 PixelIndex = 0; PixelIndex < Color16.Num(); PixelIndex++)
{
FFloat16Color& Pixel16 = Color16[PixelIndex];
float R = Pixel16.R.GetFloat();
float G = Pixel16.G.GetFloat();
float B = Pixel16.B.GetFloat();
float Max = FMath::Max3(R, G, B);
if (Max > MaxValue)
{
MaxValue = Max;
}
}
if (MaxValue <= 0.01f)
{
// Black emissive, drop it
return false;
}
// Now convert Float16 to Color
OutBMP.SetNumUninitialized(Color16.Num());
float Scale = 255.0f / MaxValue;
for (int32 PixelIndex = 0; PixelIndex < Color16.Num(); PixelIndex++)
{
FFloat16Color& Pixel16 = Color16[PixelIndex];
FColor& Pixel8 = OutBMP[PixelIndex];
Pixel8.R = (uint8)FMath::RoundToInt(Pixel16.R.GetFloat() * Scale);
Pixel8.G = (uint8)FMath::RoundToInt(Pixel16.G.GetFloat() * Scale);
Pixel8.B = (uint8)FMath::RoundToInt(Pixel16.B.GetFloat() * Scale);
}
}
FMaterialBakingHelpers::PerformUVBorderSmear(OutBMP, InRenderTarget->GetSurfaceWidth(), InRenderTarget->GetSurfaceHeight(), bNormalmap);
#ifdef SAVE_INTERMEDIATE_TEXTURES
FString FilenameString = FString::Printf(
TEXT( "D:/TextureTest/%s-mat%d-prop%d.bmp"),
*InMaterialProxy->GetFriendlyName(), InMaterialData.MaterialIndex, (int32)InMaterialProperty);
FFileHelper::CreateBitmap(*FilenameString, InRenderTarget->GetSurfaceWidth(), InRenderTarget->GetSurfaceHeight(), OutBMP.GetData());
#endif // SAVE_INTERMEDIATE_TEXTURES
return result;
}
bool FMeshRenderer::RenderMaterialTexCoordScales(struct FMaterialMergeData& InMaterialData, FMaterialRenderProxy* InMaterialProxy, UTextureRenderTarget2D* InRenderTarget, TArray<FFloat16Color>& OutScales)
{
check(IsInGameThread());
check(InRenderTarget);
// create ViewFamily
float CurrentRealTime = 0.f;
float CurrentWorldTime = 0.f;
float DeltaWorldTime = 0.f;
// Create a canvas for the render target and clear it to black
FTextureRenderTargetResource* RTResource = InRenderTarget->GameThread_GetRenderTargetResource();
FCanvas Canvas(RTResource, NULL, FApp::GetCurrentTime() - GStartTime, FApp::GetDeltaTime(), FApp::GetCurrentTime() - GStartTime, GMaxRHIFeatureLevel);
const FRenderTarget* CanvasRenderTarget = Canvas.GetRenderTarget();
Canvas.Clear(FLinearColor::Black);
// Set show flag view mode to output tex coord scale
FEngineShowFlags ShowFlags(ESFIM_Game);
ApplyViewMode(VMI_MaterialTextureScaleAccuracy, false, ShowFlags);
ShowFlags.OutputMaterialTextureScales = true; // This will bind the DVSM_OutputMaterialTextureScales
FSceneViewFamily ViewFamily(FSceneViewFamily::ConstructionValues(CanvasRenderTarget, nullptr, ShowFlags)
.SetWorldTimes(CurrentWorldTime, DeltaWorldTime, CurrentRealTime)
.SetGammaCorrection(CanvasRenderTarget->GetDisplayGamma()));
// The next line ensures a constant view vector of (0,0,1) for all pixels. Required because here SVPositionToTranslatedWorld is identity, making excessive view angle increase per pixel.
// That creates bad side effects for anything that depends on the view vector, like parallax or bump offset mappings. For those, we want the tangent
// space view vector to be perpendicular to the surface in order to generate the same results as if the feature was turned off. Which gives the good results
// since any sub height sampling would in pratice requires less and less texture resolution, where as we are only concerned about the highest resolution the material needs.
// This can be seen in the debug view mode, by a checkboard of white and cyan (up to green) values. The white value meaning the highest resolution taken is the good one
// (blue meaning the texture has more resolution than required). Checkboard are only possible when a texture is sampled several times, like in parallax.
//
// Additionnal to affecting the view vector, it also forces a constant world position value, zeroing any textcoord scales that depends on the world position (as the UV don't change).
// This is alright thought since the uniform quad can obviously not compute a valid mapping for world space texture mapping (only rendering the mesh at its world position could fix that).
// The zero scale will be caught as an error, and the computed scale will fallback to 1.f
ViewFamily.bNullifyWorldSpacePosition = true;
// add item for rendering
FMeshMaterialRenderItem2::EnqueueMaterialRender(
&Canvas,
&ViewFamily,
InMaterialData.Mesh,
InMaterialData.LODData,
InMaterialData.LightMapIndex,
InMaterialData.MaterialIndex,
InMaterialData.TexcoordBounds,
InMaterialData.TexCoords,
FVector2D(InRenderTarget->SizeX, InRenderTarget->SizeY),
InMaterialProxy,
InMaterialData.LightMap,
InMaterialData.ShadowMap,
InMaterialData.Buffer
);
// rendering is performed here
Canvas.Flush_GameThread();
FlushRenderingCommands();
Canvas.SetRenderTarget_GameThread(NULL);
FlushRenderingCommands();
return RTResource->ReadFloat16Pixels(OutScales);
}
| [
"ouczbs@qq.com"
] | ouczbs@qq.com |
8c716bda74a77db828e6e365cb348553dc060e11 | a4bc6065ab865ca85750f86a2055ecd55b5f493f | /football/main.cpp | 3b62050db79f664b76f53cb384cbab9fb45c35de | [] | no_license | fmrafi/graphic | 9f8e1ba1aa6e7e8187ebb890d72e1a3e9b201a61 | b32c46eb72b391d0eeb492f6f282fd77cce79a40 | refs/heads/master | 2020-04-21T15:54:59.218697 | 2019-02-08T04:15:04 | 2019-02-08T04:15:04 | 169,683,260 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,935 | cpp | /*
* GLUT Shapes Demo
*
* Written by Nigel Stewart November 2003
*
* This program is test harness for the sphere, cone
* and torus shapes in GLUT.
*
* Spinning wireframe and smooth shaded shapes are
* displayed until the ESC or q key is pressed. The
* number of geometry stacks and slices can be adjusted
* using the + and - keys.
*/
#include<windows.h>
#ifdef __APPLE__
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
#include<math.h>
#include <stdlib.h>
void Draw()
{
float x,y,ang,radius=0.09;
static float RAD_DEG=57.296;
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.33, 1.0, 0.50);
glBegin(GL_QUAD_STRIP);
glVertex3f(0.1, 0.1, 0.0);
glVertex3f(0.1, 0.9, 0.0);
glVertex3f(0.9, 0.1, 0.0); //GreenYard Vertex
glVertex3f(0.9, 0.9, 0.0);
glEnd();
glFlush();
glBegin(GL_LINES);
glColor3f(0.0, 0.0, 0.0);
glVertex3f(0.5, 0.1, 0.0); //Mid Line ( Ground Divider )
glVertex3f(0.5, 0.9, 0.0);
glEnd();
glFlush();
// left side of the Ground
glBegin(GL_LINES);
glColor3f(0.0, 0.0, 0.0);
glVertex3f(0.25, 0.25, 0.0); // Goal keeper Front line
glVertex3f(0.25, 0.75, 0.0);
glEnd();
glFlush();
glBegin(GL_LINES);
glColor3f(0.0, 0.0, 0.0);
glVertex3f(0.1, 0.75, 0.0); //Goal Keeper left Line
glVertex3f(0.25, 0.75, 0.0);
glEnd();
glFlush();
glBegin(GL_LINES);
glColor3f(0.0, 0.0, 0.0);
glVertex3f(0.1, 0.25, 0.0); //Goal Keeper Right Line
glVertex3f(0.25, 0.25, 0.0);
glEnd();
glFlush();
glBegin(GL_QUAD_STRIP);
glColor3f(1, 1, 1);
glVertex3f(0.1, 0.35, 0.0);
glVertex3f(0.1, 0.65, 0.0); //Inner White Quad
glVertex3f(0.17, 0.35, 0.0);
glVertex3f(0.17, 0.65, 0.0);
glEnd();
glFlush();
// Right Side of the Ground
glBegin(GL_LINES);
glColor3f(0.0, 0.0, 0.0);
glVertex3f(0.75, 0.25, 0.0); //Goal Keeper front line
glVertex3f(0.75, 0.75, 0.0);
glEnd();
glFlush();
glBegin(GL_LINES);
glColor3f(0.0, 0.0, 0.0);
glVertex3f(0.75, 0.25, 0.0); //Goal Keeper Left Line
glVertex3f(0.9, 0.25, 0.0);
glEnd();
glFlush();
glBegin(GL_LINES);
glColor3f(0.0, 0.0, 0.0);
glVertex3f(0.75, 0.75, 0.0); //Goal Keeper ki Right wali line
glVertex3f(0.9, 0.75, 0.0);
glEnd();
glFlush();
glBegin(GL_QUAD_STRIP);
glColor3f(1, 1, 1);
glVertex3f(0.9, 0.35, 0.0);
glVertex3f(0.9, 0.65, 0.0);
glVertex3f(0.83, 0.35, 0.0); //Inner White Quad
glVertex3f(0.83, 0.65, 0.0);
glEnd();
glFlush();
glBegin(GL_LINE_LOOP);
for(ang=0.0;ang<360.0;ang+=10.0)
{
x=radius*cos(ang/RAD_DEG)+1.0;
y=radius*sin(ang/RAD_DEG)+0.5; //Circle at the center of the field
glVertex2f(x/2.0,y);
}
glEnd();
glFlush();
}
void Initialize()
{
glClearColor(0.60, 0.40, 0.12, 0.20);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
}
int main(int iArgc, char** cppArgv)
{
glutInit(&iArgc, cppArgv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(900, 450);
glutInitWindowPosition(200, 200);
glutCreateWindow("Football Ground OpenGL");
Initialize();
glutDisplayFunc(Draw);
glutMainLoop();
return 0;
}
| [
"FMRafi.vu51@gmail.com"
] | FMRafi.vu51@gmail.com |
a85998c52df39a84ab8c0c43e2c76c6032432e71 | 0e4de7b8dc768e39c051a006e18bfcf90008d502 | /DKApps/SDL2RendererRml/GifAnimate.h | dfed79d22afb2043896fc220a3df3e4c0b429b42 | [] | no_license | aquawicket/DKTestApps | a35e2f391e80f53e2d431a05904882e97d7d9d00 | 813ceb3504569ce0f672d7fab465adbc5ed3009c | refs/heads/master | 2023-03-05T13:29:08.102269 | 2022-06-02T14:51:55 | 2022-06-02T14:51:55 | 83,649,975 | 1 | 0 | null | 2022-06-02T14:51:56 | 2017-03-02T07:48:46 | C++ | UTF-8 | C++ | false | false | 1,828 | h | /*
* This source file is part of RmlUi, the HTML/CSS Interface Middleware
*
* For the latest information, see http://github.com/mikke89/RmlUi
*
* Copyright (c) 2008-2010 Nuno Silva
* Copyright (c) 2019 The RmlUi Team, and contributors
*
* 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.
*
*/
#ifndef GIFANIMATE_H
#define GIFANIMATE_H
#include <map>
#include <SDL_image.h>
#include <RmlUi/Core/Types.h>
struct GifData
{
IMG_Animation* anim;
SDL_Texture** textures;
int current_frame, delay, lastTime, currentTime;
};
static std::map<Rml::TextureHandle, GifData> gif_map;
bool LoadGifAnimation(SDL_Renderer* renderer, const Rml::String& source, Rml::TextureHandle& texture_handle, Rml::Vector2i& texture_dimensions);
SDL_Texture* GetGifAnimation(const Rml::TextureHandle texture);
#endif
| [
"aquawicket@hotmail.com"
] | aquawicket@hotmail.com |
f8d1a2f8718205739c53aeb257ee250bea58f395 | 58c9c52e545f748304f20a4dd9a81d0047f1991a | /Project/Dev_class11_handout/Motor2D/GuiWindow.h | 781841ae9ee803390c1f5fdfb5a2b7bbc9b0efe6 | [
"Apache-2.0"
] | permissive | cleancoindev/The-Legend-of-Zelda-Hyrule-Conquest | 8122c94386e90062672a0c1629969246e287e91c | af954426efce06937671f02ac0a5840e5faefb0e | refs/heads/master | 2021-06-27T13:44:45.120044 | 2017-09-16T14:54:46 | 2017-09-16T14:54:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 539 | h | #ifndef __GUIWINDOW_H__
#define __GUIWINDOW_H__
#include "Gui.h"
class GuiWindow : public Gui
{
public:
GuiWindow(iPoint position, SDL_Rect* rect, bool has_background, bool movable, AddGuiTo addto);
~GuiWindow();
void Update(const Gui* mouse_hover, const Gui* focus);
void Draw();
void push_back_item(Gui* newitem);
private:
void DebugDraw() const;
private:
bool has_background = false;
SDL_Rect background_rect = { 0,0,0,0 };
std::list<Gui*> WindowElements;
iPoint OriginalPosition = { 0,0 };
};
#endif // __GUIWINDOW_H__ | [
"yotolivenza@gmail.com"
] | yotolivenza@gmail.com |
a138f2dc4b57524887b1e0c06a038c99f2974b14 | 9258eea7b49238df4bf69189e3b5dd9fd9c34633 | /mohfa_bearbeitbar/motor.cpp | 56270709d9122bd2d89f1ea7617f225365d2f359 | [] | no_license | flmiot/MoHFA | 103532533ed1e934954d5535333f8f97bd09de89 | d84e6a3923806355f83c8a9327888659014f3d32 | refs/heads/master | 2021-01-09T06:11:14.473155 | 2017-02-04T17:14:53 | 2017-02-04T17:14:53 | 80,934,084 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,049 | cpp | #include "motor.h"
Motor::Motor( int MAX_STEPS, int DirPin, int StepPin, int SleepPin, int ResetPin, int MS1Pin ) :
_MAX_STEPS(MAX_STEPS),
_set_point(_MAX_STEPS / 2),
_actual_value(_MAX_STEPS / 2),
_pin_dir(DirPin),
_pin_step(StepPin),
_pin_sleep(SleepPin),
_pin_reset(ResetPin),
_pin_ms1(MS1Pin),
_pin_stop_front( -1 ),
_pin_stop_back( -1)
{
// Azimu Motor
_delay_microseconds = 3000;
_microsteps = 1;
pinMode(_pin_dir, OUTPUT);
pinMode(_pin_step, OUTPUT);
pinMode(_pin_sleep, OUTPUT);
pinMode(_pin_reset, OUTPUT);
pinMode(_pin_ms1, OUTPUT);
digitalWrite(_pin_ms1, LOW);
digitalWrite(_pin_sleep, HIGH);
digitalWrite(_pin_reset, HIGH);
}
Motor::Motor( int MAX_STEPS, int DirPin, int StepPin, int SleepPin, int ResetPin, int MS1Pin, int StopPinFront, int StopPinBack ) :
_MAX_STEPS(MAX_STEPS),
_set_point(_MAX_STEPS / 2),
_actual_value(_MAX_STEPS / 2),
_pin_dir(DirPin),
_pin_step(StepPin),
_pin_sleep(SleepPin),
_pin_reset(ResetPin),
_pin_ms1(MS1Pin),
_pin_stop_front( StopPinFront ),
_pin_stop_back( StopPinBack )
{
// Trans Motor
_delay_microseconds = 2000;
_microsteps = 10;
pinMode(_pin_dir, OUTPUT);
pinMode(_pin_step, OUTPUT);
pinMode(_pin_sleep, OUTPUT);
pinMode(_pin_reset, OUTPUT);
pinMode(_pin_ms1, OUTPUT);
pinMode(_pin_stop_front, INPUT);
pinMode(_pin_stop_back, INPUT);
digitalWrite(_pin_ms1, LOW);
digitalWrite(_pin_sleep, HIGH);
digitalWrite(_pin_reset, HIGH);
}
void Motor::NewPosition( int New_Position ) {
if ( New_Position < 0 || New_Position > _MAX_STEPS)
return;
else
_set_point = New_Position;
}
void Motor::UpdateMotorPosition( ) {
if ( !Busy() ) return;
else {
// Do some motor magic ( drive only one step in the right direction! ) e.g.
if ( _actual_value < _set_point ) {
digitalWrite(_pin_dir, LOW);
for (int i = 0; i < _microsteps; i++){
if( _pin_stop_front != -1 && digitalRead(_pin_stop_front) == HIGH){
_actual_value = TRANS_MAX_STEPS;
break;
}
digitalWrite(_pin_step, HIGH);
delayMicroseconds(_delay_microseconds);
digitalWrite(_pin_step, LOW);
if( i == _microsteps -1 ) _actual_value++;
}
}
else {
digitalWrite(_pin_dir, HIGH);
for (int i = 0; i < _microsteps; i++){
if( _pin_stop_back != -1 && digitalRead(_pin_stop_back) == HIGH){
_actual_value = 0;
break;
}
digitalWrite(_pin_step, HIGH);
delayMicroseconds(_delay_microseconds);
digitalWrite(_pin_step, LOW);
if( i == _microsteps - 1) _actual_value--;
}
}
}
}
// Warning: Calling this method will abort all previous position commands
void Motor::TakeCurrentPositionAsNewZero() {
this->_actual_value = _MAX_STEPS / 2;
this->_set_point = _MAX_STEPS / 2;
}
bool Motor::Busy() {
return !( _set_point == _actual_value);
}
int Motor::GetPosition() {
return _actual_value;
}
int Motor::GetSetPointPosition(){
return _set_point;
}
| [
"noreply@github.com"
] | noreply@github.com |
520d2af23105bfd32ec1d67fa54a1990f022feb3 | 46f9f7f2595768ec48f8636e9b70ada23c6304ab | /4四、对象和类(基础)/2.对象拷贝以及分离声明与实现.cpp | 4627daabcf9ed3adfac99a67bcff3cf8919b4396 | [] | no_license | ChaselWu/CPP-Learning | 66acd173f427c468a3de8612f93e7dfd083b93f3 | e54bf403f35b78ec58385d23c074c32b8aa0c36c | refs/heads/master | 2023-04-02T01:02:39.976446 | 2021-04-10T10:09:48 | 2021-04-10T10:09:48 | 340,542,261 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,140 | cpp | //1.class is a type类是一种类型
//2.member copy
/*
1)use assignment operator =
2)默认情况下,每个数据域都被拷贝的对应部分
*/
//3.匿名对象
/*
有时需要创建一个只用一次的不命名对象,称之为匿名对象
*/
//4.结构体:C++中,结构体已被class取代
//5.局部类和嵌套类
/*
局部类是在一个函数中声明的类
嵌套类是在另一个类中声明的类
*/
//6.分离
/*
1)C++中类声明和类实现可以分离为两个文件:
.h:类声明
.cpp:类实现
?????????????????????????????????????????????? 2)二元作用域解析运算符
*/
//7.内联声明和内联函数
/*
* 作用:将函数的声明与定义分离到类中与类外
当函数在类声明中实现时,他自动成为内联函数
*/
//8.若不同文件间出现了函数重定义,则编译器无法发现该错误,只能在link阶段检测出来
//9.避免头文件被多次包含
/*
1)
//#ifndef MY_HEADER_FILE_H
//#define MY_HEADER_FILE_H
////blablabla
//#endif
2)
//#pragma once//C++03
3)
//_Pragma("once")//C++11
*/
//#include<iostream>
//#include<string>
//using std::string;
//using uint=unsigned int;
//enum {MALE,FEMALE};
//class Human {
//
//private:
//
// //variable
// static uint count;
// string name;
// bool sex;
// double height;
// double weight;
//
//public:
//
// //ctor
// Human(string name,bool sex,double h,double w) {
// this->name = name;
// this->sex = sex;
// height = h;
// weight = w;
// }
//
//
// //get
// string getName() {//getName自动成为内联函数
// return name;
// }
// bool getSex();//在内声明,在外实现,getSex不是内联函数
// double getHeight();
//};
//
//
//
//bool Human::getSex() { return sex; }
//inline double Human::getHeight() { return height; }//定义时写了inline,getHeight是内联函数
//
//
//
//
//
//int main() {
// Human spidy{"spidy", MALE, 180, 180};
// Human candy = spidy;
// Human nancy = Human{"nancy", MALE, 170, 100};//匿名对象
// return 0; } | [
"2590549807@qq.com"
] | 2590549807@qq.com |
e5f89fcb0724137f4632a8d52e546e984ecaf0a0 | db6663b1fc2af0ca9290968deb4b23549f9dc1d2 | /solution/daal_lenet.h | 4ead90f387480e6ec4b643bacd0da041426c4151 | [] | no_license | daaltces/daal_lenet | 64ae9dc8f6de3e33d95f60ad8b457d350cb41afe | bae66c36d08635369d030c07d0f40999b42c980b | refs/heads/master | 2021-01-11T18:10:17.200075 | 2017-01-19T20:26:53 | 2017-01-19T20:26:53 | 79,491,434 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,241 | h | /* file: daal_lenet.h */
/*
// INTEL CORPORATION PROPRIETARY INFORMATION
// This software is supplied under the terms of a license agreement or
// nondisclosure agreement with Intel Corporation and may not be copied
// or disclosed except in accordance with the terms of that agreement.
// Copyright (C) 2014-2016 Intel Corporation. All Rights Reserved.
*/
#include "daal.h"
using namespace daal;
using namespace daal::algorithms;
using namespace daal::data_management;
using namespace daal::algorithms::neural_networks;
using namespace daal::algorithms::neural_networks::layers;
using namespace daal::services;
typedef services::SharedPtr<Tensor> TensorPtr;
typedef initializers::uniform::Batch<> UniformInitializer;
typedef SharedPtr<UniformInitializer> UniformInitializerPtr;
typedef initializers::xavier::Batch<> XavierInitializer;
typedef SharedPtr<XavierInitializer> XavierInitializerPtr;
training::TopologyPtr configureNet()
{
/*Create convolution layer*/
SharedPtr<convolution2d::Batch<> > convolution1(new convolution2d::Batch<>() );
convolution1->parameter.kernelSizes = convolution2d::KernelSizes(3, 3);
convolution1->parameter.strides = convolution2d::Strides(1, 1);
convolution1->parameter.nKernels = 32;
convolution1->parameter.weightsInitializer = XavierInitializerPtr(new XavierInitializer());
convolution1->parameter.biasesInitializer = UniformInitializerPtr(new UniformInitializer(0, 0));
/*Create pooling layer*/
SharedPtr<maximum_pooling2d::Batch<> > maxpooling1(new maximum_pooling2d::Batch<>(4));
maxpooling1->parameter.kernelSizes = pooling2d::KernelSizes(2, 2);
maxpooling1->parameter.paddings = pooling2d::Paddings(0, 0);
maxpooling1->parameter.strides = pooling2d::Strides(2, 2);
/*Create convolution layer*/
SharedPtr<convolution2d::Batch<> > convolution2(new convolution2d::Batch<>());
convolution2->parameter.kernelSizes = convolution2d::KernelSizes(5, 5);
convolution2->parameter.strides = convolution2d::Strides(1, 1);
convolution2->parameter.nKernels = 64;
convolution2->parameter.weightsInitializer = XavierInitializerPtr(new XavierInitializer());
convolution2->parameter.biasesInitializer = UniformInitializerPtr(new UniformInitializer(0, 0));
/*Create pooling layer*/
SharedPtr<maximum_pooling2d::Batch<> > maxpooling2(new maximum_pooling2d::Batch<>(4));
maxpooling2->parameter.kernelSizes = pooling2d::KernelSizes(2, 2);
maxpooling2->parameter.paddings = pooling2d::Paddings(0, 0);
maxpooling2->parameter.strides = pooling2d::Strides(2, 2);
/*Create fullyconnected layer*/
SharedPtr<fullyconnected::Batch<> > fullyconnected3(new fullyconnected::Batch<>(256));
fullyconnected3->parameter.weightsInitializer = XavierInitializerPtr(new XavierInitializer());
fullyconnected3->parameter.biasesInitializer = UniformInitializerPtr(new UniformInitializer(0, 0));
/*Create ReLU layer*/
SharedPtr<relu::Batch<> > relu3(new relu::Batch<>);
/*Create fully connected layer*/
SharedPtr<fullyconnected::Batch<> > fullyconnected4(new fullyconnected::Batch<>(10));
fullyconnected4->parameter.weightsInitializer = XavierInitializerPtr(new XavierInitializer());
fullyconnected4->parameter.biasesInitializer = UniformInitializerPtr(new UniformInitializer(0, 0));
/*Create Softmax layer*/
SharedPtr<loss::softmax_cross::Batch<> > softmax(new loss::softmax_cross::Batch<>());
/*Create LeNet Topology*/
training::TopologyPtr topology(new training::Topology());
const size_t conv1 = topology->add(convolution1);
const size_t pool1 = topology->add(maxpooling1); topology->get(conv1).addNext(pool1);
const size_t conv2 = topology->add(convolution2); topology->get(pool1).addNext(conv2);
const size_t pool2 = topology->add(maxpooling2); topology->get(conv2).addNext(pool2);
const size_t fc3 = topology->add(fullyconnected3); topology->get(pool2).addNext(fc3);
const size_t r3 = topology->add(relu3); topology->get(fc3).addNext(r3);
const size_t fc4 = topology->add(fullyconnected4); topology->get(r3).addNext(fc4);
const size_t sm1 = topology->add(softmax); topology->get(fc4).addNext(sm1);
return topology;
}
| [
"intel.daal@intel.com"
] | intel.daal@intel.com |
74a474c54c953e9bf61d5cf473a5673e8c43396f | f66a33f8cdd8286320da730be67c89ee00d83d8d | /src/arch/x86/pseudo_inst_abi.hh | 05bf66f5f24e8e88db7054065726ccc94c4305fa | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license",
"LGPL-2.0-or-later",
"MIT"
] | permissive | H2020-COSSIM/cgem5 | 0d5812632757e6146f7852c9bf4abe4e9628296a | 1222cc0c5618875e048f288e998187c236508a64 | refs/heads/main | 2023-05-13T14:08:01.665322 | 2023-05-08T08:39:50 | 2023-05-08T08:39:50 | 468,039,890 | 3 | 2 | BSD-3-Clause | 2022-10-12T14:29:33 | 2022-03-09T18:05:40 | C++ | UTF-8 | C++ | false | false | 3,352 | hh | /*
* Copyright (c) 2020 The Regents of the University of California.
* All rights reserved.
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "arch/x86/regs/int.hh"
#include "sim/guest_abi.hh"
namespace gem5
{
struct X86PseudoInstABI
{
using State = int;
};
GEM5_DEPRECATED_NAMESPACE(GuestABI, guest_abi);
namespace guest_abi
{
template <typename T>
struct Result<X86PseudoInstABI, T>
{
static void
store(ThreadContext *tc, const T &ret)
{
// This assumes that all pseudo ops have their return value set
// by the pseudo op instruction. This may need to be revisited if we
// modify the pseudo op ABI in util/m5/m5op_x86.S
tc->setReg(X86ISA::int_reg::Rax, ret);
}
};
template <>
struct Argument<X86PseudoInstABI, uint64_t>
{
static uint64_t
get(ThreadContext *tc, X86PseudoInstABI::State &state)
{
// The first 6 integer arguments are passed in registers, the rest
// are passed on the stack.
panic_if(state >= 6, "Too many psuedo inst arguments.");
using namespace X86ISA;
constexpr RegId int_reg_map[] = {
int_reg::Rdi, int_reg::Rsi, int_reg::Rdx,
int_reg::Rcx, int_reg::R8, int_reg::R9
};
return tc->getReg(int_reg_map[state++]);
}
};
} // namespace guest_abi
} // namespace gem5
| [
"ntampouratzis@isc.tuc.gr"
] | ntampouratzis@isc.tuc.gr |
11c0affea5a22aba3b2ece1af263e4dd06a6ccc3 | 19b21d10eddf671e8575837cfd7194ce35a3b402 | /Renderium/src/Engine/EngineWindow/RenderiumWindow.h | fcdcec299b4031e232b27dbceebb6614001c90b1 | [] | no_license | mastari/Renderium | df6eb350945bb24368e4abab0d70e6cced99f91d | 5385a9a1acc03748850358a5905d854e5848094e | refs/heads/master | 2020-05-16T07:30:57.427672 | 2019-05-01T13:07:27 | 2019-05-01T13:07:27 | 182,881,014 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 456 | h | #pragma once
#include "../Engine.h"
#include <iostream>
#include "../../ContextDevice/ContextDevice.h"
class RenderiumWindow {
public:
RenderiumWindow(std::string name, GLint width, GLint height, bool resizable);
GLFWwindow* getContext();
GLint getWidth();
GLint getHeight();
std::string getTitle();
private:
GLint windowWidth, windowHeight;
std::string windowTitle;
bool windowIsResizable;
GLFWwindow* contextWindow;
static int netWindows;
};
| [
"arikatz.d@gmail.com"
] | arikatz.d@gmail.com |
270ac23c2ddd71e58b3053367f712be238905d6d | 06a6e2759828d4397956e65d17cec04f30470f51 | /src/basis/Renderer.cpp | 1347bdc935677035240118ed79b36d9b1ba1ba64 | [] | no_license | findorlolz/PhotonMaping | ff0e4262d425c21a997617606b1c66e793ecb7e0 | 3812dcb8f19c6db8b3d3caa572cd83cfab5185f9 | refs/heads/master | 2021-01-02T09:14:13.583713 | 2014-04-27T22:45:42 | 2014-04-27T22:45:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 32,630 | cpp | #include "Renderer.h"
#include "RayTracer.h"
#include "3d/Texture.hpp"
#include "Memory.h"
#include "Sampling.h"
void Renderer::startUp(FW::GLContext* gl, FW::CameraControls* camera, AssetManager* assetManager)
{
std::cout << "Starting up the Renderer..." << std::endl;
m_context = gl;
m_assetManager = assetManager;
m_camera = camera;
m_projection = FW::Mat4f();
m_worldToCamera = FW::Mat4f();
m_camera->setPosition(FW::Vec3f(.0f, .8f, .8f));
m_camera->setForward(FW::Vec3f(.0f, -1.f, -1.f));
m_camera->setFar(20.0f);
m_camera->setSpeed(4.0f);
m_randomGen = FW::Random();
m_launcher = new FW::MulticoreLauncher();
m_launcher->setNumThreads(m_launcher->getNumCores());
m_renderWithPhotonMaping = false;
m_hasPhotonMap = false;
m_mesh = new MeshC();
m_mesh->append(*(m_assetManager->getMesh(MeshType_Pheonix)));
m_photonTestMesh = new FW::Mesh<FW::VertexPNC>();
m_photonTestMesh->addSubmesh();
updateTriangleToMeshDataPointers();
for (auto i = 0u; i < m_mesh->numVerticesU(); ++i )
m_mesh->mutableVertex(i).c = FW::Vec3f(1,1,1);
RayTracer::get().startUp();
m_sceneTree = RayTracer::get().constructHierarchy(m_triangles, m_indexListFromScene);
std::cout << std::endl;
std::cout << "Welcome to the most EPIC PhotonMapingEexperience! Have a nice ride <-(0_o)/~" << std::endl;
std::cout << std::endl;
std::cout << "///////////////////////////////////////////////" << std::endl;
std::cout << "Press 1 for casting photons and image synthesis" << std::endl;
std::cout << "Press 2 for image synthesis from existing PM" << std::endl;
std::cout << "Press 3 to toggle between rendering options" << std::endl;
std::cout << "Press 4 to toggle visibility of PM parameters" << std::endl;
std::cout << "//////////////////////////////////////////////" << std::endl;
std::cout << std::endl;
}
void Renderer::shutDown()
{
delete m_mesh;
delete m_photonTestMesh;
delete m_launcher;
RayTracer::get().demolishTree(m_sceneTree);
if(m_hasPhotonMap)
{
RayTracer::get().demolishTree(m_photonTree);
delete m_image;
}
RayTracer::get().shutDown();
delete &get();
}
void Renderer::drawFrame()
{
glClearColor(0.2f, 0.4f, 0.8f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
if(m_renderWithPhotonMaping)
{
if(m_launcher->getNumFinished() == m_launcher->getNumTasks())
m_context->drawImage(*m_image, FW::Vec2f());
return;
}
else
{
m_projection = m_context->xformFitToView(FW::Vec2f(-1.0f, -1.0f), FW::Vec2f(2.0f, 2.0f)) * m_camera->getCameraToClip();
m_worldToCamera = m_camera->getWorldToCamera();
m_mesh->draw(m_context, m_worldToCamera, m_projection);
}
glDrawBuffer(GL_BACK);
glBindVertexArray(0);
glUseProgram(0);
}
void Renderer::clearTriangles()
{
m_vertices.clear();
m_triangles.clear();
m_triangleToMeshData.clear();
}
void Renderer::updateTriangleToMeshDataPointers()
{
for (size_t i = 0u; i < m_mesh->numVerticesU(); ++i )
{
FW::Vec3f p = m_mesh->getVertexAttrib(i, FW::MeshBase::AttribType_Position).getXYZ();
m_vertices.push_back(p);
}
for (size_t i = 0u; i < m_mesh->numSubmeshes(); ++i )
{
const FW::Array<FW::Vec3i>& idx = m_mesh->indices(i);
FW::MeshBase::Material* mat = &(m_mesh->material(i));
for (size_t j = 0u; j < idx.getSize(); ++j )
{
TriangleToMeshData m;
m.submeshIndex = i;
m.vertexIndex = j;
m_triangleToMeshData.push_back(m);
Triangle t;
t.m_userPointer = 0;
t.m_vertices[0] = &m_vertices[0] + idx[j][0];
t.m_vertices[1] = &m_vertices[0] + idx[j][1];
t.m_vertices[2] = &m_vertices[0] + idx[j][2];
if(mat->emissive != FW::Vec3f())
{
t.m_lightPower = &(mat->emissive);
m_lightSources.push_back(m_triangles.size());
}
m_triangles.push_back(t);
}
}
for ( size_t i = 0; i < m_triangles.size(); ++i )
m_triangles[ i ].m_userPointer = &m_triangleToMeshData[i];
}
void Renderer::castPhotons(const size_t numOfPhotons, std::vector<Hit>& tmpHitList)
{
std::vector<float> areas = std::vector<float> (m_lightSources.size());
float total = .0f;
for(auto i = 0u; i < m_lightSources.size(); ++i)
{
float tmp = .5f * (FW::cross((*(m_triangles[m_lightSources[i]].m_vertices[1]) - *(m_triangles[m_lightSources[i]].m_vertices[0])), (*(m_triangles[m_lightSources[i]].m_vertices[2]) - *(m_triangles[m_lightSources[i]].m_vertices[0])))).length();
areas[i] = tmp;
total += tmp;
}
FW::Random randomGen = FW::Random();
Node* buffer[1028];
FW::Vec3f photonPower = FW::Vec3f(m_contextData.d_totalLight)/(numOfPhotons+m_lightSources.size());
for(auto i = 0u; i < m_lightSources.size(); ++i)
{
size_t s = numOfPhotons * areas[i]/total + 1u;
const FW::Vec3f& lightSourcePower = *(m_triangles[m_lightSources[i]].m_lightPower);
const Triangle& tri = m_triangles[m_lightSources[i]];
FW::Vec3f A = *tri.m_vertices[0];
FW::Vec3f B = *tri.m_vertices[1];
FW::Vec3f C = *tri.m_vertices[2];
for(auto j = 0u; j < s; ++j)
{
float sqr_r1 = FW::sqrt(randomGen.getF32(0,1.0f));
float r2 = randomGen.getF32(0,1.0f);
FW::Vec3f orig = (1-sqr_r1)*A + sqr_r1*(1-r2)*B + sqr_r1*r2*C;
FW::Vec3f normalLightSource = (interpolateAttribute(tri, orig, m_mesh, m_mesh->findAttrib(FW::MeshBase::AttribType_Normal)));
normalLightSource = normalLightSource.normalized();
FW::Vec3f albedoLightSource = getAlbedo((TriangleToMeshData*)tri.m_userPointer, m_mesh,getBarys(tri, orig, m_mesh));
FW::Vec3f dir = randomVectorToHalfUnitSphere(normalLightSource, m_randomGen);
FW::Vec3f E = lightSourcePower * photonPower * albedoLightSource;
tracePhoton(orig, dir, E, 0u, buffer, tmpHitList, false);
}
}
}
void Renderer::tracePhoton(const FW::Vec3f& orig, const FW::Vec3f& d, const FW::Vec3f& E, const size_t bounce, Node** buffer, std::vector<Hit>& tmpHitList, bool g, const float n1)
{
if(bounce >= maxBounces)
return;
FW::Vec3f dir = d.normalized();
Hit hit = Hit(10.f);
if(!RayTracer::get().rayCast(orig, dir, hit, m_triangles, m_indexListFromScene, m_sceneTree, buffer))
{
return;
}
const Triangle& tri = hit.triangle;
FW::MeshBase::Material mat;
MaterialPM matType = shader(hit, m_mesh, mat);
FW::Vec3f n = interpolateAttribute(tri, hit.intersectionPoint, m_mesh, m_mesh->findAttrib(FW::MeshBase::AttribType_Normal));
n = n.normalized();
FW::Vec3f newOrig = hit.intersectionPoint + .0001f * n;
if(matType == MaterialPM_Mirror)
{
FW::Vec3f newDir = dir - 2.f*FW::dot(dir, n)*n;
newDir = dir.normalized();
FW::Vec3f newE = E * mat.tf;
tracePhoton(newOrig, newDir, newE, bounce + 1, buffer, tmpHitList, g);
}
else if(matType == MaterialPM_GlassSolid)
{
const float n2 = mat.opticalDensity;
const float nDiv = (n1/n2);
bool toDenser = (n1 <= n2);
// Dot product of I-ray and surface normal, this is also the cosine of I-ray's angle since Iray and n are unit lenght
const float dotI = FW::dot(-dir, n);
// If we are moving to lighter, this means we are inside a mesh => flip normal
if(!toDenser)
n = -n;
//Define directions of both refraction and reflection
FW::Vec3f transmittanceDir = (-nDiv * (-dir - dotI*n) -n*FW::sqrt(1.f-(nDiv*nDiv)*(1-(dotI*dotI)))).normalized();
FW::Vec3f reflectanceDir = (2.f*FW::dot(-dir, n)*n-dir).normalized();
//Schlick's approximation
float RShclick;
float R0 = std::pow(((n1-n2)/(n1+n2)), 2);
//From lighter to denser
if(toDenser)
RShclick = R0 + (1-R0)*std::pow((1.f-dotI),5);
else
{
//Define if there is Total Iternal Reflection
if(FW::asin(n2/n1) >= FW::acos(dotI))
RShclick = 1.f;
else
{
//Cosine of T-ray and normal. NB! We are still inside the mesh, but we fliped normal earlier
const float dotT = FW::dot(transmittanceDir, -n);
RShclick = R0 + (1-R0)*std::pow((1.f-dotT),5);
}
}
//Russian roulette based on Shclick approximation and size of n1 and n2
float r = m_randomGen.getF32(.0f, 1.f);
if(r < RShclick && toDenser) //To denser, reflected
tracePhoton(newOrig, reflectanceDir, E , bounce + 1, buffer, tmpHitList, g);
else if (r >= RShclick && toDenser) //To denser, refraction
tracePhoton(hit.intersectionPoint - .0001f * n, transmittanceDir, E, bounce + 1, buffer, tmpHitList, true, n2);
else if(r < RShclick && !toDenser) //To lighter, reflected
tracePhoton(newOrig, reflectanceDir, E, bounce + 1, buffer, tmpHitList, g, n2);
else if (r >= RShclick && !toDenser) //To lighter, refraction
tracePhoton(hit.intersectionPoint - .0001f * n, transmittanceDir, E, bounce + 1, buffer, tmpHitList, g);
}
else if (matType == MaterialPM_GlassBillboard)
{
const float n2 = mat.opticalDensity;
const float nDiv = (n1/n2);
//Billboard is just surface, which each vertex has same normal => if hit comes from behind whe just swap this normal around.
float dotI = FW::dot(-dir, n);
if(dotI < .0f)
{
n *= -1.f;
dotI = FW::dot(-dir, n);
}
//Unlike with real glass, with billboard always n1<n2 which makes things easier
float R0 = std::pow(((n1-n2)/(n1+n2)), 2);
float RShclick = R0 + (1-R0)*std::pow((1.f-dotI),5);
//Russian roulette based on Shclick approximation
float r = m_randomGen.getF32(.0f, 1.f);
if(r < RShclick)
tracePhoton(hit.intersectionPoint + 0.0001f * n, (2.f*FW::dot(-dir, n)*n-dir).normalized(), E, bounce+1, buffer, tmpHitList, g);
else
tracePhoton(hit.intersectionPoint - 0.0001f * n, (-nDiv * (-dir - dotI*n) -n*FW::sqrt(1.f-(nDiv*nDiv)*(1-(dotI*dotI)))).normalized(), E, bounce+1, buffer, tmpHitList, g);
}
else if(matType == MaterialPM_Lightsource)
{
//Photon hits a lightsource, for not losing energy cast a new one from that source.
FW::Vec3f newDir = randomVectorToHalfUnitSphere(n, m_randomGen);
tracePhoton(newOrig, newDir, E, bounce+1, buffer, tmpHitList, false);
}
else if(matType == MaterialPM_Diffuse)
{
//Ideal diffuse BRDF
FW::Vec3f albedo = getAlbedo((TriangleToMeshData*) hit.triangle.m_userPointer, m_mesh, FW::Vec3f((1.0f - hit.u - hit.v, hit.u, hit.v)));
FW::Vec3f newE = E * FW::dot(n, -dir);
FW::Vec3f newDir = randomVectorToHalfUnitSphere(n, m_randomGen);
Photon photon = Photon(hit.intersectionPoint, newE, -(dir.normalized()));
m_photons.push_back(photon);
tmpHitList.push_back(hit);
float r3 = m_randomGen.getF32(0,1.f);
float threshold = (albedo.x + albedo.y + albedo.z)/3.f;
if(r3 < threshold)
tracePhoton(newOrig, newDir, newE * albedo, bounce+1, buffer, tmpHitList, false);
}
}
void Renderer::initPhotonMaping(const size_t numOfPhotons, const float r, const size_t FG, const float totalLight, const size_t numberOfSamplesByDimension,const FW::Vec2i& size)
{
std::cout << "Initiliaze photon maping: " << std::endl;
std::cout << "Radius - " << r << " / FG rays - " << FG << " / totalLight - " << totalLight << std::endl;
std::cout << std::endl;
FW::Timer timerTotal;
timerTotal.start();
updateContext(r, FG, totalLight, numberOfSamplesByDimension);
m_photons.clear();
m_photonIndexList.clear();
m_photonTestMesh->clear();
m_photonTestMesh->addSubmesh();
if(m_hasPhotonMap)
RayTracer::get().demolishTree(m_photonTree);
std::cout << "Starting photon cast...";
std::vector<Hit> tmpHitList;
tmpHitList.reserve(numOfPhotons);
updatePhotonListCapasity(numOfPhotons);
castPhotons(numOfPhotons, tmpHitList);
m_hasPhotonMap = true;
std::cout << " done! " << m_photons.size() << " photons total!" << std::endl;
m_photonTree = RayTracer::get().constructHierarchy(m_photons, m_photonIndexList);
FW::Timer timer;
timer.start();
std::cout << "Precalculate outgoinging light for each photon... " << std::endl;
preCalculateOutgoingLight(tmpHitList);
std::cout << " done! Time spend: " << timer.getElapsed() << std::endl;
std::cout << "Start image synthesis, image size as pixels: " << size.x << "/" << size.y << "..." << std::endl;
timer.start();
synthesisImage(size);
std::cout << " done! Time spend: " << timer.getElapsed() << std::endl;
std::cout << "Everything done... Time spend: " << timerTotal.getElapsed() << std::endl;
std::cout << "___________________________________________________________________" << std::endl;
std::cout << std::endl;
m_renderWithPhotonMaping = true;
}
void Renderer::initImageSynthesisFromExistingPM(const float r, const size_t FG, const float totalLight, const size_t numberOfSamplesByDimension,const FW::Vec2i& size)
{
if(!m_hasPhotonMap)
{
std::cout << "Couldn't start image synthesis, because PM doesn't exist!!!" << std::endl;
std::cout << "Press 1 for photong casting and image synthesis" << std::endl;
std::cout << "___________________________________________________________________" << std::endl;
return;
}
FW::Timer timer;
updateContext(r, FG, totalLight, numberOfSamplesByDimension);
std::cout << "Start image synthesis based on existing PM, image size as pixels: " << size.x << "/" << size.y << "..." << std::endl;
std::cout << "Radius - " << r << " / FG rays - " << FG << " / totalLight - " << totalLight << std::endl;
std::cout << "Attention!!! Changes in amount of totalLight effect direct LS hits, no PM energies!!!" << std::endl;
timer.start();
synthesisImage(size);
std::cout << " done! Time spend: " << timer.getElapsed() << std::endl;
std::cout << "___________________________________________________________________" << std::endl;
}
void Renderer::preCalculateOutgoingLight(std::vector<Hit>& tmpHitList)
{
m_contextData.d_tmpHitList = &tmpHitList;
m_contextData.d_photonTree = m_photonTree;
m_launcher->popAll();
m_launcher->setNumThreads(m_launcher->getNumCores());
//m_launcher->setNumThreads(1);
m_launcher->push(outgoingLightFunc, &m_contextData, 0, 64);
while(m_launcher->getNumFinished() != m_launcher->getNumTasks())
{
printf("~ %.2f %% \r", 100.0f*m_launcher->getNumFinished()/(float)m_launcher->getNumTasks());
}
}
void Renderer::outgoingLightFunc(FW::MulticoreLauncher::Task& t)
{
contextData& data = *(contextData*)t.data;
int thread = t.idx;
int index = thread;
Node* buffer[1028];
while(index < (*data.d_photons).size())
{
Photon& photon = (*data.d_photons)[index];
Hit& h = (*data.d_tmpHitList)[index];
std::vector<HeapNode> nodes;
float r = data.d_FGRadius;
RayTracer::get().searchPhotons(h.intersectionPoint, *data.d_photons, *data.d_photonIndexList, data.d_photonTree, r, 50u, nodes, buffer);
if(nodes.empty())
{
index += 64;
continue;
}
const Triangle& tri = h.triangle;
FW::Vec3f normal = interpolateAttribute(tri, h.intersectionPoint, data.d_mesh, data.d_mesh->findAttrib(FW::MeshBase::AttribType_Normal));
normal = normal.normalized();
const float alpha = 10.818f;
const float beta = 1.953f;
const float e = 2.718281f;
FW::Vec3f Li = FW::Vec3f();
for ( int j = 1; j < nodes.size(); ++j )
{
FW::Vec3f lightDir = (*data.d_photons)[nodes[j].value].dir;
float dot = FW::dot(lightDir, normal);
if(dot < .0f)
continue;
float d = nodes[j].key;
float t1 = 1.0f - pow( e, ( -beta * d * d / ( 2.0f * r * r) ) );
float t2 = 1.0f - pow( e, -beta );
float w = alpha * ( 1.0f - (t1 / t2) );
const Hit& photonHit = (*data.d_tmpHitList)[nodes[j].value];
TriangleToMeshData* map = (TriangleToMeshData*) photonHit.triangle.m_userPointer;
FW::Vec3f barys = FW::Vec3f((1.0f - photonHit.u - photonHit.v, photonHit.u, photonHit.v));
Li += w * (*data.d_photons)[nodes[j].value].power * dot * getAlbedo(map, data.d_mesh, barys);
}
float A = FW_PI*r*r;
photon.E = Li / A;
index += 64;
}
}
void Renderer::synthesisImage(const FW::Vec2i& size)
{
if(m_renderWithPhotonMaping)
delete m_image;
m_image = new FW::Image(size, FW::ImageFormat::RGBA_Vec4f);
FW::Vec2i imageSize = m_image->getSize();
FW::Mat4f worldToCamera = m_camera->getWorldToCamera();
FW::Mat4f projection = FW::Mat4f::fitToView(FW::Vec2f(-1,-1), FW::Vec2f(2,2), imageSize)*m_camera->getCameraToClip();
FW::Mat4f invP = (projection * worldToCamera).inverted();
m_contextData.d_invP = invP;
m_contextData.d_image = m_image;
//m_launcher->setNumThreads(1);
m_launcher->popAll();
m_launcher->push(imageScanline, &m_contextData, 0, imageSize.y );
while(m_launcher->getNumFinished() != m_launcher->getNumTasks())
{
printf("~ %.2f %% \r", 100.0f*m_launcher->getNumFinished()/(float)m_launcher->getNumTasks());
}
}
void Renderer::imageScanline(FW::MulticoreLauncher::Task& t)
{
contextData& data = *(contextData*)t.data;
const int y = t.idx;
const FW::Vec2f imageSize = data.d_image->getSize();
Node* buffer[1028];
for(int x = 0; x < imageSize.x; ++x)
{
const float yP = (y + .5f) / imageSize.y * -2.0f + 1.0f;
const float xP = (x + .5f) / imageSize.x * 2.0f - 1.0f;
FW::Vec3f E = FW::Vec3f();
float totalW = .0f;
MultiJitteredSamplingWithTentFilter sampling = MultiJitteredSamplingWithTentFilter(data.d_numberOfSamplesByDimension, FW::Vec2f(xP, yP), imageSize);
while(!sampling.isDone())
{
float w = .0f;
FW::Vec2f p = sampling.getNextSamplePos(w);
FW::Vec4f P0( p.x, p.y, 0.0f, 1.0f );
FW::Vec4f P1( p.x, p.y, 1.0f, 1.0f );
FW::Vec4f Roh = (data.d_invP * P0);
FW::Vec3f Ro = (Roh * (1.0f / Roh.w)).getXYZ();
FW::Vec4f Rdh = (data.d_invP * P1);
FW::Vec3f Rd = (Rdh * (1.0f / Rdh.w)).getXYZ();
Rd = Rd - Ro;
E += traceRay(Ro, Rd, data, buffer, 0u);
totalW += w;
}
E *= 1.f/totalW;
data.d_image->setVec4f(FW::Vec2i(x,y), FW::Vec4f(E, 1.f));
}
}
FW::Vec3f Renderer::finalGathering(const Hit& h, const FW::Vec3f& normal, const contextData& data, Node** buffer, const size_t rays)
{
if(rays == 1)
{
float r = data.d_FGRadius;
int index = RayTracer::get().findNearestPhoton(h.intersectionPoint, *data.d_photons, *data.d_photonIndexList, data.d_photonTree, r, buffer);
if(index == -1)
return FW::Vec3f();
else
return (*data.d_photons)[index].E;
}
else
{
FW::Vec3f org = h.intersectionPoint + 0.001f * normal;
FW::Vec3f total = FW::Vec3f();
FW::Random random = FW::Random();
float r = data.d_FGRadius;
int index = RayTracer::get().findNearestPhoton(h.intersectionPoint, *data.d_photons, *data.d_photonIndexList, data.d_photonTree, r, buffer);
if(!(*data.d_photons)[index].g)
{
for(auto i = 0u; i < data.d_numberOfFGRays; ++i)
{
FW::Vec3f dir = randomVectorToHalfUnitSphere(normal, random);
total += traceRay(org, dir, data, buffer, 0u, true);
}
total *= 1.f/(float) rays;
return total;
}
else
{
std::vector<HeapNode> nodes;
float r = data.d_FGRadius;
RayTracer::get().searchPhotons(h.intersectionPoint, *data.d_photons, *data.d_photonIndexList, data.d_photonTree, r, 50u, nodes, buffer);
if(nodes.empty())
return FW::Vec3f();
const Triangle& tri = h.triangle;
FW::Vec3f normal = interpolateAttribute(tri, h.intersectionPoint, data.d_mesh, data.d_mesh->findAttrib(FW::MeshBase::AttribType_Normal));
normal = normal.normalized();
const float alpha = 10.818f;
const float beta = 1.953f;
const float e = 2.718281f;
FW::Vec3f Li = FW::Vec3f();
for ( int j = 1; j < nodes.size(); ++j )
{
FW::Vec3f lightDir = (*data.d_photons)[nodes[j].value].dir;
float dot = FW::dot(lightDir, normal);
if(dot < .0f)
continue;
float d = nodes[j].key;
float t1 = 1.0f - pow( e, ( -beta * d * d / ( 2.0f * r * r) ) );
float t2 = 1.0f - pow( e, -beta );
float w = alpha * ( 1.0f - (t1 / t2) );
const Hit& photonHit = (*data.d_tmpHitList)[nodes[j].value];
TriangleToMeshData* map = (TriangleToMeshData*) photonHit.triangle.m_userPointer;
FW::Vec3f barys = FW::Vec3f((1.0f - photonHit.u - photonHit.v, photonHit.u, photonHit.v));
Li += w * (*data.d_photons)[nodes[j].value].power * dot * getAlbedo(map, data.d_mesh, barys);
}
float A = FW_PI*r*r;
return (Li / A);
}
}
};
FW::Vec3f Renderer::traceRay(const FW::Vec3f& orig, const FW::Vec3f& d, const contextData& data, Node** buffer, const size_t bounce, bool FGRay, const float n1)
{
const FW::Vec3f dir = d.normalized();
MeshC* mesh = data.d_mesh;
if(bounce >= maxBounces)
return FW::Vec3f(.95, .0f, .95f);
Hit hit = Hit(10.f);
if(!RayTracer::get().rayCast(orig, dir, hit, *(data.d_triangles), *(data.d_indexListFromScene), data.d_sceneTree, buffer))
{
hit.t = -1.f;
return FW::Vec3f();
}
const Triangle& tri = hit.triangle;
FW::MeshBase::Material mat;
MaterialPM matType = shader(hit, mesh, mat);
FW::Vec3f n = interpolateAttribute(tri, hit.intersectionPoint, data.d_mesh, data.d_mesh->findAttrib(FW::MeshBase::AttribType_Normal));
n = n.normalized();
FW::Vec3f newOrig = hit.intersectionPoint + 0.0001f * n;
if(matType == MaterialPM_Diffuse)
{
FW::Vec3f albedo = getAlbedo((TriangleToMeshData*) hit.triangle.m_userPointer, mesh, FW::Vec3f(1.f-hit.u-hit.v, hit.u, hit.v));
size_t rays = 1u;
if(!FGRay)
rays = data.d_numberOfFGRays;
return albedo * finalGathering(hit, n, data, buffer, rays);
}
else if(matType == MaterialPM_Mirror)
{
FW::Vec3f newDir = dir - 2.f*FW::dot(dir, n)*n;
newDir = newDir.normalized();
return mat.tf * traceRay(newOrig, newDir, data, buffer, bounce + 1, FGRay);
}
else if (matType == MaterialPM_GlassBillboard)
{
const float n2 = mat.opticalDensity;
const float nDiv = (n1/n2);
//Billboard is just surface, which each vertex has same normal => if hit comes from behind whe just swap this normal around.
float dotI = FW::dot(-dir, n);
if(dotI < .0f)
{
n *= -1.f;
dotI = FW::dot(-dir, n);
}
//Unlike with real glass, with billboard always n1<n2 which makes things easier
float R0 = std::pow(((n1-n2)/(n1+n2)), 2);
float RShclick = R0 + (1-R0)*std::pow((1.f-dotI),5);
FW::Vec3f refractionDir = (nDiv*dir-(nDiv*dotI+FW::sqrt(1.f-(nDiv*nDiv)*(1.f-dotI*dotI)))*n).normalized();
FW::Vec3f reflectionDir = (2.f*FW::dot(-dir, n)*n-dir).normalized();
FW::Vec3f reflection = RShclick * traceRay(hit.intersectionPoint + 0.0001f * n, reflectionDir, data, buffer, bounce+1,FGRay);
FW::Vec3f refraction = (1.f- RShclick) * traceRay(hit.intersectionPoint - 0.0001f * n, refractionDir, data, buffer, bounce+1, FGRay);
FW::Vec3f albedo = getAlbedo((TriangleToMeshData*) hit.triangle.m_userPointer, mesh, FW::Vec3f(1.f-hit.u-hit.v, hit.u, hit.v));
return mat.tf*(reflection + refraction);
}
else
{
float n2;
if(n1 < 1.001f)
n2 = mat.opticalDensity;
else
n2 = 1.f;
const float nDiv = (n1/n2);
bool toDenser = (n1 < n2);
if(!toDenser)
n *= -1.f;
//Define direction of reflection.
FW::Vec3f reflectionDir = (2.f*FW::dot(-dir, n)*n-dir).normalized();
// Dot product of I-ray and surface normal, this is also the cosine of I-ray's angle since Iray and n are unit lenght
float dotI = FW::dot(-dir, n);
//Special case, angle between incoming light and normal that is interpolated from vertex is greater than PI. We dodge this by doing TIR as ideal mirror.
if(dotI < 0.f)
{
return traceRay(hit.intersectionPoint + n*.0001f, reflectionDir, data, buffer, bounce + 1, FGRay);
}
//Fresnel term -> Schlick's approximation
float RShclick = 0.f;
FW::Vec3f refractionDir = FW::Vec3f();
bool TIR = false;
// n1 > n2
if(!toDenser)
{
// Check if there is TIR, aka crital angle <= angle between incoming light and surface normal
if(std::asin(n2/n1) <= std::acos(dotI))
{
TIR = true;
RShclick = 1.f;
}
}
//There is no TIR => define refraction direction
if(!TIR)
refractionDir = (nDiv*dir-(nDiv*dotI+FW::sqrt(1.f-(nDiv*nDiv)*(1.f-dotI*dotI)))*n).normalized();
float R0 = std::pow(((n1-n2)/(n1+n2)), 2);
//Shclick approxmation case 1, n1 < n2
if(toDenser)
RShclick = R0 + (1-R0)*std::pow((1.f-dotI),5);
else
{
if(!TIR)
{
//Shclick approxrimation case 2, n1 > n2, no TIR
float dotT = FW::dot(refractionDir, -n);
RShclick = R0 + (1-R0)*std::pow((1.f-dotT),5);
}
}
if(matType == MaterialPM_GlassSolid)
{
FW::Vec3f reflection = FW::Vec3f();
FW::Vec3f refraction = FW::Vec3f();
//Reflection, if TIR => RShclick = 1.f. First one is n1 < n2 ray from outside glass object, seconed one is ray inside object.
if(bounce < 5u)
{
if(toDenser)
reflection = RShclick * traceRay(hit.intersectionPoint + n*.0001f, reflectionDir, data, buffer, bounce + 1, FGRay);
else
reflection = RShclick * traceRay(hit.intersectionPoint + n*.0001f, reflectionDir, data, buffer, bounce + 1, FGRay, n2);
}
//Refratino if there is no TIR, ray's movement same as above. To note, starting position of new ray must be behind of hit.
if(!TIR)
{
if(toDenser)
refraction = (1.f-RShclick)*traceRay(hit.intersectionPoint - n*.0001f, refractionDir, data, buffer, bounce + 1, FGRay, n2);
else
refraction = (1.f-RShclick)*traceRay(hit.intersectionPoint - n*.0001f, refractionDir, data, buffer, bounce + 1, FGRay);
}
return reflection + refraction;
}
else if(matType == MaterialPM_Lightsource)
{
FW::Vec3f albedo = getAlbedo((TriangleToMeshData*) hit.triangle.m_userPointer, mesh,FW::Vec3f(1.f-hit.u-hit.v, hit.u, hit.v));
const float e = 2.718281f;
const float m = mat.roughness;
const FW::Vec3f hVec = (-dir + n)*.5f;
const float dotHN = FW::dot(hVec, n);
const float exp = (dotHN*dotHN-1.f)/(m*m*dotHN*dotHN);
const float D = std::pow(e,exp)/(m*m*std::pow(dotHN, 4));
return mat.tf * albedo * D;
}
}
//To shut the compiler up, should never get here
std::cout << "ERROR - No material found" << std::endl;
return FW::Vec3f();
}
MaterialPM Renderer::shader(const Hit& h, MeshC* mesh)
{
return shader(h, mesh, FW::MeshBase::Material());
}
MaterialPM Renderer::shader(const Hit& h, MeshC* mesh, FW::MeshBase::Material& mat)
{
const TriangleToMeshData* data = (TriangleToMeshData*) h.triangle.m_userPointer;
mat = mesh->material(data->submeshIndex);
if(mat.emissive != FW::Vec3f())
return MaterialPM_Lightsource;
if(mat.illuminationModel == 5u)
return MaterialPM_Mirror;
if(mat.illuminationModel == 7u)
return MaterialPM_GlassSolid;
if(mat.illuminationModel == 6u)
return MaterialPM_GlassBillboard;
else
return MaterialPM_Diffuse;
}
FW::Vec3f Renderer::randomVectorToHalfUnitSphere(const FW::Vec3f& vec, FW::Random& r)
{
FW::Vec2f rndUnitSquare = r.getVec2f(0.0f,1.0f);
FW::Vec2f rndUnitDisk = toUnitDisk(rndUnitSquare);
FW::Mat3f formBasisMat = formBasis(vec);
FW::Vec3f rndToUnitHalfSphere = FW::Vec3f(rndUnitDisk.x, rndUnitDisk.y, FW::sqrt(1.0f-(rndUnitDisk.x*rndUnitDisk.x)-(rndUnitDisk.y*rndUnitDisk.y)));
return formBasisMat*rndToUnitHalfSphere;
}
void Renderer::updateContext(const float r, const size_t FG, const float totalLight, const size_t numberOfSamplesByDimension)
{
/*
Doesn't update image pointer, hitList for outgoing light, invP camera matrix or root to photon hierarchy tree!!!!
*/
m_contextData.d_numberOfFGRays= FG;
m_contextData.d_numberOfSamplesByDimension = numberOfSamplesByDimension;
m_contextData.d_FGRadius= r;
m_contextData.d_totalLight = totalLight;
m_contextData.d_vertices = &m_vertices;
m_contextData.d_triangles = &m_triangles;
m_contextData.d_triangleToMeshData = &m_triangleToMeshData;
m_contextData.d_indexListFromScene = &m_indexListFromScene;
m_contextData.d_photons = &m_photons;
m_contextData.d_photonIndexList = &m_photonIndexList;
m_contextData.d_mesh = m_mesh;
m_contextData.d_sceneTree = m_sceneTree;
}
void Renderer::updatePhotonListCapasity(const size_t numberOfPhotons)
{
size_t c = m_photons.capacity();
if(c < numberOfPhotons)
{
size_t s = numberOfPhotons - c;
m_photonIndexList.reserve(s);
m_photons.reserve(s);
}
}
void Renderer::drawTriangleToCamera(const FW::Vec3f& pos, const FW::Vec4f& color)
{
const float particleSize = .003;
FW::Vec3f n = (m_camera->getPosition() - pos).normalized();
FW::Vec3f t = n.cross(m_camera->getUp());
FW::Vec3f p = pos + 0.00001f * n;
FW::Vec3f b = n.cross(t);
FW::VertexPNC vertexArray[] =
{
FW::VertexPNC((p + t * particleSize + b * particleSize), n, color),
FW::VertexPNC((p - t * particleSize + b * particleSize), n, color),
FW::VertexPNC((p + t * particleSize - b * particleSize), n, color),
FW::VertexPNC((p - t * particleSize - b * particleSize), n, color)
};
static const FW::Vec3i indexArray[] =
{
FW::Vec3i(0,1,2), FW::Vec3i(1,3,2)
};
int base = m_photonTestMesh->numVertices();
m_photonTestMesh->addVertices(vertexArray, FW_ARRAY_SIZE(vertexArray));
FW::Array<FW::Vec3i>& indices = m_photonTestMesh->mutableIndices(0);
for (int i = 0; i < (int)FW_ARRAY_SIZE(indexArray); i++)
indices.add(indexArray[i] + base);
}
FW::Vec3f Renderer::getAlbedo(const TriangleToMeshData* map, const MeshC* mesh, const FW::Vec3f& barys)
{
FW::Vec3f Kd;
const FW::MeshBase::Material& mat = mesh->material(map->submeshIndex);
if ( mat.textures[FW::MeshBase::TextureType_Diffuse].exists() )
{
const FW::Texture& tex = mat.textures[FW::MeshBase::TextureType_Diffuse];
const FW::Image& teximg = *tex.getImage();
FW::Vec3f indices = mesh->indices(map->submeshIndex)[map->vertexIndex];
int attribidx = mesh->findAttrib(FW::MeshBase::AttribType_TexCoord);
FW::Vec2f v[3];
v[0] = mesh->getVertexAttrib( indices[0], attribidx ).getXY();
v[1] = mesh->getVertexAttrib( indices[1], attribidx ).getXY();
v[2] = mesh->getVertexAttrib( indices[2], attribidx ).getXY();
FW::Vec2f UV = barys[0]*v[0] + barys[1]*v[1] + barys[2]*v[2];
FW::Vec2i imageSize = teximg.getSize();
int x = UV.x * imageSize.x;
while(x < 0)
x += imageSize.x;
x = x % imageSize.x;
int y = UV.y * imageSize.y;
while(x < 0)
y += imageSize.x;
y = y % imageSize.x;
FW::Vec2i pos = FW::Vec2i(x,y);
FW::Vec3f color = teximg.getVec4f(pos).getXYZ();
Kd = color;
}
else
Kd = mat.diffuse.getXYZ();
return Kd;
}
FW::Vec3f Renderer::interpolateAttribute(const Triangle& tri, const FW::Vec3f& p, const FW::MeshBase* mesh, int attribidx )
{
const TriangleToMeshData* map = (const TriangleToMeshData*)tri.m_userPointer;
FW::Vec3f barys = getBarys(tri, p, mesh);
FW::Vec3f v[3];
v[0] = mesh->getVertexAttrib( mesh->indices(map->submeshIndex)[map->vertexIndex][0], attribidx ).getXYZ();
v[1] = mesh->getVertexAttrib( mesh->indices(map->submeshIndex)[map->vertexIndex][1], attribidx ).getXYZ();
v[2] = mesh->getVertexAttrib( mesh->indices(map->submeshIndex)[map->vertexIndex][2], attribidx ).getXYZ();
return barys[0]*v[0] + barys[1]*v[1] + barys[2]*v[2];
}
FW::Vec3f Renderer::getBarys(const Triangle& tri, const FW::Vec3f& p, const FW::MeshBase* mesh)
{
const TriangleToMeshData* map = (const TriangleToMeshData*)tri.m_userPointer;
int posIndex = mesh->findAttrib(FW::MeshBase::AttribType_Position);
FW::Vec3f pos[3];
pos[0] = mesh->getVertexAttrib( mesh->indices(map->submeshIndex)[map->vertexIndex][0], posIndex ).getXYZ();
pos[1] = mesh->getVertexAttrib( mesh->indices(map->submeshIndex)[map->vertexIndex][1], posIndex ).getXYZ();
pos[2] = mesh->getVertexAttrib( mesh->indices(map->submeshIndex)[map->vertexIndex][2], posIndex ).getXYZ();
FW::Vec3f f[3];
f[0] = pos[0] - p;
f[1] = pos[1] - p;
f[2] = pos[2] - p;
float aTotal = FW::cross(pos[0]-pos[1], pos[0] - pos[2]).length();
float a1 = FW::cross(f[1], f[2]).length() / aTotal;
float a2 = FW::cross(f[2], f[0]).length() / aTotal;
float a3 = FW::cross(f[0], f[1]).length() / aTotal;
return FW::Vec3f(a1, a2, a3);
}
void Renderer::drawPhotonMap()
{
/* m_photonTestMesh->draw(m_context, m_worldToCamera, m_projection);
glLineWidth(2.f);
glBegin(GL_LINES);
float l = .1f;
for (int i = 0; i < m_photons.size(); ++i )
{
FW::Vec3f c = FW::Vec3f(1.f, .0f, .0f);
glColor3fv(&c.x);
glVertex3f( m_photons[i].pos.x, m_photons[i].pos.y, m_photons[i].pos.z );
glVertex3f( m_photons[i].previouspos.x, m_photons[i].previouspos.y, m_photons[i].previouspos.z );
}
glEnd();*/
} | [
"niklas.smal@aalto.fi"
] | niklas.smal@aalto.fi |
89c1f0bf75fd7ccb66b01a3ec57b3aabd6d92647 | ec8f839f1563e58cbbd6e14f60849943335183d1 | /Assets/StreamingAssets/Audio/GeneratedSoundBanks/Wwise_IDs.h | ee482d03c3d6b1a2ff896ee5a05f18d1b7f9fd2a | [] | no_license | jameskanCa/WezardRushMain | 3ec9e0114ca86ae3d4444e8fe9d9517c4a5a7b0a | 0befd46890b17561bdcf6fdf155f75beae267224 | refs/heads/master | 2020-04-14T09:38:44.507214 | 2019-01-01T20:58:44 | 2019-01-01T20:58:44 | 163,764,876 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,735 | h | /////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Audiokinetic Wwise generated include file. Do not edit.
//
/////////////////////////////////////////////////////////////////////////////////////////////////////
#ifndef __WWISE_IDS_H__
#define __WWISE_IDS_H__
#include <AK/SoundEngine/Common/AkTypes.h>
namespace AK
{
namespace EVENTS
{
static const AkUniqueID PLAY_FALL = 2712047697U;
static const AkUniqueID PLAY_GRAB = 17721092U;
} // namespace EVENTS
namespace GAME_PARAMETERS
{
static const AkUniqueID SS_AIR_FEAR = 1351367891U;
static const AkUniqueID SS_AIR_FREEFALL = 3002758120U;
static const AkUniqueID SS_AIR_FURY = 1029930033U;
static const AkUniqueID SS_AIR_MONTH = 2648548617U;
static const AkUniqueID SS_AIR_PRESENCE = 3847924954U;
static const AkUniqueID SS_AIR_RPM = 822163944U;
static const AkUniqueID SS_AIR_SIZE = 3074696722U;
static const AkUniqueID SS_AIR_STORM = 3715662592U;
static const AkUniqueID SS_AIR_TIMEOFDAY = 3203397129U;
static const AkUniqueID SS_AIR_TURBULENCE = 4160247818U;
} // namespace GAME_PARAMETERS
namespace BANKS
{
static const AkUniqueID INIT = 1355168291U;
static const AkUniqueID GENERAL_SOUNDBANK = 3657742645U;
} // namespace BANKS
namespace BUSSES
{
static const AkUniqueID MASTER_AUDIO_BUS = 3803692087U;
} // namespace BUSSES
namespace AUDIO_DEVICES
{
static const AkUniqueID NO_OUTPUT = 2317455096U;
static const AkUniqueID SYSTEM = 3859886410U;
} // namespace AUDIO_DEVICES
}// namespace AK
#endif // __WWISE_IDS_H__
| [
"james0077721@hotmail.com"
] | james0077721@hotmail.com |
10c9ed1d557ce884a96416b5fa042e2b17753a84 | bdfd435e25ca9496dcfce054b4be6636b5064bb2 | /src/DispatchThread.cpp | f7db1d7061526f1bbeb39ed303d6187819615434 | [] | no_license | KatekovAnton/DispatchCpp | 83baca62eb7b7944b4d6d9cd6466ed5072b3c301 | c98d8923af5bf416761cbcbd47e124c1da964a82 | refs/heads/master | 2023-04-15T01:40:53.330659 | 2021-04-15T13:25:52 | 2021-04-15T13:25:52 | 316,879,082 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,268 | cpp | //
// DispatchThread.cpp
// DispatchCpp
//
// Created by Katekov Anton on 24/10/20.
// Copyright © 2020 AntonKatekov. All rights reserved.
//
#include "DispatchThread.hpp"
DispatchThreadStatistic &DispatchThread::GetStatistic()
{
static DispatchThreadStatistic s;
return s;
}
DispatchThread::DispatchThread(DispatchThreadDelegate *delegate)
:_delegate(delegate)
{}
void DispatchThread::run()
{
DispatchThread::GetStatistic().ThreadSpawned();
Thread::run();
_delegate->ThreadExecuting(this);
_delegate->ThreadDidFinish(this);
}
bool DispatchMutexBase::TryLock(const std::string &from)
{
_locked = true;
_lockedFrom = from;
return true;
}
void DispatchMutexBase::Lock(const std::string &from)
{
_locked = true;
_lockedFrom = from;
}
void DispatchMutexBase::Unlock()
{
_locked = false;
}
DispatchMutex::DispatchMutex()
{}
bool DispatchMutex::TryLock(const std::string &from)
{
if (_mutex.try_lock()) {
_locked = true;
_lockedFrom = from;
return true;
}
return false;
}
void DispatchMutex::Lock(const std::string &from)
{
_mutex.lock();
_locked = true;
_lockedFrom = from;
}
void DispatchMutex::Unlock()
{
_locked = false;
_mutex.unlock();
}
| [
"void0main@gmail.com"
] | void0main@gmail.com |
a1766e4fb909d42ac08300abf0bdc5e899becb89 | e18075c755573e4718b88ff07795fe208202a4b0 | /Abhi_test1/Abhi_test1OLD.cpp | 64e1c018e7a5ffc1bac7073eec65e662d24d879d | [] | no_license | spagad7/CVLab | 19deb2010d2657d230f461af24dfeae783b8a05d | 49ba0de2bdbf4ff4237f0d9a0a4703acc2edeb77 | refs/heads/master | 2021-01-13T05:23:32.891082 | 2017-02-24T03:30:51 | 2017-02-24T03:30:51 | 81,402,308 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,420 | cpp | /**
* @example Acquisition.cpp
*
* @brief Acquisition.cpp shows how to acquire images. It relies on
* information provided in the Enumeration example. Also, check out the
* ExceptionHandling and NodeMapInfo examples if you haven't already.
* ExceptionHandling shows the handling of standard and Spinnaker exceptions
* while NodeMapInfo explores retrieving information from various node types.
*
* This example touches on the preparation and cleanup of a camera just before
* and just after the acquisition of images. Image retrieval and conversion,
* grabbing image data, and saving images are all covered as well.
*
* Once comfortable with Acquisition, we suggest checking out
* AcquisitionMultipleCamera, NodeMapCallback, or SaveToAvi.
* AcquisitionMultipleCamera demonstrates simultaneously acquiring images from
* a number of cameras, NodeMapCallback serves as a good introduction to
* programming with callbacks and events, and SaveToAvi exhibits video creation.
*/
#include "Spinnaker.h"
#include "SpinGenApi/SpinnakerGenApi.h"
#include <iostream>
#include <sstream>
#include <sys/timeb.h>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>
using namespace Spinnaker;
using namespace Spinnaker::GenApi;
using namespace Spinnaker::GenICam;
using namespace std;
using namespace cv;
int getMilliCount(){
timeb tb;
ftime(&tb);
int nCount = tb.millitm + (tb.time & 0xfffff) * 1000;
return nCount;
}
int getMilliSpan(int nTimeStart){
int nSpan = getMilliCount() - nTimeStart;
if(nSpan < 0)
nSpan += 0x100000 * 1000;
return nSpan;
}
// This function acquires and live stream images from a device.
int AcquireImages(CameraPtr pCam, INodeMap & nodeMap, INodeMap & nodeMapTLDevice)
{
int result = 0;
int counter = 0;
try
{
//
// Set acquisition mode to continuous
//
// *** NOTES ***
// Because the example acquires and saves 10 images, setting acquisition
// mode to continuous lets the example finish. If set to single frame
// or multiframe (at a lower number of images), the example would just
// hang. This would happen because the example has been written to
// acquire 10 images while the camera would have been programmed to
// retrieve less than that.
//
// Setting the value of an enumeration node is slightly more complicated
// than other node types. Two nodes must be retrieved: first, the
// enumeration node is retrieved from the nodemap; and second, the entry
// node is retrieved from the enumeration node. The integer value of the
// entry node is then set as the new value of the enumeration node.
//
// Notice that both the enumeration and the entry nodes are checked for
// availability and readability/writability. Enumeration nodes are
// generally readable and writable whereas their entry nodes are only
// ever readable.
//
// Retrieve enumeration node from nodemap
CEnumerationPtr ptrAcquisitionMode = nodeMap.GetNode("AcquisitionMode");
if (!IsAvailable(ptrAcquisitionMode) || !IsWritable(ptrAcquisitionMode))
{
cout << "Unable to set acquisition mode to continuous "
"(enum retrieval). Aborting..." << endl << endl;
return -1;
}
// Retrieve entry node from enumeration node
CEnumEntryPtr ptrAcquisitionModeContinuous
= ptrAcquisitionMode->GetEntryByName("Continuous");
if (!IsAvailable(ptrAcquisitionModeContinuous) || !IsReadable(ptrAcquisitionModeContinuous))
{
cout << "Unable to set acquisition mode to continuous "
"(entry retrieval). Aborting..." << endl << endl;
return -1;
}
// Retrieve Acquisition frame rate
CFloatPtr ptrAcquisitionResultingFrameRate = nodeMap.GetNode("AcquisitionResultingFrameRate");
if (!IsAvailable(ptrAcquisitionFrameRate) || !IsReadable(ptrAcquisitionFrameRate))
{
cout << "Unable to retrieve frame rate. Aborting..." << endl << endl;
return -1;
}
float resultingFrameRate = static_cast<float>(ptrAcquisitionResultingFrameRate->GetValue());
cout << "Resulting Frame Rate: " << resultingFrameRate << "...";
// Retrieve integer value from entry node
int64_t acquisitionModeContinuous = ptrAcquisitionModeContinuous->GetValue();
// Set integer value from entry node as new value of enumeration node
ptrAcquisitionMode->SetIntValue(acquisitionModeContinuous);
//cout << "Acquisition mode set to continuous..." << endl;
//
// Begin acquiring images
//
// *** NOTES ***
// What happens when the camera begins acquiring images depends on the
// acquisition mode. Single frame captures only a single image, multi
// frame catures a set number of images, and continuous captures a
// continuous stream of images. Because the example calls for the
// retrieval of 10 images, continuous mode has been set.
//
// *** LATER ***
// Image acquisition must be ended when no more images are needed.
//
pCam->BeginAcquisition();
cout << "Acquiring images..." << endl;
//-------------------Changes start from here onwards--------------------//
// Retrieve, convert, and save images
//const unsigned int k_numImages = 20;
char key = 0;
int start = getMilliCount();
//for (unsigned int imageCnt = 0; imageCnt < k_numImages; imageCnt++)
while(key!=27 && key!='q')
{
try
{
//
// Retrieve next received image
//
// *** NOTES ***
// Capturing an image houses images on the camera buffer. Trying
// to capture an image that does not exist will hang the camera.
//
// *** LATER ***
// Once an image from the buffer is saved and/or no longer
// needed, the image must be released in order to keep the
// buffer from filling up.
//
ImagePtr pResultImage = pCam->GetNextImage();
//
// Ensure image completion
//
// *** NOTES ***
// Images can easily be checked for completion. This should be
// done whenever a complete image is expected or required.
// Further, check image status for a little more insight into
// why an image is incomplete.
//
if (pResultImage->IsIncomplete())
{
cout << "Image incomplete with image status " <<
pResultImage->GetImageStatus() << "..." << endl << endl;
}
else
{
//
// Convert image to mono 8
//
// *** NOTES ***
// Images can be converted between pixel formats by using
// the appropriate enumeration value. Unlike the original
// image, the converted one does not need to be released as
// it does not affect the camera buffer.
//
// When converting images, color processing algorithm is an
// optional parameter.
//
ImagePtr convertedImage =
pResultImage->Convert(PixelFormat_Mono8, HQ_LINEAR);
// Storing the images in OpenCV Mat and showing it.
unsigned int rowBytes =
(int)convertedImage->GetImageSize()/convertedImage->GetHeight();
Mat image = cv::Mat(convertedImage->GetHeight(),
convertedImage->GetWidth(), CV_8UC1, convertedImage->GetData(),
rowBytes);
cv::resize(image, image, Size(800, 600), 0, 0, INTER_LINEAR);
cv::imshow("image", image);
/*char temp[1000];
sprintf(temp, "/home/umh-admin/Downloads/spinnaker_1_0_0_295_amd64/bin/test/image%07d.jpg", counter);
counter++;
cv::imwrite(temp, image);*/
key = cv::waitKey(1);
}
//
// Release image
//
// *** NOTES ***
// Images retrieved directly from the camera (i.e. non-converted
// images) need to be released in order to keep from filling the
// buffer.
//
pResultImage->Release();
}
catch (Spinnaker::Exception &e)
{
cout << "Error: " << e.what() << endl;
result = -1;
}
}
int milliSecondsElapsed = getMilliSpan(start);
cout << "End system Time in milliseconds is " << milliSecondsElapsed << "." << endl;
//
// End acquisition
//
// *** NOTES ***
// Ending acquisition appropriately helps ensure that devices clean up
// properly and do not need to be power-cycled to maintain integrity.
//
pCam->EndAcquisition();
}
catch (Spinnaker::Exception &e)
{
cout << "Error: " << e.what() << endl;
result = -1;
}
return result;
}
// This function prints the device information of the camera from the transport
// layer; please see NodeMapInfo example for more in-depth comments on printing
// device information from the nodemap.
int PrintDeviceInfo(INodeMap & nodeMap)
{
int result = 0;
cout << endl << "*** DEVICE INFORMATION ***" << endl << endl;
try
{
FeatureList_t features;
CCategoryPtr category = nodeMap.GetNode("DeviceInformation");
if (IsAvailable(category) && IsReadable(category))
{
category->GetFeatures(features);
FeatureList_t::const_iterator it;
for (it = features.begin(); it != features.end(); ++it)
{
CNodePtr pfeatureNode = *it;
cout << pfeatureNode->GetName() << " : ";
CValuePtr pValue = (CValuePtr)pfeatureNode;
cout << (IsReadable(pValue) ? pValue->ToString() : "Node not readable");
cout << endl;
}
}
else
{
cout << "Device control information not available." << endl;
}
}
catch (Spinnaker::Exception &e)
{
cout << "Error: " << e.what() << endl;
result = -1;
}
return result;
}
// This function acts as the body of the example; please see NodeMapInfo example
// for more in-depth comments on setting up cameras.
int RunSingleCamera(CameraPtr pCam)
{
int result = 0;
try
{
// Retrieve TL device nodemap and print device information
INodeMap & nodeMapTLDevice = pCam->GetTLDeviceNodeMap();
//result = PrintDeviceInfo(nodeMapTLDevice);
// Initialize camera
pCam->Init();
// Retrieve GenICam nodemap
INodeMap & nodeMap = pCam->GetNodeMap();
// Acquire images
result = result | AcquireImages(pCam, nodeMap, nodeMapTLDevice);
// Deinitialize camera
pCam->DeInit();
}
catch (Spinnaker::Exception &e)
{
cout << "Error: " << e.what() << endl;
result = -1;
}
return result;
}
// Example entry point; please see Enumeration example for more in-depth
// comments on preparing and cleaning up the system.
int main(int /*argc*/, char** /*argv*/)
{
int result = 0;
// Print application build information
cout << "Application build date: " << __DATE__ << " " << __TIME__ << endl << endl;
// Retrieve singleton reference to system object
SystemPtr system = System::GetInstance();
// Retrieve list of cameras from the system
CameraList camList = system->GetCameras();
unsigned int numCameras = camList.GetSize();
cout << "Number of cameras detected: " << numCameras << endl << endl;
// Finish if there are no cameras
if (numCameras == 0)
{
// Clear camera list before releasing system
camList.Clear();
// Release system
system->ReleaseInstance();
cout << "Not enough cameras!" << endl;
cout << "Done! Press Enter to exit..." << endl;
getchar();
return -1;
}
//
// Create shared pointer to camera
//
// *** NOTES ***
// The CameraPtr object is a shared pointer, and will generally clean itself
// up upon exiting its scope. However, if a shared pointer is created in the
// same scope that a system object is explicitly released (i.e. this scope),
// the reference to the shared point must be broken manually.
//
// *** LATER ***
// Shared pointers can be terminated manually by assigning them to NULL.
// This keeps releasing the system from throwing an exception.
//
CameraPtr pCam = NULL;
pCam = camList.GetByIndex(0);
// Run example on each camera
/*for (unsigned int i = 0; i < numCameras; i++)
{
// Select camera
pCam = camList.GetByIndex(i);
cout << endl << "Running example for camera " << i << "..." << endl;
*/
// Run example
result = result | RunSingleCamera(pCam);
/*
cout << "Camera " << i << " example complete..." << endl << endl;
}*/
//
// Release reference to the camera
//
// *** NOTES ***
// Had the CameraPtr object been created within the for-loop, it would not
// be necessary to manually break the reference because the shared pointer
// would have automatically cleaned itself up upon exiting the loop.
//
pCam = NULL;
// Clear camera list before releasing system
camList.Clear();
// Release system
system->ReleaseInstance();
cout << endl << "Done! Press Enter to exit..." << endl;
getchar();
return result;
}
| [
"shishir.pagad@gmail.com"
] | shishir.pagad@gmail.com |
7c523bedbb599cd3876022180a0ed3a798b69474 | 000729986ff4c193b5d1b5f9c10ba724e5462537 | /Game/Scripts/Block.h | 6bd6be4b32636f8bcd68f965608628f4f58b8666 | [
"Apache-2.0"
] | permissive | resul4e/Runtime-Recompiled-CPP | 62376440098f711252f123771ad3396b43c8e797 | ef0c8918782b67a431cf7dc0e9a2f2770f8bed67 | refs/heads/master | 2022-02-07T04:35:26.765359 | 2022-02-03T18:42:30 | 2022-02-03T18:42:30 | 248,596,599 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,218 | h | #pragma once
#define _SILENCE_EXPERIMENTAL_FILESYSTEM_DEPRECATION_WARNING
#include "Core/Object.h"
#include "Transform/Vector.h"
class Block : public Object
{
public:
Block(){};
virtual ~Block(){};
virtual void Start() override;
virtual void Setup(glm::vec2 aPos) {};
virtual void Restart() override;
virtual void FixedUpdate() override;
virtual void Update(float aDeltatime) override;
virtual void Delete() override;
virtual void Serialize(Storage& storage) override;
virtual void HitBlock();
virtual PhysicsCompHandle GetPhysicsComponent();
void SetColliderIndex(size_t index);
size_t GetColliderIndex();
void SetBlockIndex(size_t index);
size_t GetBlockIndex();
glm::vec2 GetPosition();
size_t floorColliderIndex;
size_t blockIndex;
AnimationCompHandle block;
PhysicsCompHandle blockCollider;
glm::vec2 position;
glm::vec2 startPos;
};
INTERFACE_START(Block)
PUBLIC_FUNCTION(HitBlock, Block)
PUBLIC_FUNCTION(GetPhysicsComponent,Block)
PUBLIC_FUNCTION(SetColliderIndex, Block)
PUBLIC_FUNCTION(GetColliderIndex, Block)
PUBLIC_FUNCTION(SetBlockIndex, Block)
PUBLIC_FUNCTION(GetBlockIndex, Block)
PUBLIC_FUNCTION(GetPosition, Block)
PUBLIC_FUNCTION(Setup, Block)
INTERFACE_END() | [
"resul_celik@hotmail.com"
] | resul_celik@hotmail.com |
1a175b537d6cce4b6d3d22bb8c4f878b01764395 | a8a11d555d37c33dd1fbafc9cbf705728e6ec4f3 | /MFCA4-0323-0/MFCA4-0323-0/MFCA4-0323-0.h | 714988295a60788fa7e8e9d41ad170c20076967a | [] | no_license | youhavegot/Test | fe451b6a48afe52ceb51fe481bd74032807c35ce | 6eec3cec505bb76003c8c4ebadbf04188c499c84 | refs/heads/master | 2021-07-17T22:00:32.130183 | 2021-07-12T11:04:59 | 2021-07-12T11:04:59 | 244,651,749 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 545 | h |
// MFCA4-0323-0.h : MFCA4-0323-0 应用程序的主头文件
//
#pragma once
#ifndef __AFXWIN_H__
#error "在包含此文件之前包含“stdafx.h”以生成 PCH 文件"
#endif
#include "resource.h" // 主符号
// CMFCA403230App:
// 有关此类的实现,请参阅 MFCA4-0323-0.cpp
//
class CMFCA403230App : public CWinApp
{
public:
CMFCA403230App();
// 重写
public:
virtual BOOL InitInstance();
virtual int ExitInstance();
// 实现
afx_msg void OnAppAbout();
DECLARE_MESSAGE_MAP()
};
extern CMFCA403230App theApp;
| [
"gechentiande@qq.com"
] | gechentiande@qq.com |
6c8608d8d512e06c30e27e7af1a71097f54a3e2a | b71b8bd385c207dffda39d96c7bee5f2ccce946c | /testcases/CWE590_Free_Memory_Not_on_Heap/s01/CWE590_Free_Memory_Not_on_Heap__delete_array_int_declare_09.cpp | afbb12b6acbccd5328cf71117ebfdbe60bf1512b | [] | no_license | Sporknugget/Juliet_prep | e9bda84a30bdc7938bafe338b4ab2e361449eda5 | 97d8922244d3d79b62496ede4636199837e8b971 | refs/heads/master | 2023-05-05T14:41:30.243718 | 2021-05-25T16:18:13 | 2021-05-25T16:18:13 | 369,334,230 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,483 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE590_Free_Memory_Not_on_Heap__delete_array_int_declare_09.cpp
Label Definition File: CWE590_Free_Memory_Not_on_Heap__delete_array.label.xml
Template File: sources-sink-09.tmpl.cpp
*/
/*
* @description
* CWE: 590 Free Memory Not on Heap
* BadSource: declare Data buffer is declared on the stack
* GoodSource: Allocate memory on the heap
* Sink:
* BadSink : Print then free data
* Flow Variant: 09 Control flow: if(GLOBAL_CONST_TRUE) and if(GLOBAL_CONST_FALSE)
*
* */
#include "std_testcase.h"
#include <wchar.h>
namespace CWE590_Free_Memory_Not_on_Heap__delete_array_int_declare_09
{
#ifndef OMITBAD
void bad()
{
int * data;
data = NULL; /* Initialize data */
{
{
/* FLAW: data is allocated on the stack and deallocated in the BadSink */
int dataBuffer[100];
{
size_t i;
for (i = 0; i < 100; i++)
{
dataBuffer[i] = 5;
}
}
data = dataBuffer;
}
}
printIntLine(data[0]);
/* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */
delete [] data;
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B1() - use goodsource and badsink by changing the GLOBAL_CONST_TRUE to GLOBAL_CONST_FALSE */
static void goodG2B1()
{
int * data;
data = NULL; /* Initialize data */
{
{
/* FIX: data is allocated on the heap and deallocated in the BadSink */
int * dataBuffer = new int[100];
{
size_t i;
for (i = 0; i < 100; i++)
{
dataBuffer[i] = 5;
}
}
data = dataBuffer;
}
}
printIntLine(data[0]);
/* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */
delete [] data;
}
/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */
static void goodG2B2()
{
int * data;
data = NULL; /* Initialize data */
{
{
/* FIX: data is allocated on the heap and deallocated in the BadSink */
int * dataBuffer = new int[100];
{
size_t i;
for (i = 0; i < 100; i++)
{
dataBuffer[i] = 5;
}
}
data = dataBuffer;
}
}
printIntLine(data[0]);
/* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */
delete [] data;
}
void good()
{
goodG2B1();
goodG2B2();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE590_Free_Memory_Not_on_Heap__delete_array_int_declare_09; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| [
"jaredzap@rams.colostate.edu"
] | jaredzap@rams.colostate.edu |
95553dc21e408d6723d54f350a1dd1e00ca69309 | b3b87531e4e23fe3bf7008169064d57950186235 | /PrototypeFightEngine/PrototypeFightEngine/prototypefightengine/GameManager.cpp | ec83602a55eb6eb24487d98c676cfc6b08e4489d | [] | no_license | MrChuckchucky/FightEngine_DEVIENNE_BRUN | fced705a438c9e69fb81971910b31e5fb47cff6f | 0d7f806ad3ac62633d9be364a2bb26d605a09997 | refs/heads/master | 2021-01-10T16:26:58.264941 | 2016-01-12T21:45:46 | 2016-01-12T21:45:46 | 49,530,901 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 977 | cpp | #include "stdafx.h"
#include "GameManager.h"
#include "PlayerManager.h"
#include "AbstractCharacter.h"
GameManager* GameManager::instance = nullptr;
GameManager::GameManager()
{
}
GameManager::~GameManager()
{
}
GameManager * GameManager::getInstance()
{
if (instance == nullptr)
{
instance = new GameManager();
}
return instance;
}
//Setter
void GameManager::setTimerRound(int timerRound)
{
mTimerRound = timerRound;
}
void GameManager::updateObservable(AbstractObservable* observable)
{
if (((AbstractCharacter*)observable)->getLife() <= 0)
{
endOfGame(observable);
}
}
void GameManager::initializeVariable(MenuManager* menuInstance)
{
mTimerRound = menuInstance->getTimer();
}
void GameManager::endOfGame(AbstractObservable* observable)
{
if ( ( (AbstractCharacter*)observable )->getName().compare("Octopus") == 0 )
{
PlayerManager::getInstance()->printWinner("Rossignol");
}
else
{
PlayerManager::getInstance()->printWinner("Octopus");
}
} | [
"b.devienne@rubika-edu.com"
] | b.devienne@rubika-edu.com |
acb9353fe69e4c4906e73a972d06faba79aff34b | 5814f77b77a24802773357a79838392da1102061 | /dep/include/mygui/MyGUI_OverlappedLayer.h | f0bd458b3c534f4ecd2310e39e7404e1d5602242 | [] | no_license | rudolf123/gibdd | 1080bd3e94c580ddde09256c93f7b64685504f11 | 947e667ace82b827a01d479afc729b0957b78647 | refs/heads/master | 2021-01-01T06:49:51.391362 | 2013-11-14T06:04:41 | 2013-11-14T06:04:41 | 32,856,697 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 2,061 | h | /*!
@file
@author Albert Semenov
@date 02/2008
@module
*/
/*
This file is part of MyGUI.
MyGUI is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
MyGUI 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 MyGUI. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __MYGUI_OVERLAPPED_LAYER_H__
#define __MYGUI_OVERLAPPED_LAYER_H__
#include "MyGUI_Prerequest.h"
#include "MyGUI_Types.h"
#include "MyGUI_ILayer.h"
namespace MyGUI
{
class MYGUI_EXPORT OverlappedLayer :
public ILayer
{
MYGUI_RTTI_DERIVED( OverlappedLayer )
public:
OverlappedLayer();
virtual ~OverlappedLayer();
virtual void deserialization(xml::ElementPtr _node, Version _version);
// создаем дочерний нод
virtual ILayerNode* createChildItemNode();
// удаляем дочерний нод
virtual void destroyChildItemNode(ILayerNode* _node);
// поднимаем дочерний нод
virtual void upChildItemNode(ILayerNode* _node);
// список детей
virtual EnumeratorILayerNode getEnumerator();
// возвращает виджет по позиции
virtual ILayerItem* getLayerItemByPoint(int _left, int _top);
virtual IntPoint getPosition(int _left, int _top) const;
virtual const IntSize& getSize() const;
// рисует леер
virtual void renderToTarget(IRenderTarget* _target, bool _update);
virtual void dumpStatisticToLog();
protected:
bool mIsPick;
VectorILayerNode mChildItems;
};
} // namespace MyGUI
#endif // __MYGUI_OVERLAPPED_LAYER_H__
| [
"rudolf123@narod.ru@6270124d-f72d-35ae-a914-af412bf1d36c"
] | rudolf123@narod.ru@6270124d-f72d-35ae-a914-af412bf1d36c |
45678f5916566e17128ecbc38ad059cd2b684456 | a81ad9fcba58121eb6c20bb6c2acc99f2b4c7874 | /src/controller/archive/cellmemento.cpp | 4cad2072111bad1b5bb52e0a1b65ffe1097a1677 | [] | no_license | dkamakin/OOP | 34cdef74ccfc1517b4b54f4444e9abae7cb58382 | 6e438a08c623533f6e6053b89604cc2f5f88f6a2 | refs/heads/main | 2023-02-08T16:18:57.996429 | 2020-12-23T05:49:26 | 2020-12-23T05:49:26 | 316,035,364 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 440 | cpp | #include "controller/archive/cellmemento.h"
CellMemento::CellMemento(Point2D coords, CellType type, size_t object, bool passable) :
coords_(coords), type_(type), object_(object), passable_(passable) {}
Point2D& CellMemento::getCoords() {
return coords_;
}
CellType& CellMemento::getType() {
return type_;
}
size_t& CellMemento::getObject() {
return object_;
}
bool& CellMemento::getPassable() {
return passable_;
}
| [
"cursedowguy@gmail.com"
] | cursedowguy@gmail.com |
864f43096333a68dd9e11482e62393c5445e7e00 | e159bf4dcc05fcbf4837f4b9aeeb0083c47f20ae | /include/unstruc/block.h | 7b106fddd10c1bab099e538bd0d89e3070bd4665 | [] | no_license | drewkett/unstruc | d0ccf9a36d4187da939f370af833b08df9e9dcb6 | 4d42cbc2693232a64988dde2a8c9f2f7414f0b5f | refs/heads/master | 2022-02-13T04:16:57.296595 | 2022-02-07T03:06:15 | 2022-02-07T03:06:15 | 27,942,404 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 537 | h | #ifndef BLOCK_H_17859E7C_9108_4D1B_8805_3FA4F71F11EF
#define BLOCK_H_17859E7C_9108_4D1B_8805_3FA4F71F11EF
#include <vector>
#include "point.h"
namespace unstruc {
struct Grid;
struct Block {
size_t size1, size2, size3;
std::vector <Point> points;
Block(size_t s1, size_t s2, size_t s3);
Point at(size_t i, size_t j, size_t k);
double * at_ref(size_t i, size_t j, size_t k, size_t l);
size_t index(size_t i, size_t j, size_t k);
};
struct MultiBlock {
std::vector <Block> blocks;
Grid to_grid();
};
}
#endif
| [
"burkett.andrew@gmail.com"
] | burkett.andrew@gmail.com |
b9147329869d6496ef11c4789a382e058a5fa006 | f0207698f6b85cf4a5de59145629bdd6357bb1d0 | /example_cmake/frame2.cpp | eb5fc806cd8a9f3c17b43776e292d32a5ac60214 | [] | no_license | KimMJ/raspberryPi | d7930c8a7b549b118ba3e8d6745432122f67274c | 81e98244cd0a6263106bb8af7ee298aa4790cda2 | refs/heads/master | 2018-12-20T15:07:02.119639 | 2018-09-19T07:05:28 | 2018-09-19T07:05:28 | 125,629,894 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,141 | cpp | #include <highgui.h>
#include <cv.h>
int g_slider_position = 0;
CvCapture* g_capture = NULL;
void onTrackbarSlide(int pos)
{
cvSetCaptureProperty(
g_capture,
CV_CAP_PROP_POS_FRAMES,
pos
);
}
int main(int argc, char** argv)
{
cvNamedWindow("Example", CV_WINDOW_AUTOSIZE);
g_capture = cvCreateFileCapture(argv[1]);
int frameCount = (int) cvGetCaptureProperty(
g_capture,
CV_CAP_PROP_FRAME_COUNT
);
/*
if(frameCount != 0)
{
cvCreateTrackbar(
"Position",
"Example",
&g_slider_position,
frameCount,
onTrackbarSlide
);
}
*/
IplImage* frame;
char c;
int pos;
//동영상 진행 간 연속 출력
while(1){
cvSetCaptureProperty(g_capture, CV_CAP_PROP_POS_FRAMES, pos);
cvGrabFrame(g_capture);
printf("%d\n", pos);
pos += 25;
frame = cvRetrieveFrame(g_capture);
//cvSetTrackbarPos("Position", "Example", pos);
if(!frame) {
break;
}
cvShowImage("Example", frame);
//pos = (int)cvGetCaptureProperty(g_capture, CV_CAP_PROP_POS_FRAMES);
c = cvWaitKey(1);
if(c == 27){
break;
}
}
cvReleaseCapture(&g_capture);
cvDestroyWindow("Example");
return 0;
}
| [
"ss59s@nate.com"
] | ss59s@nate.com |
56f54041f8e349114b7890d29581e06a87530e3b | af46c38cf1e425e46a34f8f74f0cacfad2030837 | /hxemu/src/ui/button.h | 4adee6d710fa9ce0d76f3cc9ea89061d2228996a | [
"MIT"
] | permissive | hx20er/HXEmu | 4b233bad42633386f7dfff5aef61801cfd557022 | 9764886879309d58cde125aeb0d3523a8983c17a | refs/heads/master | 2020-03-27T03:46:38.817915 | 2015-01-29T09:18:51 | 2015-01-29T09:18:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 515 | h | #ifndef __BUTTON_H__
#define __BUTTON_H__
#include "widget.h"
#include <functional>
class CButton : public CWidget {
public:
CButton(const char *c, int x, int y, int w, int h);
~CButton();
virtual bool update();
virtual void draw(SDL_Surface *dest);
virtual void mouseup(int x, int y);
void set_caption(const char *new_caption);
void set_click_callback(std::function<void(CWidget*)> callback);
protected:
char *caption;
bool updated;
std::function<void(CWidget*)> cb_click;
};
#endif
| [
"frigolit@frigolit.net"
] | frigolit@frigolit.net |
411c84f59c5d9b2ddc9b687d797eff09888461f6 | 22a0106720df168e5d0f42df9d649cc5c4c098c6 | /aa.cpp | ae9a6ff934809343a7ac3af04bc8ced1309a1280 | [] | no_license | ledsar/lagi | 0faa536766aa10fc2f7859369a3352103b376f62 | 9cd2f6bcebb1514fa9a42c3e07e25e473a4e4912 | refs/heads/master | 2020-05-30T18:35:38.316896 | 2015-05-01T09:00:41 | 2015-05-01T09:00:41 | 34,893,504 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10 | cpp | class Aa;
| [
"desreverliamesserdda@yahoo.com"
] | desreverliamesserdda@yahoo.com |
19ccc1631d883309f867a606e5341cb236fe5866 | 9a3b9d80afd88e1fa9a24303877d6e130ce22702 | /src/Providers/UNIXProviders/BGPRoutingPolicy/tests/BGPRoutingPolicy.Tests/UNIX_BGPRoutingPolicyFixture.cpp | 6db55d49915aa6eb92911e04bd2725c044f9711d | [
"MIT"
] | permissive | brunolauze/openpegasus-providers | 3244b76d075bc66a77e4ed135893437a66dd769f | f24c56acab2c4c210a8d165bb499cd1b3a12f222 | refs/heads/master | 2020-04-17T04:27:14.970917 | 2015-01-04T22:08:09 | 2015-01-04T22:08:09 | 19,707,296 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,471 | cpp | //%LICENSE////////////////////////////////////////////////////////////////
//
// Licensed to The Open Group (TOG) under one or more contributor license
// agreements. Refer to the OpenPegasusNOTICE.txt file distributed with
// this work for additional information regarding copyright ownership.
// Each contributor licenses this file to you under the OpenPegasus Open
// Source License; you may not use this file except in compliance with the
// 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 "UNIX_BGPRoutingPolicyFixture.h"
#include <BGPRoutingPolicy/UNIX_BGPRoutingPolicyProvider.h>
UNIX_BGPRoutingPolicyFixture::UNIX_BGPRoutingPolicyFixture()
{
}
UNIX_BGPRoutingPolicyFixture::~UNIX_BGPRoutingPolicyFixture()
{
}
void UNIX_BGPRoutingPolicyFixture::Run()
{
CIMName className("UNIX_BGPRoutingPolicy");
CIMNamespaceName nameSpace("root/cimv2");
UNIX_BGPRoutingPolicy _p;
UNIX_BGPRoutingPolicyProvider _provider;
Uint32 propertyCount;
CIMOMHandle omHandle;
_provider.initialize(omHandle);
_p.initialize();
for(int pIndex = 0; _p.load(pIndex); pIndex++)
{
CIMInstance instance = _provider.constructInstance(className,
nameSpace,
_p);
CIMObjectPath path = instance.getPath();
cout << path.toString() << endl;
propertyCount = instance.getPropertyCount();
for(Uint32 i = 0; i < propertyCount; i++)
{
CIMProperty propertyItem = instance.getProperty(i);
if (propertyItem.getType() == CIMTYPE_REFERENCE) {
CIMValue subValue = propertyItem.getValue();
CIMInstance subInstance;
subValue.get(subInstance);
CIMObjectPath subPath = subInstance.getPath();
cout << " Name: " << propertyItem.getName().getString() << ": " << subPath.toString() << endl;
Uint32 subPropertyCount = subInstance.getPropertyCount();
for(Uint32 j = 0; j < subPropertyCount; j++)
{
CIMProperty subPropertyItem = subInstance.getProperty(j);
cout << " Name: " << subPropertyItem.getName().getString() << " - Value: " << subPropertyItem.getValue().toString() << endl;
}
}
else {
cout << " Name: " << propertyItem.getName().getString() << " - Value: " << propertyItem.getValue().toString() << endl;
}
}
cout << "------------------------------------" << endl;
cout << endl;
}
_p.finalize();
}
| [
"brunolauze@msn.com"
] | brunolauze@msn.com |
10076d9b1a2e5e023cfd7026bb7d593d2980bb16 | ab3e1070934f7e1f6011fda6ff3013aecbb7a04a | /BackToOrigin/origin_check.cpp | 23165f396d2ef5e0c7930dd6bab74bb15dd56108 | [] | no_license | Chubek/CodingChallenges | 43fe117aaa8143e5c7f693d5c76563e824f401ae | cd2cccde512b0ce7af05b5764f7e81e16d623ded | refs/heads/master | 2020-04-06T07:07:39.036746 | 2019-07-28T17:53:19 | 2019-07-28T17:53:19 | 62,030,561 | 8 | 9 | null | null | null | null | UTF-8 | C++ | false | false | 604 | cpp | #include <iostream>
#include <string>
bool back_to_origin(const std::string &moves)
{
signed int vector[] = {0, 0};
for (auto &c : moves)
{
switch (c)
{
case 'U':
vector[1] += 1;
break;
case 'D':
vector[1] -= 1;
break;
case 'R':
vector[0] += 1;
break;
case 'L':
vector[0] -= 1;
break;
}
}
if (vector[0] == 0 && vector[1] == 0)
return true;
else
return false;
}
| [
"noreply@github.com"
] | noreply@github.com |
c9199a46a381454bbb240ad10051931495bafd6f | 702e1a904dcc4b94696c5c972224e35a054d87f6 | /Client/Headers/MainApp.h | 18486fc15d3203791ad13a4608d3904552e1b4eb | [] | no_license | KFGD/Graduation_Project_DOD | e27dafa94204d85ff141f00cd7fdc02a440984de | 4386b492f1e7dce354585ed298e35de010b763dc | refs/heads/master | 2023-01-31T18:15:31.849603 | 2020-12-15T06:01:31 | 2020-12-15T06:01:31 | 285,205,998 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 855 | h | #pragma once
#include "Base.h"
#include "Defines.h"
#include "Client_Defines.h"
// System
class GraphicDevice;
class InputDevice;
class ModeController;
class CameraController;
class KeyManager;
class MainApp final :
public Base
{
private:
explicit MainApp();
virtual ~MainApp() = default;
private:
bool Initialize();
public:
int Update(const double timeDelta);
bool Render();
private:
bool ReadySystem(const HWND hWnd, const bool bWinMode, const UINT sizeX, const UINT sizeY);
private:
GraphicDevice* mGraphicDeviceSys = nullptr;
InputDevice* mInputDevice = nullptr;
private:
ModeController* mModeController = nullptr;
CameraController* mCameraController = nullptr;
KeyManager* mKeyManager = nullptr;
private:
LPDIRECT3DDEVICE9 mGraphicDevice = nullptr;
public:
static MainApp* Create();
virtual void Free() override;
};
| [
"kky960105@naver.com"
] | kky960105@naver.com |
3f1ef80e7eca2c8b92e43bdda6868143548e42e4 | 794e7fb625ed41880f035360652347c5303e1319 | /StellarFay/StellarFay/SourceCode/ObjMeshShaderWrapper.cpp | f5abbc7ea508043cb75e3b4a25b145c0257712dc | [] | no_license | Rikuya-Matsuo/SF | 15c63045db883e127bcc591381a20613bb9157a1 | 20c61cc40547d4248fa1002d3bf46c748c332bfc | refs/heads/main | 2023-05-17T10:52:02.875239 | 2021-06-07T06:13:51 | 2021-06-07T06:13:51 | 357,021,501 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,056 | cpp | #include "ObjMeshShaderWrapper.h"
#include "GameSystem.h"
#include "Renderer.h"
Shader * ObjMeshShaderWrapper::mObjMeshShader = nullptr;
ObjMeshShaderWrapper::ObjMeshShaderWrapper(Shader * shader)
{
if (!mObjMeshShader)
{
mObjMeshShader = RENDERER_INSTANCE.GetShader("Shaders/ObjMesh.vert", "Shaders/ObjMesh.frag");
}
mShader = (!shader) ? mObjMeshShader : shader;
}
ObjMeshShaderWrapper::~ObjMeshShaderWrapper()
{
}
void ObjMeshShaderWrapper::InputPolyUniforms(const Mesh::ObjectData::PolyGroup * polyGroup) const
{
const Mesh::MtlData * mtl = polyGroup->mUsemtl;
// ディゾルブ転送
mShader->SetUniform1f("dissolve", mtl->GetDissolve());
// テクスチャ転送
mShader->SetUniform1i("tex0", 0);
Texture::ActivateTextureUnit(0);
const Texture * tex = mtl->GetDiffuseTexture();
if (tex)
{
tex->Activate();
}
}
//////////////////////////////////////////////////////////////
// Project : StellarFay
// Copyright (c) 2021 Rikuya Matsuo. All rights reserved.
//////////////////////////////////////////////////////////////
| [
"felid.codas@gmail.com"
] | felid.codas@gmail.com |
f6e985d3340df64ae56de6b68d8bd63c41be6ef6 | 3b8ce6f63eb7155851776832c8d427f03005d732 | /LineTracer.cpp | ee5906d05e3f845c9554dd64fc5ac169ceabfd64 | [] | no_license | nenikitov/RayCaster | 510ada77e32103814d5ee6bddb4d9c6040fc795f | d5e0111153295a3fab013e372425021a7c94885d | refs/heads/main | 2023-03-31T04:40:40.313768 | 2021-04-01T14:07:39 | 2021-04-01T14:07:39 | 350,783,437 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,479 | cpp | #include "LineTracer.h"
#include <corecrt_math_defines.h>
LineTracer::LineTracer(Level& level) : level(level)
{
}
Intersection LineTracer::findIntersection(double startX, double startY, double rotation)
{
const unsigned int tileSize = this->level.getTileSize();
const double tn = tan(-rotation * M_PI / 180);
const double offsetX = fmod(startX, 1);
const double offsetY = fmod(startY, 1);
// Test vertical walls
Intersection verticalIntersection = Intersection(0, 0, 0, WallDirection::UP, false);
// If facing up or down
if (sin(-rotation * M_PI / 180) >= 0)
verticalIntersection = lineTrace(startX, startY, tn, WallDirection::UP);
else
verticalIntersection = lineTrace(startX, startY, tn, WallDirection::DOWN);
// Test for horizontal walls
Intersection horizontalIntersection = Intersection(0, 0, 0, WallDirection::RIGHT, false);
// If facing right or left
if (cos(-rotation * M_PI / 180) >= 0)
horizontalIntersection = lineTrace(startX, startY, tn, WallDirection::RIGHT);
else
horizontalIntersection = lineTrace(startX, startY, tn, WallDirection::LEFT);
bool foundHorizontal = horizontalIntersection.getIntersects();
bool foundVertical = verticalIntersection.getIntersects();
// Return empty intersection if none exists
if (!foundHorizontal && !foundVertical)
return Intersection(0, 0, 0, WallDirection::UP, false);
// Return the one that exists
else if (!foundHorizontal && foundVertical)
return verticalIntersection;
else if (foundHorizontal && !foundVertical)
return horizontalIntersection;
// Or return the closest one if both exists
else
{
double distHor =
abs(horizontalIntersection.getX() - startX) * abs(horizontalIntersection.getX() - startX)
+ abs(horizontalIntersection.getY() - startY) * abs(horizontalIntersection.getY() - startY);
double distVert =
abs(verticalIntersection.getX() - startX) * abs(verticalIntersection.getX() - startX)
+ abs(verticalIntersection.getY() - startY) * abs(verticalIntersection.getY() - startY);
if (distVert < distHor)
return verticalIntersection;
else
return horizontalIntersection;
}
}
Intersection LineTracer::lineTrace(double startX, double startY, double tn, WallDirection direction)
{
const double offsetX = fmod(startX, 1);
const double offsetY = fmod(startY, 1);
switch (direction)
{
case WallDirection::UP:
// Check for walls in the direction
for (unsigned int i = 0; i < this->MAX_TESTS; i++)
{
double intersectionX = startX + (offsetY + i) / tn;
double intersectionY = startY - offsetY - i - 0.001;
unsigned int tile = level.tileAt(intersectionX, intersectionY);
if (tile)
return Intersection(intersectionX, intersectionY, tile, WallDirection::UP, true);
}
// Nothing found, return empty intersection
return Intersection(0, 0, 0, WallDirection::UP, false);
break;
case WallDirection::DOWN:
// Check for walls in the direction
for (unsigned int i = 0; i < this->MAX_TESTS; i++)
{
double intersectionX = startX + (i + 1 - offsetY) / -tn;
double intersectionY = startY + i + 1 - offsetY + 0.001;
unsigned int tile = level.tileAt(intersectionX, intersectionY);
if (tile)
return Intersection(intersectionX, intersectionY, tile, WallDirection::DOWN, true);
}
// Nothing found, return empty intersection
return Intersection(0, 0, 0, WallDirection::DOWN, false);
break;
case WallDirection::RIGHT:
// Check for walls in the direction
for (unsigned int i = 0; i < this->MAX_TESTS; i++)
{
double intersectionX = startX + i + 1 - offsetX + 0.001;
double intersectionY = startY - (i + 1 - offsetX) * tn;
unsigned int tile = level.tileAt(intersectionX, intersectionY);
if (tile)
return Intersection(intersectionX, intersectionY, tile, WallDirection::RIGHT, true);
}
// Nothing found, return empty intersection
return Intersection(0, 0, 0, WallDirection::RIGHT, false);
break;
case WallDirection::LEFT:
// Check for walls in the direction
for (unsigned int i = 0; i < this->MAX_TESTS; i++)
{
double intersectionX = startX - offsetX - i - 0.001;
double intersectionY = startY - (offsetX + i) * -tn;
unsigned int tile = level.tileAt(intersectionX, intersectionY);
if (tile)
return Intersection(intersectionX, intersectionY, tile, WallDirection::LEFT, true);
}
// Nothing found, return empty intersection
return Intersection(0, 0, 0, WallDirection::LEFT, false);
break;
}
}
| [
"nenikitov@mail.ru"
] | nenikitov@mail.ru |
2182bb98522a32d8a8056f554e83cad116d5ddac | 46d4712c82816290417d611a75b604d51b046ecc | /Samples/Win7Samples/netds/winsock/rnr2/rnrcs.cpp | 05b55077597aaf65e93f6cca6dd2cb5c83e205a8 | [
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] | permissive | ennoherr/Windows-classic-samples | 00edd65e4808c21ca73def0a9bb2af9fa78b4f77 | a26f029a1385c7bea1c500b7f182d41fb6bcf571 | refs/heads/master | 2022-12-09T20:11:56.456977 | 2022-12-04T16:46:55 | 2022-12-04T16:46:55 | 156,835,248 | 1 | 0 | NOASSERTION | 2022-12-04T16:46:55 | 2018-11-09T08:50:41 | null | UTF-8 | C++ | false | false | 50,763 | cpp | //----------------------------------------------------------------------------
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (C) 1998 - 2000 Microsoft Corporation. All Rights Reserved.
//
// Module:
// RnrCs.cpp
//
// Abstract:
// In a traditional Winsock 1.1 client/server program, the server
// binds itself to a well known port of a particular protocol family.
// Then, any client can talk to the server only if it knows the server's
// addressing infomation which includes the server's address, protocol,
// and socket type.
//
// The Winsock 2 Name Resolution and Registration (RnR) provides a unified
// API set for client to search for registered services without having any
// prior knowledge of addressing information. Basically, a server wants to
// register its existence within one or more name spaces through a friendly
// service instance name and associate itself to a service class GUID.
// Client application will be able to find the addressing
// information of a server by the friendly name and class GUID
// in a name space.
//
// In this sample, the server program converts the user supplied Type Id
// into a service class GUID by SVCID_NETWARE() macro. (You can also
// generate your own service class GUID using uuidgen.exe or guidgen.exe
// and distribute this GUID to your client program.) It then checks the
// availability of various kind of name space providers and install this
// service class by filling out the relevant service class information
// with NS_NTDS (NT Directory Service name space provider available in Windows 2000)
// and/or NS_SAP (Service Advertising Protocol name space provider available
// both in Windows NT 4 and Windows 2000) name spaces whenever they are available.
// If NS_NTDS has been installed, it binds itself to UDP protocol addresses
// and a port number dynamically chosen by the system. If NS_SAP has been
// installed, it also binds itself to a IPX protocol address and a socket
// number chosen by the system. After filling out its bound socket addresses,
// it advertises its availability through a service name supplied by a user.
// For each bound non-blocking socket addresses, the server tries to
// receive any datagram sent by any client and print out the client's socket
// addressing information if a datagram is received.
// When a user hits CTRL-C, the server program will unregister this
// service instance, remove the service class and close all sockets.
//
// The client program converts the user supplied Type Id into a service
// class GUID by SVCID_NETWARE() macro, such that it can find any SAP
// predefined services (e.g. file server Type Id is 4) or the corresponding
// advertised server program. If the user supplies a service name, it
// will just look up the service with the same service name and Type Id.
// If the user supplies a wild card "*" for the service name, it will try
// to look up all registered services with the same
// Type Id. For each service program found, it prints out the socket addressing
// information of the service program and sends a message to it.
//
// NOTE:
// (1) To exploit the NS_NTDS name space (Active Directory):
// (a) client and server machines should have Windows 2000 or later installed and both
// machines should be members of a Windows 2000 domain.
// (b) If the server program is running in the security context of Domain Admins,
// you should have no problem in publishing the service.
// (c) If the server program is running in the context of a Domain Users, Domain
// Admins have to modify the access control list (ACLs) on the WinsockServices
// container:
// From the Active Directory Users and Computers MMC snap-in, access the View menu
// and select Advanced Features. Under the System container is another container
// listed as WinsockServices. Open the WinsockServices container,
// right-click Properties->Security, add your desired user/group with Full Control
// permission. Make sure this applies onto "this object and all child objects"
// by clicking the "Advanced..." button and "View/Edit..." your selected permission
// entry.
// (2) To advertise in the SAP name space, server program machine should have
// NWLink IPX/SPX Compatible Transport protocol and SAP Agent service installed.
// (3) To lookup servers in the SAP name space, client program machine should have
// NWLink IPX/SPX Compatible Transport protocol installed.
// (4) When the server is running on a mutihomed machine, the SAP name space
// provider will only make the first registered ipx address available, other
// ipx addresses are ignored.
//
// Usage: RnrCs
// -c (running this program as a client)
// -s (running this program as a server)
// -t server_type_id (default is: 200)
// -n server_instance_name (default is: MyServer)
// -p provider_name (default is: NS_ALL)
// (e.g. NS_NTDS, NS_SAP, NS_ALL)
// Examples:
// RnrCs -s -n MyServer ....Run as server /w server_type_id of 200, service
// instance name of MyServer
// RnrCs -c -n * .............Run as client and find all servers /w server_type_id
// of 200 from all available name spaces
// RnrCs -c -n * -p NS_SAP ...Run as client and find all servers /w server_type_id
// of 200 from the SAP name space
// RnrCs -c -t 4 -n * ........Run as client and find all SAP file servers
// Hit Ctrl-C to quit the server program
//
// Build:
// Use the headers and libs from the April98 Platform SDK or later.
// Link with ws2_32.lib
//
// Author: Frank K. Li - Microsoft Developer Support
//
//----------------------------------------------------------------------------
#ifdef _IA64_
#pragma warning (disable: 4127 4267)
#endif
#include <winsock2.h>
#include <ws2tcpip.h>
#include <wspiapi.h>
#include <svcguid.h>
#include <wsipx.h>
#include <wsnwlink.h>
#include <nspapi.h>
#include <stdio.h>
#include <stdlib.h>
#include <strsafe.h>
#define DEFAULT_STRING_LEN 256
void GetSockAddrString(SOCKADDR_STORAGE* pSAddr, int addrlen, char * dest, int destlen);
void SetIpPort(SOCKADDR_STORAGE *dest, SOCKADDR_STORAGE *src);
void DumpServiceClassInfo(LPWSASERVICECLASSINFO lpSci);
//-------Server side structures and functions-------------------
// Global socket handles
const int g_nMaxNumOfCSAddr = 20; // advertise at most 10 addresses
const int g_nMaxNumOfSocks = 3; // one for udp/ipv4, one for udp/ipv6, another for ipx
int g_nNumOfUsedSocks = 0; // number of socket created
SOCKET g_aSock[g_nMaxNumOfSocks] = {INVALID_SOCKET, INVALID_SOCKET, INVALID_SOCKET};
CSADDR_INFO g_aCSAddr[g_nMaxNumOfCSAddr] = {{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0}};
SOCKADDR_STORAGE g_aSockAddr[g_nMaxNumOfCSAddr] = {{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0}}; // SOCKADDR buffer
GUID g_MyGuid; // guid for this service class
WSAQUERYSET g_QS = {0}; // QuerySet to advertise service
SOCKADDR_STORAGE ss_in = {0}; // socket address for AF_INET
SOCKADDR_IPX sa_ipx = {0}; // socket address for AF_IPX
BOOL g_fSap = FALSE; // available name space providers on local machine
BOOL g_fNtds = FALSE;
DWORD g_dwNumNs = 0; // total number of name space providers
BOOL fEndProgram = FALSE; // signal the end of program when user hits "Ctrl-C"
BOOL DoRnrServer(char * pszServerName, int nServerType);
BOOL InstallClass(int nServerType);
BOOL Advertise(char* pszServerName);
BOOL ServerRecv();
BOOL CheckAvailableNameSpaceProviders(BOOL& fNsSap, BOOL& fNsNtds);
BOOL GetBoundIpxAddr(SOCKET soc, SOCKADDR_IPX * pSaIpx, int nAdapter);
BOOL WINAPI CtrlHandler ( DWORD dwEvent );
//-------Client side functions------------------------------
void DoRnrClient (int nServiceType, char * pszServerName, DWORD dwNameSpace);
void ClientSend(CSADDR_INFO* lpcsaBuffer);
void PrintError (char* errfunc);
#define OFFSET 1024 // a large buffer to hold returned WSAQUERYSET
//--------------------------------------------------------------
void Usage(char * pszProgramName)
{
fprintf(stderr, "Usage: %s\n", pszProgramName);
fprintf(stderr, " -c (running this program as a client)\n");
fprintf(stderr, " -s (running this program as a server)\n");
fprintf(stderr, " -t server_type_id (default is: 200)\n");
fprintf(stderr, " -n server_instance_name (default is: MyServer) \n");
fprintf(stderr, " -p provider name (default is: NS_ALL) \n");
fprintf(stderr, " (e.g. NS_NTDS, NS_SAP, NS_ALL)\n");
fprintf(stderr, "Examples:\n");
fprintf(stderr, "RnrCs -s -n MyServer ...Run as server /w server_type_id of 200, service\n");
fprintf(stderr, " instance name of MyServer\n");
fprintf(stderr, "RnrCs -c -n * ............Run as client and find all servers /w server_type_id\n");
fprintf(stderr, " of 200 from all available name spaces\n");
fprintf(stderr, "RnrCs -c -n * -p NS_SAP ..Run as client and find all servers /w server_type_id\n");
fprintf(stderr, " of 200 from the SAP name space\n");
fprintf(stderr, "RnrCs -c -t 4 -n * .......Run as client and find all SAP file servers\n");
fprintf(stderr, "Hit Ctrl-C to quit the server program\n");
}
void __cdecl main (int argc, char *argv[])
{
char * pszServerName = "MyServer"; // default server instance name
int nServerType = 200; // default server type id
char * pszNSProvider = "NS_ALL";
DWORD dwNameSpace = NS_ALL;
int i = 0;
BOOL fServer = TRUE; // by default, running this program as the server
// allow the user to override settings with command line switches
for (i = 1; i < argc; i++)
{
if ((*argv[i] == '-') || (*argv[i] == '/'))
{
switch (tolower(*(argv[i]+1)))
{
case 'n': // server instance name
pszServerName = argv[++i];
break;
case 't': // server_type, this will be used as the base for the Server class id
nServerType = atoi(argv[++i]);
break;
case 'c':
fServer = FALSE;
break;
case 's':
fServer = TRUE;
break;
case 'p':
pszNSProvider = argv[++i];
if (_strnicmp("NS_NTDS", pszNSProvider, strlen("NS_NTDS")) == 0)
dwNameSpace = NS_NTDS;
else if (_strnicmp("NS_SAP", pszNSProvider, strlen("NS_SAP")) == 0)
dwNameSpace = NS_SAP;
// default is NS_ALL
break;
case 'h':
case '?':
default:
Usage(argv[0]);
return;
}
}
else
{
Usage(argv[0]);
return;
}
}
if (fServer)
{
// check user input
if (strcmp(pszServerName, "*") == 0)
{
printf("You can't supply wildcard (*) server instance name to run this server\n");
Usage(argv[0]);
return;
}
}
__try
{
// init winsock
WSADATA wd;
int nRet;
if ( (nRet = WSAStartup (MAKEWORD (2, 2), &wd)) != 0)
{
printf ("Unable to start Winsock 2. Error: %d\n", nRet);
__leave;
}
if (fServer)
{
// running as a server program
DoRnrServer(pszServerName, nServerType);
}
else
{
// running as a client program
DoRnrClient(nServerType, pszServerName, dwNameSpace);
}
}
__finally
{
if (fServer)
{
SetConsoleCtrlHandler(CtrlHandler, FALSE);
}
WSACleanup();
}
}
//---------------------------------------------
// server side routines
//---------------------------------------------
//---------------------------------------------------------------------------
// FUNCTION: BOOL DoRnrServer(char * pszServerName, int nServerType)
//
// PURPOSE: The driver for the server side code. It forms the global
// class id "g_MyGuid" for this service class, installs this
// service class, advertises the service name "pszServerName" with
// the associated bound SOCKADDR addresses and then loop through
// for data sent by client. This routine returns if user hits "Ctrl-C"
// or any error encountered.
//
// RETURNS:
// TRUE if user hits "Ctrl-C" to end the server program.
// FALSE if there is any error encountered.
//
//---------------------------------------------------------------------------
BOOL DoRnrServer(char * pszServerName, int nServerType)
{
// I am using SVCID_NETWARE macro to form a common class id for the
// client and server program such that the client program can also query
// some known SAP services on the network without running this program
// as a server.
// You can also generate your own class id by uuidgen.exe or guidgen.exe and
// distribute the class id to client program.
//
// Please check svcguid.h for details about the macro.
GUID guidNW = SVCID_NETWARE(nServerType);
memcpy(&g_MyGuid, &guidNW, sizeof(GUID));
if (!SetConsoleCtrlHandler(CtrlHandler, TRUE))
{
printf ("SetConsoleCtrlHandler failed to install console handler: %d\n",
GetLastError());
return FALSE;
}
// Install the server class
if (!InstallClass(nServerType))
{
return FALSE;
}
// advertise the server instance
if (!Advertise(pszServerName))
{
return FALSE;
}
// Make our bound sockets non-blocking such that
// we can loop and test for data sent by client
// without blocking.
u_long arg = 1L;
for (int i = 0; i < g_nNumOfUsedSocks; i++)
{
// make the socket as non-blocking socket
if (ioctlsocket(g_aSock[i], FIONBIO, &arg) == SOCKET_ERROR)
{
printf("ioctlsocket[%d] error %d\n", i, WSAGetLastError());
return FALSE;
}
}
// receive data from client who find our address thru Winsock 2 RnR
for (;;)
{
if (ServerRecv() == FALSE)
{
return FALSE;
}
if (fEndProgram)
return TRUE;
Sleep(100);
}
}
//---------------------------------------------------------------------------
// FUNCTION: InstallClass(int nServerType)
//
// PURPOSE: Install a service class in NTDS and SAP name spaces if they are
// available on this machine. "nServerType" is a numerical number used
// to generate a service class id by using SVCID_NETWARE macro as shown in
// the main program.
// The name of this service class is obtained by composing "nServerType"
// with the string "TypeId.
//
// RETURNS:
// TRUE if succeed otherwise FALSE
//
//---------------------------------------------------------------------------
BOOL InstallClass(int nServerType)
{
WSASERVICECLASSINFO sci;
WSANSCLASSINFO aNameSpaceClassInfo[4] = {{0},{0},{0},{0}};
DWORD dwSapId = nServerType;
DWORD dwZero = 0;
TCHAR szServiceClassName[DEFAULT_STRING_LEN] = {'\0'};
int nRet = 0;
DWORD dwUdpPort = 0; // we use dynamic generated port number
HRESULT hRet;
if (FAILED(hRet = StringCchPrintf(szServiceClassName,
sizeof(szServiceClassName)/sizeof(szServiceClassName[0]),
"TypeId %d",
nServerType
)))
{
printf("StringCchPrintf failed: 0x%x\n",hRet);
return FALSE;
}
printf("Installing ServiceClassName: %s\n", szServiceClassName);
BOOL fSap = FALSE;
BOOL fNtds = FALSE;
// see what name space providers are available
if (!CheckAvailableNameSpaceProviders(fSap, fNtds))
return FALSE;
// save a copy
g_fSap = fSap;
g_fNtds = fNtds;
// our total number of interested name space providers
if (fSap)
g_dwNumNs++;
if (fNtds)
g_dwNumNs++;
// setup Service Class info
SecureZeroMemory(&sci,sizeof(sci));
sci.lpServiceClassId = (LPGUID) &g_MyGuid;
sci.lpszServiceClassName = (LPSTR) szServiceClassName;
sci.dwCount = g_dwNumNs * 2; // each name space has 2 NameSpaceClassInfo
sci.lpClassInfos = aNameSpaceClassInfo;
SecureZeroMemory(aNameSpaceClassInfo,sizeof(WSANSCLASSINFO)*4);
DWORD i =0; // index to array of WSANSCLASSINFO
// common service class registration in NTDS and SAP name spaces
if (fNtds)
{
// NTDS setup
printf("NTDS name space class installation\n");
aNameSpaceClassInfo[i].lpszName = SERVICE_TYPE_VALUE_CONN;
aNameSpaceClassInfo[i].dwNameSpace = NS_NTDS;
aNameSpaceClassInfo[i].dwValueType = REG_DWORD;
aNameSpaceClassInfo[i].dwValueSize = sizeof(DWORD);
aNameSpaceClassInfo[i].lpValue = &dwZero;
i++; // increment of the index
aNameSpaceClassInfo[i].lpszName = SERVICE_TYPE_VALUE_UDPPORT;
aNameSpaceClassInfo[i].dwNameSpace = NS_NTDS;
aNameSpaceClassInfo[i].dwValueType = REG_DWORD;
aNameSpaceClassInfo[i].dwValueSize = sizeof(DWORD);
aNameSpaceClassInfo[i].lpValue = &dwUdpPort;
i++; // increment of the index
}
if (fSap)
{
// SAP setup
printf("SAP name space class installation\n");
aNameSpaceClassInfo[i].lpszName = SERVICE_TYPE_VALUE_CONN;
aNameSpaceClassInfo[i].dwNameSpace = NS_SAP;
aNameSpaceClassInfo[i].dwValueType = REG_DWORD;
aNameSpaceClassInfo[i].dwValueSize = sizeof(DWORD);
aNameSpaceClassInfo[i].lpValue = &dwZero;
i++; // increment of the index
aNameSpaceClassInfo[i].lpszName = SERVICE_TYPE_VALUE_SAPID;
aNameSpaceClassInfo[i].dwNameSpace = NS_SAP;
aNameSpaceClassInfo[i].dwValueType = REG_DWORD;
aNameSpaceClassInfo[i].dwValueSize = sizeof(DWORD);
aNameSpaceClassInfo[i].lpValue = &dwSapId;
}
// Install the service class information
DumpServiceClassInfo(&sci);
nRet = WSAInstallServiceClass(&sci);
if (nRet == SOCKET_ERROR)
{
printf("WSAInstallServiceClass error %d\n", WSAGetLastError());
return FALSE;
}
return TRUE;
}
//---------------------------------------------------------------------------
// FUNCTION: Advertise(char* pszServerName)
//
// PURPOSE: Given the name of this service instance "pszServerName",
// advertise this instance to the available name spaces.
//
// RETURNS:
// TRUE if succeed otherwise FALSE
//
//---------------------------------------------------------------------------
BOOL Advertise(char* pszServerName)
{
int nRet = 0;
int i=0; // number of socket created
int nNumOfCSAddr = 0; // number of bound socket addresses
// Advertizing
// Set up the WSAQuery data
SecureZeroMemory(&g_QS,sizeof(WSAQUERYSET));
g_QS.dwSize = sizeof(WSAQUERYSET);
g_QS.lpszServiceInstanceName = (LPSTR)pszServerName; // service instance name
g_QS.lpServiceClassId = &g_MyGuid; // associated service class id
g_QS.dwNameSpace = NS_ALL; // advertise to all name spaces
g_QS.lpNSProviderId = NULL;
g_QS.lpcsaBuffer = g_aCSAddr; // our bound socket addresses
g_QS.lpBlob = NULL;
// Set up the g_aCSAddr data
if (g_fNtds)
{
SOCKET_ADDRESS_LIST *slist=NULL;
struct addrinfo *res=NULL,
*resptr=NULL,
hints;
char *addrbuf=NULL;
DWORD dwBytes=0;
SecureZeroMemory(&hints,sizeof(hints));
hints.ai_flags = AI_PASSIVE;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_protocol = IPPROTO_UDP;
nRet = getaddrinfo(NULL, "0", &hints, &res);
if ((nRet != 0) || (res == NULL))
{
return FALSE;
}
resptr = res;
while (resptr)
{
g_aSock[i] = socket(resptr->ai_family, resptr->ai_socktype, resptr->ai_protocol);
if (g_aSock[i] == INVALID_SOCKET)
{
printf("socket error %d\n", WSAGetLastError());
freeaddrinfo(res);
return FALSE;
}
// bind to local host ip addresses and let system to assign a port number
nRet = bind ( g_aSock[i], resptr->ai_addr, (int)resptr->ai_addrlen);
if ( SOCKET_ERROR == nRet )
{
printf("bind error %d\n", WSAGetLastError());
freeaddrinfo(res);
return FALSE;
}
int cb = sizeof(ss_in);
if (getsockname(g_aSock[i], (SOCKADDR *) &ss_in, &cb) == SOCKET_ERROR)
{
printf("getsockname error %d\n", WSAGetLastError());
freeaddrinfo(res);
return FALSE;
}
nRet = WSAIoctl(g_aSock[i], SIO_ADDRESS_LIST_QUERY, NULL, 0, NULL, 0, &dwBytes, NULL, NULL);
if (nRet == SOCKET_ERROR)
{
addrbuf = (char *)HeapAlloc(GetProcessHeap(), 0, dwBytes);
if (addrbuf == NULL)
{
freeaddrinfo(res);
return FALSE;
}
nRet = WSAIoctl(g_aSock[i], SIO_ADDRESS_LIST_QUERY, NULL, 0, addrbuf, dwBytes, &dwBytes, NULL, NULL);
if (nRet == SOCKET_ERROR)
{
printf("WSAIoctl failed: %d\n", WSAGetLastError());
HeapFree(GetProcessHeap(), 0, addrbuf);
freeaddrinfo(res);
return FALSE;
}
}
else
{
printf("WSAIoctl should have failed!\n");
freeaddrinfo(res);
return FALSE;
}
slist = (SOCKET_ADDRESS_LIST *)addrbuf;
if (resptr->ai_family == AF_INET)
printf("IPv4 addresses bound...\n");
else if (resptr->ai_family == AF_INET6)
printf("IPv6 addresses bound...\n");
else
printf("Unknown address family addresses bound...\n");
for (int j = 0; j < slist->iAddressCount ; j++)
{
if (j >= g_nMaxNumOfCSAddr)
{
printf("Max. number of socket address (%d) reached. We will not advertise extra ones\n", g_nMaxNumOfCSAddr);
break;
}
// Copy the address over
memcpy(&g_aSockAddr[j], slist->Address[j].lpSockaddr, slist->Address[j].iSockaddrLength);
// Set the port number our socket is actually bound to
SetIpPort(&g_aSockAddr[j],&ss_in);
char temp[128] = {'\0'};
GetSockAddrString (&g_aSockAddr[j], slist->Address[j].iSockaddrLength, temp, 128);
printf("Address %40s\n", temp);
g_aCSAddr[j].iSocketType = SOCK_DGRAM;
g_aCSAddr[j].iProtocol = IPPROTO_UDP;
g_aCSAddr[j].LocalAddr.lpSockaddr = (struct sockaddr *)&g_aSockAddr[j];
g_aCSAddr[j].LocalAddr.iSockaddrLength = slist->Address[j].iSockaddrLength;
g_aCSAddr[j].RemoteAddr.lpSockaddr = (struct sockaddr *)&g_aSockAddr[j];
g_aCSAddr[j].RemoteAddr.iSockaddrLength = slist->Address[j].iSockaddrLength;
nNumOfCSAddr++; // increase the number SOCKADDR buffer used
}
i++; // increase the number of socket created
// Go to the next address
resptr = resptr->ai_next;
// Free the address buffer
HeapFree(GetProcessHeap(), 0, addrbuf);
addrbuf = NULL;
}
freeaddrinfo(res);
}
if (g_fSap && (nNumOfCSAddr < g_nMaxNumOfCSAddr))
{
// advertise into the NS_SAP name space if we still have enough
// socket address buffer
SecureZeroMemory(sa_ipx.sa_netnum,sizeof(sa_ipx.sa_netnum));
SecureZeroMemory(sa_ipx.sa_nodenum,sizeof(sa_ipx.sa_nodenum));
sa_ipx.sa_family = AF_IPX;
sa_ipx.sa_socket = 0;
g_aSock[i] = socket ( AF_IPX, SOCK_DGRAM, NSPROTO_IPX );
if ( INVALID_SOCKET == g_aSock[i] )
{
printf("socket error %d\n", WSAGetLastError());
return FALSE;
}
nRet = bind ( g_aSock[i], (SOCKADDR *) &sa_ipx, sizeof (sa_ipx) );
if ( SOCKET_ERROR == nRet )
{
printf("bind error %d\n", WSAGetLastError());
return FALSE;
}
//--------------Find out our bound ipx addresses------------
int cb = 0; // size variable
int nAdapters = 0; // number of adapters bound with IPX
// get the number of adapters
cb = sizeof(nAdapters);
nRet = getsockopt(g_aSock[i], NSPROTO_IPX, IPX_MAX_ADAPTER_NUM, (char *) &nAdapters, &cb);
if (nRet == SOCKET_ERROR)
{
printf("getsockopt error %d\n", WSAGetLastError());
return FALSE;
}
SOCKADDR_IPX* pSaIpx = NULL; // a pointer to our current SOCKADDR buffer
printf("IPX addresses bound...\n");
for (int nIdx = 0; nIdx < nAdapters; nIdx++)
{
if (nNumOfCSAddr >= g_nMaxNumOfCSAddr)
{
printf("Max. number of socket address (%d) reached. We will not advertise extra ones\n", g_nMaxNumOfCSAddr);
break;
}
// get the buffer for this SOCKADDR
pSaIpx = (SOCKADDR_IPX *) &g_aSockAddr[nNumOfCSAddr];
if (GetBoundIpxAddr(g_aSock[i], pSaIpx, nIdx) == FALSE)
{
printf("No valid bound IPX address at adapter index %d\n", nIdx);
// since this link is not available, nNumOfCSAddr will reuse the current SOCKADDR buffer
continue;
}
char temp[DEFAULT_STRING_LEN] = {'\0'};
GetSockAddrString (&g_aSockAddr[nNumOfCSAddr], sizeof(SOCKADDR_IPX), temp, DEFAULT_STRING_LEN);
printf("%40s\n", temp);
g_aCSAddr[nNumOfCSAddr].iSocketType = SOCK_DGRAM;
g_aCSAddr[nNumOfCSAddr].iProtocol = NSPROTO_IPX;
g_aCSAddr[nNumOfCSAddr].LocalAddr.lpSockaddr = (struct sockaddr *)&g_aSockAddr[nNumOfCSAddr];
g_aCSAddr[nNumOfCSAddr].LocalAddr.iSockaddrLength = sizeof(sa_ipx);
g_aCSAddr[nNumOfCSAddr].RemoteAddr.lpSockaddr = (struct sockaddr *)&g_aSockAddr[nNumOfCSAddr];
g_aCSAddr[nNumOfCSAddr].RemoteAddr.iSockaddrLength = sizeof(sa_ipx);
nNumOfCSAddr++;
}
i++; // increase the number of socket created
// Note: If g_fNtds is TRUE, this ipx address will be
// available from the NTDS name space too.
}
// update counters
g_QS.dwNumberOfCsAddrs = nNumOfCSAddr;
g_nNumOfUsedSocks = i;
// Call WSASetService
printf("Advertise server of instance name: %s ...\n", pszServerName);
nRet = WSASetService(&g_QS, RNRSERVICE_REGISTER, 0L);
if (nRet == SOCKET_ERROR)
{
printf("WSASetService error %d\n", WSAGetLastError());
return FALSE;
}
printf("Wait for client talking to me, hit Ctrl-C to terminate...\n");
return TRUE;
}
//---------------------------------------------------------------------------
// FUNCTION: GetBoundIpxAddr(SOCKET soc, SOCKADDR_IPX * pSaIpx, int nAdapter)
//
// PURPOSE: Given a bound socket "soc", fill up "pSaIpx" with a valid
// ipx address corresponding to the 0-based adapter index "nAdapter".
//
// RETURNS:
// TRUE if succeed otherwise FALSE
//
//---------------------------------------------------------------------------
BOOL GetBoundIpxAddr(SOCKET soc, SOCKADDR_IPX * pSaIpx, int nAdapter)
{
IPX_ADDRESS_DATA ipx_data = {0}; // see wsnwlink.h for details
int cb = 0; // size variable
int nRet = 0;
cb = sizeof ( IPX_ADDRESS_DATA );
SecureZeroMemory(&ipx_data,sizeof(IPX_ADDRESS_DATA));
ipx_data.adapternum = nAdapter;
nRet = getsockopt ( soc, NSPROTO_IPX, IPX_ADDRESS, (char *) &ipx_data, &cb );
if ( SOCKET_ERROR == nRet)
{
printf("getsockopt error %d\n", WSAGetLastError());
return FALSE;
}
cb = sizeof(SOCKADDR_IPX);
if (getsockname(soc, (SOCKADDR *) pSaIpx, &cb) == SOCKET_ERROR)
{
printf("getsockname error %d\n", WSAGetLastError());
return FALSE;
}
else
{
if (ipx_data.status == TRUE)
{
// this link is UP
memcpy(pSaIpx->sa_netnum, ipx_data.netnum, sizeof(pSaIpx->sa_netnum));
memcpy(pSaIpx->sa_nodenum, ipx_data.nodenum, sizeof(pSaIpx->sa_nodenum));
return TRUE;
}
else
return FALSE; // this link is DOWN
}
}
//---------------------------------------------------------------------------
// FUNCTION: CheckAvailableNameSpaceProviders(BOOL& fNsSap, BOOL& fNsNtds)
//
// PURPOSE: Check the avaliable name space providers, set fNsSap to TRUE if
// SAP is available, and fNsNtds to TRUE if NT Directory Service
// is avaialble.
//
// RETURNS:
// TRUE if succeed otherwise FALSE
//
// NOTE: In this sample, we are only interested to know if NS_NTDS or NS_SAP
// name space provoder is available.
//---------------------------------------------------------------------------
BOOL CheckAvailableNameSpaceProviders(BOOL& fNsSap, BOOL& fNsNtds)
{
LPWSANAMESPACE_INFO pInfo = NULL;
DWORD dwBufLen = 0;
PBYTE pBuf = NULL;
int nCount = 0;
int nRet = 0;
dwBufLen = 0;
fNsSap = fNsNtds = FALSE;
nRet = WSAEnumNameSpaceProviders(&dwBufLen, NULL);
if (nRet == SOCKET_ERROR)
{
if (WSAGetLastError() != WSAEFAULT)
{
printf("Error %d\n", WSAGetLastError());
return FALSE;
}
}
// dwBufLen contains the needed buffer size
pBuf = (PBYTE) HeapAlloc(GetProcessHeap(), 0, dwBufLen);
if (pBuf == NULL)
{
printf("\nCould not allocate buffer\n");
return FALSE;
}
nRet = WSAEnumNameSpaceProviders(&dwBufLen, (LPWSANAMESPACE_INFO)pBuf);
if (nRet == SOCKET_ERROR)
{
printf("Error: %d\n", WSAGetLastError());
HeapFree(GetProcessHeap(), 0, pBuf);
return FALSE;
}
//Loop thru the returned info
pInfo = (LPWSANAMESPACE_INFO)pBuf;
for (nCount = 0; nCount < nRet; nCount++)
{
switch (pInfo->dwNameSpace)
{
case NS_SAP:
fNsSap = TRUE;
break;
case NS_NTDS:
fNsNtds = TRUE;
break;
default:
break;
}
pInfo++;
}
HeapFree(GetProcessHeap(), 0, pBuf);
return TRUE;
}
//---------------------------------------------------------------------------
// FUNCTION: BOOL ServerRecv()
//
// PURPOSE: For each bound socket in g_aSock[], try to do a non-blocking
// receive and print out the peer's address information.
//
// RETURNS:
// TRUE if succeed otherwise FALSE
//---------------------------------------------------------------------------
BOOL ServerRecv()
{
int nBytesReceived = 0;
char szBuf[1024] = {'\0'};
SOCKADDR_STORAGE sa_peer = {0};
int nPeerAddrLen = 0;
for (int i = 0; i < g_nNumOfUsedSocks; i++)
{
nPeerAddrLen = sizeof(SOCKADDR_STORAGE);
// You can use "nBytesReceived = recv(g_aSock[i], szBuf, sizeof(szBuf), 0 );", if
// you don't want your peer's address information.
nBytesReceived = recvfrom(g_aSock[i], szBuf, sizeof(szBuf), 0, (SOCKADDR*)&sa_peer, &nPeerAddrLen);
if (nBytesReceived == SOCKET_ERROR)
{
int nRet = WSAGetLastError();
if (nRet == WSAEWOULDBLOCK || nRet == WSAEMSGSIZE)
continue;
else
{
printf("recv error: %d\n", nRet);
return FALSE;
}
}
else
{
printf("received: [%s ", szBuf);
char temp[DEFAULT_STRING_LEN] = {'\0'};
GetSockAddrString (&sa_peer, nPeerAddrLen, temp, DEFAULT_STRING_LEN);
printf(": %s]\n", temp);
}
}
return TRUE;
}
//---------------------------------------------------------------------------
// FUNCTION: BOOL WINAPI CtrlHandler ( DWORD dwEvent )
// Intercept CTRL-C or CTRL-BRK events and cause the server to
// initiate shutdown and cleanup.
//---------------------------------------------------------------------------
BOOL WINAPI CtrlHandler ( DWORD dwEvent )
{
int nRet = 0;
int i = 0;
WCHAR szGuid[MAX_PATH] = {'\0'};
HRESULT hRet;
switch (dwEvent)
{
case CTRL_C_EVENT:
case CTRL_BREAK_EVENT:
case CTRL_LOGOFF_EVENT:
case CTRL_SHUTDOWN_EVENT:
case CTRL_CLOSE_EVENT:
fEndProgram = TRUE;
printf("CtrlHandler: cleaning up...\n");
printf("delete service instance...\n");
nRet = WSASetService(&g_QS, RNRSERVICE_DELETE, 0L);
if (nRet == SOCKET_ERROR)
{
printf("WSASetService DELETE error %d\n", WSAGetLastError());
} else
printf(" Deleted.\n");
printf("Removing Service class ");
if (SUCCEEDED(hRet = StringCchPrintfW(szGuid,
sizeof(szGuid)/sizeof(szGuid[0]),
L"%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
g_MyGuid.Data1,
g_MyGuid.Data2,
g_MyGuid.Data3,
g_MyGuid.Data4[0],
g_MyGuid.Data4[1],
g_MyGuid.Data4[2],
g_MyGuid.Data4[3],
g_MyGuid.Data4[4],
g_MyGuid.Data4[5],
g_MyGuid.Data4[6],
g_MyGuid.Data4[7]
)))
{
wprintf(L"%s",szGuid);
}
printf("... \n");
nRet = WSARemoveServiceClass(&g_MyGuid);
if (nRet == SOCKET_ERROR)
{
printf("WSARemoveServiceClass error %d\n", WSAGetLastError());
} else
printf(" Removed.\n");
for (i = 0; i < g_nMaxNumOfSocks; i++)
{
if ( g_aSock[i] != INVALID_SOCKET )
{
closesocket ( g_aSock[i] );
g_aSock[i] = INVALID_SOCKET;
}
}
break;
default:
// unknown type--better pass it on.
return FALSE;
}
return TRUE;
}
//-------------------------------------
// Client side routines
//-------------------------------------
//---------------------------------------------------------------------------
// FUNCTION: void DoRnrClient (int nServiceType, char * pszServerName, DWORD dwNameSpace)
//
// PURPOSE: Given the service type id "nServiceType", the server instance name
// "pszServerName" and the name space to query "dwNameSpace",
// perform name resolution to the server and send a message to it.
// If "nServiceType" is some known SAP Id such as Print Queue (3),
// File Server (4), Job Server (5), Print Server (7), Archive
// Server (9), Remote Bridge Server (36) or Advertising Print Server
// (71), it will not send a message to the server.
//---------------------------------------------------------------------------
void DoRnrClient (int nServiceType, char * pszServerName, DWORD dwNameSpace)
{
static GUID guid = SVCID_NETWARE ( nServiceType ); //use this as the class id
WSAQUERYSET qs = {0};
AFPROTOCOLS afp[g_nMaxNumOfSocks] = {{AF_IPX, NSPROTO_IPX}, {AF_INET, IPPROTO_UDP}, {AF_INET6, IPPROTO_UDP}};
HANDLE hLookup = NULL;
DWORD dwResult = 0;
static char szName[100] = {'\0'};
BOOL fKnownSapId = FALSE;
DWORD dwLength = 0;
BYTE abyBuf[sizeof(WSAQUERYSET) + OFFSET] = {0}; // provide a sufficient large
// buffer for returned query set
WSAQUERYSET * pQS = (WSAQUERYSETA*) abyBuf;
HRESULT hRet;
if(FAILED(hRet = StringCchCopy(szName,
sizeof(szName)/sizeof(szName[0]),
pszServerName
)))
{
printf("StringCchCopy failed: 0x%x\n",hRet);
return;
}
SecureZeroMemory (&qs, sizeof (WSAQUERYSET));
qs.dwSize = sizeof (WSAQUERYSET);
qs.lpszServiceInstanceName = szName;
qs.lpServiceClassId = &guid;
qs.dwNameSpace = dwNameSpace;
qs.dwNumberOfProtocols = g_nMaxNumOfSocks;
qs.lpafpProtocols = afp;
SecureZeroMemory (abyBuf, sizeof (WSAQUERYSET) + OFFSET);
dwLength = sizeof(WSAQUERYSET) + OFFSET;
// some well known SAP name space services
if (nServiceType == 3 || nServiceType == 4 || nServiceType == 5 ||
nServiceType == 7 || nServiceType == 9 || nServiceType == 36 || nServiceType == 71)
fKnownSapId = TRUE;
if (WSALookupServiceBegin ( &qs,
LUP_RETURN_ADDR | LUP_RETURN_NAME,
&hLookup) == SOCKET_ERROR)
{
PrintError("WSALookupServiceBegin");
return;
}
printf ("Performing Query for service (type, name) = (%d, %s) . . .\n\n", nServiceType, pszServerName);
if (strcmp(pszServerName, "*") == 0)
{ // enumerate all service instances
for (;;)
{
dwResult = WSALookupServiceNext(hLookup,
0,
&dwLength,
pQS);
if (dwResult == SOCKET_ERROR)
{
if (WSAGetLastError() == WSAEFAULT)
{
printf("WSALookupServiceNext Error: Oops, we need a larger buffer size of : %d Bytes\n", dwLength);
}
else
{
PrintError("WSALookupServiceNext");
}
WSALookupServiceEnd (hLookup);
return;
}
if (!dwResult)
{
for (DWORD i = 0; i < pQS->dwNumberOfCsAddrs; i++)
{
SOCKADDR_STORAGE *mypt = (SOCKADDR_STORAGE *) pQS->lpcsaBuffer[i].RemoteAddr.lpSockaddr;
if (mypt)
{
// we have valid remote sockaddr
char temp[DEFAULT_STRING_LEN] = {'\0'};
printf ("Name[%d]: %30s", i, pQS->lpszServiceInstanceName);
GetSockAddrString (mypt, pQS->lpcsaBuffer[i].RemoteAddr.iSockaddrLength, temp, DEFAULT_STRING_LEN);
printf("%40s\n", temp);
if (! fKnownSapId)
ClientSend(&(pQS->lpcsaBuffer[i]));
}
}
}
}
}
else
{
dwResult = WSALookupServiceNext(hLookup,
0,
&dwLength,
pQS);
if (dwResult == SOCKET_ERROR)
{
if (WSAGetLastError() == WSAEFAULT)
{
printf("WSALookupServiceNext Error: Oops, we need a larger buffer size of : %d Bytes\n", dwLength);
}
else
{
PrintError("WSALookupServiceNext");
}
WSALookupServiceEnd (hLookup);
return;
}
if (!dwResult)
{
for (DWORD i = 0; i < pQS->dwNumberOfCsAddrs; i++)
{
SOCKADDR_STORAGE *mypt = (SOCKADDR_STORAGE *) pQS->lpcsaBuffer[i].RemoteAddr.lpSockaddr;
if (mypt)
{
// we have valid remote sockaddr
char temp[DEFAULT_STRING_LEN] = {'\0'};
printf ("Name[%d]: %30s", i, pQS->lpszServiceInstanceName);
GetSockAddrString (mypt, pQS->lpcsaBuffer[i].RemoteAddr.iSockaddrLength, temp, DEFAULT_STRING_LEN);
printf("%40s\n", temp);
if (! fKnownSapId)
ClientSend(&(pQS->lpcsaBuffer[i]));
}
}
}
WSALookupServiceEnd (hLookup);
}
}
//---------------------------------------------------------------------------
// FUNCTION: void ClientSend(CSADDR_INFO* lpcsaBuffer)
//
// PURPOSE: Given the server socket address info "lpcsaBuffer",
// send a message to the peer.
//---------------------------------------------------------------------------
void ClientSend(CSADDR_INFO* lpcsaBuffer)
{
SOCKADDR_STORAGE *mypt = (SOCKADDR_STORAGE *) lpcsaBuffer->RemoteAddr.lpSockaddr;
SOCKET s = INVALID_SOCKET;
static char szMessage[DEFAULT_STRING_LEN] = "A message from the client: ";
static BOOL fHostname = FALSE;
char szName[DEFAULT_STRING_LEN] = {'\0'};
unsigned long ulSize = sizeof(szName);
HRESULT hRet;
if (fHostname == FALSE)
{
GetComputerName(szName, &ulSize);
if (FAILED(hRet = StringCchCat(szMessage,
sizeof(szMessage)/sizeof(szMessage[0]),
szName
)))
{
printf("StringCchCat failed: 0x%x\n",hRet);
return;
}
fHostname = TRUE;
}
// The client doesn't need to know the detail of the addressing
// information, it can just do the common sequence of
// socket, connect, send/recv and closesocket by using the
// discovered RemoteAddr.
s = socket(lpcsaBuffer->RemoteAddr.lpSockaddr->sa_family,
lpcsaBuffer->iSocketType,
lpcsaBuffer->iProtocol);
if (s != INVALID_SOCKET)
{
if (connect(s, (SOCKADDR*)mypt, lpcsaBuffer->RemoteAddr.iSockaddrLength) != SOCKET_ERROR)
{
// NOTE on send on 64bit. strlen returns a 64bit INT and send takes a 32bit int.
// verify that your data is NOT larger that your data is not larger than SO_MAX_MSG_SIZE
// returned by getsockopt
if (send(s, szMessage, (INT)strlen(szMessage)+1, 0) != SOCKET_ERROR )
{
printf("send a message to the peer...\n");
}
else
{
printf("send failed %d\n", WSAGetLastError());
}
}
else
{
printf("connect failed %d\n", WSAGetLastError());
}
if (INVALID_SOCKET != s)
{
closesocket(s);
s = INVALID_SOCKET;
}
}
else
printf("Failed socket call %d\n", WSAGetLastError());
}
//---------------------------------------------------------------------------
// FUNCTION: void PrintError (char* errfunc)
// PURPOSE: Print error message.
//---------------------------------------------------------------------------
void PrintError (char* errfunc)
{
fflush (stdout);
if (WSASERVICE_NOT_FOUND == WSAGetLastError())
fprintf (stderr, "No matches found.\n");
else
if (WSA_E_NO_MORE == WSAGetLastError() || WSAENOMORE == WSAGetLastError())
fprintf (stderr, "No more matches. \n");
else
fprintf (stderr, "Function %s failed with error %d\n", errfunc, WSAGetLastError());
}
//---------------------------------------------------------------------------
// FUNCTION: void GetSockAddrString(SOCKADDR* pSAddr, int addrlen, char * dest, int destlen)
//
// PURPOSE: Converts INET or IPX address in "pSAddr" into ascii string in "dest"
//
//
// COMMENTS:
//
// INET address in decimal dotted notation:
// 107.50.104.97:4790
// IPX address format in hex:
// <8 char network address>.<12 char node address>.<4 char sock address>
//
// NOTE: Since Winsock 2 WSAAddressToString API is now only working for
// IP (AF_INET) and ATM (AF_ATM) address family, I would rather implement
// my version as GetSockAddrString()
//---------------------------------------------------------------------------
void GetSockAddrString(SOCKADDR_STORAGE* pSAddr, int addrlen, char * dest, int destlen)
{
HRESULT hRet;
if (pSAddr == NULL || dest == NULL)
return;
switch (pSAddr->ss_family)
{
case AF_INET:
case AF_INET6:
{
char host[NI_MAXHOST],
serv[NI_MAXSERV];
int hostlen = NI_MAXHOST,
servlen = NI_MAXSERV,
rc;
rc = getnameinfo((SOCKADDR*)pSAddr, addrlen, host, hostlen, serv, servlen,
NI_NUMERICHOST | NI_NUMERICSERV);
if (rc != 0)
{
if (FAILED(hRet = StringCchPrintf(dest,destlen-1,"getnameinfo failed: %d",rc)))
{
printf("StringCchPrintf failed: 0x%x\n",hRet);
return;
}
return;
}
if (FAILED(hRet = StringCchPrintf(dest,destlen-1,"%s:%s",host,serv)))
{
printf("StringCchPrintf failed: 0x%x\n",hRet);
return;
}
}
break;
case AF_IPX:
{
PSOCKADDR_IPX pIpxAddr = (PSOCKADDR_IPX) pSAddr;
if (FAILED(hRet = StringCchPrintf(dest, destlen-1,
"%02X%02X%02X%02X.%02X%02X%02X%02X%02X%02X:%04X",
(unsigned char)pIpxAddr->sa_netnum[0],
(unsigned char)pIpxAddr->sa_netnum[1],
(unsigned char)pIpxAddr->sa_netnum[2],
(unsigned char)pIpxAddr->sa_netnum[3],
(unsigned char)pIpxAddr->sa_nodenum[0],
(unsigned char)pIpxAddr->sa_nodenum[1],
(unsigned char)pIpxAddr->sa_nodenum[2],
(unsigned char)pIpxAddr->sa_nodenum[3],
(unsigned char)pIpxAddr->sa_nodenum[4],
(unsigned char)pIpxAddr->sa_nodenum[5],
ntohs(pIpxAddr->sa_socket)
)))
{
printf("StringCchPrintf failed: 0x%x\n",hRet);
return;
}
}
break;
default:
if(FAILED(hRet = StringCchCopy(dest,destlen-1,"Unknown socket address family")))
{
printf("StringCchCopy failed: 0x%x\n",hRet);
}
break;
}
}
void SetIpPort(SOCKADDR_STORAGE *dest, SOCKADDR_STORAGE *src)
{
if (dest->ss_family == AF_INET)
((SOCKADDR_IN *)dest)->sin_port = ((SOCKADDR_IN *)src)->sin_port;
else if (dest->ss_family == AF_INET6)
((SOCKADDR_IN6 *)dest)->sin6_port = ((SOCKADDR_IN6 *)src)->sin6_port;
}
void DumpServiceClassInfo(LPWSASERVICECLASSINFO lpSci)
{
WCHAR szGuid[MAX_PATH] = {'\0'};
GUID TempGuid = {0};
DWORD i = 0;
HRESULT hRet;
if (NULL == lpSci)
return;
CopyMemory(&TempGuid,lpSci->lpServiceClassId,sizeof(GUID));
if (FAILED(hRet = StringCchPrintfW(szGuid,
sizeof(szGuid)/sizeof(szGuid[0]),
L"%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
TempGuid.Data1,
TempGuid.Data2,
TempGuid.Data3,
TempGuid.Data4[0],
TempGuid.Data4[1],
TempGuid.Data4[2],
TempGuid.Data4[3],
TempGuid.Data4[4],
TempGuid.Data4[5],
TempGuid.Data4[6],
TempGuid.Data4[7]
)))
{
printf("StringCchPrintfW failed: 0x%x\n",hRet);
return;
}
printf("\nWSASERVICECLASSINFO %p:\n",lpSci);
wprintf(L"lpServiceClassId:\t%s\n",szGuid);
printf("lpszServiceClassName:\t%s\n",lpSci->lpszServiceClassName);
printf("dwCount:\t\t%d\n",lpSci->dwCount);
for (i = 0; i < lpSci->dwCount; i++)
{
printf("lpClassInfos (WSANSCLASSINFOW %p):\n",&lpSci->lpClassInfos[i]);
printf("\t\tdwNameSpace:\t%d\n",lpSci->lpClassInfos[i].dwNameSpace);
printf("\t\tdwValueSize:\t%d\n",lpSci->lpClassInfos[i].dwValueSize);
printf("\t\tdwValueType:\t%d\n",lpSci->lpClassInfos[i].dwValueType);
printf("\t\tlpszName:\t%s\n",lpSci->lpClassInfos[i].lpszName);
printf("\t\tlpValue:\t%p\n",lpSci->lpClassInfos[i].lpValue);
}
printf("\n");
return;
}
| [
"chrisg@microsoft.com"
] | chrisg@microsoft.com |
0f8d3a450d0d9df578a53cc21a6a2e916d35ab4b | 086dd8c69ed54e534cc8665284e0dc2b75a1f3ac | /proj/zadatak1/src/Not.cpp | e63261d9ff76ea3bb9091e795b72c362e42c4346 | [] | no_license | uros117/system_software_project | bb9d7cc8cedbfd816045307af59d36c59bd65289 | e473f24e5387c095623933d0a8bb705621f135e4 | refs/heads/main | 2023-08-28T21:10:09.836837 | 2021-11-06T17:31:50 | 2021-11-06T17:31:50 | 425,303,355 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 214 | cpp | #include "Not.hpp"
Not::Not(unsigned int number, Argument* a1) : Instr(number, 2, "not", a1, nullptr) {
}
void Not::pass1() {
}
void Not::pass2() {
regRegInstrPass2(0b10000000, *this);
}
Not::~Not() {
}
| [
"uros@programmer.net"
] | uros@programmer.net |
bf3cf20d933ef62e7a118385e250fb7944122138 | dc29086e666691d3d1f1371708ca860c7393fd8f | /libWorld/src/libEngine/shaderManager.h | db9907d5976d5ac4f7df20850714fc43453fda07 | [] | no_license | preboy/9DayGame | acb9ee02500a7a6a8b3470d4c6adbfbd517c442a | 4947b402e5e9e9cd430ea178b8bf6debc05abbf4 | refs/heads/master | 2021-01-11T14:11:59.060933 | 2017-02-10T14:46:12 | 2017-02-10T14:46:12 | 81,573,914 | 0 | 0 | null | null | null | null | MacCentralEurope | C++ | false | false | 602 | h | #pragma once
#include "shader.h"
namespace LibEngine
{
class ShaderManager
{
public:
friend class VertexLayoutManager;
ShaderManager();
~ShaderManager();
bool Init(RenderDevice_DX11* pRenderDeviceDx11);
void Release();
public:
// š÷»ĺtexture;
VertexShader m_textureVShader;
PixelShader m_texturePShader;
// color;
VertexShader m_colorVShader;
PixelShader m_colorPShader;
RenderDevice_DX11* m_pRenderDeviceDx11;
};
}
| [
"preboy@126.com"
] | preboy@126.com |
292263b28467b9fdf8fa2393bd03e0604d9362f5 | 01837a379a09f74f7ef43807533093fa716e71ac | /src/utils/xulrunner-sdk/nsIDOMHTMLTableCaptionElem.h | bac20819846a0c4423788e1f685738e9195e5a2e | [] | no_license | lasuax/jorhy-prj | ba2061d3faf4768cf2e12ee2484f8db51003bd3e | d22ded7ece50fb36aa032dad2cc01deac457b37f | refs/heads/master | 2021-05-05T08:06:01.954941 | 2014-01-13T14:03:30 | 2014-01-13T14:03:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,130 | h | /*
* DO NOT EDIT. THIS FILE IS GENERATED FROM e:/builds/moz2_slave/rel-m-rel-xr_w32_bld-000000000/build/dom/interfaces/html/nsIDOMHTMLTableCaptionElem.idl
*/
#ifndef __gen_nsIDOMHTMLTableCaptionElem_h__
#define __gen_nsIDOMHTMLTableCaptionElem_h__
#ifndef __gen_nsIDOMHTMLElement_h__
#include "nsIDOMHTMLElement.h"
#endif
/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
/* starting interface: nsIDOMHTMLTableCaptionElement */
#define NS_IDOMHTMLTABLECAPTIONELEMENT_IID_STR "526c4dc4-25cd-46de-a9b2-1501d624f7df"
#define NS_IDOMHTMLTABLECAPTIONELEMENT_IID \
{0x526c4dc4, 0x25cd, 0x46de, \
{ 0xa9, 0xb2, 0x15, 0x01, 0xd6, 0x24, 0xf7, 0xdf }}
class NS_NO_VTABLE nsIDOMHTMLTableCaptionElement : public nsIDOMHTMLElement {
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_IDOMHTMLTABLECAPTIONELEMENT_IID)
/* attribute DOMString align; */
NS_IMETHOD GetAlign(nsAString & aAlign) = 0;
NS_IMETHOD SetAlign(const nsAString & aAlign) = 0;
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsIDOMHTMLTableCaptionElement, NS_IDOMHTMLTABLECAPTIONELEMENT_IID)
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIDOMHTMLTABLECAPTIONELEMENT \
NS_IMETHOD GetAlign(nsAString & aAlign); \
NS_IMETHOD SetAlign(const nsAString & aAlign);
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIDOMHTMLTABLECAPTIONELEMENT(_to) \
NS_IMETHOD GetAlign(nsAString & aAlign) { return _to GetAlign(aAlign); } \
NS_IMETHOD SetAlign(const nsAString & aAlign) { return _to SetAlign(aAlign); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIDOMHTMLTABLECAPTIONELEMENT(_to) \
NS_IMETHOD GetAlign(nsAString & aAlign) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetAlign(aAlign); } \
NS_IMETHOD SetAlign(const nsAString & aAlign) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetAlign(aAlign); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class nsDOMHTMLTableCaptionElement : public nsIDOMHTMLTableCaptionElement
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIDOMHTMLTABLECAPTIONELEMENT
nsDOMHTMLTableCaptionElement();
private:
~nsDOMHTMLTableCaptionElement();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS1(nsDOMHTMLTableCaptionElement, nsIDOMHTMLTableCaptionElement)
nsDOMHTMLTableCaptionElement::nsDOMHTMLTableCaptionElement()
{
/* member initializers and constructor code */
}
nsDOMHTMLTableCaptionElement::~nsDOMHTMLTableCaptionElement()
{
/* destructor code */
}
/* attribute DOMString align; */
NS_IMETHODIMP nsDOMHTMLTableCaptionElement::GetAlign(nsAString & aAlign)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsDOMHTMLTableCaptionElement::SetAlign(const nsAString & aAlign)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
#endif /* __gen_nsIDOMHTMLTableCaptionElem_h__ */
| [
"joorhy@gmail.com"
] | joorhy@gmail.com |
1e96aab2b501896458c5f7a6b63cc063b9f96310 | fa0a015d219472594f6e6a3b8692d2da0deeeb56 | /Game1.2/Player.h | 09beb684c94b89dc85f6b644229042890d01ed89 | [] | no_license | gabrielbuiar/TecProgGame | c80257b789010940671e8f8d96c0aaf3609a64c8 | efa4c4ca11580167c42c7d71562d5c6f387f85e3 | refs/heads/master | 2020-04-05T10:02:22.277027 | 2018-11-09T00:35:09 | 2018-11-09T00:35:09 | 156,785,537 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 318 | h | #pragma once
#include "Character.h"
class Player : public Character
{
public:
Player(const char* textureFile = NULL, float speed = 0, float jumpHeight = 0);
~Player();
void InitializePlayer(sf::Vector2f position, sf::Vector2f size, const char* textureFile, sf::Vector2u imgCount, float speed, float jumpHeight);
}; | [
"gabrielbuiar@gmail.com"
] | gabrielbuiar@gmail.com |
a7128b384539008395fc6fe31a16ae2a2c816f45 | 5bfe56b2b62a5496d07f3521bf34091a92c2ee75 | /todo/LocalStorage.h | a27bc959b9dbda7a3267a4878360648169fdc240 | [
"MIT"
] | permissive | AnotherFoxGuy/ogre-angelscript | d4dd0f09cfd111779ebd46691e9db14020862130 | 375d523dc3fa797a6df1ccd2814f1c8add121309 | refs/heads/master | 2021-01-20T18:20:48.665946 | 2016-06-18T15:01:32 | 2016-06-18T15:01:32 | 61,438,193 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,901 | h | /*
-----------------------------------------------------------------------------
This source file is part of OGRE-angelscript
For the latest info, see http://code.google.com/p/ogre-angelscript/
Copyright (c) 2006-2011 Thomas Fischer
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.
-----------------------------------------------------------------------------
*/
#ifndef LOCALSTORAGE_H__
#define LOCALSTORAGE_H__
#include "RoRPrerequisites.h"
#include <angelscript.h>
#include "ImprovedConfigFile.h"
void registerLocalStorage(AngelScript::asIScriptEngine *engine);
void scriptLocalStorageFactory_Generic(AngelScript::asIScriptGeneric *gen);
void scriptLocalStorageFactory2_Generic(AngelScript::asIScriptGeneric *gen);
void scriptLocalStorageFactory3_Generic(AngelScript::asIScriptGeneric *gen);
/**
* @brief A class that allows scripts to store data persistently
*/
class LocalStorage : public Ogre::ImprovedConfigFile
{
public:
// Memory management
void AddRef() const;
void Release() const;
LocalStorage(AngelScript::asIScriptEngine *engine, std::string fileName_in, const std::string §ionName_in);
LocalStorage(AngelScript::asIScriptEngine *engine_in);
~LocalStorage();
LocalStorage &operator =(LocalStorage &other);
void changeSection(const std::string §ion);
std::string get(std::string &key);
void set(std::string &key, const std::string &value);
int getInt(std::string &key);
void set(std::string &key, const int value);
float getFloat(std::string &key);
void set(std::string &key, const float value);
bool getBool(std::string &key);
void set(std::string &key, const bool value);
Ogre::Vector3 getVector3(std::string &key);
void set(std::string &key, const Ogre::Vector3 &value);
Ogre::Quaternion getQuaternion(std::string &key);
void set(std::string &key, const Ogre::Quaternion &value);
Ogre::Radian getRadian(std::string &key);
void set(std::string &key, const Ogre::Radian &value);
Ogre::Degree getDegree(std::string &key);
void set(std::string &key, const Ogre::Degree &value);
void saveDict();
// int extendDict();
bool loadDict();
// removes a key and its associated value
void eraseKey(std::string &key);
// Returns true if the key is set
bool exists(std::string &key);
// Deletes all keys
void deleteAll();
// parses a key
void parseKey(std::string &key, std::string §ion);
// Garbage collections behaviours
int GetRefCount();
void SetGCFlag();
bool GetGCFlag();
void EnumReferences(AngelScript::asIScriptEngine *engine);
void ReleaseAllReferences(AngelScript::asIScriptEngine *engine);
SettingsBySection getSettings() { return mSettings; }
std::string getFilename() { return filename; }
std::string getSection() { return sectionName; }
protected:
bool saved;
std::string sectionName;
// Our properties
AngelScript::asIScriptEngine *engine;
mutable int refCount;
};
#endif // LOCALSTORAGE_H__
| [
"edgar@anotherfoxguy.com"
] | edgar@anotherfoxguy.com |
be74f66d1e64a2a09d5de6b59ce1b80dc4a10c8e | e641bd95bff4a447e25235c265a58df8e7e57c84 | /mojo/core/node_channel_unittest.cc | e89f5a13bb02a33c9243e1a3cdd83d98d583f2f1 | [
"BSD-3-Clause"
] | permissive | zaourzag/chromium | e50cb6553b4f30e42f452e666885d511f53604da | 2370de33e232b282bd45faa084e5a8660cb396ed | refs/heads/master | 2023-01-02T08:48:14.707555 | 2020-11-13T13:47:30 | 2020-11-13T13:47:30 | 312,600,463 | 0 | 0 | BSD-3-Clause | 2022-12-23T17:01:30 | 2020-11-13T14:39:10 | null | UTF-8 | C++ | false | false | 2,585 | cc | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "mojo/core/node_channel.h"
#include "base/callback_helpers.h"
#include "base/memory/scoped_refptr.h"
#include "base/message_loop/message_pump_type.h"
#include "base/test/task_environment.h"
#include "base/threading/thread.h"
#include "mojo/core/embedder/embedder.h"
#include "mojo/core/test/mock_node_channel_delegate.h"
#include "mojo/public/cpp/platform/platform_channel.h"
#include "mojo/public/cpp/platform/platform_channel_endpoint.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace mojo {
namespace core {
namespace {
using NodeChannelTest = testing::Test;
using ports::NodeName;
scoped_refptr<NodeChannel> CreateNodeChannel(NodeChannel::Delegate* delegate,
PlatformChannelEndpoint endpoint) {
return NodeChannel::Create(delegate, ConnectionParams(std::move(endpoint)),
Channel::HandlePolicy::kAcceptHandles,
GetIOTaskRunner(), base::NullCallback());
}
TEST_F(NodeChannelTest, DestructionIsSafe) {
// Regression test for https://crbug.com/1081874.
base::test::TaskEnvironment task_environment;
PlatformChannel channel;
MockNodeChannelDelegate local_delegate;
auto local_channel =
CreateNodeChannel(&local_delegate, channel.TakeLocalEndpoint());
local_channel->Start();
MockNodeChannelDelegate remote_delegate;
auto remote_channel =
CreateNodeChannel(&remote_delegate, channel.TakeRemoteEndpoint());
remote_channel->Start();
// Verify end-to-end operation
const NodeName kRemoteNodeName{123, 456};
const NodeName kToken{987, 654};
base::RunLoop loop;
EXPECT_CALL(local_delegate,
OnAcceptInvitee(ports::kInvalidNodeName, kRemoteNodeName, kToken))
.WillRepeatedly([&] { loop.Quit(); });
remote_channel->AcceptInvitee(kRemoteNodeName, kToken);
loop.Run();
// Now send another message to the local endpoint but tear it down
// immediately. This will race with the message being received on the IO
// thread, and although the corresponding delegate call may or may not
// dispatch as a result, the race should still be memory-safe.
remote_channel->AcceptInvitee(kRemoteNodeName, kToken);
base::RunLoop error_loop;
EXPECT_CALL(remote_delegate, OnChannelError).WillOnce([&] {
error_loop.Quit();
});
local_channel.reset();
error_loop.Run();
}
} // namespace
} // namespace core
} // namespace mojo
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
53829d4f635a6bca51b9378b9b7d19e087f4c1d8 | e663b38ddc5e2f42570e9a6c0f09fa0b624a71c1 | /Medium/UVa_10141_Inspection.cpp | 5764efb993ad26e0ad7f03b8f30b17eb9df98e3f | [] | no_license | alpharmike/competitive_programming | 8f615b5b80ab4d40a0a9ceed708d56d7b404cdcb | fa1ed06d6dc94b40473cf6289f4273ee93db0044 | refs/heads/master | 2022-11-26T11:23:14.136545 | 2020-08-01T14:19:52 | 2020-08-01T14:19:52 | 282,989,089 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 952 | cpp | #include <iostream>
using namespace std;
int main() {
int n, p, counter;
char proposal[100];
counter = 0;
char requirement[100];
while (scanf("%d %d", &n, &p) && n && p) {
printf("RFP #%d\n", counter + 1);
for (int i = 0; i < n; ++i) {
scanf("%s", requirement);
}
float max_comp = 0.0;
string accepted_prop;
float price;
int req_met;
char proposal_item[100];
for (int i = 0; i < p; ++i) {
scanf("%s", proposal);
scanf("%f %d", &price, &req_met);
for (int j = 0; j < req_met; ++j) {
scanf("%s", proposal_item);
}
float compliance = req_met / n;
if (compliance > max_comp) {
max_comp = compliance;
accepted_prop = proposal;
}
}
printf("%s\n", accepted_prop.c_str());
++counter;
}
}
| [
"ec.moeini01@gmail.com"
] | ec.moeini01@gmail.com |
488c7017b22991413c501adb2c8c4313efce5f70 | b1461525494f3cae26a7ea2f7dd4a665b92419cd | /ml/full_connected_layer.cpp | 13c21f1943c29dd006c72ef137638ed964b86f41 | [] | no_license | seaslee/rome | a9a19f0eade0831f5c93c9f87047f2c61682a178 | efcf55a0d5976361e4d7d249c81c26bddb2e9bd1 | refs/heads/master | 2021-01-21T05:21:27.826176 | 2017-04-23T02:49:09 | 2017-04-23T02:49:09 | 83,178,579 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,604 | cpp | #include "full_connected_layer.h"
#include "layer_factory.h"
#include "../matrix/random.h"
namespace snoopy {
namespace ml {
template<typename DataType>
void FCLayer<DataType>::init_spec_layer(const vector<Blob<DataType> *> & input_blob,
const vector<Blob<DataType> *> & output_blob) {
//check
size_t input_blob_size = input_blob.size();
size_t output_blob_size = output_blob.size();
CHECK_EQ(input_blob_size, 1);
CHECK_EQ(output_blob_size, 1);
size_t input_blob_dim0 = input_blob[0]->dim_at(0);
size_t input_blob_dim1 = input_blob[0]->dim_at(1);
size_t output_blob_dim0 = output_blob[0]->dim_at(0);
size_t output_blob_dim1 = output_blob[0]->dim_at(1);
size_t in_nodes_dim = this->param_blob_[0]->dim_at(0);
size_t out_nodes_dim = this->param_blob_[0]->dim_at(1);
CHECK_EQ(input_blob_dim1, in_nodes_dim);
CHECK_EQ(output_blob_dim1, out_nodes_dim);
CHECK_NE(this->param_blob_[0]->get_data(), nullptr);
CHECK_NE(this->param_blob_[0]->get_diff(), nullptr);
n_in_ = input_blob_dim1;
n_out_ = output_blob_dim1;
n_nums_ = input_blob_dim0;
is_add_bias_ = false;
Matrix<DataType, 2> param_matrix = this->param_blob_[0]->get_data()->flatten_2d_matrix();
//initialize the parameter
float a = -1. / sqrt(n_in_);
float b = -1. / sqrt(n_in_);
Random::uniform(param_matrix, a, b);
}
template<typename DataType>
void FCLayer<DataType>::reshape(const vector<Blob<DataType> *> & input_blob,
const vector<Blob<DataType> *> & output_blob) {
}
template<typename DataType>
void FCLayer<DataType>::forward_cpu(const vector<Blob<DataType> *> & input_blob,
const vector<Blob<DataType> *> & output_blob) {
Matrix<DataType, 2> input_matrix = input_blob[0]->get_data()->flatten_2d_matrix();
Matrix<DataType, 2> param_matrix = this->param_blob_[0]->get_data()->flatten_2d_matrix();
Matrix<DataType, 2> out_matrix = output_blob[0]->get_data()->flatten_2d_matrix();
out_matrix.copy_from(dot(input_matrix, param_matrix));
}
template<typename DataType>
void FCLayer<DataType>::backward_cpu(const vector<Blob<DataType> *> & input_blob,
const vector<bool> & need_bp,
const vector<Blob<DataType> *> & output_blob) {
//backward, transpose mat
Matrix<DataType, 2> output_diff_matrix = output_blob[0]->get_diff()->flatten_2d_matrix();
Matrix<DataType, 2> param_matrix = this->param_blob_[0]->get_data()->flatten_2d_matrix();
Matrix<DataType, 2> param_diff_matrix = this->param_blob_[0]->get_diff()->flatten_2d_matrix();
Matrix<DataType, 2> in_diff_matrix = input_blob[0]->get_diff()->flatten_2d_matrix();
Matrix<DataType, 2> in_data_maxtrix = input_blob[0]->get_data()->flatten_2d_matrix();
//gradient with respect to input
size_t dim0 = this->param_blob_[0]->dim_at(0);
size_t dim1 = this->param_blob_[0]->dim_at(1);
MatrixShape<2> mat_shape(0, {dim1, dim0});
Matrix<DataType, 2> trans_param_mat(mat_shape); //storage TODO @xinchao
transpose(trans_param_mat, param_matrix);
in_diff_matrix.copy_from(dot(output_diff_matrix, trans_param_mat));
//gradient with respect to weights
size_t in_dim0 = input_blob[0]->dim_at(0);
size_t in_dim1 = input_blob[0]->dim_at(1);
MatrixShape<2> trans_in_shape(0, {in_dim1, in_dim0});
Matrix<DataType, 2> in_trans_mat(trans_in_shape);
transpose(in_trans_mat, in_data_maxtrix);
param_diff_matrix.copy_from(dot(in_trans_mat, output_diff_matrix));
}
//regesite
LAYER_REGISTER_CLASS(FC)
} //end namespace
} //end namespace
| [
"xxinchao@gmail.com"
] | xxinchao@gmail.com |
29dcb54acd403821e5ef4778f2175544ca7acd92 | 8c91366c2119e88d34ddb036b0fcce724038b986 | /reciever_with_gps.ino | e445bed6a981548ae8d6abe342bcda508c114256 | [
"MIT"
] | permissive | srijanshetty/arduino-sketches | f239d464edc7e1ce89b3ec83abb3819ffe477772 | 1d627700f8930f1f2bec250d7b59db4ce7ed6f6c | refs/heads/master | 2021-01-10T03:43:23.302429 | 2016-04-03T10:19:37 | 2016-04-03T10:19:37 | 55,341,093 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,438 | ino | #include <VirtualWire.h>
#include <TinyGPS.h>
#include <SoftwareSerial.h>
#define SENSOR_PIN 8
#define GARAGE "0"
#define FIRST "1"
#define SECOND "2"
#define THIRD "3"
#define RXPIN 2
#define TXPIN 3
TinyGPS gps;
SoftwareSerial nss( RXPIN, TXPIN );
char input[ 100 ];
void setup()
{
vw_set_ptt_inverted(true); // Required for DR3100
vw_set_tx_pin(SENSOR_PIN);
vw_setup(2000); // Bits per sec
vw_rx_start(); // Start the receiver PLL running
Serial.begin( 9600 );
}
void loop()
{
while( nss.avaliable() ) {
int c = nss.read();
if( gps.encode(c) ) {
long lat, lon;
unsigned long fix_age, time, date, speed, course;
unsigned long chars;
unsigned short sentences, failed_checksum;
// retrieves +/- lat/long in 100000ths of a degree
gps.get_position(&lat, &lon, &fix_age);
// time in hhmmsscc, date in ddmmyy
gps.get_datetime(&date, &time, &fix_age);
// returns speed in 100ths of a knot
speed = gps.speed();
// course in 100ths of a degree
course = gps.course();
Serial.println( speed );
Serial.println( course );
}
}
while( Serial.available() > 0 ) {
input[0] = Serial.parseInt() + '0';
input[1] = '\0';
Serial.print( "Sending coordinate: " );
Serial.println( input );
switch( input[0] ) {
case '0': vw_send( (uint8_t *)GARAGE, strlen( GARAGE ) );
vw_wait_tx();
delay(1000);
break;
case '1': vw_send( (uint8_t *)FIRST, strlen( FIRST ) );
vw_wait_tx();
delay(1000);
break;
case '2': vw_send( (uint8_t *)SECOND, strlen( SECOND ) );
vw_wait_tx();
delay(1000);
break;
case '3': vw_send( (uint8_t *)THIRD, strlen( THIRD ) );
vw_wait_tx();
delay(1000);
break;
default: Serial.println( "Wrong input" );
}
Serial.println( "Sending coordinate: " );
Serial.print( input[0] );
}
}
| [
"srijan.shetty@gmail.com"
] | srijan.shetty@gmail.com |
fa77e47f3e169747ebe4b3cb4f99e0f414b1c13a | 9ded4c4fc135c2154ea85bc6a8fb4dcf2ce84863 | /codejam/Rotate.cpp | 310df22672a847fe5cfc89b202da3ff1cea7ecc8 | [] | no_license | yanhuanwang/codekata | 5389a1e958c7c2d79582098b89a26648dcc188ba | 9369f7461ddcc731b318bc701b2f17ad2990f285 | refs/heads/master | 2016-09-06T01:17:37.255599 | 2014-06-19T12:31:06 | 2014-06-19T12:31:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,036 | cpp | //#include <cstdio>
//#include <cstdlib>
//#include <memory.h>
//#include <algorithm>
//#include <string>
//#include <map>
//#include <set>
//#include <vector>
//#include <cmath>
//#include <queue>
//#include <cassert>
//#include <iostream>
//using namespace std;
//#define PI 3.14159265358979323846264338327950288
//void rotate(vector<vector<char>>&matrix) { //rotate the matrix by 90 degrees clockwise
// int n = matrix.size();
// if (n == 0 || n == 1)
// return;
// for (int i = 0; i < n / 2; ++i) {
// for (int j = i; j < n - i - 1; ++j) {
// int temp = matrix[i][j];
// matrix[i][j] = matrix[n - 1 - j][i];
// matrix[n - 1 - j][i] = matrix[n - 1 - i][n - 1 - j];
// matrix[n - 1 - i][n - 1 - j] = matrix[j][n - 1 - i];
// matrix[j][n - 1 - i] = temp;
// }
// }
//}
//void gravity(vector<vector<char>>&matrix) {
// int n = matrix.size();
// for (int i = 0; i < n; i++) {
// for (int row = n - 1; row >= 0; row--) {
// if (matrix[row][i] == '.') {
// for (int j = row - 1; j >= 0; j--) {
// if (matrix[j][i] == 'R' || matrix[j][i] == 'B') {
// swap(matrix[row][i], matrix[j][i]);
// break;
// }
// }
// }
// }
// }
//}
//vector<int> dx = { 0, 0, 1, 1, -1 };
//vector<int> dy = { 0, 1, 0, 1, 1 };
//bool check2(int x, int y, int f, char chr, vector<vector<char>>&c, int K) {
// int n = c.size();
//
// for (int i = 0; i < K; i++) {
//
// if ((x + dx[f] * i < 0) || (x + dx[f] * i >= n)) {
// return false;
// }
// else {
// int l = c[x + dx[f] * i].size();
// if ((y + dy[f] * i < 0) || (y + dy[f] * i >= l)) {
// return false;
// }
//
// else if (c[x + dx[f] * i][y + dy[f] * i] != chr) {
// return false;
// }
// }
// }
// return true;
//}
//bool check(vector<vector<char>>&matrix, int k, string&res, char c) {
// int n = matrix.size();
// for (int i = 0; i < n; i++) {
// for (int j = 0; j < matrix[i].size(); j++) {
// if (matrix[i][j] == c) {
//
// for (int f = 1; f < 5; f++) {
// if (check2(i, j, f, c, matrix, k)) {
// return true;
// }
// }
// }
// }
// }
// return false;
//}
//string process(vector<vector<char>> &v, int K) {
// string res;
// bool isB = false;
// bool isR = false;
// if (check(v, K, res, 'B')) {
// isB = true;
// }
// if (check(v, K, res, 'R')) {
// isR = true;
// }
// if (!isB && !isR) {
// res = "Neither";
// } else if (isB && !isR) {
// res = "Blue";
// } else if (isR && !isB) {
// res = "Red";
// } else {
// res = "Both";
// }
// return res;
//}
//int T;
//int N, K;
//char tmp[100];
//string ans;
//
//int main() {
// int i;
// int Case = 1;
// int T;
// scanf("%d", &T);
// while (T--) {
// scanf("%d%d", &N, &K);
// vector<vector<char>> v;
// for (i = 0; i < N; i++) {
// scanf("%s", tmp);
// string s;
// for (int j = 0; j < N; j++) {
// if (tmp[j] == 'R' || tmp[j] == 'B') {
// s += tmp[j];
// }
// }
// vector<char> row(s.rbegin(), s.rend());
// v.push_back(row);
// }
// ans = process(v, K);
// printf("Case #%d: %s\n", Case++, ans.c_str());
// }
// return 0;
//}
| [
"martin.yan.seu@gmail.com"
] | martin.yan.seu@gmail.com |
8b19335714d9a27989a137491343b6643ee3282f | 7904a752a66bd5beda02e879ae1f1538adb7e15c | /modules/temporaltreemaps/src/processors/treemeshgeneratortopo.cpp | a839c5a93940cf17154da16bf9c0a519c50092fb | [] | no_license | Wiebke/TemporalTreeMaps | 8f9c595e9a36138031d06d08452886af4d4577b0 | 0a23b4f0f41481c64ccbbce0f9d13bdf3f8647b5 | refs/heads/master | 2021-06-27T06:13:19.998639 | 2020-10-26T19:20:50 | 2020-10-26T19:20:50 | 172,705,518 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,799 | cpp | /*********************************************************************
* Author : Tino Weinkauf and Wiebke Koepp
* Init : Monday, December 11, 2017 - 19:50:26
*
* Project : KTH Inviwo Modules
*
* License : Follows the Inviwo BSD license model
*********************************************************************
*/
#include <modules/temporaltreemaps/processors/treemeshgeneratortopo.h>
#include <inviwo/core/util/colorconversion.h>
namespace inviwo {
namespace kth {
// The Class Identifier has to be globally unique. Use a reverse DNS naming scheme
const ProcessorInfo TemporalTreeMeshGeneratorTopo::processorInfo_{
"org.inviwo.TemporalTreeMeshGeneratorTopo", // Class identifier
"Tree Mesh Generator Topo", // Display name
"Temporal Tree", // Category
CodeState::Experimental, // Code state
Tags::None, // Tags
};
const ProcessorInfo TemporalTreeMeshGeneratorTopo::getProcessorInfo() const {
return processorInfo_;
}
TemporalTreeMeshGeneratorTopo::TemporalTreeMeshGeneratorTopo()
: Processor()
, portInTree("InTree")
, portOutMeshBands("OutMeshBands")
, propSpacing("Spacing", "Spacing", 10, 0, 50)
, propLevelPortion("LevelPortion", "Level Portion", 50, 0, 100)
, propConstraintIndication("ConstraintIndication", "Constraint Indication", 2, 0, 10) {
addPort(portInTree);
addPort(portOutMeshBands);
addProperty(propSpacing);
addProperty(propLevelPortion);
addProperty(propConstraintIndication);
}
namespace {
void GetLayerOrder(const TemporalTree& Tree, const std::vector<size_t>& LeafOrder,
const std::map<size_t, size_t>& LeafOrderMap,
const std::vector<size_t>& LevelIndices,
TemporalTreeMeshGeneratorTopo::TLayerOrder& LayerOrder) {
// Prepare memory
const size_t NumLeaves = LeafOrder.size();
LayerOrder.reserve(NumLeaves);
LayerOrder.clear();
// For each parent, get all its leaves and make sure to be rendered there.
std::set<size_t> LeavesOfParent;
for (const size_t idxParent : LevelIndices) {
// Get this parent's leaves
LeavesOfParent.clear();
const uint64_t tMinParent = Tree.nodes[idxParent].startTime();
const uint64_t tMaxParent = Tree.nodes[idxParent].endTime();
Tree.getLeaves(idxParent, tMinParent, tMaxParent, tMinParent, tMaxParent, LeavesOfParent);
// Add to render queue
size_t MinOrderRow(NumLeaves);
size_t MaxOrderRow(0);
for (const size_t idxLeaf : LeavesOfParent) {
LayerOrder.emplace_back();
LayerOrder.back().idxNodeToBeDrawn = idxParent;
LayerOrder.back().idxLeaf = idxLeaf;
LayerOrder.back().OrderRow = LeafOrderMap.at(idxLeaf);
// LayerOrder.back().bFullCoverage = false; //later
if (LayerOrder.back().OrderRow < MinOrderRow) MinOrderRow = LayerOrder.back().OrderRow;
if (LayerOrder.back().OrderRow > MaxOrderRow) MaxOrderRow = LayerOrder.back().OrderRow;
}
// Compute coverage
int NumOverlap((int)LeavesOfParent.size());
if (int(MaxOrderRow) - int(MinOrderRow) + 1 == NumOverlap) {
for (auto it = LayerOrder.rbegin();
it != LayerOrder.rend() && it->idxNodeToBeDrawn == idxParent; it++) {
it->bFullCoverage = true;
}
} else {
// Gotta check temporal overlaps
for (size_t r(MinOrderRow); r <= MaxOrderRow && r < NumLeaves && NumOverlap >= 0; r++) {
// A leaf in the drawing area; may not be ours. If it is not ours, but it overlaps,
// then we do not have full coverage.
// Leaf's time
const uint64_t tMinLeaf = Tree.nodes[LeafOrder[r]].startTime();
const uint64_t tMaxLeaf = Tree.nodes[LeafOrder[r]].endTime();
// Overlap?
// |------| (Parent)
// Cases to exclude:
//|---| (Leaf completely before, fulfills tMinLeaf<tMaxParent)
// |------| (Leaf completely after, fulfills tMaxLeaf>tMinParent)
if (std::max(tMinLeaf, tMinParent) < std::min(tMaxLeaf, tMaxParent)) NumOverlap--;
}
ivwAssert(NumOverlap <= 0, "Missed a child? How? Not ok!");
for (auto it = LayerOrder.rbegin();
it != LayerOrder.rend() && it->idxNodeToBeDrawn == idxParent; it++) {
it->bFullCoverage = (NumOverlap == 0);
}
}
}
}
} // namespace
void TemporalTreeMeshGeneratorTopo::CreateMesh(const TemporalTree& Tree, const size_t Level,
const size_t MaxLevel, const size_t NumRows,
const TLayerOrder& Order,
std::shared_ptr<BasicMesh>& Mesh,
std::vector<BasicMesh::Vertex>& Vertices) {
// Get temporal min/max
uint64_t tMin, tMax;
Tree.getMinMaxTimeShallow(0, tMin, tMax); // I am assuming root here!
// Prepare buffer
const size_t NumItems = Order.size();
const size_t NumVerticesBefore(Vertices.size());
Vertices.resize(NumVerticesBefore + NumItems * 8);
// Prepare for normalization in x-direction
const float Range(float(tMax - tMin));
const float fMin = float(tMin);
const float xIndicatorSize = propConstraintIndication / 100.0f;
// Prepare for computations in y-direction
const float yBandWidth = 1.0f / float(NumRows);
const float ySpacing = propSpacing / float(2 * 100 * NumRows);
const float yActualBandWidth = yBandWidth - 2.0f * ySpacing;
const float yLevelOffset =
yActualBandWidth * (float(Level) / float(MaxLevel)) * (propLevelPortion / (2.0f * 100.0f));
const float yOffset = ySpacing + yLevelOffset;
// Colors
// Black for MaxLevel, White for Root
vec4 DefaultColor(1.0f - float(Level) / float(MaxLevel));
DefaultColor[3] = 1.0f;
vec4 RuptureColor(0.5, 0.2, 0.2, 1);
// Constraints
std::vector<std::pair<int, int>> Constraints;
const size_t NumConstraints = Tree.getConstraintClusters(Constraints);
// Draw each element
for (size_t i(0); i < NumItems; i++) {
// Shorthand
const size_t idxThisNode = Order[i].idxNodeToBeDrawn;
const size_t idRow = Order[i].OrderRow;
const bool bIndicateRupture = !Order[i].bFullCoverage;
const TemporalTree::TNode& ThisNode = Tree.nodes[idxThisNode];
const size_t StartVertex = NumVerticesBefore + 8 * i;
// Get time and normalize
const uint64_t StartTime = ThisNode.startTime();
const uint64_t EndTime = ThisNode.endTime();
const float xLeft = (float(StartTime) - fMin) / Range;
const float xRight = (float(EndTime) - fMin) / Range;
const float xMiddle = 0.5f * (xRight + xLeft);
float xLeftIndication = xLeft + xIndicatorSize;
if (xLeftIndication > xMiddle) xLeftIndication = xMiddle;
float xRightIndication = xRight - xIndicatorSize;
if (xRightIndication < xMiddle) xRightIndication = xMiddle;
// Get height
const float yBottom = float(idRow) / float(NumRows) + yOffset;
const float yTop = float(idRow + 1) / float(NumRows) - yOffset;
// Set colors
// - color to indicate constraints at the left of the node
vec4 LeftColor(DefaultColor);
if (Constraints[idxThisNode].first >= 0) {
vec3 LeftColor3 = color::hsv2rgb(
vec3(float(Constraints[idxThisNode].first) / float(NumConstraints), 1.0f, 1.0f));
LeftColor[0] = LeftColor3[0];
LeftColor[1] = LeftColor3[1];
LeftColor[2] = LeftColor3[2];
}
// - color to indicate constraints at the right of the node
vec4 RightColor(DefaultColor);
if (Constraints[idxThisNode].second >= 0) {
vec3 RightColor3 = color::hsv2rgb(
vec3(float(Constraints[idxThisNode].second) / float(NumConstraints), 1.0f, 1.0f));
RightColor[0] = RightColor3[0];
RightColor[1] = RightColor3[1];
RightColor[2] = RightColor3[2];
}
// Set vertices
vec3 pos = {xLeft, yBottom, float(Level)};
Vertices[StartVertex + 0] = {pos, vec3(0, 0, 0), pos, LeftColor};
pos = {xLeft, yTop, float(Level)};
Vertices[StartVertex + 1] = {pos, vec3(0, 0, 0), pos, LeftColor};
pos = {xLeftIndication, yBottom, float(Level)};
Vertices[StartVertex + 2] = {pos, vec3(0, 0, 0), pos,
bIndicateRupture ? RuptureColor : DefaultColor};
pos = {xLeftIndication, yTop, float(Level)};
Vertices[StartVertex + 3] = {pos, vec3(0, 0, 0), pos,
bIndicateRupture ? RuptureColor : DefaultColor};
pos = {xRightIndication, yBottom, float(Level)};
Vertices[StartVertex + 4] = {pos, vec3(0, 0, 0), pos,
bIndicateRupture ? RuptureColor : DefaultColor};
pos = {xRightIndication, yTop, float(Level)};
Vertices[StartVertex + 5] = {pos, vec3(0, 0, 0), pos,
bIndicateRupture ? RuptureColor : DefaultColor};
pos = {xRight, yBottom, float(Level)};
Vertices[StartVertex + 6] = {pos, vec3(0, 0, 0), pos, RightColor};
pos = {xRight, yTop, float(Level)};
Vertices[StartVertex + 7] = {pos, vec3(0, 0, 0), pos, RightColor};
// Add to indexbuffer
auto IdxBuffer = Mesh->addIndexBuffer(DrawType::Triangles, ConnectivityType::Strip);
IdxBuffer->add(uint32_t(StartVertex + 0));
IdxBuffer->add(uint32_t(StartVertex + 1));
IdxBuffer->add(uint32_t(StartVertex + 2));
IdxBuffer->add(uint32_t(StartVertex + 3));
IdxBuffer->add(uint32_t(StartVertex + 4));
IdxBuffer->add(uint32_t(StartVertex + 5));
IdxBuffer->add(uint32_t(StartVertex + 6));
IdxBuffer->add(uint32_t(StartVertex + 7));
}
}
void TemporalTreeMeshGeneratorTopo::process() {
// Get the inputs
std::shared_ptr<const TemporalTree> pTree = portInTree.getData();
if (!pTree) return;
if (!treeorder::fitsWithTree(*pTree, pTree->order)) {
LogError("Order does not fit with the tree.");
return;
}
// Get a proper order
TemporalTree::TTreeOrder Order(pTree->order);
const size_t NumLeaves = Order.size();
TemporalTree::TTreeOrderMap OrderMap;
treeorder::toOrderMap(OrderMap, Order);
// Get the output
std::shared_ptr<BasicMesh> MeshBands = std::make_shared<BasicMesh>();
std::vector<BasicMesh::Vertex> Vertices;
// Mesh!
TLayerOrder LayerOrder;
size_t Level(1);
size_t MaxLevel(pTree->getNumLevels(0));
std::vector<size_t> LevelIndices;
LevelIndices = pTree->getLevel(Level, LevelIndices, 0);
while (!LevelIndices.empty()) {
ivwAssert(Level <= MaxLevel, "Too deep!");
// Create an order of nodes in this layer, but depending on the leaves layer
GetLayerOrder(*pTree, Order, OrderMap, LevelIndices, LayerOrder);
// Create the actual mesh
CreateMesh(*pTree, Level, MaxLevel, NumLeaves, LayerOrder, MeshBands, Vertices);
// Forward to the next level
LevelIndices = pTree->getLevel(Level + 1, LevelIndices, Level);
Level++;
}
// Push it out!
MeshBands->addVertices(Vertices);
portOutMeshBands.setData(MeshBands);
}
} // namespace kth
} // namespace inviwo
| [
"wiebke.koepp@googlemail.com"
] | wiebke.koepp@googlemail.com |
8b874ec6204aa7ccb050397696439b895e61b76e | 47a509cfd0d669320a32e86d45485294d77380e0 | /ObjOrientedProgramming/Furniture/Furniture/Furniture.h | bd37d942abf7048e7f61c33a4b8d6f0004f8d9e2 | [
"MIT"
] | permissive | JinnnnH/LearningProgress-Cpp | de4ba401cd0ed830c24259fdffc8df1cd2afdb5f | de7b9d037aa0b5e1ec8199b4eabfcd1e24c73bcb | refs/heads/master | 2022-11-27T04:22:56.979272 | 2020-08-04T05:44:56 | 2020-08-04T05:44:56 | 276,496,543 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 586 | h | // Lab 7-1
// Furniture.h
#ifndef FURNITURE_H_
#define FURNITURE_H_
#include <iostream>
#include <iomanip>
using namespace std;
class Furniture
{
private:
string brand;
int yearMade;
public:
//constructors
Furniture()
{
brand = "";
yearMade = 0;
}
Furniture(string b, int y)
{
brand = b;
yearMade = y;
}
//mutator methods
void setYear(int y) { yearMade = y; }
void setBrand(string b) { brand = b; }
//other methods
void print()
{
cout << "Brand: " << brand << endl;
cout << "Year made: " << yearMade << endl;
}
};
#endif | [
"noreply@github.com"
] | noreply@github.com |
cbd680695a1e78d797ae0a51937d13f133745270 | 2f10f807d3307b83293a521da600c02623cdda82 | /deps/boost/win/debug/include/boost/geometry/algorithms/detail/equals/collect_vectors.hpp | 7370baa381a07d73a4222523cdf4f733d2d84853 | [] | no_license | xpierrohk/dpt-rp1-cpp | 2ca4e377628363c3e9d41f88c8cbccc0fc2f1a1e | 643d053983fce3e6b099e2d3c9ab8387d0ea5a75 | refs/heads/master | 2021-05-23T08:19:48.823198 | 2019-07-26T17:35:28 | 2019-07-26T17:35:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 130 | hpp | version https://git-lfs.github.com/spec/v1
oid sha256:9b32952a226b5365bda5a98a020b66d61dd0f930aaa95ad24f3439cfea2f0d20
size 17346
| [
"YLiLarry@gmail.com"
] | YLiLarry@gmail.com |
b1f1586dd2ad3d4d212ecdbbaba08442b1623f32 | d8c149edd5b614afa1ca531eb1198aa143a5e049 | /src/ZcloudMsgPopup/ActivityWidget.cpp | 20af54bde7bee14770cdcfcd0b669aaa671bda6e | [] | no_license | gispda/ZcloudDesk | ecb9d08231373815107a082d2f6a517d668e8513 | c4a0c126c2261a6d087d96175a457783c2f43ebd | refs/heads/master | 2022-12-03T13:51:49.978571 | 2020-08-24T16:46:27 | 2020-08-24T16:46:27 | 283,679,013 | 1 | 1 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 1,559 | cpp | #include "ActivityWidget.h"
#include <QDesktopWidget>
#include <QApplication>
ActivityWidget::ActivityWidget(QString strUid, QString strToken, QString strCompId, QString strAvId, QString strTitle, QWidget *parent)
: QWidget(parent)
, m_strUid(strUid)
, m_strToken(strToken)
, m_strAvId(strAvId)
, m_strCompId(strCompId)
{
ui.setupUi(this);
setWindowTitle(QString::fromLocal8Bit("×îл"));
setWindowFlags(Qt::FramelessWindowHint | Qt::Tool);
setAttribute(Qt::WA_TranslucentBackground);
setAttribute(Qt::WA_DeleteOnClose);
setStyleSheet("outline: none");
m_pClient = new NamePipeClinet;
m_pClient->connectToServer("ZcloudMsgNamePipe");
ui.pushButton->setText(strTitle);
ui.pushButton->adjustSize();
adjustSize();
connect(ui.pushButton, SIGNAL(clicked()), this, SLOT(onActivittyBtnClick()));
QDesktopWidget *deskWgt = QApplication::desktop();
QRect availableRect = deskWgt->availableGeometry();
int nAvailableWidth = availableRect.width();
int nWidth = rect().width();
setGeometry(nAvailableWidth - nWidth, 30 + 5, nWidth, 26);
connect(deskWgt, &QDesktopWidget::workAreaResized, [this](int)
{
QDesktopWidget *deskWgt = QApplication::desktop();
QRect availableRect = deskWgt->availableGeometry();
int nAvailableWidth = availableRect.width();
int nWidth = rect().width();
setGeometry(nAvailableWidth - nWidth, 30 + 5, nWidth, 26);
});
}
ActivityWidget::~ActivityWidget()
{
}
void ActivityWidget::onActivittyBtnClick()
{
m_pClient->sendMessage(4, m_strUid, m_strToken, m_strCompId,m_strAvId, "", -1, "", true);
}
| [
"gispda@qq.com"
] | gispda@qq.com |
8882e24cc7cc79f374ca9041d2ea1139878ff28f | deaa518c6ba667f4fe2ab28b55de11d515ecc176 | /find Last element.cpp | 22072af910c31211e6dbfe1edb48ea0e1a6135f2 | [] | no_license | keshavjaiswal39/Coding-Block-Algo-plusplus | 1c154451c2aa44c73d45ebc05c4c2bbe1d4c9293 | 908351f12717942955afddc9dbe143fab7446784 | refs/heads/master | 2023-03-21T10:22:33.104054 | 2021-03-12T04:41:11 | 2021-03-12T04:41:11 | 346,939,743 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 408 | cpp | #include<iostream>
using namespace std;
int LastElement(int arr[],int n,int key)
{
if(n==0)
{
return -1;
}
int index=LastElement(arr+1,n-1,key);
if(index==-1)
{
if(arr[0]==key)
{
return 0;
}
else
{
return -1;
}
}
return index+1;
}
int main()
{
int n;
cin>>n;
int arr[100005];
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
int key;
cin>>key;
cout<<LastElement(arr,n,key);
}
| [
"keshav.jaiswal39@gmail.com"
] | keshav.jaiswal39@gmail.com |
dd2c113aa2cf75257addb5e561d24246d237dd85 | 457449e0f3a079fbf39656bc21c2540c91ca4a44 | /Ch_14/14-8/14-8/14-8.cpp | 29fdc8d85d686f72d20625b8b6da504e84dc08a3 | [] | no_license | kth4540/c_study | 6c0a2f991c562f92ddae1c3da0ab703a4bba4690 | c9a321af9b6867482eb676064da43def8da2ba9c | refs/heads/main | 2023-03-16T06:55:03.545983 | 2021-03-04T15:21:39 | 2021-03-04T15:21:39 | 335,520,136 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 1,221 | cpp | #define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#define NLEN 30
typedef struct
{
char first[NLEN];
char last[NLEN];
int num;
}name_count;
void receive_input(name_count*);
void count_characters(name_count*);
void show_result(const name_count*);
char* s_gets(char* st, int n);
int main()
{
name_count user_name;
receive_input(&user_name);
count_characters(&user_name);
show_result(&user_name);
return 0;
}
char* s_gets(char* st, int n)
{
char* ret_val;
char* find;
ret_val = fgets(st, n, stdin);
if (ret_val)
{
find = strchr(st, '\n');
if (find)
*find = '\0';
else
while (getchar() != '\n')
continue;
}
return ret_val;
}
void receive_input(name_count* cnt)
{
int flag;
printf("input your first name: ");
//s_gets(cnt->first, NLEN);
flag = scanf("%[^\n]%*c", cnt->first);
//%[^a] -> a가 나타날 때 까지 받음
//%*c -> 입력은 받지만 변수에 저장하지 않음
//->
if (flag != 1)
printf("wrong input");
}
void count_characters(name_count* cnt)
{
cnt->num = strlen(cnt->first) + strlen(cnt->last);
}
void show_result(name_count* cnt)
{
printf("hi, %s %s, your name has a %d characters.\n",
cnt->first, cnt->last, cnt->num);
}
| [
"harypoteck@naver.com"
] | harypoteck@naver.com |
1ea7b73a168528e048e0f85cc9d82a56123c73fc | b708f8ecb325ffa96877fba774d75b54041a5523 | /src/ZSynchronization.cpp | 9e3bfa3bc199bff70a0be038bfb51b9f7c67fcee | [] | no_license | 19317362/ZThreadControl | d29c256a62455d8fe3ea83efcfd16228af29ab55 | 0937a9ae72c1bd88068c077bb39b838ecd1aed28 | refs/heads/master | 2020-03-27T14:43:05.375895 | 2017-02-14T15:18:36 | 2017-02-14T15:18:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,053 | cpp | #include "ZSynchronization.h"
ZSynchronization::ZSynchronization(uint amount, error_t *err)
{
mAmount = amount;
int ret = sem_init(&mSem,0,mAmount);
if (ret == -1 && err != nullptr)
{
*err = errno;
}
else if (ret == 0 && err != nullptr)
{
*err = 0;
}
}
ZSynchronization::~ZSynchronization()
{
wait();
sem_destroy(&mSem);
}
void ZSynchronization::run(const list<Fnt> &l)
{
for (const auto &each : l)
{
run(each);
}
}
void ZSynchronization::run(const Fnt &f)
{
sem_wait(&mSem);
ZThread thread(true);
thread.run(Fnt([&]()
{
f();
sem_post(&mSem);
}
));
}
uint ZSynchronization::amount() const
{
return mAmount;
}
int ZSynchronization::wait()
{
int ret = 0;
uint times = 0;
do
{
ret = sem_wait(&mSem);
}while (++times < mAmount && ret == 0);
while (times-- && ret == 0)
{
ret = sem_post(&mSem);
}
return ret;
}
| [
"1270504295@qq.com"
] | 1270504295@qq.com |
ffbc858cb3d0ea08401c6077ee48054e2a31c025 | 64aca0dda6624b956cac6d22d892d6416476e814 | /Binary Tree/Heightbalanced_tree.cpp | 57bfccdf32e4e35ae967f5c58bdafcf91a0ed8b0 | [] | no_license | Darkknight1299/C-plus-plus | c772331a87ab36fb01036703370b1108d8aff901 | 0255dfa1609401234eb627463f1e7d0a3058b684 | refs/heads/main | 2023-06-24T11:05:55.068853 | 2021-07-20T12:59:48 | 2021-07-20T12:59:48 | 344,157,787 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,698 | cpp | #include<bits/stdc++.h>
using namespace std;
class node{
public:
int data;
node* left;
node* right;
node(int d){
data=d;
left=NULL;
right=NULL;
}
};
node* buildtree(){
int d;
cin>>d;
if(d==-1){
return NULL;
}
node* root=new node(d);
root->left=buildtree();
root->right=buildtree();
return root;
}
void printAsTree(node* root){
queue<node*> q;
q.push(root);
q.push(NULL);
while(!q.empty()){
node* f=q.front();
if(f==NULL){
cout<<endl;
q.pop();
if(!q.empty()){
q.push(NULL);
}
}
else{
cout<<f->data;
q.pop();
if(f->left){
q.push(f->left);
}
if(f->right){
q.push(f->right);
}
}
}
return;
}
class HBPair{
public:
int height;
bool balanced;
};
HBPair isHeightBalanced(node* root){
HBPair p;
if(root==NULL){
p.height=0;
p.balanced=true;
return p;
}
//rec case
HBPair left=isHeightBalanced(root->left);
HBPair right=isHeightBalanced(root->right);
p.height=max(left.height,right.height)+1;
if(abs(left.height-right.height)<=1 and left.balanced and right.balanced){ //abs=absolute value
p.balanced=true;
}
else{
p.balanced=false;
}
return p;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
// code starts
node* root=buildtree();
printAsTree(root);
cout<<endl;
HBPair q;
q=isHeightBalanced(root);
if(q.balanced){
cout<<"It is balanced";
}
else{
cout<<"It is not balanced";
}
} | [
"noreply@github.com"
] | noreply@github.com |
e96818645d6cb4c623216f762f66e94caa58b31b | 899774b7e97fb12cdd3585c9df6cfba04237f984 | /xsns_hlw8012.ino | 32ce62a4d33a309b6b70c30b4402b7675992f7a2 | [] | no_license | TuHuynhthanh/stu-01 | 8689471e844de36a7b60b281851029197f2ebc49 | 833c38b771353679540fe0485633be20503cf2f0 | refs/heads/master | 2021-01-02T08:31:23.598226 | 2017-08-02T02:58:39 | 2017-08-02T02:58:39 | 99,017,679 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,146 | ino |
/*********************************************************************************************\
* HLW8012 - Energy
*
* Based on Source: Shenzhen Heli Technology Co., Ltd
\*********************************************************************************************/
#define FEATURE_POWER_LIMIT true
/*********************************************************************************************/
#define HLW_PREF 10000 // 1000.0W
#define HLW_UREF 2200 // 220.0V
#define HLW_IREF 4545 // 4.545A
byte hlw_pminflg = 0;
byte hlw_pmaxflg = 0;
byte hlw_uminflg = 0;
byte hlw_umaxflg = 0;
byte hlw_iminflg = 0;
byte hlw_imaxflg = 0;
byte power_steady_cntr;
byte hlw_mkwh_state = 0;
#if FEATURE_POWER_LIMIT
byte hlw_mplr_counter = 0;
uint16_t hlw_mplh_counter = 0;
uint16_t hlw_mplw_counter = 0;
#endif // FEATURE_POWER_LIMIT
byte hlw_SELflag;
byte hlw_cf_timer;
byte hlw_cf1_timer;
byte hlw_fifth_second;
byte hlw_startup;
unsigned long hlw_cf_plen;
unsigned long hlw_cf_last;
unsigned long hlw_cf1_plen;
unsigned long hlw_cf1_last;
unsigned long hlw_cf1_ptot;
unsigned long hlw_cf1_pcnt;
unsigned long hlw_cf1u_plen;
unsigned long hlw_cf1i_plen;
unsigned long hlw_Ecntr;
unsigned long hlw_EDcntr;
unsigned long hlw_kWhtoday;
uint32_t hlw_lasttime;
unsigned long hlw_cf1u_pcntmax;
unsigned long hlw_cf1i_pcntmax;
Ticker tickerHLW;
#ifndef USE_WS2812_DMA // Collides with Neopixelbus but solves exception
void hlw_cf_interrupt() ICACHE_RAM_ATTR;
void hlw_cf1_interrupt() ICACHE_RAM_ATTR;
#endif // USE_WS2812_DMA
void hlw_cf_interrupt() // Service Power
{
hlw_cf_plen = micros() - hlw_cf_last;
hlw_cf_last = micros();
if (hlw_cf_plen > 4000000) {
hlw_cf_plen = 0; // Just powered on
}
hlw_cf_timer = 15; // Support down to 4W which takes about 3 seconds
hlw_EDcntr++;
hlw_Ecntr++;
}
void hlw_cf1_interrupt() // Service Voltage and Current
{
hlw_cf1_plen = micros() - hlw_cf1_last;
hlw_cf1_last = micros();
if ((hlw_cf1_timer > 2) && (hlw_cf1_timer < 8)) { // Allow for 300 mSec set-up time and measure for up to 1 second
hlw_cf1_ptot += hlw_cf1_plen;
hlw_cf1_pcnt++;
if (10 == hlw_cf1_pcnt) {
hlw_cf1_timer = 8; // We need up to ten samples within 1 second (low current could take up to 0.3 second)
}
}
}
void hlw_200mS()
{
unsigned long hlw_len;
unsigned long hlw_temp;
hlw_fifth_second++;
if (5 == hlw_fifth_second) {
hlw_fifth_second = 0;
if (hlw_EDcntr) {
hlw_len = 10000 / hlw_EDcntr;
hlw_EDcntr = 0;
hlw_temp = ((HLW_PREF * sysCfg.hlw_pcal) / hlw_len) / 36;
hlw_kWhtoday += hlw_temp;
rtcMem.hlw_kWhtoday = hlw_kWhtoday;
}
if (rtcTime.Valid) {
if (rtc_loctime() == rtc_midnight()) {
sysCfg.hlw_kWhyesterday = hlw_kWhtoday;
sysCfg.hlw_kWhtotal += (hlw_kWhtoday / 1000);
rtcMem.hlw_kWhtotal = sysCfg.hlw_kWhtotal;
hlw_kWhtoday = 0;
rtcMem.hlw_kWhtoday = hlw_kWhtoday;
hlw_mkwh_state = 3;
}
if ((rtcTime.Hour == sysCfg.hlw_mkwhs) && (3 == hlw_mkwh_state)) {
hlw_mkwh_state = 0;
}
if (hlw_startup && (rtcTime.DayOfYear == sysCfg.hlw_kWhdoy)) {
hlw_kWhtoday = sysCfg.hlw_kWhtoday;
rtcMem.hlw_kWhtoday = hlw_kWhtoday;
hlw_startup = 0;
}
}
}
if (hlw_cf_timer) {
hlw_cf_timer--;
if (!hlw_cf_timer) {
hlw_cf_plen = 0; // No load for over three seconds
}
}
hlw_cf1_timer++;
if (hlw_cf1_timer >= 8) {
hlw_cf1_timer = 0;
hlw_SELflag = (hlw_SELflag) ? 0 : 1;
digitalWrite(pin[GPIO_HLW_SEL], hlw_SELflag);
if (hlw_cf1_pcnt) {
hlw_cf1_plen = hlw_cf1_ptot / hlw_cf1_pcnt;
} else {
hlw_cf1_plen = 0;
}
if (hlw_SELflag) {
hlw_cf1u_plen = hlw_cf1_plen;
hlw_cf1u_pcntmax = hlw_cf1_pcnt;
} else {
hlw_cf1i_plen = hlw_cf1_plen;
hlw_cf1i_pcntmax = hlw_cf1_pcnt;
}
hlw_cf1_ptot = 0;
hlw_cf1_pcnt = 0;
}
}
void hlw_savestate()
{
sysCfg.hlw_kWhdoy = (rtcTime.Valid) ? rtcTime.DayOfYear : 0;
sysCfg.hlw_kWhtoday = hlw_kWhtoday;
sysCfg.hlw_kWhtotal = rtcMem.hlw_kWhtotal;
}
boolean hlw_readEnergy(byte option, float &et, float &ed, uint16_t &e, uint16_t &w, uint16_t &u, float &i, float &c)
{
unsigned long cur_kWhtoday = hlw_kWhtoday;
unsigned long hlw_len;
unsigned long hlw_temp;
unsigned long hlw_w;
unsigned long hlw_u;
unsigned long hlw_i;
int hlw_period;
int hlw_interval;
//char log[LOGSZ];
//snprintf_P(log, sizeof(log), PSTR("HLW: CF %d, CF1U %d (%d), CF1I %d (%d)"), hlw_cf_plen, hlw_cf1u_plen, hlw_cf1u_pcntmax, hlw_cf1i_plen, hlw_cf1i_pcntmax);
//addLog(LOG_LEVEL_DEBUG, log);
et = (float)(rtcMem.hlw_kWhtotal + (cur_kWhtoday / 1000)) / 100000;
if (cur_kWhtoday) {
ed = (float)cur_kWhtoday / 100000000;
} else {
ed = 0;
}
if (option) {
if (!hlw_lasttime) {
hlw_period = sysCfg.tele_period;
} else {
hlw_period = rtc_loctime() - hlw_lasttime;
}
hlw_lasttime = rtc_loctime();
hlw_interval = 3600 / hlw_period;
if (hlw_Ecntr) {
hlw_len = hlw_period * 1000000 / hlw_Ecntr;
hlw_Ecntr = 0;
hlw_temp = ((HLW_PREF * sysCfg.hlw_pcal) / hlw_len) / hlw_interval;
e = hlw_temp / 10;
} else {
e = 0;
}
}
if (hlw_cf_plen) {
hlw_w = (HLW_PREF * sysCfg.hlw_pcal) / hlw_cf_plen;
w = hlw_w / 10;
} else {
w = 0;
}
if (hlw_cf1u_plen && (w || (power &1))) {
hlw_u = (HLW_UREF * sysCfg.hlw_ucal) / hlw_cf1u_plen;
u = hlw_u / 10;
} else {
u = 0;
}
if (hlw_cf1i_plen && w) {
hlw_i = (HLW_IREF * sysCfg.hlw_ical) / hlw_cf1i_plen;
i = (float)hlw_i / 1000;
} else {
i = 0;
}
if (hlw_i && hlw_u && hlw_w && w) {
hlw_temp = (hlw_w * 100) / ((hlw_u * hlw_i) / 1000);
if (hlw_temp > 100) {
hlw_temp = 100;
}
c = (float)hlw_temp / 100;
} else {
c = 0;
}
return true;
}
void hlw_init()
{
if (!sysCfg.hlw_pcal || (4975 == sysCfg.hlw_pcal)) {
sysCfg.hlw_pcal = HLW_PREF_PULSE;
sysCfg.hlw_ucal = HLW_UREF_PULSE;
sysCfg.hlw_ical = HLW_IREF_PULSE;
}
hlw_cf_plen = 0;
hlw_cf_last = 0;
hlw_cf1_plen = 0;
hlw_cf1_last = 0;
hlw_cf1u_plen = 0;
hlw_cf1i_plen = 0;
hlw_cf1u_pcntmax = 0;
hlw_cf1i_pcntmax = 0;
hlw_Ecntr = 0;
hlw_EDcntr = 0;
hlw_kWhtoday = (RTC_Valid()) ? rtcMem.hlw_kWhtoday : 0;
hlw_SELflag = 0; // Voltage;
pinMode(pin[GPIO_HLW_SEL], OUTPUT);
digitalWrite(pin[GPIO_HLW_SEL], hlw_SELflag);
pinMode(pin[GPIO_HLW_CF1], INPUT_PULLUP);
attachInterrupt(pin[GPIO_HLW_CF1], hlw_cf1_interrupt, FALLING);
pinMode(pin[GPIO_HLW_CF], INPUT_PULLUP);
attachInterrupt(pin[GPIO_HLW_CF], hlw_cf_interrupt, FALLING);
hlw_startup = 1;
hlw_lasttime = 0;
hlw_fifth_second = 0;
hlw_cf_timer = 0;
hlw_cf1_timer = 0;
tickerHLW.attach_ms(200, hlw_200mS);
}
/********************************************************************************************/
boolean hlw_margin(byte type, uint16_t margin, uint16_t value, byte &flag, byte &saveflag)
{
byte change;
if (!margin) {
return false;
}
change = saveflag;
if (type) {
flag = (value > margin);
} else {
flag = (value < margin);
}
saveflag = flag;
return (change != saveflag);
}
void hlw_setPowerSteadyCounter(byte value)
{
power_steady_cntr = 2;
}
void hlw_margin_chk()
{
char log[LOGSZ];
char svalue[200]; // was MESSZ
float pet;
float ped;
float pi;
float pc;
uint16_t uped;
uint16_t piv;
uint16_t pe;
uint16_t pw;
uint16_t pu;
boolean flag;
boolean jsonflg;
if (power_steady_cntr) {
power_steady_cntr--;
return;
}
hlw_readEnergy(0, pet, ped, pe, pw, pu, pi, pc);
if (power && (sysCfg.hlw_pmin || sysCfg.hlw_pmax || sysCfg.hlw_umin || sysCfg.hlw_umax || sysCfg.hlw_imin || sysCfg.hlw_imax)) {
piv = (uint16_t)(pi * 1000);
// snprintf_P(log, sizeof(log), PSTR("HLW: W %d, U %d, I %d"), pw, pu, piv);
// addLog(LOG_LEVEL_DEBUG, log);
snprintf_P(svalue, sizeof(svalue), PSTR("{"));
jsonflg = 0;
if (hlw_margin(0, sysCfg.hlw_pmin, pw, flag, hlw_pminflg)) {
snprintf_P(svalue, sizeof(svalue), PSTR("%s%s\"PowerLow\":\"%s\""), svalue, (jsonflg)?", ":"", getStateText(flag));
jsonflg = 1;
}
if (hlw_margin(1, sysCfg.hlw_pmax, pw, flag, hlw_pmaxflg)) {
snprintf_P(svalue, sizeof(svalue), PSTR("%s%s\"PowerHigh\":\"%s\""), svalue, (jsonflg)?", ":"", getStateText(flag));
jsonflg = 1;
}
if (hlw_margin(0, sysCfg.hlw_umin, pu, flag, hlw_uminflg)) {
snprintf_P(svalue, sizeof(svalue), PSTR("%s%s\"VoltageLow\":\"%s\""), svalue, (jsonflg)?", ":"", getStateText(flag));
jsonflg = 1;
}
if (hlw_margin(1, sysCfg.hlw_umax, pw, flag, hlw_umaxflg)) {
snprintf_P(svalue, sizeof(svalue), PSTR("%s%s\"VoltageHigh\":\"%s\""), svalue, (jsonflg)?", ":"", getStateText(flag));
jsonflg = 1;
}
if (hlw_margin(0, sysCfg.hlw_imin, piv, flag, hlw_iminflg)) {
snprintf_P(svalue, sizeof(svalue), PSTR("%s%s\"CurrentLow\":\"%s\""), svalue, (jsonflg)?", ":"", getStateText(flag));
jsonflg = 1;
}
if (hlw_margin(1, sysCfg.hlw_imax, piv, flag, hlw_imaxflg)) {
snprintf_P(svalue, sizeof(svalue), PSTR("%s%s\"CurrentHigh\":\"%s\""), svalue, (jsonflg)?", ":"", getStateText(flag));
jsonflg = 1;
}
if (jsonflg) {
snprintf_P(svalue, sizeof(svalue), PSTR("%s}"), svalue);
mqtt_publish_topic_P(2, PSTR("MARGINS"), svalue);
}
}
#if FEATURE_POWER_LIMIT
// Max Power
if (sysCfg.hlw_mpl) {
if (pw > sysCfg.hlw_mpl) {
if (!hlw_mplh_counter) {
hlw_mplh_counter = sysCfg.hlw_mplh;
} else {
hlw_mplh_counter--;
if (!hlw_mplh_counter) {
snprintf_P(svalue, sizeof(svalue), PSTR("{\"MaxPowerReached\":\"%d%s\"}"), pw, (sysCfg.flag.value_units) ? " W" : "");
mqtt_publish_topic_P(1, PSTR("WARNING"), svalue);
do_cmnd_power(1, 0);
if (!hlw_mplr_counter) {
hlw_mplr_counter = MAX_POWER_RETRY +1;
}
hlw_mplw_counter = sysCfg.hlw_mplw;
}
}
}
else if (power && (pw <= sysCfg.hlw_mpl)) {
hlw_mplh_counter = 0;
hlw_mplr_counter = 0;
hlw_mplw_counter = 0;
}
if (!power) {
if (hlw_mplw_counter) {
hlw_mplw_counter--;
} else {
if (hlw_mplr_counter) {
hlw_mplr_counter--;
if (hlw_mplr_counter) {
snprintf_P(svalue, sizeof(svalue), PSTR("{\"PowerMonitor\":\"%s\"}"), getStateText(1));
mqtt_publish_topic_P(5, PSTR("POWERMONITOR"), svalue);
do_cmnd_power(1, 1);
} else {
snprintf_P(svalue, sizeof(svalue), PSTR("{\"MaxPowerReachedRetry\":\"%s\"}"), getStateText(0));
mqtt_publish_topic_P(1, PSTR("WARNING"), svalue);
}
}
}
}
}
// Max Energy
if (sysCfg.hlw_mkwh) {
uped = (uint16_t)(ped * 1000);
if (!hlw_mkwh_state && (rtcTime.Hour == sysCfg.hlw_mkwhs)) {
hlw_mkwh_state = 1;
snprintf_P(svalue, sizeof(svalue), PSTR("{\"EnergyMonitor\":\"%s\"}"), getStateText(1));
mqtt_publish_topic_P(5, PSTR("ENERGYMONITOR"), svalue);
do_cmnd_power(1, 1);
}
else if ((1 == hlw_mkwh_state) && (uped >= sysCfg.hlw_mkwh)) {
hlw_mkwh_state = 2;
dtostrf(ped, 1, 3, svalue);
snprintf_P(svalue, sizeof(svalue), PSTR("{\"MaxEnergyReached\":\"%s%s\"}"), svalue, (sysCfg.flag.value_units) ? " kWh" : "");
mqtt_publish_topic_P(1, PSTR("WARNING"), svalue);
do_cmnd_power(1, 0);
}
}
#endif // FEATURE_POWER_LIMIT
}
/*********************************************************************************************\
* Commands
\*********************************************************************************************/
boolean hlw_command(char *type, uint16_t index, char *dataBuf, uint16_t data_len, int16_t payload, char *svalue, uint16_t ssvalue)
{
boolean serviced = true;
if (!strcmp_P(type,PSTR("POWERLOW"))) {
if ((data_len > 0) && (payload >= 0) && (payload < 3601)) {
sysCfg.hlw_pmin = payload;
}
snprintf_P(svalue, ssvalue, PSTR("{\"PowerLow\":\"%d%s\"}"), sysCfg.hlw_pmin, (sysCfg.flag.value_units) ? " W" : "");
}
else if (!strcmp_P(type,PSTR("POWERHIGH"))) {
if ((data_len > 0) && (payload >= 0) && (payload < 3601)) {
sysCfg.hlw_pmax = payload;
}
snprintf_P(svalue, ssvalue, PSTR("{\"PowerHigh\":\"%d%s\"}"), sysCfg.hlw_pmax, (sysCfg.flag.value_units) ? " W" : "");
}
else if (!strcmp_P(type,PSTR("VOLTAGELOW"))) {
if ((data_len > 0) && (payload >= 0) && (payload < 501)) {
sysCfg.hlw_umin = payload;
}
snprintf_P(svalue, ssvalue, PSTR("{\"VoltageLow\":\"%d%s\"}"), sysCfg.hlw_umin, (sysCfg.flag.value_units) ? " V" : "");
}
else if (!strcmp_P(type,PSTR("VOLTAGEHIGH"))) {
if ((data_len > 0) && (payload >= 0) && (payload < 501)) {
sysCfg.hlw_umax = payload;
}
snprintf_P(svalue, ssvalue, PSTR("[\"VoltageHigh\":\"%d%s\"}"), sysCfg.hlw_umax, (sysCfg.flag.value_units) ? " V" : "");
}
else if (!strcmp_P(type,PSTR("CURRENTLOW"))) {
if ((data_len > 0) && (payload >= 0) && (payload < 16001)) {
sysCfg.hlw_imin = payload;
}
snprintf_P(svalue, ssvalue, PSTR("{\"CurrentLow\":\"%d%s\"}"), sysCfg.hlw_imin, (sysCfg.flag.value_units) ? " mA" : "");
}
else if (!strcmp_P(type,PSTR("CURRENTHIGH"))) {
if ((data_len > 0) && (payload >= 0) && (payload < 16001)) {
sysCfg.hlw_imax = payload;
}
snprintf_P(svalue, ssvalue, PSTR("{\"CurrentHigh\":\"%d%s\"}"), sysCfg.hlw_imax, (sysCfg.flag.value_units) ? " mA" : "");
}
else if (!strcmp_P(type,PSTR("ENERGYRESET"))) {
if ((data_len > 0) && (payload >= 1) && (payload <= 3)) {
switch (payload) {
case 1:
hlw_kWhtoday = 0;
rtcMem.hlw_kWhtoday = 0;
sysCfg.hlw_kWhtoday = 0;
break;
case 2:
sysCfg.hlw_kWhyesterday = 0;
break;
case 3:
rtcMem.hlw_kWhtotal = 0;
sysCfg.hlw_kWhtotal = rtcMem.hlw_kWhtotal;
break;
}
}
char stemp0[10];
char stemp1[10];
char stemp2[10];
dtostrf((float)sysCfg.hlw_kWhyesterday / 100000000, 1, sysCfg.flag.energy_resolution, stemp0);
dtostrf((float)rtcMem.hlw_kWhtoday / 100000000, 1, sysCfg.flag.energy_resolution, stemp1);
dtostrf((float)(rtcMem.hlw_kWhtotal + (hlw_kWhtoday / 1000)) / 100000, 1, sysCfg.flag.energy_resolution, stemp2);
snprintf_P(svalue, ssvalue, PSTR("{\"EnergyReset\":{\"Total\":%s, \"Yesterday\":%s, \"Today\":%s}}"), stemp2, stemp0, stemp1);
}
else if (!strcmp_P(type,PSTR("HLWPCAL"))) {
if ((data_len > 0) && (payload > 0) && (payload < 32001)) {
sysCfg.hlw_pcal = (payload > 9999) ? payload : HLW_PREF_PULSE; // 12530
}
snprintf_P(svalue, ssvalue, PSTR("(\"HlwPcal\":\"%d%s\"}"), sysCfg.hlw_pcal, (sysCfg.flag.value_units) ? " uS" : "");
}
else if (!strcmp_P(type,PSTR("HLWUCAL"))) {
if ((data_len > 0) && (payload > 0) && (payload < 32001)) {
sysCfg.hlw_ucal = (payload > 999) ? payload : HLW_UREF_PULSE; // 1950
}
snprintf_P(svalue, ssvalue, PSTR("{\"HlwUcal\":\"%d%s\"}"), sysCfg.hlw_ucal, (sysCfg.flag.value_units) ? " uS" : "");
}
else if (!strcmp_P(type,PSTR("HLWICAL"))) {
if ((data_len > 0) && (payload > 0) && (payload < 32001)) {
sysCfg.hlw_ical = (payload > 2499) ? payload : HLW_IREF_PULSE; // 3500
}
snprintf_P(svalue, ssvalue, PSTR("{\"HlwIcal\":\"%d%s\"}"), sysCfg.hlw_ical, (sysCfg.flag.value_units) ? " uS" : "");
}
#if FEATURE_POWER_LIMIT
else if (!strcmp_P(type,PSTR("MAXPOWER"))) {
if ((data_len > 0) && (payload >= 0) && (payload < 3601)) {
sysCfg.hlw_mpl = payload;
}
snprintf_P(svalue, ssvalue, PSTR("{\"MaxPower\":\"%d%s\"}"), sysCfg.hlw_mpl, (sysCfg.flag.value_units) ? " W" : "");
}
else if (!strcmp_P(type,PSTR("MAXPOWERHOLD"))) {
if ((data_len > 0) && (payload >= 0) && (payload < 3601)) {
sysCfg.hlw_mplh = (1 == payload) ? MAX_POWER_HOLD : payload;
}
snprintf_P(svalue, ssvalue, PSTR("{\"MaxPowerHold\":\"%d%s\"}"), sysCfg.hlw_mplh, (sysCfg.flag.value_units) ? " Sec" : "");
}
else if (!strcmp_P(type,PSTR("MAXPOWERWINDOW"))) {
if ((data_len > 0) && (payload >= 0) && (payload < 3601)) {
sysCfg.hlw_mplw = (1 == payload) ? MAX_POWER_WINDOW : payload;
}
snprintf_P(svalue, ssvalue, PSTR("{\"MaxPowerWindow\":\"%d%s\"}"), sysCfg.hlw_mplw, (sysCfg.flag.value_units) ? " Sec" : "");
}
else if (!strcmp_P(type,PSTR("SAFEPOWER"))) {
if ((data_len > 0) && (payload >= 0) && (payload < 3601)) {
sysCfg.hlw_mspl = payload;
}
snprintf_P(svalue, ssvalue, PSTR("{\"SafePower\":\"%d%s\"}"), sysCfg.hlw_mspl, (sysCfg.flag.value_units) ? " W" : "");
}
else if (!strcmp_P(type,PSTR("SAFEPOWERHOLD"))) {
if ((data_len > 0) && (payload >= 0) && (payload < 3601)) {
sysCfg.hlw_msplh = (1 == payload) ? SAFE_POWER_HOLD : payload;
}
snprintf_P(svalue, ssvalue, PSTR("{\"SafePowerHold\":\"%d%s\"}"), sysCfg.hlw_msplh, (sysCfg.flag.value_units) ? " Sec" : "");
}
else if (!strcmp_P(type,PSTR("SAFEPOWERWINDOW"))) {
if ((data_len > 0) && (payload >= 0) && (payload < 1440)) {
sysCfg.hlw_msplw = (1 == payload) ? SAFE_POWER_WINDOW : payload;
}
snprintf_P(svalue, ssvalue, PSTR("{\"SafePowerWindow\":\"%d%s\"}"), sysCfg.hlw_msplw, (sysCfg.flag.value_units) ? " Min" : "");
}
else if (!strcmp_P(type,PSTR("MAXENERGY"))) {
if ((data_len > 0) && (payload >= 0) && (payload < 3601)) {
sysCfg.hlw_mkwh = payload;
hlw_mkwh_state = 3;
}
snprintf_P(svalue, ssvalue, PSTR("{\"MaxEnergy\":\"%d%s\"}"), sysCfg.hlw_mkwh, (sysCfg.flag.value_units) ? " Wh" : "");
}
else if (!strcmp_P(type,PSTR("MAXENERGYSTART"))) {
if ((data_len > 0) && (payload >= 0) && (payload < 24)) {
sysCfg.hlw_mkwhs = payload;
}
snprintf_P(svalue, ssvalue, PSTR("{\"MaxEnergyStart\":\"%d%s\"}"), sysCfg.hlw_mkwhs, (sysCfg.flag.value_units) ? " Hr" : "");
}
#endif // FEATURE_POWER_LIMIT
else {
serviced = false;
}
return serviced;
}
/*********************************************************************************************\
* Presentation
\*********************************************************************************************/
void hlw_mqttStat(byte option, char* svalue, uint16_t ssvalue)
{
char stemp0[10];
char stemp1[10];
char stemp2[10];
char stemp3[10];
char stemp4[10];
char speriod[20];
float pet;
float ped;
float pi;
float pc;
uint16_t pe;
uint16_t pw;
uint16_t pu;
hlw_readEnergy(option, pet, ped, pe, pw, pu, pi, pc);
dtostrf((float)sysCfg.hlw_kWhyesterday / 100000000, 1, sysCfg.flag.energy_resolution, stemp0);
dtostrf(ped, 1, sysCfg.flag.energy_resolution, stemp1);
dtostrf(pc, 1, 2, stemp2);
dtostrf(pi, 1, 3, stemp3);
dtostrf(pet, 1, sysCfg.flag.energy_resolution, stemp4);
snprintf_P(speriod, sizeof(speriod), PSTR(", \"Period\":%d"), pe);
snprintf_P(svalue, ssvalue, PSTR("%s\"Total\":%s, \"Yesterday\":%s, \"Today\":%s%s, \"Power\":%d, \"Factor\":%s, \"Voltage\":%d, \"Current\":%s}"),
svalue, stemp4, stemp0, stemp1, (option) ? speriod : "", pw, stemp2, pu, stemp3);
#ifdef USE_DOMOTICZ
dtostrf(pet * 1000, 1, 1, stemp1);
domoticz_sensor4(pw, stemp1);
#endif // USE_DOMOTICZ
}
void hlw_mqttPresent()
{
// {"Time":"2017-03-04T13:37:24", "Total":0.013, "Yesterday":0.013, "Today":0.000, "Period":0, "Power":0, "Factor":0.00, "Voltage":0, "Current":0.000}
char svalue[200]; // was MESSZ
snprintf_P(svalue, sizeof(svalue), PSTR("{\"Time\":\"%s\", "), getDateTime().c_str());
hlw_mqttStat(1, svalue, sizeof(svalue));
mqtt_publish_topic_P(2, PSTR("ENERGY"), svalue);
}
void hlw_mqttStatus(char* svalue, uint16_t ssvalue)
{
snprintf_P(svalue, ssvalue, PSTR("{\"StatusPWR\":{"));
hlw_mqttStat(0, svalue, ssvalue);
snprintf_P(svalue, ssvalue, PSTR("%s}"), svalue);
}
#ifdef USE_WEBSERVER
const char HTTP_ENERGY_SNS[] PROGMEM =
"<tr><th>Điện áp</th><td>%d V</td></tr>"
"<tr><th>Dòng</th><td>%s A</td></tr>"
"<tr><th>Công suất</th><td>%d W</td></tr>"
"<tr><th>Hệ số công suất</th><td>%s</td></tr>"
"<tr><th>Hôm nay dùng</th><td>%s kWh</td></tr>"
"<tr><th>Hôm qua dùng</th><td>%s kWh</td></tr>"
"<tr><th>Tổng dùng</th><td>%s kWh</td></tr>";
String hlw_webPresent()
{
String page = "";
char stemp[10];
char stemp2[10];
char stemp3[10];
char stemp4[10];
char stemp5[10];
char sensor[320];
float pet;
float ped;
float pi;
float pc;
uint16_t pe;
uint16_t pw;
uint16_t pu;
hlw_readEnergy(0, pet, ped, pe, pw, pu, pi, pc);
dtostrf(pi, 1, 3, stemp);
dtostrf(pc, 1, 2, stemp2);
dtostrf(ped, 1, sysCfg.flag.energy_resolution, stemp3);
dtostrf((float)sysCfg.hlw_kWhyesterday / 100000000, 1, sysCfg.flag.energy_resolution, stemp4);
dtostrf(pet, 1, sysCfg.flag.energy_resolution, stemp5);
snprintf_P(sensor, sizeof(sensor), HTTP_ENERGY_SNS, pu, stemp, pw, stemp2, stemp3, stemp4, stemp5);
page += sensor;
return page;
}
#endif // USE_WEBSERVER
| [
"tu.huynhthanh@stu.edu.vn"
] | tu.huynhthanh@stu.edu.vn |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.