blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
201
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 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
sequencelengths 1
1
| author
stringlengths 0
119
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e3152a4726a3beb2e59ff0fbe3336091dfbc5ebe | 3cd3f31d2703c66428db461c3c61d07e69b9d223 | /Tuto_Graphe_GL/src/exemples/01_static/06_histogram/02_glut/HistoGlut.h | 70de17c8783dc53dc79026de2725d28f8cbca614 | [] | no_license | bastou2316/cuda | 1195318cf0ae094d2bbbfea331fbd890bd584534 | da6a5bdb99bbfa47c9fb2ce6e65d0ca72fdd9de4 | refs/heads/master | 2016-08-11T22:16:33.928569 | 2016-04-10T23:00:57 | 2016-04-10T23:00:57 | 55,926,681 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,108 | h | #pragma once
#include "GLUTGraphWindow.h"
#include "HistoGraphe.h"
/*----------------------------------------------------------------------*\
|* Declaration *|
\*---------------------------------------------------------------------*/
/*--------------------------------------*\
|* Public *|
\*-------------------------------------*/
class HistoGlut
{
/*--------------------------------------*\
|* Constructor *|
\*-------------------------------------*/
public:
HistoGlut(int w, int h, int px, int py);
virtual ~HistoGlut();
/*--------------------------------------*\
|* Methodes *|
\*-------------------------------------*/
public:
/*--------------------------------------*\
|* Attribut *|
\*-------------------------------------*/
private:
// Tools
HistoGraphe* ptrGraphe;
GLUTGraphWindow* ptrGLUTGraphWindow;
};
/*----------------------------------------------------------------------*\
|* End *|
\*---------------------------------------------------------------------*/
| [
"[email protected]"
] | |
1c17add65e44c78e38d42da06c17e609d82929ae | 782e8b221d2d106a15a17e60e8620c7fed278429 | /cachelib/shm/tests/test_page_size.cpp | 8ebe5b249cdc88d0f5d33661f3bace8c91b30e11 | [
"Apache-2.0"
] | permissive | ilkerhalil/CacheLib | d02985bba68af40c036fc12411efe317487c50de | d131b686ac135ea873dc4bb62e9133858eaad238 | refs/heads/main | 2023-08-18T07:39:27.272731 | 2021-09-11T02:49:48 | 2021-09-11T02:50:55 | 405,455,233 | 1 | 0 | Apache-2.0 | 2021-09-11T18:33:55 | 2021-09-11T18:33:54 | null | UTF-8 | C++ | false | false | 2,278 | cpp | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "cachelib/shm/PosixShmSegment.h"
#include "cachelib/shm/Shm.h"
#include "cachelib/shm/ShmCommon.h"
#include "cachelib/shm/SysVShmSegment.h"
#include "cachelib/shm/tests/common.h"
using facebook::cachelib::detail::getPageAlignedSize;
using facebook::cachelib::detail::getPageSizeInSMap;
using facebook::cachelib::detail::isPageAlignedSize;
namespace facebook {
namespace cachelib {
namespace tests {
void ShmTest::testPageSize(PageSizeT p, bool posix) {
ShmSegmentOpts opts{p};
size_t size = getPageAlignedSize(4096, p);
ASSERT_TRUE(isPageAlignedSize(size, p));
// create with unaligned size
ASSERT_NO_THROW({
ShmSegment s(ShmNew, segmentName, size, posix, opts);
ASSERT_TRUE(s.mapAddress(nullptr));
ASSERT_EQ(p, getPageSizeInSMap(s.getCurrentMapping().addr));
});
ASSERT_NO_THROW({
ShmSegment s2(ShmAttach, segmentName, posix, opts);
ASSERT_TRUE(s2.mapAddress(nullptr));
ASSERT_EQ(p, getPageSizeInSMap(s2.getCurrentMapping().addr));
});
}
// The following tests will fail on sandcastle. THP requires sysctls to be set
// up as root and even after that, the posix api support for THP is not
// complete yet. See https://fburl.com/f0umrcwq . We will re-enable these
// tests on sandcastle when these get fixed.
TEST_F(ShmTestPosix, PageSizesNormal) { testPageSize(PageSizeT::NORMAL, true); }
TEST_F(ShmTestPosix, PageSizesTwoMB) { testPageSize(PageSizeT::TWO_MB, true); }
TEST_F(ShmTestSysV, PageSizesNormal) { testPageSize(PageSizeT::NORMAL, false); }
TEST_F(ShmTestSysV, PageSizesTwoMB) { testPageSize(PageSizeT::TWO_MB, false); }
} // namespace tests
} // namespace cachelib
} // namespace facebook
| [
"[email protected]"
] | |
8c1bd732407784e65418546f8a126d2b43f17b16 | 808521268c124ce346753ce46219c29127b68b27 | /SandboxSandbox/Mitigations.cpp | 380c6d5a55844b063d22d8e01e25047e94fb26ed | [] | no_license | tomrittervg/sandboxsandbox | b709795afd77ca5e9dee52422e785391a02bf1b8 | 6b0cc2a3a5de2f57d68abb8f2ccea0f775ee2747 | refs/heads/master | 2021-01-01T04:23:13.173855 | 2017-07-14T16:23:40 | 2017-07-14T16:23:40 | 97,167,238 | 6 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 584 | cpp | #include "stdafx.h"
#include "Mitigations.h"
// ========================================
void Arbitrary_Code_Guard(bool on)
{
printf("%s: %s\n", __FUNCTION__, on ? "On" : "Off");
PROCESS_MITIGATION_DYNAMIC_CODE_POLICY policy;
if(on)
policy.Flags = 0x01;
else
policy.Flags = 0x00;
BOOL success = SetProcessMitigationPolicy(
ProcessDynamicCodePolicy,
&policy,
sizeof(policy)
);
if (!success)
GET_ERROR_AND_PRINT("set mitigation");
}
// ========================================
void ApplyMitigations()
{
Arbitrary_Code_Guard(true);
}
| [
"[email protected]"
] | |
99e416003b313943a193236f455b6993dc788970 | 5499e8b91353ef910d2514c8a57a80565ba6f05b | /garnet/tests/fidl-dangerous-identifiers/cpp/fidl.test.dangerous.method.response.arguments.camel_test.cc | 731c79747ebcb08168a798f26244d36d50dcd4b0 | [
"BSD-3-Clause"
] | permissive | winksaville/fuchsia | 410f451b8dfc671f6372cb3de6ff0165a2ef30ec | a0ec86f1d51ae8d2538ff3404dad46eb302f9b4f | refs/heads/master | 2022-11-01T11:57:38.343655 | 2019-11-01T17:06:19 | 2019-11-01T17:06:19 | 223,695,500 | 3 | 2 | BSD-3-Clause | 2022-10-13T13:47:02 | 2019-11-24T05:08:59 | C++ | UTF-8 | C++ | false | false | 293 | cc | // Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Generated by generate.py.
#include <fidl/test/dangerous/method/response/arguments/camel/cpp/fidl.h>
int main() { return 0; }
| [
"[email protected]"
] | |
98e07e2e9874c7caaa402490b798c83d584711f9 | 049dfdffbcf8bd0ab2e143a8116815f3cbb67714 | /SharedCode/Sound/SoundPlayer.h | 94cacdfdf312655a31a3e10c82d573d429fa66d2 | [] | no_license | thathollywood/PixelPyros | 2759036defcb4a2e5be3d74347dbe3a3f2648278 | 6c653bee90efa9dc2d2b95dac408aa3dd9e1684c | refs/heads/master | 2021-01-10T21:10:46.287328 | 2012-09-06T08:10:44 | 2012-09-06T08:10:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 990 | h | //
// SoundPlayer.h
// ParticlePlay5
//
// Created by Seb Lee-Delisle on 19/08/2012.
//
//
#pragma once
#include "ofMain.h"
#include "Sound.h"
class SoundPlayer {
public :
SoundPlayer(){
globalVolume = 1;
};
bool addSound(string filename, string reference, float vol = 1, float speed = 1, float speedVar = 0, string fileType = "aif", float retriggerMin = 0.02){
sounds[reference] = Sound();// = (Sound);
Sound& newsound = sounds[reference];
newsound.masterVolume = vol;
newsound.speed = speed;
newsound.speedVariation = speedVar;
newsound.minRetriggerTime = retriggerMin;
if(!newsound.addSound(defaultPath, filename, vol,fileType)) {
sounds.erase(reference);
};
};
bool playSound(string soundname, float volume = 1, float pan = 0){
if(sounds.find(soundname) == sounds.end()) return false;
sounds[soundname].play(volume * globalVolume, pan);
}
map <string, Sound> sounds;
string defaultPath;
float globalVolume;
};
| [
"[email protected]"
] | |
7cdda2d69bca910a723b7eb1577ecf23002cd5a6 | 9ee6b3ba658fb674433ade32d71d59bff9086325 | /.removed/src/fullscore/ui/PlotterEditor/KeyboardCommands.cpp | 9400f7b9505a24c259d1800c551b83a29eaf6c60 | [] | no_license | MarkOates/fullscore | 01f7aa843805f221b1547ab16deaaf91b513446e | ccd9449aa235d355bf1c24b0ff8fcc3a0fa83e23 | refs/heads/master | 2022-09-15T14:54:01.980708 | 2022-09-14T12:52:50 | 2022-09-14T12:52:50 | 33,223,354 | 1 | 0 | null | 2019-08-25T00:06:51 | 2015-04-01T02:59:18 | C++ | UTF-8 | C++ | false | false | 440 | cpp |
#include <fullscore/UI/PlotterEditor/KeyboardCommands.hpp>
#include <fullscore/UI/PlotterEditor/Actions.hpp>
namespace UI::PlotterEditor
{
KeyboardCommands::KeyboardCommands()
{
set_keyboard_commands();
}
KeyboardCommands::~KeyboardCommands()
{
}
void KeyboardCommands::set_keyboard_commands()
{
set_mapping(ALLEGRO_KEY_H, false, false, false, {Actions::SAY_HELLO_ACTION_IDENTIFIER});
}
} // namespace UI::PlotterEditor
| [
"[email protected]"
] | |
0ca96bd1c8cc61911e41a7525db0c8be88b92079 | 1f5306c3e0078995f23c3071d1406899b69baa18 | /src/GameCommand.cpp | da9178f2fa9e220f7c83bee499761eaf047374d1 | [] | no_license | oinkatron/PathfindingDemo | edd15b697b8dc92a42eeba25ba2bbc91aedb75f4 | caff736066f24b9e37e8b3c136ae5d30cef24863 | refs/heads/master | 2020-02-26T17:26:54.821124 | 2016-10-25T16:31:01 | 2016-10-25T16:31:01 | 71,756,730 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 584 | cpp | #include "../include/GameCommand.h"
vector<GameCommand*> GameCommand::cmd_pmp;
size_t GameCommand::cur_cmd = 0;
GameCommand::GameCommand()
{
cmd_pmp.push_back(this);
}
GameCommand::~GameCommand()
{
}
GameCommand* GameCommand::getNextCommand()
{
if (cur_cmd >= cmd_pmp.size())
{
flushPump();
return 0;
}
cur_cmd++;
return cmd_pmp[cur_cmd-1];
}
void GameCommand::flushPump()
{
cur_cmd = 0;
for (int i = 0; i < cmd_pmp.size(); i++)
{
delete cmd_pmp[i];
}
cmd_pmp.clear();
}
| [
"[email protected]"
] | |
9c6a43f931428179d1393c7b90c5401304f21da8 | 22b392dc072f7516d908b3b215a170c1ffec3de6 | /timentris/Input.h | 4cfacf570563321089c9952aff48052cf0180112 | [] | no_license | CruelCrow/timentris | 772f19479af959720472f0f66453a0d90ef6ef40 | 9d82cf9e7912c8428878bcb9231131a1dc966121 | refs/heads/master | 2020-05-18T17:50:53.074351 | 2018-02-05T21:22:16 | 2018-02-05T21:22:16 | 6,948,092 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,091 | h | #pragma once
#include <thread>
#include <memory>
#include <atomic>
#include <chrono>
#include <boost/predef.h>
#include <boost/lockfree/queue.hpp>
#include "TimentrisGame.h"
#include "Render.h"
#include "CircularReferenceFix.h"
#if defined(BOOST_OS_WINDOWS)
#include <Windows.h>
#elif defined(BOOST_OS_LINUX)
//
#elif defined(BOOST_OS_MACOS)
//
#endif
using namespace std;
using namespace boost::lockfree;
using namespace TimentrisMessages;
#define QUEUE_CAPACITY 1024*10
class Input {
private:
TimentrisGamePtr _gamePtr;
RenderPtr _renderPtr;
atomic<bool> _running;
queue<MSG>* _qIn;
thread* _inputLoopThreadPtr;
static void inputLoop(Input* _this);
void stopInputLoop();
public:
Input();
Input(const Input& other); //disallow copy constructor
Input& operator=(const Input&); //disallow assignment operator
~Input(void);
void attachGame(TimentrisGamePtr game);
void attachRender(RenderPtr render);
void run();
bool isRunning() const;
friend Input& operator<< (Input &i, const MSG &m);
};
typedef shared_ptr<Input> InputPtr;
//TODO: split camera input and game input | [
"[email protected]"
] | |
3352e9e78dbbca299b9df140689227b0c525a76a | 2fe5cc7977fe083ecd260ad8c9cbd213ba99365f | /tests/binaries/spu_render/spu/spurstask/render/source/fs_constant_patch.cpp | f9b054f7ea1143ecb37391904733c9b1a69a611b | [] | no_license | lasyka/ps3emu | f5feaf2fb5d3ae16652f985c2b4720b52a20a51d | 69f36338d4aa7f729d3832b91188d26c95760661 | refs/heads/master | 2023-03-18T16:43:42.507305 | 2021-02-26T23:22:33 | 2021-02-26T23:22:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,242 | cpp | #include <cell/spurs.h>
#include "spu_render.h"
#include <spu_printf.h>
#include "fs_constant_patch.h"
FsConstantPatch* FsConstantPatch::m_instance = NULL;
uint32_t FsConstantPatch::sendFragmentProgramInternal(CellGcmContextData* context, CGprogram fragmentShader){
CgBinaryProgram* fs = reinterpret_cast<CgBinaryProgram*>(fragmentShader);
uint32_t code_size = fs->ucodeSize;
uint32_t required_buffer_size = calcBufferSizeWithOverfetch(code_size);
//J Local MemoryにBufferを確保する。
uint32_t ea_reserved_buffer = (getEaSegmentCurrent() + CELL_GCM_FRAGMENT_UCODE_LOCAL_ALIGN_OFFSET - 1) & ~( CELL_GCM_FRAGMENT_UCODE_LOCAL_ALIGN_OFFSET - 1);
if(ea_reserved_buffer + required_buffer_size >= getEaSegmentEnd()){ //J セグメント内のバッファが不足した場合、次のSegmentへ移動する
switchToNextSegment(context);
ea_reserved_buffer = (getEaSegmentCurrent() + CELL_GCM_FRAGMENT_UCODE_LOCAL_ALIGN_OFFSET - 1) & ~( CELL_GCM_FRAGMENT_UCODE_LOCAL_ALIGN_OFFSET - 1);
}
setEaSegmentCurrent(ea_reserved_buffer + required_buffer_size); //J ポインタを必要なバッファ分進める
//J ucodeをLocal Memoryに転送する。
//J See also: RSX Access Ordering 1.3.4.4. SPU からのJTS 解除による制御
static vec_uint4 dirtyBuffer;
uint32_t* ucode = reinterpret_cast<uint32_t*>((uintptr_t)fs + fs->ucode);
cellDmaLargePut(ucode, ea_reserved_buffer, code_size, TAG_FOR_GPU_SYNC,0,0);
char buf[500] = {0};
//spu_printf("sendFragmentProgramInternal 1 (%x, %x, %x): %08x %08x %08x %08x\n", ucode, ea_reserved_buffer, code_size,
// ucode[0], ucode[1], ucode[2], ucode[3]);
cellDmaSmallGetf(&dirtyBuffer, ea_reserved_buffer, 4, TAG_FOR_GPU_SYNC,0,0);
//J offset値を取得する
uint32_t offset = m_instance->getOffset(ea_reserved_buffer);
return offset;
}
void FsConstantPatch::switchToNextSegment(CellGcmContextData* context){
volatile CellGcmReportData* ls_report_data_read_buffer = reinterpret_cast<CellGcmReportData*>(CELL_SPURS_LOCK_LINE);
//J Atomicを利用してReport領域のzeroメンバを非ゼロ(SHADER_PRODUCED)にマークする
//J ここでは普通にDMAで更新してもよい。
do{
cellDmaGetllar(ls_report_data_read_buffer, getEaMainMemoryReportStart(), 0, 0);
cellDmaWaitAtomicStatus();
ls_report_data_read_buffer[getSegmentIndex()].zero = SHADER_PRODUCED;
cellDmaPutllc(ls_report_data_read_buffer, getEaMainMemoryReportStart(), 0, 0);
}while(cellDmaWaitAtomicStatus());
//J RSXによって、RSX_CONSUMEDにマークさせるためにReportコマンドを設定する。
cellGcmSetReportInline(context, CELL_GCM_ZPASS_PIXEL_CNT, getSegmentIndex() + getReportIndexBegin() );
uint32_t nextSegmentIdx = (getSegmentIndex() + 1) % SEGMENT_NUM;
#if 0 //J Yieldを伴わないポーリングを行う場合
//J Atomic更新時に読み込んだデータを利用して、次のバッファのステータスを確認する。
if(unlikely(ls_report_data_read_buffer[nextSegmentIdx].zero != RSX_CONSUMED)){
spu_write_event_mask(MFC_LLR_LOST_EVENT); // LockLine Reservation 消失イベントを有効化する。
do{
spu_write_event_ack(MFC_LLR_LOST_EVENT); // LockLine Reservation 消失イベントをAcknowledgeしてリセットする。
//J LockLine Reservationとともに再度読み込みを行う
cellDmaGetllar(ls_report_data_read_buffer, getEaMainMemoryReportStart(), 0, 0);
cellDmaWaitAtomicStatus(); // Lock Line Resevationを確保する。
if(ls_report_data_read_buffer[nextSegmentIdx].zero == RSX_CONSUMED)
break;//J 更新されていれば、Breakする。
spu_read_event_status(); //J LockLine Reservation 消失イベントを待つ
}while(1);
spu_write_event_mask(0); //J LockLine Reservation 消失イベントを無効化する。
}
#else //J Yieldを伴うポーリングを行う場合
if(unlikely(ls_report_data_read_buffer[nextSegmentIdx].zero != RSX_CONSUMED)){
do{
spu_write_event_mask(MFC_LLR_LOST_EVENT); //J LockLine Reservation 消失イベントを有効化する。
spu_write_event_ack(MFC_LLR_LOST_EVENT); //J LockLine Reservation 消失イベントをAcknowledgeしてリセットする。
//J LockLine Reservationとともに再度読み込みを行う
cellDmaGetllar(ls_report_data_read_buffer, getEaMainMemoryReportStart(), 0, 0);
cellDmaWaitAtomicStatus(); //J Lock Line Resevationを確保する。
if(ls_report_data_read_buffer[nextSegmentIdx].zero == RSX_CONSUMED)
break;//J 更新されていれば、Breakする。
do{
//J Eventのノンブロッキング関数spu_stat_event_status()による
//J LockLine Reservation 消失イベント待ち
if(spu_stat_event_status()) break;
//J 最後のTaskPoll()から一定時間経過した場合は、TaskPollを実行し、必要な場合はYieldする
uint32_t current = spu_read_decrementer();
uint32_t delta = (SpuRender::decremneter > current) ? SpuRender::decremneter - current : SpuRender::decremneter + (0xffffffff - current);
if(delta > SpuRender::kTaskPollCycleInDecrementerCount){
MY_LSGUARD_CHECK();
if(cellSpursTaskPoll2()){
cellSpursYield(); //
//J Yieldから戻ってきたとき、decrementerの値が大きく変わっている可能性があるため再度読み込む
SpuRender::decremneter = spu_read_decrementer();
}
else{
SpuRender::decremneter = current;
}
MY_LSGUARD_REHASH();
//J これらの関数内で、LockLine Resevation 消失イベントが
//J 無効化される可能性があるので、先頭で再度有効化する。
break;
}
}while(1);
}while(1);
}
#endif
setSegment(nextSegmentIdx);//J 利用するセグメントを更新する
//J バッファをラップラウンドする時に、Texture Cacheをクリアする。
if (unlikely(nextSegmentIdx == 0)){
cellGcmSetWaitForIdleInline(context); //J WaitForIdleで選考するdrawコマンドを完全に終了させる
cellGcmSetInvalidateTextureCacheInline(context,CELL_GCM_INVALIDATE_TEXTURE);
}
}
inline vec_uint4 swap_hw_in_word(vec_float4 v)
{
vec_uint4 data = (vec_uint4)v;
return spu_sl(data, 16) | spu_rlmask(data, -16);
}
void patchFragmentProgramParameter(const CGprogram prog, const CGparameter param, const vec_float4* value){
const CgBinaryProgram* fs = reinterpret_cast<const CgBinaryProgram*>(prog);
const CgBinaryParameter* p = reinterpret_cast<const CgBinaryParameter*>(param);
vec_uint4* ucode = reinterpret_cast<vec_uint4*>(reinterpret_cast<uintptr_t>(fs) + fs->ucode);
uint32_t count_max = 1;
switch (p->type){
case CG_FLOAT:
case CG_BOOL:
case CG_FLOAT1:
case CG_BOOL1:
case CG_FLOAT2:
case CG_BOOL2:
case CG_FLOAT3:
case CG_BOOL3:
case CG_FLOAT4:
case CG_BOOL4:
count_max = 1;
break;
case CG_FLOAT3x3: // Assume vector4 x 3
case CG_BOOL3x3:
case CG_FLOAT3x4:
case CG_BOOL3x4:
p++;
count_max = 3;
break;
case CG_FLOAT4x3: // Assume vector4 x 4
case CG_BOOL4x3:
case CG_FLOAT4x4:
case CG_BOOL4x4:
p++;
count_max = 4;
break;
default:
MY_ASSERT(false);
break;
}
for (uint32_t cnt = 0; cnt < count_max; cnt++, p++, value++) {
if (p->embeddedConst)
{
// set embedded constants
CgBinaryEmbeddedConstant *ec = (CgBinaryEmbeddedConstant*)
(reinterpret_cast<uintptr_t>(fs) + p->embeddedConst);
vec_uint4 val;
// hw bug workaround, swap 16bit value
val = swap_hw_in_word(*value);
//J countはほぼ1〜3なので3つアンロール
uint32_t count = ec->ucodeCount;
const uint32_t* index = ec->ucodeOffset;
unsigned index0 = index[0]/16;
unsigned index1 = index[1]/16;
unsigned index2 = index[2]/16;
index1 = 1 < count ? index1 : index0;
index2 = 2 < count ? index2 : index0;
ucode[index0] = val;
ucode[index1] = val;
ucode[index2] = val;
//J 残りは条件分岐で飛ばしてからループ処理
if UNLIKELY(3 < count) {
for (unsigned i = 3; i < count; ++i) {
ucode[index[i]] = val;
}
}
}
}
} | [
"[email protected]"
] | |
071b7746290bf2c69524cf110c939c99d276edbd | 28ccb703343b7c907f65584f7ce9919281560514 | /include/FWCS/Config.hpp | 714ac7f1e3fbaf5621300217cf2c70a74c680382 | [] | no_license | TankOs/flexworld-fwcs | 9bd8416e06afc3248bddc1ce796686c053d17535 | a3bc57d800b2c89b1ee2bb5b214f01b2156d2714 | refs/heads/master | 2021-01-20T16:59:57.410855 | 2017-02-22T20:57:17 | 2017-02-22T20:57:17 | 82,851,813 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 662 | hpp | #pragma once
#if defined( _WIN32 ) || defined( __WIN32__ )
#define FWSC_SYSTEM_WINDOWS
#define WIN32_LEAN_AND_MEAN
#ifndef NOMINMAX
#define NOMINMAX
#endif
#endif
#if defined( FWSC_SYSTEM_WINDOWS ) && !defined( FWSC_STATIC )
#ifdef FWSC_EXPORTS
#define FWSC_API __declspec( dllexport )
#else
#define FWSC_API __declspec( dllimport )
#endif
#else
#define FWSC_API
#endif
#ifdef _MSC_VER
#pragma warning(disable : 4251) // Suppress a warning which is meaningless for us
#pragma warning(disable : 4503) // Suppress warnings about truncated names. Enable again if linker errors occur.
#endif
/** FlexWorld component system.
*/
namespace cs {
}
| [
"[email protected]"
] | |
54139359fe993c11f5c1b65af4c7a0ecfaa5bb45 | bbb36da28e5036805a6d3b739e007009ad917303 | /BattleTank/Source/BattleTank/Tank.h | 9f507eed618193bea99de87d06be141198728365 | [] | no_license | happylittlelark/04_BattleTank | 6eb73afc73d15eee4f3883555860fc9c7b2c0489 | b595b6c9ea28b30ac1f01ffcd043166b59b1f966 | refs/heads/master | 2021-01-23T23:13:39.945059 | 2017-09-27T18:39:09 | 2017-09-27T18:39:09 | 102,959,700 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,251 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Pawn.h"
#include "Tank.generated.h"
class UTankBarrel;
class UTankTurret;
class UTankAimingComponent;
class AProjectile;
class UTankMovementComponent;
UCLASS()
class BATTLETANK_API ATank : public APawn
{
GENERATED_BODY()
public:
// Sets default values for this pawn's properties
ATank();
void AimAt(FVector HitLocation);
UFUNCTION(BlueprintCallable)
void Fire();
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
UPROPERTY(BlueprintReadOnly)
UTankAimingComponent* TankAimComponent = nullptr;
UPROPERTY(BlueprintReadOnly)
UTankMovementComponent* TankMoveComponent = nullptr;
private:
// Called to bind functionality to input
//virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;
UPROPERTY(EditAnywhere, Category = Firing)
float LaunchSpeed = 10000;
UPROPERTY(EditDefaultsOnly, Category = Firing)
float ReloadTime = 3.0f;
double LastFireTime = 0;
UPROPERTY(EditDefaultsOnly, Category = Setup)
TSubclassOf<AProjectile> ProjectileBlueprint;
UTankBarrel* TankBarrel;
UTankTurret* Turret;
};
| [
"[email protected]"
] | |
b6ae620b8e2981a70e6b789137cda6be67f9e7ba | 946a169c5e667fad79f21538cee0ffaee8bc8e41 | /BattleTank/Source/BattleTank/Public/TankBarrel.h | 4c4810907f320190e7ae67198517993274cf339d | [] | no_license | RomanSolomatin/04_BattleTank-1 | 986c65fb200b5c4233243ad6e17fb382b7d44916 | 678dd95a3e9327b645b176c23921a37b5305d7d3 | refs/heads/master | 2020-03-10T20:36:59.960537 | 2017-06-07T16:15:55 | 2017-06-07T16:15:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 755 | h | // Copyright Nicholas Wilkie
#pragma once
#include "Components/StaticMeshComponent.h"
#include "TankBarrel.generated.h"
/**
*
*/
UCLASS(meta = (BlueprintSpawnableComponent))
class BATTLETANK_API UTankBarrel : public UStaticMeshComponent
{
GENERATED_BODY()
public:
// -1 is max downward movement, and +1 is max upward movement
void Elevate(float RelativeSpeed);
private:
UPROPERTY(EditDefaultsOnly, Category = "Setup") // If adding new tanks, make this EditAnywhere to allow different barrel movement speeds in editor.
float MaxDegreesPerSecond = 7; // Sensible default
UPROPERTY(EditDefaultsOnly, Category = "Setup")
float MaxElevationDegrees = 30;
UPROPERTY(EditDefaultsOnly, Category = "Setup")
float MinElevationDegrees = -2;
};
| [
"[email protected]"
] | |
a90018ecee0d0d500241ec2a81f107a76f0fe5b0 | 337d62ee666c693e5cb4ba66f9c06d61e1772cec | /main.cpp | 5a0253bc0b3660c1793e61486145524bb168132d | [] | no_license | jaynathani/Simulated-Annealing-implementation-for-Hardware-Software-Partitioning-of-PSoC | 6766e34dca9cb47ccbbcd760d1c0f365e1e2a792 | 935f49af15acf4f08ce4578f186ed76a9ee2115e | refs/heads/master | 2021-01-22T09:41:29.009802 | 2016-12-19T00:12:55 | 2016-12-19T00:12:55 | 76,078,595 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 234 | cpp | #include <iostream>
#include <vector>
#include "Simulated-Annealing-Algorithm.h"
using namespace std;
int main()
{
GetData();
// displayOutput(lines); //Debug
// CalculateCostFunct(lines); //Debug
SA_Algorithm();
return 0;
}
| [
"[email protected]"
] | |
b5ac5982c3e7cd896d6227b15eb077f8d119fdc2 | 36183993b144b873d4d53e7b0f0dfebedcb77730 | /GameDevelopment/AI Game Programming Wisdom/SourceCode/03 Pathfinding with Astar/01 Matthews/ase/ase.h | df521638d736d97aefe7e07e2db0c1c1058bc7d2 | [] | no_license | alecnunn/bookresources | b95bf62dda3eb9b0ba0fb4e56025c5c7b6d605c0 | 4562f6430af5afffde790c42d0f3a33176d8003b | refs/heads/master | 2020-04-12T22:28:54.275703 | 2018-12-22T09:00:31 | 2018-12-22T09:00:31 | 162,790,540 | 20 | 14 | null | null | null | null | UTF-8 | C++ | false | false | 458 | h |
#ifndef _AFX_ASE_H_
#define _AFX_ASE_H_
#if _MSC_VER > 1000
#pragma once
#endif
#ifndef __AFXWIN_H__
#error include 'stdafx.h' before including this file for PCH
#endif
#include "resource.h"
class CAseApp : public CWinApp
{
public:
CAseApp();
//{{AFX_VIRTUAL(CAseApp)
public:
virtual BOOL InitInstance();
//}}AFX_VIRTUAL
//{{AFX_MSG(CAseApp)
afx_msg void OnAppAbout();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
#endif
| [
"[email protected]"
] | |
f69e966ab2d9cf46586cd601b5cd6bca75d5a8e4 | 5d29460dedec0ef4e6918fd9a32d6a32e93bac1d | /GameCharacter.h | b75e06a44d09fdea241af16ef24d368d7bcb6d85 | [] | no_license | FrancescoAmorosini/Progetto_Programmazione | ca9afbe7409476b4cc42596b52ec6b9405ed2a8f | 216d8f9fe99a816ef90a95167d17c026e0f2071e | refs/heads/master | 2021-01-11T02:56:05.465790 | 2019-03-02T20:41:16 | 2019-03-02T20:41:16 | 70,906,999 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,264 | h | //
// Created by Francesco Amorosini on 22/06/16.
//
#ifndef PROGETTO_PROGRAMMAZIONE_GAMECHARACTER_H
#define PROGETTO_PROGRAMMAZIONE_GAMECHARACTER_H
#include <string>
#include "RNG.h"
enum class CharacterClass {Warrior, Thief, Mage, Undead, BigBaldGuy, Witch, Bat};
enum class Face {Up, Down, Left, Right};
class GameCharacter {
public:
GameCharacter(){}
GameCharacter(CharacterClass r, int HP=100, int atk=10, int evade=1, int critical=1);
virtual ~GameCharacter(){}
virtual void updatePosition()=0;
virtual void fight(GameCharacter* enemy)=0;
int getHP() const;
virtual void setHP(int HP);
int getmaxHP() const;
void setmaxHP(int maxHP);
void heal(int HP);
int getAtk() const;
void setAtk(int atk);
int getEvade() const;
void setEvade(int evade);
int getCritical() const;
void setCritical(int critical);
CharacterClass getRole() const;
bool canMoveUP=true;
bool canMoveDOWN=true;
bool canMoveLEFT=true;
bool canMoveRIGHT=true;
int speedMovement=3;
int walkingCounter=1;
Face face= Face::Down;
private:
int HP;
int maxHP;
int atk;
int evade;
int critical;
CharacterClass role;
};
#endif //PROGETTO_PROGRAMMAZIONE_GAMECHARACTER_H
| [
"[email protected]"
] | |
6a8049ad720c9604976345ad3101dfae9800e073 | 3763d97d1eed58e1edf74499ced7138be4baddf8 | /pintool/analyze_pin_log.cpp | 09b3d6cc43545cba0098e23e9b07fb3866620b3f | [] | no_license | cheewill/UBSI | 5fd94f8b4b75bfa48739fa45723d61d6e5f4cb40 | 5a222ed2114401d01ab6f90624bbe937ba7132fc | refs/heads/master | 2021-10-16T18:37:13.995961 | 2019-02-12T16:02:43 | 2019-02-12T16:02:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 27,485 | cpp | #include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <map>
#include <set>
#include <stack>
#include <vector>
#include "intervalTree/interval.H"
#include <assert.h>
using namespace std;
//#define ANALYZE_MEM
#define NDEBUG
#define NDEBUG_MEM
#ifdef NDEBUG
#define debug(M, ...)
#else
#define debug(M, ...) fprintf(stderr, "DEBUG %s:%d: " M, __FILE__, __LINE__, ##__VA_ARGS__)
#endif
#ifdef NDEBUG_MEM
#define debug_mem(M, ...)
#else
#define debug_mem(M, ...) fprintf(stderr, "DEBUG %s:%d: " M, __FILE__, __LINE__, ##__VA_ARGS__)
#endif
#define MAX_THREAD 1024
#define MAX_LOOP_DEPTH 2
#define MIN_ITERATION 3
#define LOWADDR 0x7f1994bf0000
#define HIGHADDR 0x7f199e45bdd3
enum TYPE {
LOOP_ENTRY,
LOOP_EXIT,
WRITE,
READ,
SYSCALL,
MALLOC,
FREE,
REALLOC
};
typedef struct {
TYPE type;
unsigned long long time;
int tid;
int num;
int numOfLoopSyscall;
int id;
uint64_t ip;
uint64_t addr; // for mem read/write
uint64_t size;
uint64_t addrSrc; // for realloc
int iterNum;
} Entry;
typedef struct {
int iter;
int firstAppear;
int lastAppear;
int syscall;
} LoopEntry;
typedef struct {
map<int, int> readBy; // <unit_num, count>
map<int, int> writtenBy; // <unit_num, count>
set<int> readTid;
set<int> writeTid;
set<int> readLoopId;
set<int> writeLoopId;
} MemEntry;
map<int, Entry> log;
map<int, Entry> loop[MAX_THREAD];
map<int, LoopEntry> selectedLoops[MAX_THREAD]; // <loop_id, {# of iteration, # of syscalls}>
map<int, MemEntry> memMap; // <memId, >
map<int, int> unitId2LoopId; // <unit_num, loop_id>
map<int, int> unitId2Tid; // <unit_num, tid>
int numOfSyscall[MAX_THREAD];
int numOfLoopSyscall[MAX_THREAD];
int maxTid = 0;
void print_progress(float progress)
{
int i;
int barWidth = 70;
fprintf(stdout, "\r[");
int pos = barWidth * progress;
for (i = 0; i < barWidth; ++i) {
if (i < pos) fprintf(stdout,"=");
else if (i == pos) fprintf(stdout,">");
else fprintf(stdout," ");
}
fprintf(stdout,"] %.1f%%", (float)(progress * 100.0));
fflush(stdout);
if(progress >= 1) fprintf(stdout,"\n");
}
bool read_trace(const char *name)
{
FILE *fp;
char tmp[512];
fp = fopen(name, "r");
if(fp == NULL) {
fprintf(stdout, "File open error: %s\n", name);
return false;
}
unsigned long long processed = 0;
unsigned long long total;
float progress = 0;
int i = 0;
fseek(fp, 0L, SEEK_END);
total = ftell(fp);
fseek(fp, 0L, SEEK_SET);
char type[2];
int no = 0;
unsigned long long ts;
unsigned long long seq = 0;
char line[512];
multimap<unsigned long long, string> records;
fprintf(stdout, "Reading input file %s...\n", name);
while(fgets(line, 512, fp))
{
processed+=strlen(line);
progress = (float)((float)processed / (float)total);
sscanf(line, "%llu: %[^\n]", &ts, tmp);
records.insert(pair<unsigned long long, string>(ts, tmp));
if(i++ % 100000 == 0) print_progress(progress);
//records.insert(pair<unsigned long long, string>(seq++, tmp));
}
print_progress(1);
multimap<unsigned long long, string>::iterator iter = records.begin();
fprintf(stdout, "Inserting records into a map structure...\n");
total = records.size();
i = 0;
for (; iter != records.end(); ++iter)
{
//printf("%llu: %s\n", iter->first, iter->second.c_str());
const string& str = iter->second;
Entry ent;
sscanf(str.c_str(), "[%d] %s", &ent.tid, type);
if(maxTid < ent.tid) {
maxTid = ent.tid;
if(maxTid >= MAX_THREAD) {
fprintf(stdout, "Increase MAX_THREAD! : maxTid = %d\n", maxTid);
return false;
}
}
ent.time = iter->first;
if(strncmp(type, "LE", 2) == 0) {
ent.type = LOOP_ENTRY;
} else if(strncmp(type, "LX", 2) == 0) {
ent.type = LOOP_EXIT;
} else if(strncmp(type, "WR", 2) == 0) {
ent.type = WRITE;
} else if(strncmp(type, "RD", 2) == 0) {
ent.type = READ;
} else if(strncmp(type, "SC", 2) == 0) {
ent.type = SYSCALL;
numOfSyscall[ent.tid]++;
} else if(strncmp(type, "MA", 2) == 0) {
ent.type = MALLOC;
} else if(strncmp(type, "RA", 2) == 0) {
ent.type = REALLOC;
} else if(strncmp(type, "FR", 2) == 0) {
ent.type = FREE;
} else {
fprintf(stdout, "TYPE ERROR: %s\n", str.c_str());
return false;
}
no++;
ent.num = no;
if(ent.type == LOOP_ENTRY || ent.type == LOOP_EXIT || ent.type == SYSCALL) {
ent.numOfLoopSyscall = ++numOfLoopSyscall[ent.tid];
}
if(ent.type == LOOP_ENTRY || ent.type == LOOP_EXIT || ent.type == SYSCALL)
{
if(sscanf(str.c_str(), "[%d] %s ip %lx id %d", &ent.tid, type, &ent.ip, &ent.id) < 4) {
fprintf(stdout, "Read trace failed! : %s\n", str.c_str());
return false;
}
loop[ent.tid].insert(pair<int, Entry> (no, ent));
} else if(ent.type == WRITE || ent.type == READ || ent.type == MALLOC || ent.type == FREE) {
if(sscanf(str.c_str(), "[%d] %s ip %lx id %d addr %lx size %ld", &ent.tid, type, &ent.ip, &ent.id, &ent.addr, &ent.size) < 6) {
fprintf(stdout, "Read trace failed! : %s\n", str.c_str());
return false;
}
if(ent.size < 4096) continue; //KYU
} else if(ent.type == REALLOC) {
if(sscanf(str.c_str(), "[%d] %s ip %lx id %d addr %lx size %ld addr_src %lx", &ent.tid, type, &ent.ip, &ent.id, &ent.addr, &ent.size, &ent.addrSrc) < 7) {
fprintf(stdout, "Read trace failed! : %s\n", str.c_str());
return false;
}
}
log.insert(pair<int, Entry> (no, ent));
if(i++ % 100000 == 0) {
print_progress((float)((float)i / (float)total));
}
}
print_progress(1);
return true;
}
void print_preprocessed(char *name)
{
map<int, Entry>::iterator it;
// output just like input file.
char fname[256];
sprintf(fname, "%s.preprocessed", name);
FILE *fp = fopen(fname, "w");
for(it = log.begin(); it != log.end(); it++)
{
fprintf(fp, "%llu: [%d] ", it->second.time, it->second.tid);
if(it->second.type == LOOP_ENTRY) fprintf(fp, "LE ");
else if(it->second.type == LOOP_EXIT) fprintf(fp, "LX ");
else if(it->second.type == WRITE) fprintf(fp, "WR ");
else if(it->second.type == READ) fprintf(fp, "RD ");
else if(it->second.type == MALLOC) fprintf(fp, "MA ");
else if(it->second.type == REALLOC) fprintf(fp, "RA ");
else if(it->second.type == FREE) fprintf(fp, "FR ");
else if(it->second.type == SYSCALL) fprintf(fp, "SC ");
if(it->second.type == LOOP_ENTRY || it->second.type == LOOP_EXIT || it->second.type == SYSCALL) {
fprintf(fp, "ip %lx id %d\n", it->second.ip, it->second.id);
} else if(it->second.type == REALLOC) {
fprintf(fp, "ip %lx id %d addr %lx size %ld addr_src %lx\n", it->second.ip, it->second.id, it->second.addr, it->second.size, it->second.addrSrc);
} else if(it->second.type == READ || it->second.type == WRITE || it->second.type == FREE) {
fprintf(fp, "ip %lx id %d addr %lx size %ld\n", it->second.ip, it->second.id, it->second.addr, it->second.size);
}
}
fclose(fp);
}
void print_map(int tid, int flag)
{
map<int, Entry>::iterator it;
if(flag == 1) {
printf("PRINT LOG: %d ENTRIES\n", (int)log.size());
for(it = log.begin(); it != log.end(); it++)
{
printf("[%d] %d ", it->second.tid, it->second.num);
if(it->second.type == LOOP_ENTRY) printf("LE ");
else if(it->second.type == LOOP_EXIT) printf("LX ");
else if(it->second.type == WRITE) printf("WR ");
else if(it->second.type == READ) printf("RD ");
else if(it->second.type == SYSCALL) printf("SC ");
else if(it->second.type == MALLOC) printf("MA ");
else if(it->second.type == REALLOC) printf("RA ");
else if(it->second.type == FREE) printf("FR ");
printf(" ip %lx id %d num %d\n", it->second.ip, it->second.id, it->second.num);
}
}
if(flag == 2) {
printf("PRINT LOOP: %d ENTRIES\n", (int)loop[tid].size());
for(it = loop[tid].begin(); it != loop[tid].end(); it++)
{
printf("%d ", it->second.num);
if(it->second.type == LOOP_ENTRY) printf("LE ");
else if(it->second.type == LOOP_EXIT) printf("LX ");
else if(it->second.type == SYSCALL) printf("SC ");
printf(" id %d ip %lx\n", it->second.id, it->second.ip);
}
}
}
void delete_entry(int tid, int no)
{
debug("DELETE : %d\n", no);
log.erase(no);
loop[tid].erase(no);
}
void loop_pairing(int tid)
{
debug("======= Loop Entry/Exit pairing ======\n");
stack<Entry> loop_stack;
stack<int> to_delete;
map<int, Entry>::iterator it;
for(it = loop[tid].begin(); it != loop[tid].end(); it++)
{
if(it->second.type == LOOP_ENTRY) loop_stack.push(it->second);
else if(it->second.type == LOOP_EXIT) {
if(loop_stack.size() == 0) {
debug("Encounter exit(id %d, num %d), but stack is empty.\n", it->second.id, it->second.num);
continue;
}
Entry ent;
if(loop_stack.size() > 0) ent = loop_stack.top();
else continue;
if(ent.id == it->second.id) loop_stack.pop();
else if(loop_stack.size() > 0) {
while(ent.id != it->second.id) {
debug("Stack(%ld) top is not match to the loop exit, top %d(no %d), exit %d(no %d), remove top\n", loop_stack.size(), ent.id, ent.num, it->second.id, it->second.num);
to_delete.push(ent.num);
loop_stack.pop();
if(loop_stack.size() == 0) break;
ent = loop_stack.top();
}
if(loop_stack.size() > 0) {
loop_stack.pop();
debug("Match: top %d(no %d), exit %d(no %d), stacksize %ld\n", ent.id, ent.num, it->second.id, it->second.num, loop_stack.size());
}
}
}
}
// Remove remaining loop entries in stack.
while(loop_stack.size() > 0)
{
Entry ent = loop_stack.top();
delete_entry(tid, ent.num);
loop_stack.pop();
}
while(to_delete.size()) {
delete_entry(tid, to_delete.top());
to_delete.pop();
}
}
void remove_nested_loops(int tid)
{
debug("===== Remove nested(> %d depth) loops=====\n", MAX_LOOP_DEPTH);
stack<Entry> loop_stack;
stack<int> to_delete;
map<int, Entry>::iterator it;
// Delete nested loops
for(it = loop[tid].begin(); it != loop[tid].end(); it++)
{
debug("# %d\n", it->second.num);
if(it->second.type == LOOP_ENTRY) loop_stack.push(it->second);
else if(it->second.type == LOOP_EXIT) {
if(loop_stack.size() > MAX_LOOP_DEPTH) {
Entry ent = loop_stack.top();
debug("Loop depth %d, Delete Entry %d, Exit %d\n", (int)loop_stack.size(), ent.num, it->second.num);
to_delete.push(ent.num);
to_delete.push(it->second.num);
}
if(loop_stack.size() > 0) loop_stack.pop();
}
}
while(to_delete.size()) {
delete_entry(tid, to_delete.top());
to_delete.pop();
}
}
typedef struct {
int num;
int id;
int syscall;
} _loop;
void detecting_loop_with_syscall(int tid)
{
stack<_loop> loop_stack;
stack<int> to_delete;
//insert remaining loops into loop_set. We will use it to detect loops with syscalls
for(map<int, Entry>::iterator it = loop[tid].begin(); it != loop[tid].end(); it++)
{
if(it->second.type == LOOP_ENTRY) {
map<int,LoopEntry>::iterator it2 = selectedLoops[tid].find(it->second.id);
if(it2 == selectedLoops[tid].end()) {
LoopEntry l = {1,0,0,0};
selectedLoops[tid].insert(pair<int, LoopEntry>(it->second.id, l));
}
else it2->second.iter++;
}
}
for(map<int, Entry>::iterator it = loop[tid].begin(); it != loop[tid].end(); it++)
{
if(it->second.type == LOOP_ENTRY) {
_loop l = {it->second.num, it->second.id, 0};
loop_stack.push(l);
} else if(it->second.type == LOOP_EXIT) {
if(loop_stack.size() == 0) {
debug("Loop pairing failed!\n");
continue;
//exit(0);
}
int syscall_called = loop_stack.top().syscall;
if(syscall_called == 0) {
debug("Loop %d [%d,%d] does not have syscalls. Delete\n", loop_stack.top().id, loop_stack.top().num, it->second.num);
selectedLoops[tid].erase(loop_stack.top().id);
} else {
debug("Loop %d [%d,%d] called syscalls %d times.\n", loop_stack.top().id, loop_stack.top().num, it->second.num, syscall_called);
map<int,LoopEntry>::iterator it2 = selectedLoops[tid].find(loop_stack.top().id);
if(it2 != selectedLoops[tid].end()) {
it2->second.lastAppear = it->second.numOfLoopSyscall;
if(it2->second.firstAppear == 0) it2->second.firstAppear = it->second.numOfLoopSyscall;
it2->second.syscall += syscall_called;
}
}
loop_stack.pop();
if(loop_stack.size() > 0) loop_stack.top().syscall += syscall_called;
} else if(it->second.type == SYSCALL) {
if(loop_stack.size() > 0) loop_stack.top().syscall++;
}
}
for(map<int, LoopEntry>::iterator it = selectedLoops[tid].begin(); it != selectedLoops[tid].end(); it++)
{
if(it->second.iter < MIN_ITERATION) selectedLoops[tid].erase(it);
}
}
void remove_unselected_loops()
{
stack<int> to_delete;
stack<int> to_delete_loop;
for(int tid = 0; tid <= maxTid; tid++) {
for(map<int, LoopEntry>::iterator it = selectedLoops[tid].begin(); it != selectedLoops[tid].end(); it++)
{
// Some heuristics..
if((it->second.lastAppear - it->second.firstAppear) * 3 < numOfLoopSyscall[tid]) {
debug("Loop id %d DELETED!! : %d iterations, %d/%d syscall called inside the loop. First appeared: %d, Last appeared: %d, total log entries %d\n", it->first, it->second.iter, it->second.syscall, numOfSyscall[tid], it->second.firstAppear, it->second.lastAppear, numOfLoopSyscall[tid]);
to_delete_loop.push(it->first);
//continue;
}
if(it->second.syscall * 5 < numOfSyscall[tid]) {
debug("Loop id %d DELETED2!! : %d iterations, %d/%d syscall called inside the loop. First appeared: %d, Last appeared: %d, total log entries %d\n", it->first, it->second.iter, it->second.syscall, numOfSyscall[tid], it->second.firstAppear, it->second.lastAppear, numOfLoopSyscall[tid]);
to_delete_loop.push(it->first);
// continue;
}
}
debug("Delete: %ld loops\n", to_delete_loop.size());
while(to_delete_loop.size()) {
selectedLoops[tid].erase(to_delete_loop.top());
debug("Delete loop %d\n", to_delete_loop.top());
to_delete_loop.pop();
}
}
for(map<int, Entry>::iterator it = log.begin(); it != log.end(); it++)
{
if(it->second.type == LOOP_ENTRY || it->second.type == LOOP_EXIT)
{
map<int,LoopEntry>::iterator it2 = selectedLoops[it->second.tid].find(it->second.id);
if(it2 == selectedLoops[it->second.tid].end()) {
to_delete.push(it->first);
}
}
if(it->second.type == SYSCALL) to_delete.push(it->first);
}
while(to_delete.size()) {
log.erase(to_delete.top());
to_delete.pop();
}
}
void analyze_loop(int tid)
{
//fprintf(stderr, "Analyzing loops.. thread #%d\n", tid);
loop_pairing(tid);
//print_map(0,1);
remove_nested_loops(tid);
debug("==============\n");
//print_map(tid, 2);
detecting_loop_with_syscall(tid);
}
void preprocess_memory()
{
ITNode *ITRoot = NULL;
int memId = 1;
stack<int> to_delete;
Interval t, *res;
int i = 0;
int total = log.size();
fprintf(stdout, "Preprocessing memory accesses..\n");
for(map<int, Entry>::iterator it = log.begin(); it != log.end(); it++)
{
i++;
if(i % 100000 == 0) print_progress((float)((float)i / (float)total));
if(it->second.type == MALLOC) {
t.low = it->second.addr;
t.high = it->second.addr+it->second.size;
t.id = it->second.id;
t.active = true;
debug_mem("MA %llx, %d\n", it->second.addr, it->second.size);
ITRoot = IT_insert(ITRoot, t);
to_delete.push(it->first);
} else if(it->second.type == FREE) {
//if(IT_erase(ITRoot, it->second.addr) == false) {
//fprintf(stdout, "IT_erase failed. num %d, addr = %lx\n", it->first, it->second.addr);
//}
to_delete.push(it->first);
} else if(it->second.type == REALLOC) {
IT_erase(ITRoot, it->second.addrSrc);
t.low = it->second.addr;
t.high = it->second.addr+it->second.size;
t.id = memId++;
t.active = true;
ITRoot = IT_insert(ITRoot, t);
debug_mem("MA %llx, %d\n", it->second.addr, it->second.size);
to_delete.push(it->first);
} else if(it->second.type == READ) {
//continue;
t.low = it->second.addr;
t.high = it->second.addr+it->second.size;
t.id = 0;
t.active = true;
res = IT_overlapSearch(ITRoot, t);
if(res != NULL) {
it->second.id = res->id;
debug_mem("READ valid: %llx, id %d\n", it->second.addr, it->second.id);
} else {
debug_mem("READ delete: %llx\n", it->second.addr);
to_delete.push(it->first);
}
} else if(it->second.type == WRITE) {
//continue;
t.low = it->second.addr;
t.high = it->second.addr+it->second.size;
t.id = 0;
t.active = true;
res = IT_overlapSearch(ITRoot, t);
if(res != NULL) {
it->second.id = res->id;
debug_mem("WRITE valid: %llx, id %d\n", it->second.addr, it->second.id);
} else {
debug_mem("WRITE delete: %llx\n", it->second.addr);
to_delete.push(it->first);
}
}
}
print_progress(1);
while(to_delete.size()) {
log.erase(to_delete.top());
to_delete.pop();
}
}
void print_memMap()
{
int total = 0;
printf("print_memMap\n");
for(map<int, MemEntry>::iterator it = memMap.begin(); it != memMap.end(); it++)
{
if(it->second.readBy.empty() || it->second.writtenBy.empty()) continue;
printf("MemId: %d, (loopId, iterNum[tid]) - X times accessed\n", it->first);
printf(" ReadBy: ");
for(map<int,int>::iterator it2 = it->second.readBy.begin(); it2 != it->second.readBy.end(); it2++)
{
printf(" (%d,%d[%d])-%d times\n", unitId2LoopId[it2->first], it2->first, unitId2Tid[it2->first], it2->second);
}
printf("\n WrittenBy: ");
for(map<int,int>::iterator it2 = it->second.writtenBy.begin(); it2 != it->second.writtenBy.end(); it2++)
{
printf(" (%d,%d[%d])-%d times\n", unitId2LoopId[it2->first], it2->first, unitId2Tid[it2->first], it2->second);
}
printf("\n");
}
printf("Print_map: total mem object %d\n", total);
}
int insert_units_into_memMap(int tid, vector<Entry> & v, int type, int memId)
{
debug("insert_units_into_memMap, tid %d, type %d, memId %d\n");
// type: 1.read, 2.write
if(v.size() == 0) return 0;
map<int, MemEntry>::iterator mit;
if((mit = memMap.find(memId)) == memMap.end()) {
MemEntry m;
memMap.insert(pair<int, MemEntry>(memId, m));
}
mit = memMap.find(memId);
map<int,int>::iterator it2;
int iter;
// For nested unit loops
for(vector<Entry>::iterator vit = v.begin(); vit != v.end(); vit++)
{
iter = vit->iterNum;
if(type == 1) {
it2 = mit->second.readBy.find(v.back().iterNum);
if(it2 == mit->second.readBy.end()) {
mit->second.readBy.insert(pair<int,int>(v.back().iterNum, 1));
mit->second.readTid.insert(vit->tid);
mit->second.readLoopId.insert(vit->id);
} else {
it2->second++;
}
} else if(type == 2) {
it2 = mit->second.writtenBy.find(v.back().iterNum);
if(it2 == mit->second.writtenBy.end()) {
mit->second.writtenBy.insert(pair<int,int>(v.back().iterNum, 1));
mit->second.writeTid.insert(vit->tid);
mit->second.writeLoopId.insert(vit->id);
} else {
it2->second++;
}
}
}
}
void prepare_memMap()
{
fprintf(stdout, "Preparing the memory map..\n");
vector<Entry> loop_vector[MAX_THREAD];
int iterNum = 1;
//memMap
int total = log.size();
int i = 0;
map<int, MemEntry>::iterator mit;
for(map<int, Entry>::iterator it = log.begin(); it != log.end(); it++)
{
if(i % 100000 == 0) print_progress((float)((float)i / (float)total));
int tid = it->second.tid;
//printf("tid = %d\n",tid);
assert(tid < MAX_THREAD);
if(it->second.type == LOOP_ENTRY) {
it->second.iterNum = iterNum;
loop_vector[tid].push_back(it->second);
unitId2LoopId[iterNum] = it->second.id;
unitId2Tid[iterNum] = tid;
iterNum++;
} else if(it->second.type == LOOP_EXIT) {
if(loop_vector[tid].size() == 0) continue;
if(loop_vector[tid].back().id != it->second.id) {
debug("Loop pair is not MATCH! top : %d, exit : %d\n", loop_vector[tid].back().id, it->second.id);
}
loop_vector[tid].pop_back();
} else if(it->second.type == READ) {
insert_units_into_memMap(tid, loop_vector[tid], 1, it->second.id);
} else if(it->second.type == WRITE) {
insert_units_into_memMap(tid, loop_vector[tid], 2, it->second.id);
} else {
fprintf(stdout, "Unexpected type: %d, id %d\n", it->second.type, it->second.id);
}
}
print_progress(1);
}
/*
If the memory block (mallocked) is accessed by
1) Different units from the same loop (same code) --> Low-level dependence: erase
2) Different units from different loops --> Workflow dependence
*/
void analyze_memMap()
{
stack<int> to_delete;
for(map<int, MemEntry>::iterator it = memMap.begin(); it != memMap.end(); it++)
{
if(it->second.readBy.empty()) {
debug_mem("Mem Delete: memId %d - write only\n", it->first);
to_delete.push(it->first);
continue;
}
if(it->second.writtenBy.empty()) {
debug_mem("Mem Delete: memId %d - read only\n", it->first);
to_delete.push(it->first);
continue;
}
if(it->second.readLoopId.size() == 1 &&
it->second.writeLoopId.size() == 1 &&
*(it->second.readLoopId.begin()) == *(it->second.writeLoopId.begin()))
{
debug_mem("!!!Delete low-level dependence: memId %d, readBy(loopid) %d, writted by %d\n", it->first, *(it->second.readLoopId.begin()), *(it->second.writeLoopId.begin()));
to_delete.push(it->first);
continue;
}
/*
printf("MemId: %d, (loopId, iterNum[tid]) - X times accessed\n", it->first);
printf(" ReadBy: ");
for(map<int,int>::iterator it2 = it->second.readBy.begin(); it2 != it->second.readBy.end(); it2++)
{
printf("(%d,%d[%d])-%dtimes ", unitId2LoopId[it2->first], it2->first, unitId2Tid[it2->first], it2->second);
}
printf("\n WrittenBy: ");
for(map<int,int>::iterator it2 = it->second.writtenBy.begin(); it2 != it->second.writtenBy.end(); it2++)
{
printf("(%d,%d[%d])-%dtimes ", unitId2LoopId[it2->first], it2->first, unitId2Tid[it2->first], it2->second);
}
printf("\n");
*/
}
while(to_delete.size()) {
memMap.erase(to_delete.top());
to_delete.pop();
}
}
void remove_unselected_meminst()
{
stack<int> to_delete;
map<int, MemEntry>::iterator mit;
for(map<int, Entry>::iterator it = log.begin(); it != log.end(); it++)
{
if(it->second.type == READ || it->second.type == WRITE)
{
mit = memMap.find(it->second.id);
if(mit == memMap.end()) {
to_delete.push(it->first);
}
}
if(it->second.type == MALLOC || it->second.type == FREE || it->second.type == REALLOC) to_delete.push(it->first);
}
while(to_delete.size()) {
log.erase(to_delete.top());
to_delete.pop();
}
}
void analyze_memory()
{
prepare_memMap();
printf("Analyze_memMap\n");
analyze_memMap();
printf("====================\n");
print_memMap();
}
void print_output(char *name)
{
uint64_t lowAddr, highAddr;
lowAddr = highAddr = 0;
lowAddr = LOWADDR;
highAddr = HIGHADDR;
uint64_t offset = 0;
map<int, Entry>::iterator it;
map<int, MemEntry>::iterator mit;
set<int> loopOut;
set<uint64_t> loopEntryOut;
set<uint64_t> loopExitOut;
set<uint64_t> writeOut; // ip - to detect duplicated entries
set<uint64_t> readOut; // ip
// output file
char fname[256];
sprintf(fname, "%s.out", name);
FILE *fp = fopen(fname, "w");
for(it = log.begin(); it != log.end(); it++)
{
offset = 0;
if(it->second.ip >= lowAddr && it->second.ip <= highAddr) offset = it->second.ip-lowAddr;
if(it->second.type == LOOP_ENTRY) {
if(loopEntryOut.find(it->second.ip) == loopEntryOut.end()) {
fprintf(fp, "LE ip %lx (offset %lx) id %d\n", it->second.ip, offset, it->second.id);
loopEntryOut.insert(it->second.ip);
loopOut.insert(it->second.id);
}
} else if(it->second.type == LOOP_EXIT) {
if(loopExitOut.find(it->second.ip) == loopExitOut.end()) {
fprintf(fp, "LX ip %lx (offset %lx) id %d\n", it->second.ip, offset, it->second.id);
loopExitOut.insert(it->second.ip);
}
} else if(it->second.type == WRITE || it->second.type == READ) {
mit = memMap.find(it->second.id);
if(mit == memMap.end()) continue;
if(it->second.type == READ) {
if(readOut.find(it->second.ip) == readOut.end()) {
fprintf(fp, "RD ip %lx (offset %lx) id %d\n", it->second.ip, offset, it->second.id);
readOut.insert(it->second.ip);
}
}
else {
if(writeOut.find(it->second.ip) == writeOut.end()) {
fprintf(fp, "WR ip %lx (offset %lx) id %d\n", it->second.ip, offset, it->second.id);
writeOut.insert(it->second.ip);
}
}
} else {
fprintf(stdout, "!!ERROR: unexpected type %d , id %d!\n", it->second.type, it->second.id);
//exit(0);
}
}
fclose(fp);
printf("LoopId in the output: ");
for(set<int>::iterator lit = loopOut.begin(); lit != loopOut.end(); lit++)
{
printf("%d ", *lit);
}
printf("\n");
printf("MemId in the output: ");
for(mit = memMap.begin(); mit != memMap.end(); mit++)
{
printf("%d ", mit->first);
}
printf("\n");
}
int main(int argc, char** argv)
{
bool isPreprocessed = false;
set<int> totalSelectedLoops;
if(argc < 2) {
return 0;
}
if(read_trace(argv[1]) == false)
{
return 0;
}
// print_map(0,1);
if(strstr(argv[1], "preprocessed") != NULL) isPreprocessed = true;
if(isPreprocessed == false) {
fprintf(stdout, "NOT PREPROCESSED file.\n");
for(int i = 0; i <= maxTid; i++)
{
analyze_loop(i);
}
remove_unselected_loops();
for(int i = 0; i <= maxTid; i++) {
fprintf(stdout, "Tid %d: %ld Loops to instrument!\n", i, selectedLoops[i].size());
for(map<int, LoopEntry>::iterator it = selectedLoops[i].begin(); it != selectedLoops[i].end(); it++)
{
totalSelectedLoops.insert(it->first);
fprintf(stdout, "Loop id %d: %d iterations, %d/%d syscall called inside the loop. First appeared: %d, Last appeared: %d, total log entries %d\n", it->first, it->second.iter, it->second.syscall, numOfSyscall[i], it->second.firstAppear, it->second.lastAppear, numOfLoopSyscall[i]);
}
}
#ifdef ANALYZE_MEM
if(totalSelectedLoops.size() > 1) {
// debug("=================Final map==============\n");
// print_map(1);
preprocess_memory();
print_preprocessed(argv[1]);
}
#endif
} else {
printf("preprocessed file!\n");
}
#ifdef ANALYZE_MEM
if(isPreprocessed || totalSelectedLoops.size() > 1) {
analyze_memory();
}
remove_unselected_meminst();
#endif
print_output(argv[1]);
}
| [
"[email protected]"
] | |
d1de4736ac67d61dc08723797b64ab44f8cc4549 | bec4ce7862948e5057b9573dd82a4aa0733ff485 | /src/ch4/++ && --/order.cc | 3e7c1334fa52065035098aae50121a88dd336b6b | [
"MIT"
] | permissive | HerculesShek/cpp-practise | 27b850a9c446a6571a95629cb6045e18957e6071 | aa0cdc3101c831c1c677f0de46a2f85a4b407bc3 | refs/heads/master | 2016-09-06T13:05:04.184703 | 2014-09-23T01:41:38 | 2014-09-23T01:41:38 | 17,898,200 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 237 | cc | #include <iostream>
#include <string>
using namespace std;
int main()
{
string text = "Here is something";
for(auto b = text.begin(); b != text.end() && !isspace(*b); ++b)
*b = toupper(*b);
cout << text << endl;
return 0;
}
| [
"[email protected]"
] | |
cbf56f0069fcc17a13eab0f1e73b3391d982bc60 | 61d3105e970640919cfd0645d01234241ef24b1d | /s1_Landmark_detect/a4_2_SRC_create_test_data_demo.cpp | ac1936fa41753a9ab6a63d0d66f73744b5b8792b | [] | no_license | AvLab-CV/Face-Recognition | 9726baab5810df80116462c59683c84263780626 | 9c39cb1e059d0da09ba6d4bef9efb8d4e9b00168 | refs/heads/master | 2021-06-18T03:07:03.484704 | 2017-05-22T08:43:56 | 2017-05-22T08:43:56 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 6,698 | cpp | #include "stdlib.h"
#include "dlib/all/source.cpp"
#include <dlib/opencv.h>
#include <opencv2/highgui/highgui.hpp>
#include <dlib/image_processing/frontal_face_detector.h>
#include <dlib/image_processing/render_face_detections.h>
#include <dlib/gui_widgets.h>
#include <opencv2/opencv.hpp>
#include <opencv2/legacy/legacy.hpp>
#include <vector>
#include <string>
#include <iostream>
#include <fstream>
#include <dirent.h>
#include <direct.h>
#include <algorithm>
#include <openGL-vs2010/glew.h>
#include <openGL-vs2010/freeglut.h>
#include "LandmarkDetect_v2.h"
#include "file_read_mine.h"
#include "LM_set.h"
#include "mine_imgProc.h"
#include <Windows.h> //using for Virtual-Key Codes ex: VK_ESCAPE
#include "GaborFR.h"
#include "Ill_Nor.h"
#include "SolveHomotopy.h"
#include "SRC_sort.h"
using namespace std;
using namespace cv;
string data_file_title="../../using_data/";//¤u§@¸ô®|
int main(int argc, char* argv[])
{
// train data save path //
string light="06";
//cout<<"input light : ";
//cin>>light;
string angle="L15_14_0";
//cout<<"input angle : ";
//cin>>angle;
// F00_05_1 //
// R90_24_0 R75_01_0 R60_20_0 R45_19_0 R30_04_1 R15_05_0 //
// L90_11_0 L75_12_0 L60_09_0 L45_08_0 L30_13_0 L15_14_0 //
string glass_model_type="no_glass_1";
// glass_frame_full glass_frame_half glass_frame_none no_glass //
string recog_data_sPath_title=data_file_title+"Test_Data_xml"+"/"+light+"/";
_mkdir(recog_data_sPath_title.c_str());
recog_data_sPath_title=data_file_title+"Test_Data_xml"+"/"+light+"/"+angle+"/";
_mkdir(recog_data_sPath_title.c_str());
recog_data_sPath_title=data_file_title+"Test_Data_xml"+"/"+light+"/"+angle+"/"+glass_model_type+"/";
_mkdir(recog_data_sPath_title.c_str());
string train_sPath=recog_data_sPath_title+"train"+"/";
_mkdir(train_sPath.c_str());
string test_sPath=recog_data_sPath_title+"test"+"/";
_mkdir(test_sPath.c_str());
// initial class Gabor //
GaborFR Gabor;
// load train image //
string test_image_title=data_file_title+"Test_Data"+"/"+light+"/"+angle+"/"+glass_model_type+"/"+"test"+"/";
vector<string> test_img_name;
Load_insideFile_name(test_image_title,&test_img_name);
double t = (double)getTickCount();
for (int i = 0; i < test_img_name.size(); i++)
{
string test_img_path_in=test_image_title+test_img_name[i]+"/";
vector<string> test_img_name_in;
Load_insideFile_name(test_img_path_in,&test_img_name_in);
Mat Data_Tar_test;
vector<string> Name_Tar_test;
test_sPath=recog_data_sPath_title+"test"+"/"+test_img_name[i]+"/";
_mkdir(test_sPath.c_str());
for (int j = 0; j < test_img_name_in.size(); j++)
{
string img_name_path=test_img_path_in+test_img_name_in[j]+"/";
vector<string> img_name;
Load_insideFile_name(img_name_path,&img_name);
for (int k = 0; k < img_name.size(); k++)
{
string img_load_path=img_name_path+img_name[k];
Mat train_img=imread(img_load_path,0);//¦Ç¶¥Åª¤J
//-----Illumiantion Normalize image by TT
CvMat *Mat_TT_in = cvCreateMat(train_img.rows,train_img.cols,CV_8UC1);
CvMat temp = train_img;
cvCopy(&temp, Mat_TT_in);
//Mat_TT_in = &train_img.operator CvMat();
CvMat *Mat_TT_out = cvCreateMat(train_img.rows,train_img.cols,CV_32FC1);
//cvShowImage("tt", Mat_TT_in);
//waitKey(1);
TT(Mat_TT_in,cvSize(train_img.cols,train_img.rows),Mat_TT_out,0);
// show TT result //
//cvShowImage("Mat_TT_in", Mat_TT_in);
Mat Mat_TT_out_show = Mat(Mat_TT_out, true); //CvMat copy to Mat
cv::normalize(Mat_TT_out_show,Mat_TT_out_show,0,1,cv::NORM_MINMAX,-1);
//imshow("Mat_TT_out_show",Mat_TT_out_show);waitKey(1);
//cvShowImage("Mat_TT_out",Mat_TT_out);waitKey(0);
//-----Feature Extract by Gabor filter
Mat m_ori = Mat_TT_out_show.clone();//CvMat->Mat
//Mat m_ori = Mat_TT_out;//CvMat->Mat
Mat Gabor_out;
Gabor.Gabor_compute(m_ori,Gabor_out,0);
//imshow("Gabor_out",Gabor_out.reshape(1,Mat_TT_out_show.cols));waitKey(0);
//cv::normalize(Gabor_out,Gabor_out,0,1,cv::NORM_MINMAX,-1);
//FILE* fgfg;
//fgfg=fopen("QUE.txt","w");
///*cout<<Gabor_out.rows<<endl;
//cout<<Gabor_out.cols<<endl;
//cout<<Gabor_out.type()<<endl;*/
//for (int ggg=0;ggg<6720;ggg++)
//{
// double hhh=Gabor_out.at<float>(ggg);
// fprintf(fgfg,"%f\n",hhh);
//}
//fclose(fgfg);
//dct
//Mat img_dct = Mat( Mat_TT_out_show.rows, Mat_TT_out_show.cols, CV_32FC1);
//Mat_TT_out_show.convertTo(img_dct, CV_32FC1);
//resize(img_dct, img_dct, Size(cvRound(img_dct.cols/4),cvRound(img_dct.rows/4)));
//Mat img_dct_freq;
//dct(img_dct, img_dct_freq);
//imshow("img_dct",img_dct);waitKey(1);
//imshow("img_dct_freq",img_dct_freq);waitKey(1);
//int start=cvRound(img_dct_freq.rows/8);
//int use_start=start*1;
//img_dct_freq.rowRange(use_start,img_dct_freq.rows)=0;
//img_dct_freq.colRange(use_start,img_dct_freq.cols)=0;
//cout<<img_name[k].substr(0,3)<<endl;
//Mat comb_m((Gabor_out.cols*Gabor_out.rows+img_dct_freq.cols*img_dct_freq.rows),1,CV_32FC1);
//for (int i = 0; i < Gabor_out.rows; i++)
//{
// comb_m.at<float>(i,0)=Gabor_out.at<float>(i,0);
//}
//Mat temp_i=img_dct_freq.reshape(0,img_dct_freq.rows*img_dct_freq.cols);
//for (int i = Gabor_out.rows; i < Gabor_out.rows+temp_i.rows; i++)
//{
// comb_m.at<float>(i,0)=temp_i.at<float>(i-Gabor_out.rows,0);
//}
//-----store Regrister Data
Data_Tar_test.push_back(Gabor_out);
//Data_Tar_test.push_back(img_dct_freq.reshape(0,img_dct_freq.rows*img_dct_freq.cols));
//Data_Tar_test.push_back(Mat_TT_out_show.reshape(0,Mat_TT_out_show.rows*Mat_TT_out_show.cols));
//Data_Tar_test.push_back(comb_m);
Name_Tar_test.push_back(img_name[k].substr(0,3));
//-----Release Memory
if( Mat_TT_in )
cvDecRefData(&Mat_TT_in);
if( Mat_TT_out )
cvDecRefData(&Mat_TT_out);
}
}
string name_xml=recog_data_sPath_title+"test"+"/"+test_img_name[i]+"/"+"name.xml";
string data_xml=recog_data_sPath_title+"test"+"/"+test_img_name[i]+"/"+"data.xml";
//-----Save the Data into xml
FileStorage FS_NT;
FS_NT.open(name_xml, FileStorage::WRITE);
FS_NT << "Name_Tar" << Name_Tar_test;
FS_NT.release();
FileStorage FS_DT;
FS_DT.open(data_xml, FileStorage::WRITE);
FS_DT << "Data_Tar" << Data_Tar_test;
FS_DT.release();
}
t = ((double)getTickCount() - t)/getTickFrequency();
cout<<"total : "<< t <<" sec."<<endl;
cout << '\a';
//system("pause");
return 0;
} | [
"[email protected]"
] | |
39a1ac24ca2c70fd46c7b47312e3d7bcef5be2a1 | 2266e6c2e4713279a7fef0293d1806808a944a25 | /Graph/edkarp.cpp | d1465b2013e9e8b65772b8e2270c3bc8b3c4f521 | [
"MIT"
] | permissive | Nilesh-Das/dsalgo | 9e2d7d1c050995c5195ce77b7051934abbaec564 | 2454f272a5de47e7b9cfbde73bf7c01d0d1492a2 | refs/heads/main | 2023-06-24T18:07:55.131414 | 2021-07-24T22:15:15 | 2021-07-24T22:15:15 | 389,197,236 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,536 | cpp | #include <bits/stdc++.h>
using namespace std;
const int INF = 1e9+7;
// Maxflow - Edmonds-Karp algorithm
int n;
vector<vector<int>> adj, capacity;
vector<int> parent;
int bfs(int s, int t) {
int curr, flow, new_flow;
parent.assign(n, -1);
parent[s] = -2;
queue<pair<int, int>> q;
q.push({s, INF});
while(!q.empty()) {
curr = q.front().first;
flow = q.front().second;
q.pop();
for(int next : adj[curr]) {
if(parent[next]==-1 && capacity[curr][next]) {
parent[next] = curr;
new_flow = min(flow, capacity[curr][next]);
if(next==t) return new_flow;
q.push({next, new_flow});
}
}
}
}
int maxflow(int s, int t) {
int flow=0, new_flow;
while(new_flow=bfs(s,t)) {
flow += new_flow;
for(int curr=t; curr!=s; curr=parent[curr]) {
capacity[parent[curr]][curr] -= new_flow;
capacity[curr][parent[curr]] += new_flow;
}
}
return flow;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int m, s, t, u, v, w;
cin >> n >> m >> s >> t;
adj.resize(n);
capacity.resize(n, vector<int>(n));
while(m--) {
cin >> u >> v >> w;
adj[u].push_back(v);
adj[v].push_back(u);
capacity[u][v] = w;
capacity[v][u] = 0;
}
cout << maxflow(s, t) << '\n';
return 0;
}
/*
input:
6 9 0 5
0 1 7
0 2 4
1 3 5
1 4 3
2 1 3
2 4 2
3 5 8
4 3 3
4 5 5
output:
10
*/ | [
"[email protected]"
] | |
a10ecbf12acc2ddef942242c479eeae3540ec80e | bd1fea86d862456a2ec9f56d57f8948456d55ee6 | /000/082/922/CWE190_Integer_Overflow__int64_t_rand_multiply_81_goodG2B.cpp | 76c23980aa02a44037184da0b6e61f7067c6f6fe | [] | no_license | CU-0xff/juliet-cpp | d62b8485104d8a9160f29213368324c946f38274 | d8586a217bc94cbcfeeec5d39b12d02e9c6045a2 | refs/heads/master | 2021-03-07T15:44:19.446957 | 2020-03-10T12:45:40 | 2020-03-10T12:45:40 | 246,275,244 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,167 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE190_Integer_Overflow__int64_t_rand_multiply_81_goodG2B.cpp
Label Definition File: CWE190_Integer_Overflow.label.xml
Template File: sources-sinks-81_goodG2B.tmpl.cpp
*/
/*
* @description
* CWE: 190 Integer Overflow
* BadSource: rand Set data to result of rand()
* GoodSource: Set data to a small, non-zero number (two)
* Sinks: multiply
* GoodSink: Ensure there will not be an overflow before multiplying data by 2
* BadSink : If data is positive, multiply by 2, which can cause an overflow
* Flow Variant: 81 Data flow: data passed in a parameter to an virtual method called via a reference
*
* */
#ifndef OMITGOOD
#include "std_testcase.h"
#include "CWE190_Integer_Overflow__int64_t_rand_multiply_81.h"
namespace CWE190_Integer_Overflow__int64_t_rand_multiply_81
{
void CWE190_Integer_Overflow__int64_t_rand_multiply_81_goodG2B::action(int64_t data) const
{
if(data > 0) /* ensure we won't have an underflow */
{
/* POTENTIAL FLAW: if (data*2) > LLONG_MAX, this will overflow */
int64_t result = data * 2;
printLongLongLine(result);
}
}
}
#endif /* OMITGOOD */
| [
"[email protected]"
] | |
c7cb6487a2a04f17822dcc2d04b0b692740246ad | 9caa419d1f3d820f8a7c240fb5d037d3d8036375 | /quiapplication.h | b61056f046aa7a3c8913e321bfd1a4fff7a4d242 | [] | no_license | 114254644/player | 009539c16f152d47467ec4683b5e32e917c38d48 | 8d45a26cd9d22083407e85ab094fc7facf8cde28 | refs/heads/master | 2022-11-22T19:42:50.404958 | 2020-07-22T07:10:15 | 2020-07-22T07:10:15 | 277,490,407 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 803 | h | #ifndef QUIAPPLICATION_H
#define QUIAPPLICATION_H
#include <QApplication>
#include <functional>
using UIRunable = std::function<void()>;
class QUIApplication : public QApplication
{
Q_OBJECT
public:
QUIApplication(int &argc, char **argv);
virtual ~QUIApplication();
Q_SIGNALS:
//同步UI执行 (当前UI线程则直接执行)
void syncExecSignal(UIRunable runable);
//异步UI执行 (当前UI线程则直接执行)
void asyncExecSignal(UIRunable runable);
public:
//获取应用实例
static QUIApplication* getApp();
//在UI线程同步执行
static void syncExec(UIRunable runable);
//在UI线程异步执行
static void asyncExec(UIRunable runable);
};
Q_DECLARE_METATYPE(UIRunable)
#endif // QUIAPPLICATION_H
| [
"[email protected]"
] | |
4718278f5f43cbc616477655cdf314a66769359c | fbe60fa0d8e888bfdcf20beb2ef062f0f24fbcbd | /Algorithms/add-two-numbers-ii.cpp | 04c65368ea83537b40fd2caf79a2250265657db7 | [] | no_license | aman1228/LeetCode | 552e5feff8a67c05ba318efa3a8a2d121ab64636 | 76a3d6878719643cbca59643ff8e697498411498 | refs/heads/master | 2023-04-03T13:27:06.340091 | 2021-04-18T00:15:51 | 2021-04-18T00:20:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,390 | cpp | // 445. Add Two Numbers II
// https://leetcode.com/problems/add-two-numbers-ii/
/*
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
Example:
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
stack<int> A, B;
while (l1) {
A.push(l1->val);
l1 = l1->next;
}
while (l2) {
B.push(l2->val);
l2 = l2->next;
}
ListNode * dummy = new ListNode(0);
int carry = 0, base = 10;
while (!A.empty() or !B.empty() or carry > 0) {
int x = 0, y = 0;
if (!A.empty()) {
x = A.top();
A.pop();
}
if (!B.empty()) {
y = B.top();
B.pop();
}
int z = x + y + carry;
carry = z / base;
z %= base;
ListNode * t = dummy->next;
dummy->next = new ListNode(z);
dummy->next->next = t;
}
return dummy->next;
}
}; | [
"[email protected]"
] | |
a958d32819c14cba01e6f2461fa90e18976c2595 | ff98a177902b8b97888a5e44eb59e5397a1826d8 | /tests/unittest/FaceliftUtilsTest.cpp | 99bc40c266fded5861f3fff737b3b5a4c90a6307 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | bitmouse/facelift | 471c39415c1d6667ddc9552abb764e48f3ac4755 | 229d7ad81d8c3e361a207251759b4fc9a6f225cb | refs/heads/master | 2021-07-06T04:48:00.323219 | 2020-10-26T17:48:45 | 2020-10-26T17:48:45 | 199,874,162 | 0 | 0 | MIT | 2020-08-26T07:28:25 | 2019-07-31T14:38:35 | C++ | UTF-8 | C++ | false | false | 2,308 | cpp | #include <gtest/gtest.h>
#include "FaceliftUtils.h"
namespace {
using namespace facelift;
class MostRecentlyUsedCacheTest : public ::testing::Test
{
public:
const unsigned int cacheSize = 3;
const int key1 = 1;
const int val1 = 100;
const int key2 = 2;
const int val2 = 200;
const int key3 = 3;
const int val3 = 300;
const int key4 = 4;
const int val4 = 400;
MostRecentlyUsedCache<int, int> cache;
MostRecentlyUsedCacheTest() : cache(cacheSize) {}
/**
* @brief insert inserts pair key-value and verifies if added
* @param key
* @param val
*/
void insert(int key, int val)
{
EXPECT_FALSE(cache.exists(key));
cache.insert(key, val);
ASSERT_TRUE(cache.exists(key));
EXPECT_EQ(cache.get(key), val);
}
};
TEST_F(MostRecentlyUsedCacheTest, instertExistsAndGet)
{
insert(key1, val1);
insert(key2, val2);
insert(key3, val3);
// key1 should be removed
insert(key4, val4);
EXPECT_FALSE(cache.exists(key1));
EXPECT_TRUE(cache.exists(key2));
EXPECT_TRUE(cache.exists(key3));
EXPECT_TRUE(cache.exists(key4));
}
TEST_F(MostRecentlyUsedCacheTest, mostRecent)
{
insert(key1, val1);
insert(key2, val2);
insert(key3, val3);
// change key1 to be most recent
EXPECT_EQ(cache.get(key1), val1);
// key2 should be removed
insert(key4, val4);
EXPECT_TRUE(cache.exists(key1));
EXPECT_FALSE(cache.exists(key2));
EXPECT_TRUE(cache.exists(key3));
EXPECT_TRUE(cache.exists(key4));
}
TEST_F(MostRecentlyUsedCacheTest, remove)
{
insert(key1, val1);
insert(key2, val2);
insert(key3, val3);
EXPECT_TRUE(cache.exists(key1));
EXPECT_TRUE(cache.exists(key2));
EXPECT_TRUE(cache.exists(key3));
cache.remove(key2);
EXPECT_TRUE(cache.exists(key1));
EXPECT_FALSE(cache.exists(key2));
EXPECT_TRUE(cache.exists(key3));
}
TEST_F(MostRecentlyUsedCacheTest, clear)
{
insert(key1, val1);
insert(key2, val2);
insert(key3, val3);
EXPECT_TRUE(cache.exists(key1));
EXPECT_TRUE(cache.exists(key2));
EXPECT_TRUE(cache.exists(key3));
cache.clear();
EXPECT_FALSE(cache.exists(key1));
EXPECT_FALSE(cache.exists(key2));
EXPECT_FALSE(cache.exists(key3));
}
} // end namespace
| [
"[email protected]"
] | |
11d6aa4e2c4ad7da058796d47827d6eb98218f95 | 034afa81e1df2cb5e6da44fa887ea1512d651bae | /Classes/Menu.h | e8e4665cbeba05afdd6f95afed5771681e05a87f | [] | no_license | 2011conquer/FlappyBird | 67d8ef0ff1860e863e09f3cc1ed215f3a06ce52f | 4af86374f3c6607ea6089a05710e5597048266ff | refs/heads/master | 2020-05-16T23:58:06.693704 | 2014-07-03T16:15:19 | 2014-07-03T16:15:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 465 | h | //
// Menu.h
// FlappyBirdSimulator
//
// Created by 程龙元 on 14-7-2.
//
//
#ifndef __FlappyBirdSimulator__Menu__
#define __FlappyBirdSimulator__Menu__
#include <iostream>
#include "cocos2d.h"
#include "HelloWorldScene.h"
USING_NS_CC;
class GameMenu:public Layer
{
public:
CREATE_FUNC(GameMenu);
static Scene *scene();
bool init();
void startGame(Ref *sender);
};
#endif /* defined(__FlappyBirdSimulator__Menu__) */
| [
"[email protected]"
] | |
a939c2cf1d3e5550be92bcaf917c137590cc458d | b4f7bb50f0035eee1dc8d6a45f486d94bbb80a40 | /BuildingEscape/Source/BuildingEscape/PositionReport.cpp | 75bc484f65bb04e439c6cd7e6fa9fae021b001ca | [] | no_license | TechLovin/03_Build_Escape | f53f02a7330a9e78ca608f623db9f2ee92f13fc2 | 10cb1c285cc6ba925594037711d30e17b5ba8c33 | refs/heads/master | 2021-06-24T15:41:17.400706 | 2017-09-15T20:18:23 | 2017-09-15T20:18:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 986 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "PositionReport.h"
#include "Gameframework/Actor.h"
// Sets default values for this component's properties
UPositionReport::UPositionReport()
{
// Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features
// off to improve performance if you don't need them.
PrimaryComponentTick.bCanEverTick = true;
// ...
}
// Called when the game starts
void UPositionReport::BeginPlay()
{
Super::BeginPlay();
FString ObjectName = GetOwner()->GetName();
FString ObjectPos = GetOwner()->GetActorLocation().ToString();
UE_LOG(LogTemp, Warning, TEXT("Position Report: %s : %s"), *ObjectName, *ObjectPos);
// ....
}
// Called every frame
void UPositionReport::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
// ...
}
| [
"[email protected]"
] | |
532617d60af23161270950ff0f67cf40902e9706 | f0c04d720a27000a3e5b47dd4eb47c3e1ad24edd | /Ryno Engine/Source/Rendering/Material.cpp | 57d50040cb4856074d56b264bf7e54ad71b5b440 | [] | no_license | Ceffa/Ryno-Engine | 30a0d4a7107681eeb4206325bb10bc29f889f059 | 94db0fb654e854eaf79429032aa8c3c0b16452b2 | refs/heads/master | 2020-12-29T18:47:44.865994 | 2018-01-10T10:17:05 | 2018-01-10T10:17:05 | 45,530,828 | 39 | 8 | null | null | null | null | UTF-8 | C++ | false | false | 1,102 | cpp | #include "Material.h"
namespace Ryno {
bool Material::set_shader(Shader * _shader)
{
shader = _shader;
if(attribute_memory)
free(attribute_memory);
if (uniform_memory)
free(uniform_memory);
attribute_memory = calloc(shader->attributes_struct_size, 1);
uniform_memory = calloc(shader->uniforms_map_size, 1);
if (!attribute_memory || !uniform_memory){
std::cout << "Failed to allocate material structs" << std::endl;
return false;
}
return true;
}
void Material::send_uniforms_to_shader() const
{
U8 sampler_index = 0;
for (auto& entry : shader->uniforms_map) {
auto& x = entry.second;
shader->send_uniform_to_shader(entry.first, (void*)((U64)uniform_memory + x.offset), &sampler_index);
}
}
Material::Material(const Material& cp)
{
copy(cp);
}
void Material::copy(const Material& cp)
{
//Set same shader
set_shader(cp.shader);
//Copy attributes memory
std::memcpy(attribute_memory, cp.attribute_memory, shader->attributes_struct_size);
std::memcpy(uniform_memory, cp.uniform_memory, shader->uniforms_map_size);
}
}
| [
"[email protected]"
] | |
d6cdc5db215819261b7e1eddbd813e719e6f0e94 | 4fe94c6c37eda3fcdff737c3db2b9e01dad5d89d | /brown_belt/w3/pipeline/pipeline.cpp | ffea33e0faca62f62a9a42585b01ac30ac63ea18 | [] | no_license | KushnirDmytro/cpp_belts_coursera | a2a3b070a6162b2dc96fb00a65f6f3074068aa26 | 7ada0052c19efbe2a1a6c8252e8816046b4a755c | refs/heads/master | 2020-07-18T21:59:46.134029 | 2020-01-18T15:33:13 | 2020-01-18T15:33:13 | 206,320,214 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,721 | cpp | #include "test_runner.h"
#include <functional>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
#include <list>
using namespace std;
struct Email {
string from;
string to;
string body;
};
class Worker {
private: unique_ptr<Worker> next_{nullptr};
public:
virtual ~Worker() = default;
virtual void Process(unique_ptr<Email> email) = 0;
virtual void Run() {
throw logic_error("Unimplemented");
}
protected:
void PassOn(unique_ptr<Email> email) const{
if (next_){
next_->Process(move(email));
}
}
public:
void SetNext(unique_ptr<Worker> next){
next_ = move(next);
}
};
class Reader : public Worker {
public:
Reader(istream& is) : is_{is}
{
}
void Run() override {
unique_ptr<Email> new_em = make_unique<Email>();
while (
getline(is_, new_em->from) &&
getline(is_, new_em->to) &&
getline(is_, new_em->body)
)
{
PassOn(move(new_em));
new_em = make_unique<Email>();
}
}
void Process(unique_ptr<Email> email = nullptr) override {
Run();
};
private:
istream& is_;
};
class Filter : public Worker {
public:
using Predicate = function<bool(const Email&)>;
Filter(Predicate pred)
: pred_( move(pred) )
{
}
public:
void Process(unique_ptr<Email> email) override {
if (pred_(*email))
PassOn(move(email));
};
private:
Predicate pred_;
};
class Copier : public Worker {
public:
Copier(string new_receiver_address) : additional_receiver_address_{move(new_receiver_address)}
{
}
void Process(unique_ptr<Email> email) override {
if (email->to != additional_receiver_address_){
Email copy {email->from, additional_receiver_address_, email->body};
PassOn( move(email) );
PassOn( make_unique<Email>(copy) );
}
else {
PassOn(move(email));
}
};
private:
const string additional_receiver_address_;
};
class Sender : public Worker {
public:
Sender(ostream& os) : os_{os}
{
}
void Process(unique_ptr<Email> email) override {
os_.write(email->from.c_str(), email->from.size());
os_ << endl;
os_.write(email->to.c_str(), email->to.size());
os_ << endl;
os_.write(email->body.c_str(), email->body.size());
os_ << endl;
PassOn(move(email));
};
private:
ostream& os_;
};
class PipelineBuilder {
public:
explicit PipelineBuilder(istream& in)
: head_{make_unique<Reader>(in)}
{
}
PipelineBuilder& FilterBy(Filter::Predicate filter){
pipeline_.push_back(make_unique<Filter>(filter));
return *this;
}
PipelineBuilder& CopyTo(string recipient) {
pipeline_.push_back(make_unique<Copier>(move(recipient)));
return *this;
}
PipelineBuilder& Send(ostream& out){
pipeline_.push_back(make_unique<Sender>(out));
return *this;
}
unique_ptr<Worker> Build(){
if (!pipeline_.empty()){
unique_ptr<Worker> old_tail = move(pipeline_.back());
pipeline_.pop_back();
unique_ptr<Worker> new_tail;
while(!pipeline_.empty()){
new_tail = move(pipeline_.back());
new_tail->SetNext(move(old_tail));
old_tail = move(new_tail);
pipeline_.pop_back();
}
head_->SetNext(move(old_tail)); //
}
return move(head_);
}
private:
list<unique_ptr<Worker>> pipeline_;
unique_ptr<Worker> head_;
};
void TestSanity() {
string input = (
"[email protected]\n"
"[email protected]\n"
"Hello there\n"
"[email protected]\n"
"[email protected]\n"
"Are you sure you pressed the right button?\n"
"[email protected]\n"
"[email protected]\n"
"I do not make mistakes of that kind\n"
);
istringstream inStream(input);
ostringstream outStream;
PipelineBuilder builder(inStream);
builder.FilterBy([](const Email& email) {
return email.from == "[email protected]";
});
builder.CopyTo("[email protected]");
builder.Send(outStream);
auto pipeline = builder.Build();
pipeline->Run();
string expectedOutput = (
"[email protected]\n"
"[email protected]\n"
"Hello there\n"
"[email protected]\n"
"[email protected]\n"
"Are you sure you pressed the right button?\n"
"[email protected]\n"
"[email protected]\n"
"Are you sure you pressed the right button?\n"
);
ASSERT_EQUAL(expectedOutput, outStream.str());
}
int main() {
TestRunner tr;
RUN_TEST(tr, TestSanity);
return 0;
}
| [
"[email protected]"
] | |
699b89a8babc00b7f5cf0aa1c6152ad9708bae5a | d70a8896fab79eb3ac0f7d340a7cec094f3fbcc5 | /code/FRED2/AddVariableDlg.cpp | 219d0bc0be786458a64e1be39b2c1dc66334afcd | [] | no_license | mmastro/freespace2 | ce3699124ada832d6b306dc8910e4d822906bf09 | 60787ca0068156211436f7716a1d1ee27c88048e | refs/heads/master | 2020-05-15T08:38:34.077297 | 2015-06-20T14:02:24 | 2015-06-20T14:02:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,630 | cpp | /*
* Copyright (C) Volition, Inc. 1999. All rights reserved.
*
* All source code herein is the property of Volition, Inc. You may not sell
* or otherwise commercially exploit the source or things you created based on the
* source.
*
*/
// AddVariableDlg.cpp : implementation file
//
#include "stdafx.h"
#include "fred.h"
#include "AddVariableDlg.h"
#include "Sexp.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#define NO_RESET_FOCUS 0
#define RESET_FOCUS 1
/////////////////////////////////////////////////////////////////////////////
// CAddVariableDlg dialog
CAddVariableDlg::CAddVariableDlg(CWnd* pParent /*=NULL*/)
: CDialog(CAddVariableDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CAddVariableDlg)
m_default_value = _T("");
m_variable_name = _T("");
//}}AFX_DATA_INIT
}
void CAddVariableDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CAddVariableDlg)
DDX_Text(pDX, IDC_ADD_VARIABLE_DEFAULT_VALUE, m_default_value);
DDV_MaxChars(pDX, m_default_value, 31);
DDX_Text(pDX, IDC_ADD_VARIABLE_NAME, m_variable_name);
DDV_MaxChars(pDX, m_variable_name, 31);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CAddVariableDlg, CDialog)
//{{AFX_MSG_MAP(CAddVariableDlg)
ON_BN_CLICKED(IDC_TYPE_NUMBER, OnTypeNumber)
ON_BN_CLICKED(IDC_TYPE_STRING, OnTypeString)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CAddVariableDlg message handlers
void CAddVariableDlg::OnOK()
{
// validation name
validate_variable_name(RESET_FOCUS);
// validate data
if ( m_name_validated ) {
validate_data(RESET_FOCUS);
}
// both ok, then store results
if ( m_name_validated && m_data_validated ) {
// int sexp_add_variable(char *text, char*, int type);
// char temp_name[32];
// char temp_value[32];
// strcpy(temp_name, m_variable_name);
// strcpy(temp_value, m_default_value);
// SEXP_VARIABLE_NUMBER SEXP_VARIABLE_STRING
// int type;
//
// if (m_type_number) {
// type = SEXP_VARIABLE_NUMBER;
// } else {
// type = SEXP_VARIABLE_STRING;
// }
// m_sexp_var_index = sexp_add_variable(temp_value, temp_name, type);
// this get done for free CDialog::OnOk() UpdateData(TRUE);
m_create = true;
CDialog::OnOK();
}
}
BOOL CAddVariableDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// TODO: Add extra initialization here
m_variable_name = "<Variable Name>";
m_default_value = "<Default Value>";
// Set variable type to number
m_type_number = true;
set_variable_type();
m_name_validated = false;
m_data_validated = false;
m_create = false;
// Send default name and values into dialog box
UpdateData(FALSE);
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
bool is_sexp_variable_name(const char* temp_name)
{
for (int i=0; i<MAX_SEXP_VARIABLES; i++) {
if (Sexp_variables[i].type & SEXP_VARIABLE_SET) {
if ( !strcmp(Sexp_variables[i].text, temp_name) ) {
return false;
}
}
}
// name not found
return true;
}
// Check variable name (1) changed (2) > 0 length (3) does not already exist
void CAddVariableDlg::validate_variable_name(int set_focus)
{
CString temp_name;
CEdit *edit = (CEdit *) GetDlgItem(IDC_ADD_VARIABLE_NAME);
edit->GetWindowText(temp_name);
// Check if any change and not already in list
if ( stricmp(temp_name, "<Variable Name>") ) {
if ( (strlen(temp_name) > 0) && (get_index_sexp_variable_name(LPCTSTR(temp_name)) == -1) ) { //not already in list and length > 0 {
m_name_validated = true;
} else {
// conflicting variable name
if (strlen(temp_name) == 0) {
edit->SetWindowText("<Variable Name>");
}
m_name_validated = false;
if (set_focus == RESET_FOCUS) {
MessageBox("Conflicting variable name");
edit->SetFocus();
edit->SetSel(0, -1);
}
}
} else {
// name unchanged from default
m_name_validated = false;
if (set_focus == RESET_FOCUS) {
MessageBox("Invalid variable name");
edit->SetFocus();
edit->SetSel(0, -1);
}
}
}
void CAddVariableDlg::validate_data(int set_focus)
{
CString temp_data;
CEdit *edit = (CEdit *) GetDlgItem(IDC_ADD_VARIABLE_DEFAULT_VALUE);
edit->GetWindowText(temp_data);
// check for 0 string length
if (strlen(temp_data) == 0) {
m_data_validated = false;
} else {
if (m_type_number) {
// verify valid number
int temp_num = atoi(temp_data);
char buf[TOKEN_LENGTH];
sprintf(buf, "%d", temp_num);
if ( stricmp(buf, temp_data) ) {
m_data_validated = false;
} else {
m_data_validated = true;
}
} else {
m_data_validated = true;
}
}
// Display message and reset focus
if ( (!m_data_validated) && (set_focus == RESET_FOCUS) ) {
MessageBox("Invalid Default Value.");
edit->SetFocus();
edit->SetSel(0, -1);
}
}
// Set type to number
void CAddVariableDlg::OnTypeNumber()
{
m_type_number = true;
set_variable_type();
}
// Set type to string
void CAddVariableDlg::OnTypeString()
{
m_type_number = false;
set_variable_type();
}
// Set type check boxes
void CAddVariableDlg::set_variable_type()
{
CButton *button_string = (CButton *) GetDlgItem(IDC_TYPE_STRING);
CButton *button_number = (CButton *) GetDlgItem(IDC_TYPE_NUMBER);
button_number->SetCheck( m_type_number);
button_string->SetCheck(!m_type_number);
}
| [
"[email protected]"
] | |
faa0435fa24e749ed4d53fdcfd2f2a1ddc61d0ab | 406fd11771828c25b66664e1f47f890de511d00e | /include/IWallet.h | c00e8f485d43041aaf42e91cd6669dd140796893 | [
"BSD-3-Clause"
] | permissive | romankosoj/protect | f903f874d5d931fcc067636186ba2a02d1788999 | 473cd33e97435777ca8885dc3f418e012fdb6cb1 | refs/heads/master | 2021-07-15T17:13:37.270241 | 2017-10-19T14:35:08 | 2017-10-19T14:35:08 | 107,504,869 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,745 | h | // Copyright (c) 2014-2017, The Protect Security Coin
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers
#pragma once
#include <array>
#include <cstdint>
#include <istream>
#include <limits>
#include <ostream>
#include <string>
#include <system_error>
#include <vector>
namespace CryptoNote {
typedef size_t TransactionId;
typedef size_t TransferId;
typedef std::array<uint8_t, 32> TransacitonHash;
struct Transfer {
std::string address;
int64_t amount;
};
const TransactionId INVALID_TRANSACTION_ID = std::numeric_limits<TransactionId>::max();
const TransferId INVALID_TRANSFER_ID = std::numeric_limits<TransferId>::max();
const uint64_t UNCONFIRMED_TRANSACTION_HEIGHT = std::numeric_limits<uint64_t>::max();
struct Transaction {
TransferId firstTransferId;
size_t transferCount;
int64_t totalAmount;
uint64_t fee;
TransacitonHash hash;
bool isCoinbase;
uint64_t blockHeight;
uint64_t timestamp;
std::string extra;
};
class IWalletObserver {
public:
virtual void initCompleted(std::error_code result) {}
virtual void saveCompleted(std::error_code result) {}
virtual void synchronizationProgressUpdated(uint64_t current, uint64_t total) {}
virtual void actualBalanceUpdated(uint64_t actualBalance) {}
virtual void pendingBalanceUpdated(uint64_t pendingBalance) {}
virtual void externalTransactionCreated(TransactionId transactionId) {}
virtual void sendTransactionCompleted(TransactionId transactionId, std::error_code result) {}
virtual void transactionUpdated(TransactionId transactionId) {}
};
class IWallet {
public:
virtual ~IWallet() = 0;
virtual void addObserver(IWalletObserver* observer) = 0;
virtual void removeObserver(IWalletObserver* observer) = 0;
virtual void initAndGenerate(const std::string& password) = 0;
virtual void initAndLoad(std::istream& source, const std::string& password) = 0;
virtual void shutdown() = 0;
virtual void save(std::ostream& destination, bool saveDetailed = true, bool saveCache = true) = 0;
virtual std::error_code changePassword(const std::string& oldPassword, const std::string& newPassword) = 0;
virtual std::string getAddress() = 0;
virtual uint64_t actualBalance() = 0;
virtual uint64_t pendingBalance() = 0;
virtual size_t getTransactionCount() = 0;
virtual size_t getTransferCount() = 0;
virtual TransactionId findTransactionByTransferId(TransferId transferId) = 0;
virtual bool getTransaction(TransactionId transactionId, Transaction& transaction) = 0;
virtual bool getTransfer(TransferId transferId, Transfer& transfer) = 0;
virtual TransactionId sendTransaction(const Transfer& transfer, uint64_t fee, const std::string& extra = "", uint64_t mixIn = 0, uint64_t unlockTimestamp = 0) = 0;
virtual TransactionId sendTransaction(const std::vector<Transfer>& transfers, uint64_t fee, const std::string& extra = "", uint64_t mixIn = 0, uint64_t unlockTimestamp = 0) = 0;
virtual std::error_code cancelTransaction(size_t transferId) = 0;
};
}
| [
"[email protected]"
] | |
a74bb5942dc2c7e11aefedef5f97c07cd73132c2 | 2687c31493d0aa7adce9366fb062faf3f22fc85a | /d04/ex03/Character.hpp | fdf15077da3f063076d1754b2ab72297f32b2b80 | [] | no_license | kantum/piscine_cpp | 9afbdece844dac400288e3ee47622353954c4935 | 39664dd613fcaf321028761ba1925065b1d56ded | refs/heads/master | 2022-03-01T13:37:49.711337 | 2019-10-24T20:26:49 | 2019-10-24T20:26:49 | 214,853,970 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,398 | hpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Character.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: acompagn <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/10/20 23:03:26 by acompagn #+# #+# */
/* Updated: 2019/10/20 23:21:59 by acompagn ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef CHARACTER_HPP
# define CHARACTER_HPP
class Character : public ICharacter
{
private:
AMateria* _inventory[4];
std::string _name;
public:
Character(void);
Character(std::string const & name);
Character(Character const & src);
virtual ~Character(void);
Character& operator=(Character const & rhs);
virtual std::string const & getName() const;
virtual void equip(AMateria* m);
virtual void unequip(int idx);
virtual void use(int idx, ICharacter& target);
};
#endif
| [
"[email protected]"
] | |
577acee7efb1fdd6ba1950e28d4f59958dbe4292 | 24f26f85f379676764c05f92f1ec75c6354f2a05 | /Dynamic programming 2/Knapsack.cpp | c8396c1a31c1c394dcb903c56f7284e004106bcc | [] | no_license | Mehulcoder/Coding-ninjas-competitive | 09fcbf2267da521eabeda112ed803c76c782d7ed | a167d473c9d2c7df45a38d5c4454f8e651964fb7 | refs/heads/master | 2022-02-27T12:35:34.657228 | 2021-09-02T16:37:23 | 2021-09-02T16:37:23 | 201,101,214 | 290 | 183 | null | 2022-02-16T02:08:20 | 2019-08-07T17:54:08 | C++ | UTF-8 | C++ | false | false | 1,310 | cpp | /*
Name: Mehul Chaturvedi
IIT-Guwahati
*/
/*
A thief robbing a store and can carry a maximal weight of W into his knapsack. There are N items and ith item weigh wi and is of value vi. What is the maximum value V, that thief can take ?
Space complexity should be O(n).
Input Format :
Line 1 : N i.e. number of items
Line 2 : N Integers i.e. weights of items separated by space
Line 3 : N Integers i.e. values of items separated by space
Line 4 : Integer W i.e. maximum weight thief can carry
Output Format :
Line 1 : Maximum value V
Constraints
1 <= N <= 10^4
1<= wi <= 100
1 <= vi <= 100
Sample Input 1 :
4
1 2 4 5
5 4 8 6
5
Sample Output :
13
*/
#include <bits/stdc++.h>
using namespace std;
int knapSack(int W, int wt[], int val[], int n)
{
int i, w;
int K[n+1][W+1];
// Build table K[][] in bottom up manner
for (i = 0; i <= n; i++)
{
for (w = 0; w <= W; w++)
{
if (i==0 || w==0)
K[i][w] = 0;
else if (wt[i-1] <= w)
K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w]);
else
K[i][w] = K[i-1][w];
}
}
return K[n][W];
}
int knapsack(int* weights, int* values, int n, int maxWeight){
return knapSack(maxWeight, weights, values, n);
}
}
| [
"[email protected]"
] | |
e3086c19cac61afcb75bbc7b67b641284987b984 | 0a1b417f238ca5cb7eac543d6a144abeaec1e8a8 | /examples/HttpServer/sources/WebRetriever.cpp | 3d61d36b8fd3f1127c8a49dbca13f7636e3d2b01 | [
"BSD-2-Clause"
] | permissive | SammyEnigma/NetLib | 2374711a51e82efbacc5a605503dce2b944dbdc5 | 1e2ca00a2d97d78f294e810a37038da88ca99704 | refs/heads/master | 2020-12-02T08:53:59.650875 | 2020-01-27T05:49:25 | 2020-01-27T05:49:25 | 230,952,305 | 0 | 0 | BSD-2-Clause | 2020-01-27T06:35:17 | 2019-12-30T17:11:57 | null | UTF-8 | C++ | false | false | 2,670 | cpp | #include <memory.h>
#include <string.h>
#include <stdlib.h>
#include "WebRetriever.h"
#include "Logger.h"
struct url_data
{
size_t size;
char* data;
};
size_t CurlCallback(void *ptr, size_t size, size_t nmemb, struct url_data *data)
{
size_t index = data->size;
size_t n = (size * nmemb);
char* tmp;
data->size += (size * nmemb);
tmp = (char*)realloc(data->data, data->size + 1); // +1 for '\0'
if(tmp)
{
data->data = tmp;
}
else
{
if(data->data)
{
free(data->data);
}
return 0;
}
memcpy((data->data + index), ptr, n);
data->data[data->size] = '\0';
return size * nmemb;
}
WebRetriever::WebRetriever()
{
curl = curl_easy_init();
}
WebRetriever::~WebRetriever()
{
if (curl)
{
curl_easy_cleanup(curl);
}
}
bool WebRetriever::retrieve(std::string url, std::string user, std::string pass)
{
struct url_data data;
data.size = 0;
data.data = (char*)malloc(4096); // reasonable size initial buffer
if(NULL == data.data)
{
return false;
}
data.data[0] = '\0';
CURLcode res;
if (curl)
{
curl_easy_reset(curl);
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &data);
curl_easy_setopt(curl, CURLOPT_HTTPAUTH, (long)CURLAUTH_BASIC);
curl_easy_setopt(curl, CURLOPT_USERNAME, user.c_str());
curl_easy_setopt(curl, CURLOPT_PASSWORD, pass.c_str());
res = curl_easy_perform(curl);
if(res != CURLE_OK)
{
writeLog(curl_easy_strerror(res), LOG_ERROR);
writeLog(url, LOG_ERROR);
return false;
}
httpbody = data.data;
}
return true;
}
bool WebRetriever::retrieve(std::string url)
{
struct url_data data;
data.size = 0;
data.data = (char*)malloc(4096); // reasonable size initial buffer
if (NULL == data.data)
{
return false;
}
data.data[0] = '\0';
CURLcode res;
if (curl)
{
curl_easy_reset(curl);
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &data);
res = curl_easy_perform(curl);
if (res != CURLE_OK)
{
fprintf(stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(res));
}
httpbody = data.data;
}
return true;
}
std::string & WebRetriever::getHttpBody()
{
return httpbody;
}
| [
"[email protected]"
] | |
536d1ac01fef73108bc673f1db1204c60e2c9686 | 93a868a6462410b5e5bd45b224b1f170e6428845 | /395.cpp | 07b68f2b1261c40343fce9c8993379d830033858 | [] | no_license | summylight/leetCplus | b2b9635ca7ede65d277ac603d0952d47a23be01d | 6af6194e053d9ed6c8e11eb03e4c850c244e4344 | refs/heads/main | 2023-01-09T12:56:36.438052 | 2020-11-15T09:16:59 | 2020-11-15T09:16:59 | 307,955,088 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 532 | cpp | #include "C.h"
#include <set>
int longestSubstring(string s, int k) {
if(s.empty()||k>s.size()) return 0;
if(k<=1) return s.size();
unordered_map<char,int> Map;
for(auto i:s)
Map[i]++;
int index=0;
while(index<s.size()&&Map[s[index]]>=k) index++;
if(index==s.size()) return index;
int left = longestSubstring(s.substr(0,index),k);
int right = longestSubstring(s.substr(index+1),k);
return max(left,right);
} | [
"[email protected]"
] | |
2460aa4cd41e05bd22751519a35adcb0e395c399 | 5c5033209087c5d2c72415ae45efab42e5658d08 | /蓝桥/计蒜客2018第一次模拟/封印之门.cpp | 04e934cd64f5e8e09ed105ad37c86a41dce72630 | [] | no_license | mqaaa/algorithmmic | 1b6f4bd8381d76625f726bad662783b28080de9d | 811b6ae7c1ff021149c79e54ce9366e95fcb8c8b | refs/heads/master | 2021-03-30T17:26:00.934151 | 2018-04-18T14:00:27 | 2018-04-18T14:00:27 | 123,786,066 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 724 | cpp | #include<iostream>
#include<cstdio>
#include<string>
using namespace std;
int main(){
string st,ans;
cin >> st;
cin >> ans;
int n;
int map[27][27] = {0};
int temp1,temp2;
char t1,t2;
cin >> n;
for(int i = 0 ; i < n ; i++){
cin >> t1 >> t2;
temp1 = t1-'a';
temp2 = t2-'a';
map[temp1][temp2] = 1;
for(int j = 0 ; j < 26 ; j++){
if(map[j][temp1]!=0){
if(map[j][temp1]+1<map[j][temp2])map[j][temp2]=map[j][temp1]+1;
else if(map[j][temp2]==0)map[j][temp2]=map[j][temp1]+1;
}
}
}
int sum = 0;
for(int i = 0 ; i < st.length() ; i++){
if(st[i]==ans[i])continue;
int c = map[st[i]-'a'][ans[i]-'a'];
if(c==0){
cout<<"-1";
return 0;
}
sum = sum + c;
}
cout << sum;
return 0;
}
| [
"[email protected]"
] | |
09068d858cf9ea13fa00ef35ab084a5d76035df2 | c2d270aff0a4d939f43b6359ac2c564b2565be76 | /src/chrome/browser/vr/webvr_tab_browser_test.cc | 8b0e2614dbdcc72f00256d4e88ccb3df8f521312 | [
"BSD-3-Clause"
] | permissive | bopopescu/QuicDep | dfa5c2b6aa29eb6f52b12486ff7f3757c808808d | bc86b705a6cf02d2eade4f3ea8cf5fe73ef52aa0 | refs/heads/master | 2022-04-26T04:36:55.675836 | 2020-04-29T21:29:26 | 2020-04-29T21:29:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,205 | cc | // Copyright 2017 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 "chrome/browser/ui/browser_tabstrip.h"
#include "chrome/browser/vr/test/vr_browser_test.h"
#include "chrome/browser/vr/test/vr_transition_utils.h"
#include "url/gurl.h"
#include "url/url_constants.h"
// Browser test equivalent of
// chrome/android/javatests/src/.../browser/vr_shell/WebVrTabTest.java.
// End-to-end tests for testing WebVR's interaction with multiple tabss.
namespace vr {
// Tests that non-focused tabs cannot get pose information
IN_PROC_BROWSER_TEST_F(VrBrowserTest, REQUIRES_GPU(TestPoseDataUnfocusedTab)) {
LoadUrlAndAwaitInitialization(
GetHtmlTestFile("test_pose_data_unfocused_tab"));
ExecuteStepAndWait("stepCheckFrameDataWhileFocusedTab()",
GetFirstTabWebContents());
chrome::AddTabAt(browser(), GURL(url::kAboutBlankURL),
-1 /* index, append to end */, true /* foreground */);
ExecuteStepAndWait("stepCheckFrameDataWhileNonFocusedTab()",
GetFirstTabWebContents());
EndTest(GetFirstTabWebContents());
}
} // namespace vr
| [
"[email protected]"
] | |
883067703b6ed6a8e959d2b765be5abe5c1182fc | 40c68fac1f8e81c7e090e322eba810e17addee8e | /Learning CPP/main.cpp | 5da5de523f57c45cb83b3f19741b5c9a74f529b2 | [] | no_license | BenWheatley/BasicsOfCPP | f03fb59cd131ff41a67e1e6d03c1557e426d9af2 | c1cf8e439e9cb00bf717aee0680cf3d49de03e0a | refs/heads/master | 2020-03-30T14:33:36.897734 | 2018-10-06T20:39:58 | 2018-10-06T20:39:58 | 151,323,909 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,375 | cpp | //
// main.cpp
// Learning CPP
//
// Created by Ben Wheatley on 2018/10/01.
// Copyright © 2018 Ben Wheatley. All rights reserved.
//
#include <iostream>
// Following https://www.youtube.com/watch?v=vLnPwxZdW4Y tutorial
// Then https://www.youtube.com/watch?v=Rub-JsjMhWY tutorial
#include <cmath>
#include <vector>
#include <map>
#include <fstream>
using namespace std;
// Classes
class Box {
private:
int l = 0;
int b = 0;
int h = 0;
public:
Box() : l(0), b(0), h(0) {};
Box(int l, int b, int h) : l(l), b(b), h(h) {};
Box(Box *otherBox);
int getLength() { return l; }
int getBreadth() { return b; }
int getHeight() { return h; }
long long CalculateVolume() {
long long ll = l, lb = b, lh = h; // Because this wouldn't be specified long-long if none of the test cases overflowed
return ll*lb*lh;
}
bool operator < (Box& b) {
return (this->l < b.l) ||
(this->b < b.b && this->l == b.l) ||
(this->h < b.h && this->b == b.b && this->l == b.l);
}
};
class BadLengthException : public runtime_error {
public:
BadLengthException(int length) : runtime_error(to_string(length)) {};
};
Box::Box(Box *otherBox) { l=otherBox->l; b=otherBox->b; h=otherBox->h; }
ostream& operator << (ostream& out, Box& B) {
out << B.getLength() << " " << B.getBreadth() << " " << B.getHeight();
return out;
}
class Animal {
private:
double height;
double weight;
string name;
static int numOfAnimals;
public:
double getHeight() { return height; }
double getWeight() { return weight; }
string getName() { return name; }
void setHeightCM(double height) { this->height = height; }
void setWeightKG(double weight) { this->weight = weight; }
void setName(string name) { this->name = name; }
void setAll(double, double, string);
Animal(double, double, string);
Animal();
~Animal();
static int getNumOfAnimals() { return numOfAnimals; }
void toString();
virtual void getClass() { cout << "I'm an animal (virtual method)" << endl; }
};
int Animal::numOfAnimals = 0;
void Animal::setAll(double height, double weight, string name) {
this->height = height;
this->weight = weight;
this->name = name;
}
Animal::Animal(double height, double weight, string name) {
this->setAll(height, weight, name);
Animal::numOfAnimals++;
}
Animal::Animal() {
Animal::numOfAnimals++;
}
Animal::~Animal() {
cout << "Animal of name " << this->name << " was deleted" << endl;
Animal::numOfAnimals--;
}
void Animal::toString() {
cout << this->name << " weighs " << this->weight << "kg and is " << this->height << "cm tall" << endl;
}
class Dog: public Animal {
private:
string breed = "Mongrel";
public:
void printBreed() { cout << breed << endl; }
Dog(double, double, string, string);
Dog() : Animal(){}; // One possible way to initialize default constructor; note to self, this syntax is completely different from what I'm used to
void toString();
void getClass() { cout << "I'm a dog (overwritten virtual method)" << endl; }
};
Dog::Dog(double height, double weight, string name, string breed) : Animal(height, weight, name) {
this->breed = breed;
}
void Dog::toString() {
cout << this->getName() << " weighs " << this->getWeight() << "kg, is "
<< this->getHeight() << "cm tall, and is a " << this->breed << endl;
}
class GermanShepherd : public Dog {
public:
void getClass() {
cout << "I'm a German Shepherd" << endl;
}
void getDerived() {
cout << "I'm an animal and a dog" << endl;
}
};
void whatClassAreYou(Animal *animal) {
// Without "virtual" keyword, will always be Animal::getClass
// With "virtual" keyword, will be <instancetype>::getClass
animal->getClass();
}
void whatClassAreYou(shared_ptr<Animal> animal) {
// Without "virtual" keyword, will always be Animal::getClass
// With "virtual" keyword, will be <instancetype>::getClass
animal->getClass();
}
// MARK: cache challenge
struct Node{
Node* next;
Node* prev;
int value;
int key;
Node(Node* p, Node* n, int k, int val):prev(p),next(n),key(k),value(val){};
Node(int k, int val):prev(NULL),next(NULL),key(k),value(val){};
};
class Cache{
protected:
map<int,Node*> mp; //map the key to the node in the linked list
int cp; //capacity
Node* tail; // double linked list tail pointer
Node* head; // double linked list head pointer
virtual void set(int, int) = 0; //set function
virtual int get(int) = 0; //get function
};
class LRUCache : public Cache {
public:
LRUCache(int capacity) { cp = capacity; };
void set(int key, int value) {
// seek key:
// key found:
// extract, move to front
// key missing:
// insert at front
// delete last item
try {
Node *node = mp.at(key);
if (node->prev != nullptr) {
node->prev->next = node->next;
}
if (node->next != nullptr) {
node->next->prev = node->prev;
}
node->prev = nullptr;
node->next = this->head;
this->head->prev = node;
this->head = node;
} catch (...) {
Node *n = new Node(NULL, head, key, value);
mp[key] = n;
this->head = n;
if (mp.size()==1) {
this->tail = n;
}
if (mp.size() > cp && this->tail != NULL) {
mp.erase(this->tail->key);
Node *newTail = this->tail->prev;
if (newTail != NULL) {
newTail->next = NULL;
}
}
}
};
int get(int key) {
try {
return (mp.at(key))->value;
} catch (...) {
return -1;
}
};
};
void challenge() {
cout << "Challenge:" << endl;
int out;
LRUCache cache(644);
out = cache.get(3); cout << out << endl;
out = cache.get(19); cout << out << endl;
out = cache.get(8); cout << out << endl;
cache.set(1, 1195);
cache.set(5, 1404);
out = cache.get(6); cout << out << endl;
cache.set(15, 1020);
cache.set(7, 1010);
out = cache.get(8); cout << out << endl;
cache.set(7, 1628);
cache.set(16, 1498);
out = cache.get(11); cout << out << endl;
out = cache.get(14); cout << out << endl;
out = cache.get(19); cout << out << endl;
out = cache.get(8); cout << out << endl;
cache.set(12, 267);
cache.set(19, 125);
out = cache.get(8); cout << out << endl;
cache.set(15, 1241);
cache.set(8, 1936);
out = cache.get(1); cout << out << endl;
cache.set(17, 1162);
cache.set(13, 151);
out = cache.get(19); cout << out << endl;
out = cache.get(20); cout << out << endl;
out = cache.get(14); cout << out << endl;
out = cache.get(16); cout << out << endl;
out = cache.get(7); cout << out << endl;
cache.set(2, 1305);
cache.set(12, 287);
cache.set(9, 160);
out = cache.get(16); cout << out << endl;
out = cache.get(17); cout << out << endl;
cache.set(5, 1524);
cache.set(16, 81);
cache.set(4, 312);
cache.set(9, 89);
cache.set(19, 1306);
cache.set(18, 1041);
cache.set(16, 237);
out = cache.get(8); cout << out << endl;
cache.set(11, 387);
out = cache.get(1); cout << out << endl;
out = cache.get(8); cout << out << endl;
/*LRUCache cache(4);
out = cache.get(3); cout << out << endl;
out = cache.get(19); cout << out << endl;
out = cache.get(8); cout << out << endl;
cache.set(4, 2);
cache.set( 2, 7);
out = cache.get( 2); cout << out << endl;
cache.set( 1, 8);
cache.set( 5, 9);
cache.set( 6, 15);
out = cache.get( 4); cout << out << endl;
out = cache.get( 5); cout << out << endl;
return;*/
int n, capacity,i;
cin >> n >> capacity;
LRUCache l(capacity);
for(i=0;i<n;i++) {
string command;
cin >> command;
if(command == "get") {
int key;
cin >> key;
cout << l.get(key) << endl;
}
else if(command == "set") {
int key, value;
cin >> key >> value;
l.set(key,value);
}
}
}
// MARK: main block
int main(int argc, const char * argv[]) {
cout << "Animal count: " << Animal::getNumOfAnimals() << endl;
Animal *blank = new Animal();
Animal *fred = new Animal(50, 33, "Fred");
Animal *sam = new Animal();
sam->setName("Sam");
sam->setHeightCM(160);
sam->setWeightKG(87);
cout << "Animal count: " << Animal::getNumOfAnimals() << endl;
blank->toString();
fred->toString();
sam->toString();
cout << "Animal count: " << Animal::getNumOfAnimals() << endl;
Dog *spot = new Dog(38, 16, "Spots", "Dalmation");
cout << "Animal count: " << Animal::getNumOfAnimals() << endl;
spot->toString();
spot->printBreed();
spot->Animal::toString();
// Deletion automatic at end of execution if they are not pointers, but not automatic if they are pointers
delete blank;
delete fred;
delete sam;
delete spot;
cout << "shared_ptr example: " << endl;
shared_ptr<Animal> a = make_shared<Animal>();
shared_ptr<Dog> d = make_shared<Dog>();
a->setName("Katie");
d->setName("Molly");
a->getClass();
d->getClass();
whatClassAreYou(a);
whatClassAreYou(d);
shared_ptr<GermanShepherd> gs = make_shared<GermanShepherd>();
gs->getClass();
gs->getDerived();
shared_ptr<Animal> gs2 = make_shared<GermanShepherd>();
gs2->getClass();
// gs2->getDerived(); // Can't be called even though the constructed object has this method, because this isn't python
int big1 = 0xFFFFFF;
int overflowing = big1*big1;
long long isItNow = big1*big1;
long long big2 = big1;
long long andNow = big2*big2;
cout << "big1: " << big1 <<
"\noverflowing: " << overflowing <<
"\nisItNow: " << isItNow <<
"\nandNow: " << andNow << endl;
try {
throw BadLengthException(10);
} catch (BadLengthException e) {
cout << e.what() << endl;
}
challenge();
return 0;
}
| [
"[email protected]"
] | |
662a79e099178e3ee4c605f983fa27c0f032d001 | e0b7500cff4bc94b4fffe791c8a075c33b79c489 | /3rdparty/mkldnn/tests/benchdnn/conv/bench_conv.cpp | dfb23e9321463b6a92944457a9e076f9a3ebc1fd | [
"Apache-2.0",
"BSD-3-Clause",
"Zlib",
"LicenseRef-scancode-generic-cla",
"NCSA",
"OFL-1.0",
"BSD-2-Clause-Views",
"MIT",
"Unlicense",
"BSL-1.0",
"BSD-2-Clause"
] | permissive | haimeh/mxnet_a51m | c71d098cd0a9771cad31de26b9236071bada4c24 | b62490f15937723e6076570be983ddb0180d2dea | refs/heads/master | 2022-12-22T18:29:54.881909 | 2020-08-20T01:45:40 | 2020-08-20T01:45:40 | 288,790,745 | 0 | 1 | Apache-2.0 | 2022-12-14T17:23:23 | 2020-08-19T17:08:09 | C++ | UTF-8 | C++ | false | false | 3,366 | cpp | /*******************************************************************************
* Copyright 2017-2020 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sstream>
#include "dnnl_common.hpp"
#include "dnnl_memory.hpp"
#include "parser.hpp"
#include "conv/conv.hpp"
#include "conv/conv_dw_fusion.hpp"
namespace conv {
void check_correctness(const settings_t &s) {
for_(const auto &i_dir : s.dir)
for_(const auto &i_cfg : s.cfg)
for_(const auto &i_stag : s.stag)
for_(const auto &i_wtag : s.wtag)
for_(const auto &i_dtag : s.dtag)
for (const auto &i_mb : s.mb) {
const prb_t p(s.desc, i_dir, i_cfg, i_stag, i_wtag, i_dtag, s.alg,
s.attr, i_mb);
std::stringstream ss;
ss << p;
const std::string cpp_pstr = ss.str();
const char *pstr = cpp_pstr.c_str();
if (s.pattern && !match_regex(pstr, s.pattern)) return;
BENCHDNN_PRINT(1, "run: %s\n", pstr);
res_t res {};
int status = OK;
if (s.attr.post_ops.convolution_index() != -1)
status = conv_dw_fusion::doit(&p, &res);
else
status = conv::doit(&p, &res);
bool want_perf_report = false;
parse_result(res, want_perf_report, s.allow_unimpl, status, pstr);
if (want_perf_report && bench_mode & PERF) {
perf_report_t pr(s.perf_template);
pr.report(&p, &res, pstr);
}
benchdnn_stat.tests++;
}
}
int bench(int argc, char **argv) {
driver_name = "conv";
using namespace parser;
static settings_t s;
for (; argc > 0; --argc, ++argv) {
const bool parsed_options = parse_bench_settings(argv[0])
|| parse_batch(bench, argv[0]) || parse_dir(s.dir, argv[0])
|| parse_cfg(s.cfg, str2cfg, argv[0])
|| parse_tag(s.stag, argv[0], "stag")
|| parse_tag(s.wtag, argv[0], "wtag")
|| parse_tag(s.dtag, argv[0], "dtag")
|| parse_single_value_option(s.alg, str2alg, argv[0], "alg")
|| parse_mb(s.mb, argv[0]) || parse_attr(s.attr, argv[0])
|| parse_test_pattern_match(s.pattern, argv[0])
|| parse_allow_unimpl(s.allow_unimpl, argv[0])
|| parse_perf_template(s.perf_template, s.perf_template_def,
s.perf_template_csv, argv[0])
|| parse_reset(s, argv[0]);
if (!parsed_options) {
catch_unknown_options(argv[0]);
bool is_deconv = 0;
SAFE_V(str2desc(&s.desc, argv[0], is_deconv));
check_correctness(s);
}
}
return parse_last_argument();
}
} // namespace conv
| [
"[email protected]"
] | |
bf06728cf0037b067ad58b2fcbf7b863afb04527 | 6e6e1203a095c7128f27dc3adf022b4cbe0356b4 | /src/suit/SuitLegList.h | fc692b20e055b10f5619d462338a399bd2ae81dd | [
"Apache-2.0"
] | permissive | theclashingfritz/libtoontown | c0dcbfa44a22a5f3200f3b1522c16a5436e1578c | e453b1de7185e056f95d4ee4831612b1a6598631 | refs/heads/master | 2021-06-30T08:00:35.586822 | 2017-09-19T00:43:44 | 2017-09-19T00:43:44 | 103,720,426 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,426 | h | #ifndef _H_DNA_SUITLEGLIST_
#define _H_DNA_SUITLEGLIST_
#include "DNASuitPoint.h"
#include "DNASuitPath.h"
#include "DNAStorage.h"
#include "SuitLeg.h"
typedef std::vector<SuitLeg*> leg_vec_t;
class EXPCL_DNA SuitLegList
{
PUBLISHED:
SuitLegList(DNASuitPath* path, DNAStorage* store, double suit_walk_speed=4.8);
~SuitLegList();
SuitLeg::LegType get_suit_leg_type(DNASuitPoint::PointType a,
DNASuitPoint::PointType b);
size_t get_num_legs();
SuitLeg* get_leg(size_t index);
SuitLeg::LegType get_type(size_t index);
double get_leg_time(size_t index);
zone_id_t get_zone_id(size_t index);
block_number_t get_block_number(size_t index);
DNASuitPoint* get_point_a(size_t index);
DNASuitPoint* get_point_b(size_t index);
double get_start_time(size_t index);
size_t get_leg_index_at_time(double time, size_t start_leg);
bool is_point_in_range(DNASuitPoint* point, double low_time, double high_time);
SuitLeg::LegType get_next_leg_type(size_t index);
private:
void add_leg(DNASuitPoint* point_a, DNASuitPoint* point_b,
SuitLeg::LegType type, block_number_t landmark_building_index);
leg_vec_t m_legs;
DNASuitPath* m_path;
DNAStorage* m_store;
double m_suit_walk_speed;
};
#endif
| [
"[email protected]"
] | |
0ab547529366aa01e42b5da016b2ac876afaaf66 | e60ec8da091a3bc72a55e1ebbe714c7a9d688cba | /little_math/derivative.cpp | 74e4b6b606a18a828ea242ffd8da1936b810d603 | [] | no_license | Urroke/MATH_s | 3110d3bc9fecf36fa0dfe343ee3c9704f0b799c0 | 41af60dac828b24eae1b0b62e7eca69eeb60a703 | refs/heads/master | 2021-07-13T07:20:02.745542 | 2020-05-25T20:06:24 | 2020-05-25T20:06:24 | 147,962,072 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 653 | cpp | #include "little_math.h"
template <typename type, size_t number_lattice, size_t degree>
std::function<type(type)> derivative(std::function<type(type)> func, type aprox_interval)
{
std::function<type(type)> result = [=](type value)->type{
type h = aprox_interval/(number_lattice - 1);
mvector<type, number_lattice> x, y;
for(int i = 0;i < number_lattice;i++){
x[i] = value - aprox_interval/2 + h*i;
y[i] = func(x[i]);
}
polynom<type, degree> res(method_of_min_suare<type, number_lattice, degree>(x, y));
res.derivative();
return res(value);
};
return result;
}
| [
"[email protected]"
] | |
b1c696d86388783e11aa845a8e4d9fec3d292ccd | 3f678576db5b4513ff790657db48b07a8996037b | /Source Code/virtualsoc/src/core/mem_class.h | 66ff27c33d3a4a83029f7f68c18e725538bfd7e4 | [] | no_license | henriquevs/Filtering-Modeling-Medical-Images | c6292b5c5033e52eff082c921f66f228c3f2c80e | d530c8ba6531f4a4465901ee576d710cc4ecc593 | refs/heads/master | 2020-03-21T21:37:13.805576 | 2018-06-28T23:24:18 | 2018-06-28T23:24:18 | 139,074,014 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,332 | h | #ifndef __MEM_CLASS_H__
#define __MEM_CLASS_H__
#include <systemc.h>
#include "globals.h"
#include "debug.h"
class Mem_class
{
protected:
//ID of the memory
uint16_t ID;
//Pointer to the start of the instantiation of the memory
char *myMemory;
//Indicate the kind of the memory
const char *type;
//so that if needed the child class can simply derive it
virtual uint32_t addressing(uint32_t addr) {
return addr;
};
int load_program(char *);
long hexstringtonumber(char *str, int start, int len);
public:
//Size of the memory
uint32_t size;
// method to copy TCDM initialized data in proper banks - SINGLE_CLUSTER ONLY
int load_tcdm_init_data(char *, int i, unsigned int start_addr, unsigned int offset);
inline uint32_t get_local_bank_addr(uint32_t addr, int n_bit_shift) {
return (addr>>n_bit_shift)*CL_WORD + addr%CL_WORD;
}
Mem_class(uint16_t id, uint32_t size) : ID(id), size(size) {
myMemory = new char[size];
memset(myMemory, 0, size);
};
virtual ~Mem_class(){
delete [] myMemory;
};
///////////////////////////////////////////////////////////////////////////////
// Reads data from the memory.
virtual uint32_t Read(uint32_t addr, uint8_t bw = MEM_WORD)
{
uint32_t data;
addr = addressing(addr);
if (addr >= size)
{
printf("%s Memory %d: Bad address 0x%08x\n", type, ID, addr);
exit(1);
}
switch (bw)
{
case MEM_WORD: // Read word
{
data = *((uint32_t *)(myMemory + (addr & 0xFFFFFFFC)));
break;
}
case MEM_BYTE: // Read byte
{
data= *((uint32_t *)(myMemory + addr));
data = (data & 0x000000FF);
break;
}
case MEM_HWORD: // Read half word
{
data= *((uint32_t *)(myMemory + addr));
data = (data & 0x0000FFFF);
break;
}
default: // Error
{
printf("%s Memory %d: Bad read size request %u\n", type, ID, bw);
exit(1);
}
}
return data;
};
///////////////////////////////////////////////////////////////////////////////
// Writes data to the memory.
virtual void Write(uint32_t addr, uint32_t data, uint8_t bw = MEM_WORD)
{
addr = addressing(addr);
if (addr >= size)
{
printf("%s Memory %d: Bad address 0x%08x\n", type, ID, addr);
exit(1);
}
switch (bw)
{
case MEM_WORD: // Write word
{
*((uint32_t *)(myMemory + (addr & 0xFFFFFFFC))) = data;
break;
}
case MEM_BYTE: // Write byte
{
data = data & 0x000000FF;
*((char *)(myMemory + addr)) = (char)data;
break;
}
case MEM_HWORD: // Write half word
{
data = data & 0x0000FFFF;
*((uint16_t *)(myMemory + (addr & 0xFFFFFFFE))) = (uint16_t)data;
break;
}
default: // Error
{
printf("%s Memory %d: Bad write size request %u\n", type, ID, bw);
exit(1);
}
}
};
};
#endif // __MEM_CLASS_H__
| [
"[email protected]"
] | |
1b316fa207481b743d2823f9c5b0de3a536942fd | 23cd9aef3f56acfede4881594543cdb40caeb73f | /ML/Coderaman-tech_AmanKumarShrivastava_2024cse1155_2/GettingStarted/Is_a_number_Prime.cpp | 86489feb3018870a0a4a370f7e3b0caabd6cd259 | [] | no_license | durgesh-agrhari/coderspree | a98c5085eb8bec934162c37529431413011d8596 | 30e3a6e8a040639b61f20980c0e73a4aaef459d6 | refs/heads/main | 2023-08-28T12:15:25.361443 | 2021-10-06T12:38:05 | 2021-10-06T12:38:05 | 411,664,304 | 1 | 0 | null | 2021-09-29T12:25:24 | 2021-09-29T12:25:23 | null | UTF-8 | C++ | false | false | 385 | cpp | #include <iostream>
using namespace std;
int main(){
int t;
cin >> t;
while(t--){
int n;
cin>>n;
int count=0;
for(int i=2;i<n;i++){
if(n%i==0){
cout<<"not prime"<<"\n";
count=1;
break;
}
}
if(count==0)
cout<<"prime"<<"\n";
}
return 0;
} | [
"[email protected]"
] | |
bbdce02bfd740e437ab68b92688aa65b9d82b8eb | ced51d9c2f605b87fc37b4a8068c6a4954b7637d | /vector2.cpp | b8f690be5a904a72dd806bbd02838764eaab2f39 | [] | no_license | Dillonb/DuckHaunt | 2bb389b9ea03882e19aecfe72fd211eb2c73609f | 559c69f5f6b1c70795780bdbd44c31328896bfd6 | refs/heads/master | 2021-01-13T01:26:35.968259 | 2014-12-01T18:36:46 | 2014-12-01T18:36:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,303 | cpp | #include "vector2.h"
Vector2::Vector2(double x, double y) {
this->x = x;
this->y = y;
}
Vector2::Vector2() {
this->x = 0;
this->y = 0;
}
Vector2& Vector2::operator=(const Vector2& other) {
this->x = other.x;
this->y = other.y;
}
Vector2 Vector2::operator+(Vector2 other) {
Vector2 temp;
temp.x = this->x + other.x;
temp.y = this->y + other.y;
return temp;
}
Vector2 Vector2::operator-(Vector2 other) {
Vector2 temp;
temp.x = this->x - other.x;
temp.y = this->y - other.y;
return temp;
}
Vector2 Vector2::operator*(double multiplicand) {
Vector2 temp;
temp.x = this->x * multiplicand;
temp.y = this->y * multiplicand;
return temp;
}
double Vector2::dot(Vector2 other) {
return (this->x * other.x) + (this->y * other.y);
}
double Vector2::magnitude() {
return sqrt(pow(this->x,2) + pow(this->y,2));
}
int Vector2::rightOf(Vector2 other) {
Vector2 temp(-1 * this->y, this->x); // Rotate this vector 90 degrees counter clockwise
double result = other.dot(temp);
return (result > 0) ? 1 : ((result < 0) ? -1 : 0);
}
// Returns the projection vector of this onto other
Vector2 Vector2::project(Vector2 other) {
// this = duck
// other = player
return other * (this->dot(other) / other.dot(other));
}
| [
"[email protected]"
] | |
9222365c383daae25b12c2d2f205c6d2d3d3d5d2 | b131c2c15ce365c4e0556c7c5fc9444301cb7405 | /atcoder/ABC/088/C-Takahashis-Information.cpp | 1931878b26e44f89777f9fd4b0acb58f16d10a85 | [] | no_license | wilsjame/misc-algos | 5ce20c28b9e7e1d53ece72346431d897629ca924 | d42a5ce98764598f36cfe0bc154ecb76f2302864 | refs/heads/master | 2022-09-12T22:16:15.240348 | 2022-08-20T05:24:51 | 2022-08-20T05:24:51 | 243,411,893 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,229 | cpp | #include <iostream>
#include <vector>
using namespace std;
int main() {
vector<vector<int>> C(3, vector<int>(3));
for (auto &row: C)
for (auto &a : row)
cin >> a;
// A are constants, cycle through all choices for a1-3 and calculate b1-3
// a1 + b1 = A1,1
// a1 + b2 = A1,2
// a1 + b3 = A1,3
// a2 + b1 = A2,1
// a2 + b2 = A2,2
// a2 + b3 = A2,3
// a3 + b1 = A3,1
// a3 + b2 = A3,2
// a3 + b3 = A3,3
int a[3], b[3];
for (a[0] = 0; a[0] <= 100; a[0]++) {
for (a[1] = 0; a[1] <= 100; a[1]++) {
for (a[2] = 0; a[2] <= 100; a[2]++) {
b[0] = C[0][0] - a[0];
b[1] = C[0][1] - a[0];
b[2] = C[0][2] - a[0];
bool ok = true;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (a[i] + b[j] != C[i][j]) {
ok = false;
}
}
}
if (ok) {
cout << "Yes" << endl;
return 0;
}
}
}
}
cout << "No" << endl;
return 0;
}
| [
"[email protected]"
] | |
b3f666698608c2d7061055db7dc69ba9255cad48 | 6dd18dd258b38ddf3061565496d9bb7d982eb1e4 | /26_SmartPointers/04.UsingVectors.cpp | bd53e3929b031bb07b9e9bc856c5a02975c39d91 | [] | no_license | seddon-software/cplusplus | 5d67b0ca95d24c2c4911ad6111b1a9a1ba7285bf | bcbdfb6e916ebb08eb8d507dcb18bed8a80fbf82 | refs/heads/master | 2021-06-27T06:04:23.804126 | 2020-12-04T16:38:57 | 2020-12-04T16:38:57 | 174,515,590 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,651 | cpp | #include <iostream>
#include <sstream>
#include <vector>
#include <exception>
#include <memory>
using namespace std;
class Point
{
friend ostream& operator<<(ostream& os, const Point& p);
public:
Point()
{
cout << "CTOR()" << endl;
}
Point(int x, int y) : x(x), y(y)
{
cout << "CTOR(i,i)" << endl;
}
Point(Point&& temp ) noexcept : x(temp.x), y(temp.y)
{
std::cout << "Move" << std::endl;
}
Point( const Point& rhs ) : x(rhs.x), y(rhs.y)
{
std::cout << "Copy" << std::endl;
}
~Point()
{
cout << "DTOR" << endl;
}
Point& operator=(const Point& rhs)
{
std::cout << "=(&)" << std::endl;
x = rhs.x;
y = rhs.y;
return *this;
}
Point& operator=(Point&& rhs)
{
std::cout << "=(&&)" << std::endl;
x = rhs.x;
y = rhs.y;
return *this;
}
void moveBy(int dx, int dy)
{
x += dx;
y += dy;
}
string details() const
{
stringstream result(stringstream::in | stringstream::out);
result << "[" << x << "," << y << "]";
return result.str();
}
private:
int x;
int y;
};
ostream& operator<<(ostream& os, const Point& p)
{
return os << p.x << "," << p.y;
}
int main()
{
std::vector<unique_ptr<Point>> v;
v.push_back(std::unique_ptr<Point>(new Point(3, 4)));
v.push_back(std::unique_ptr<Point>(new Point(5, 3)));
v.push_back(std::unique_ptr<Point>(new Point(7, 2)));
for (auto i = v.begin(); i != v.end(); ++i)
{
unique_ptr<Point>& p = *i;
p->moveBy(1, 1);
cout << p->details() << endl;
}
// check vector has been updated
for (auto& ptr : v)
{
cout << ptr->details() << endl;
}
}
| [
"[email protected]"
] | |
854f09cad6ac929c6612d9d8ff49dbe218e16968 | b9d9a7f792cc0d9de25a0876b1b78652c74925eb | /tvremote/ipcsender.cpp | f58d6b3495f69081f370298ff31fc07d7a8c168c | [] | no_license | Sid-003/tvremote | 9e22cb2a898dd2bd731b922bd7c7fcb96c6d119b | 5bb0a8704ad3568f1ce575635e63c0fc51207c7d | refs/heads/master | 2022-04-12T15:12:19.209545 | 2020-03-01T01:23:39 | 2020-03-01T01:23:39 | 242,912,050 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 929 | cpp | #include "ipcsender.h"
#include <QHostAddress>
#include <QTcpSocket>
ipcsender::ipcsender(QString ip)
{
succit = new QTcpSocket();
QHostAddress host (ip);
succit->connectToHost(host, 20060);
if(succit->waitForConnected())
qInfo() << "Connection successful.";
else{
qInfo() << succit->errorString();
}
}
void ipcsender::sendIRRC(QString code)
{
sendData('C', "IRCC", code.toUtf8());
}
void ipcsender::sendData(char type, QString command, QByteArray data)
{
if(succit->isOpen())
{
QByteArray messageData;
messageData.append(_header, 2);
messageData.append(type);
messageData.append(command);
messageData.append(data);
messageData.append(_footer);
qInfo() << messageData.size();
succit->write(messageData);
qInfo() << "sent";
}
else
{
qInfo() << "Not connected.";
}
}
| [
"[email protected]"
] | |
38c02c32f49e5b7b1d909086b71a7b0bbaaca1f2 | e7f3c7db44e7aa54bc88a5629f3c0fb517701ed3 | /judges/uri/iniciante/1049.cpp | 02cb267270cb31cbf684492d7a12f2b6d63918ac | [
"MIT"
] | permissive | ednunes/competitive-programming | f699ef9a176277e18b7f017876efac95ad3cd643 | 0f6bdc573b4d03d1ed20a2b77ec5388dca1ee47b | refs/heads/master | 2022-09-08T09:19:08.225422 | 2019-10-03T17:03:50 | 2019-10-03T17:03:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 626 | cpp | #include <bits/stdc++.h>
using namespace std;
int main (){
int i = 0;
string s[3];
while(i < 3){
cin >> s[i];
i++;
}
if(s[0] == "vertebrado"){
if(s[1] == "ave"){
if(s[2] == "carnivoro"){
printf("aguia\n");
}else{
printf("pomba\n");
}
}else{
if(s[2] == "onivoro"){
printf("homem\n");
}else{
printf("vaca\n");
}
}
}else{
if(s[1] == "inseto"){
if(s[2] == "hematofago"){
printf("pulga\n");
}else{
printf("lagarta\n");
}
}else{
if(s[2] == "hematofago"){
printf("sanguessuga\n");
}else{
printf("minhoca\n");
}
}
}
return 0;
} | [
"[email protected]"
] | |
9bf490128557398b371211850b8a7128c1541162 | 34a3fa29d9270398372c04e002332ddedb3c498a | /div2/573/FTokitsukazeAndStrangeRectangle.cpp | 8eac4b96240fb1910155999fc22ecc656259f5c6 | [] | no_license | tatsumack/codeforces | 643accf23bc772d136708a1170ac2200a9348efc | b99c1ff04c8756121a059f130655885705018eca | refs/heads/master | 2021-07-10T05:55:56.329203 | 2020-07-23T10:50:08 | 2020-07-23T10:50:08 | 143,435,557 | 0 | 0 | null | 2019-10-12T03:10:19 | 2018-08-03T14:12:22 | C++ | UTF-8 | C++ | false | false | 2,038 | cpp | #include <iostream>
#include <limits.h>
#include <algorithm>
#include <bitset>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <deque>
#include <functional>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <numeric>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>
#include <queue>
#include <unordered_map>
#include <unordered_set>
#define int long long
#define REP(i, n) for (int i = 0, i##_len = (n); i < i##_len; ++i)
#define REPS(i, n) for (int i = 1, i##_len = (n); i <= i##_len; ++i)
#define FOR(i, a, b) for (int i = (a), i##_len = (b); i <= i##_len; ++i)
#define REV(i, a, b) for (int i = (a); i >= (b); --i)
#define CLR(a, b) memset((a), (b), sizeof(a))
#define DUMP(x) cout << #x << " = " << (x) << endl;
#define INF 1001001001001001001ll
#define fcout cout << fixed << setprecision(12)
using namespace std;
typedef pair<int, int> P;
class FTokitsukazeAndStrangeRectangle {
public:
static constexpr int kStressIterations = 0;
static void generateTest(std::ostream& test) {
}
void solve(std::istream& cin, std::ostream& cout) {
int n;
cin >> n;
vector<int> x(n), y(n);
vector<P> v(n);
REP(i, n) {
cin >> x[i] >> y[i];
v[i] = {y[i], x[i]};
}
set<int> found;
sort(v.rbegin(), v.rend());
int num = 0;
int res = 0;
REP(i, v.size()) {
int vx, vy;
tie(vy, vx) = v[i];
if (!found.count(vx)) num++;
found.insert(vx);
while (i + 1 < v.size() && v[i + 1].first == vy) {
if (!found.count(v[i + 1].second)) num++;
found.insert(v[i + 1].second);
i++;
}
res += 1;
if (num >= 1) res += (num - 1) * 2;
if (num >= 2) res += (num - 1) * (num - 2) / 2;
}
cout << res << endl;
}
};
| [
"[email protected]"
] | |
fde74e3207918764a2a0909b9ba4795b8c674cd9 | 3723a574da913bfcbbc77b347a4f02533bf7059a | /library/incl/gd.h/delegates/delegates.h | e9ff4792571d2ee5ff93aa5e2b6065ee2f805e91 | [
"MIT",
"Unlicense",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | Pietrodjaowjao/SwingCopter | 1c38eaa3ea78d74dd05a4c99da211e43e542b6b7 | 66ded079ab45e51b0b3fbe9c80a7da69c9877988 | refs/heads/master | 2023-06-19T11:39:50.755325 | 2021-07-19T17:57:14 | 2021-07-19T17:57:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,896 | h | #ifndef DELEGATES_H
#define DELEGATES_h
#include <gd.h>
namespace gd {
class GJGameLevel;
class NumberInputLayer;
class SetIDPopup;
class CCTextInputNode;
class GJDropDownLayer;
class SongInfoObject;
class GJSpecialColorSelect;
class HSVWidgetPopup;
class GJUserScore;
enum GJSongError {
kGJSongErrorUnknown_not_REd = 0,
// dunno, didnt bother to RE
};
class TextInputDelegate {
public:
virtual void textChanged(CCTextInputNode*) {}
virtual void textInputOpened(CCTextInputNode*) {}
virtual void textInputClosed(CCTextInputNode*) {}
virtual void textInputShouldOffset(CCTextInputNode*, float) {}
virtual void textInputReturn(CCTextInputNode*) {}
virtual bool allowTextInput(CCTextInputNode*) { return true; }
};
class GooglePlayDelegate {
virtual void googlePlaySignedIn(void);
};
class ColorSelectDelegate {
public:
virtual void colorSelectClosed(cocos2d::CCNode*);
};
class ColorSetupDelegate {
public:
virtual void colorSetupClosed(int);
};
class GJSpecialColorSelectDelegate {
public:
virtual void colorSelectClosed(GJSpecialColorSelect*, int);
};
class HSVWidgetPopupDelegate {
public:
virtual void hsvPopupClosed(HSVWidgetPopup *, cocos2d::ccHSVValue);
};
class GJRotationControlDelegate {
public:
virtual void angleChanged(float);
virtual void angleChangeBegin(void);
virtual void angleChangeEnded(void);
};
class GJScaleControlDelegate {
public:
virtual void scaleChanged(float);
virtual void scaleChangeBegin(void);
virtual void scaleChangeEnded(void);
};
class MusicDownloadDelegate {
public:
virtual void downloadSongFailed(int, GJSongError);
virtual void downloadSongFinished(SongInfoObject*);
virtual void loadSongInfoFailed(int, GJSongError);
virtual void loadSongInfoFinished(SongInfoObject*);
virtual void songStateChanged(void);
};
enum UpdateResponse {
kUpdateResponseUnknown,
kUpdateResponseUpToDate,
kUpdateResponseGameVerOutOfDate,
kUpdateResponseUpdateSuccess,
};
enum CommentError {
kCommentErrorUnknown_not_REd = 0x0,
};
enum LikeItemType {
kLikeItemTypeUnknown_not_REd = 0x0,
};
class LeaderboardManagerDelegate {
virtual void updateUserScoreFinished(void);
virtual void updateUserScoreFailed(void);
virtual void loadLeaderboardFinished(cocos2d::CCArray *,char const*);
virtual void loadLeaderboardFailed(char const*);
};
class UserInfoDelegate {
virtual void getUserInfoFailed(int);
virtual void getUserInfoFinished(GJUserScore *);
virtual void userInfoChanged(GJUserScore *);
};
class CommentUploadDelegate {
virtual void commentUploadFinished(int);
virtual void commentUploadFailed(int, CommentError);
virtual void commentDeleteFailed(int, int);
};
class LevelCommentDelegate {
virtual void loadCommentsFinished(cocos2d::CCArray *, const char*);
virtual void loadCommentsFailed(const char*);
virtual void updateUserScoreFinished(void);
virtual void setupPageInfo(std::string, const char*);
};
class LevelDownloadDelegate {
public:
virtual void levelDownloadFinished(GJGameLevel *);
virtual void levelDownloadFailed(int);
};
class LevelDeleteDelegate {
public:
virtual void levelDeleteFinished(int);
virtual void levelDeleteFailed(int);
};
class LevelUpdateDelegate {
public:
virtual void levelUpdateFinished(GJGameLevel*, UpdateResponse);
virtual void levelUpdateFailed(int);
};
class UploadActionDelegate {
public:
virtual void uploadActionFinished(int, int) {};
virtual void uploadActionFailed(int, int) {};
};
class UploadPopupDelegate {
public:
virtual void onClosePopup(void) {};
};
class LikeItemDelegate {
public:
virtual void likedItem(LikeItemType, int, bool);
};
class RateLevelDelegate {
public:
virtual void rateLevelClosed(void);
};
class NumberInputDelegate {
public:
virtual void numberInputClosed(NumberInputLayer*);
};
class SetIDPopupDelegate {
public:
virtual void setIDPopupClosed(SetIDPopup*, int);
};
class GJDropDownLayerDelegate {
public:
virtual void dropDownLayerWillClose(GJDropDownLayer*);
};
}
#endif
| [
"[email protected]"
] | |
6b7395480b2284861fff3ce05ab487996fa24175 | 44905ec0c2963e9daf2c6f054d1f43c33162e66a | /uasufesjfsd.cpp | 42416532198bf4f485150142f2e2b535484e23ce | [] | no_license | mdmumin/practic | a28824893c1277ccf3b076348f8a09faec353234 | 6cbef5c6b0e813e6a7b7a9c4986e0cf36783c500 | refs/heads/master | 2020-04-23T21:20:35.296482 | 2019-02-19T12:13:11 | 2019-02-19T12:13:11 | 171,467,606 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 187 | cpp | #include<iostream>
using namespace std;
class f1{
public:
f1()
{
cout<<"nafiz ";
}
~f1()
{
cout<<"mumin ";
}
};
int main()
{
f1 ob,ob1;
}
| [
"[email protected]"
] | |
7f2de65fc32f968482ce0be508de05ac02104426 | 0c0cb16aeb0f6ef54f620d7e317c87a7a5ae0fcc | /Algorithms/381_insert_delete_getrandom_o1_duplicates_allowed.cc | f31e038fe5b70c17637cd909ecfd09379ccea269 | [] | no_license | jeffreyfox/LeetCode | 5b18d95ffc5143933a306f902b7bcce57197e25c | e05ef7ab4345beecd5ea36a63340a3618311a743 | refs/heads/master | 2022-07-28T10:29:02.490115 | 2022-07-20T16:36:38 | 2022-07-20T16:36:38 | 29,803,806 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 4,063 | cc | /RandomizedCollection is a data structure that contains a collection of numbers, possibly duplicates (i.e., a multiset). It should support inserting and removing specific elements and also removing a random element.
Implement the RandomizedCollection class:
RandomizedCollection() Initializes the empty RandomizedCollection object.
bool insert(int val) Inserts an item val into the multiset, even if the item is already present. Returns true if the item is not present, false otherwise.
bool remove(int val) Removes an item val from the multiset if present. Returns true if the item is present, false otherwise. Note that if val has multiple occurrences in the multiset, we only remove one of them.
int getRandom() Returns a random element from the current multiset of elements. The probability of each element being returned is linearly related to the number of same values the multiset contains.
You must implement the functions of the class such that each function works on average O(1) time complexity.
Note: The test cases are generated such that getRandom will only be called if there is at least one item in the RandomizedCollection.
Example 1:
Input
["RandomizedCollection", "insert", "insert", "insert", "getRandom", "remove", "getRandom"]
[[], [1], [1], [2], [], [1], []]
Output
[null, true, false, true, 2, true, 1]
Explanation
RandomizedCollection randomizedCollection = new RandomizedCollection();
randomizedCollection.insert(1); // return true since the collection does not contain 1.
// Inserts 1 into the collection.
randomizedCollection.insert(1); // return false since the collection contains 1.
// Inserts another 1 into the collection. Collection now contains [1,1].
randomizedCollection.insert(2); // return true since the collection does not contain 2.
// Inserts 2 into the collection. Collection now contains [1,1,2].
randomizedCollection.getRandom(); // getRandom should:
// - return 1 with probability 2/3, or
// - return 2 with probability 1/3.
randomizedCollection.remove(1); // return true since the collection contains 1.
// Removes 1 from the collection. Collection now contains [1,2].
randomizedCollection.getRandom(); // getRandom should return 1 or 2, both equally likely.
Constraints:
-231 <= val <= 231 - 1
At most 2 * 105 calls in total will be made to insert, remove, and getRandom.
There will be at least one element in the data structure when getRandom is called.
*/
// Similar to LC380. Similar as above, but now uses a hash set to track the indices of duplicated entries.
class RandomizedCollection {
public:
RandomizedCollection() {
}
bool insert(int val) {
val2idx[val].insert(nums.size());
nums.push_back(val);
return val2idx[val].size() == 1;
}
bool remove(int val) {
auto iter = val2idx.find(val);
if (iter == val2idx.end() || iter->second.empty()) return false;
int remove_idx = *(iter->second.begin());
val2idx[val].erase(remove_idx);
// swap last element with the item to be removed
int last_element_idx = nums.size()-1;
if (last_element_idx != remove_idx) {
int last_element_val = nums[last_element_idx];
val2idx[last_element_val].erase(last_element_idx);
val2idx[last_element_val].insert(remove_idx);
nums[remove_idx] = last_element_val;
}
nums.pop_back();
return true;
}
int getRandom() {
return nums[rand() % nums.size()];
}
unordered_map<int, unordered_set<int>> val2idx;
vector<int> nums;
};
/**
* Your RandomizedCollection object will be instantiated and called as such:
* RandomizedCollection* obj = new RandomizedCollection();
* bool param_1 = obj->insert(val);
* bool param_2 = obj->remove(val);
* int param_3 = obj->getRandom();
*/
| [
"[email protected]"
] | |
3ba2aef13f7e8b8cbe558cc8aba9ba245aa3d6fb | 6ced41da926682548df646099662e79d7a6022c5 | /aws-cpp-sdk-timestream-query/include/aws/timestream-query/model/DescribeScheduledQueryResult.h | 7fa14e5855b513ca5d783cfff37619d8a6db781c | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | irods/aws-sdk-cpp | 139104843de529f615defa4f6b8e20bc95a6be05 | 2c7fb1a048c96713a28b730e1f48096bd231e932 | refs/heads/main | 2023-07-25T12:12:04.363757 | 2022-08-26T15:33:31 | 2022-08-26T15:33:31 | 141,315,346 | 0 | 1 | Apache-2.0 | 2022-08-26T17:45:09 | 2018-07-17T16:24:06 | C++ | UTF-8 | C++ | false | false | 1,835 | h | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/timestream-query/TimestreamQuery_EXPORTS.h>
#include <aws/timestream-query/model/ScheduledQueryDescription.h>
#include <utility>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Json
{
class JsonValue;
} // namespace Json
} // namespace Utils
namespace TimestreamQuery
{
namespace Model
{
class AWS_TIMESTREAMQUERY_API DescribeScheduledQueryResult
{
public:
DescribeScheduledQueryResult();
DescribeScheduledQueryResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
DescribeScheduledQueryResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
/**
* <p>The scheduled query.</p>
*/
inline const ScheduledQueryDescription& GetScheduledQuery() const{ return m_scheduledQuery; }
/**
* <p>The scheduled query.</p>
*/
inline void SetScheduledQuery(const ScheduledQueryDescription& value) { m_scheduledQuery = value; }
/**
* <p>The scheduled query.</p>
*/
inline void SetScheduledQuery(ScheduledQueryDescription&& value) { m_scheduledQuery = std::move(value); }
/**
* <p>The scheduled query.</p>
*/
inline DescribeScheduledQueryResult& WithScheduledQuery(const ScheduledQueryDescription& value) { SetScheduledQuery(value); return *this;}
/**
* <p>The scheduled query.</p>
*/
inline DescribeScheduledQueryResult& WithScheduledQuery(ScheduledQueryDescription&& value) { SetScheduledQuery(std::move(value)); return *this;}
private:
ScheduledQueryDescription m_scheduledQuery;
};
} // namespace Model
} // namespace TimestreamQuery
} // namespace Aws
| [
"[email protected]"
] | |
a51ddef01c0aba52278f2f234aad4ea53f248de3 | 430d21cb74f19ae53bdeef572784cd0057096573 | /particle/src/water/water.cpp | 8b4ec347a23096e8a0f907f8518ddb4da0e7aab5 | [] | no_license | olaven/exam-pg5500 | d1f73a39a387be406406fa41cf0f117530b5c348 | 4e8d109d180a0e94ba24bed20ff0234b19b48881 | refs/heads/master | 2020-09-25T20:20:58.680984 | 2019-12-18T15:31:11 | 2019-12-18T15:31:11 | 226,080,032 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,157 | cpp | #include "Particle.h"
int water_sensor_pin;
bool send_water_email;
String water_email = "[email protected]"; //NOTE: anonymous email made for exam purposes
int change_water_email(String _water_email)
{
water_email = _water_email;
return 0;
}
void setup_water_sensor(int _water_sensor_pin, bool _send_email)
{
pinMode(_water_sensor_pin, INPUT);
water_sensor_pin = _water_sensor_pin;
send_water_email = _send_email;
Particle.variable("water_email", water_email);
Particle.function("change_water_email", change_water_email);
}
bool is_detecting_water()
{
const int water_value = analogRead(water_sensor_pin);
return water_value > 1000;
}
void check_water_sensor()
{
if (send_water_email && is_detecting_water())
{
static int last_water_event_publish = -1;
if (last_water_event_publish == -1 || ((millis() - last_water_event_publish) > 900000)) //i.e. do not sent more than once/15 min
{
Particle.publish("water_event", String::format("{ \"email\": \"%s\" }", water_email.c_str()), PRIVATE);
last_water_event_publish = millis();
}
}
}
| [
"[email protected]"
] | |
c925a3a2957cb61bb9c9870351c59e3c9bcb213d | c6f4505920e0ef7a4c6b9fff5fed4c9ce24d97af | /AdapterMode/Banner.h | 88050baefb853e4d1a9fccb0a136d57fc5885535 | [] | no_license | luzh0422/DesignPatterns | 43f47e85fbc6a73d24435e2117ea726a17d7cf55 | ca59713c9fa59115742da63ef0afbea1e7c6a8b2 | refs/heads/master | 2021-06-07T02:27:40.188342 | 2020-05-06T14:37:25 | 2020-05-06T14:37:25 | 153,556,496 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 324 | h | //
// Created by Luzh on 2018/10/22.
//
#ifndef ADAPTERMODE_BANNER_H
#define ADAPTERMODE_BANNER_H
#include <string>
class Banner {
public:
Banner(std::string pString) : mString(pString) {}
void printWithPattern();
void printWithAsterisk();
private:
std::string mString;
};
#endif //ADAPTERMODE_BANNER_H
| [
"[email protected]"
] | |
bb2e3dea34216a3cff47f6eaa5b6b61b1dd8549d | 82555ed986f85b47cbb189d5a15b059ba8592946 | /include/pbtrf.h | 4b1992f9b208d0adf91518a32f3a80d20b689206 | [
"BSD-3-Clause-Open-MPI",
"BSD-3-Clause"
] | permissive | langou/latl | 5596e7298f5263a64d545267351b82b01a14f096 | df838fb44a1ef5c77b57bf60bd46eaeff8db3492 | refs/heads/master | 2020-03-26T20:12:08.408112 | 2015-05-04T19:51:04 | 2015-05-04T19:51:04 | 10,975,131 | 6 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 20,513 | h | //
// pbtrf.h
// Linear Algebra Template Library
//
// Created by Stephanie Patterson on 7/20/12.
// Copyright (c) 2012 University of Colorado Denver. All rights reserved.
//
#ifndef _pbtrf_h
#define _pbtrf_h
/// @file pbtrf.h Computes the Cholesky factorization of a symmetric positive definite band matrix A.
#include "gemm.h"
#include "herk.h"
#include "potrf.h"
#include "syrk.h"
#include "trsm.h"
#include "scal.h"
#include "syr.h"
#include "her.h"
#include "lacgv.h"
#include "latl.h"
namespace LATL
{
/// @brief Computes the Cholesky factorization of a real symmetric positive definite band matrix A.
///
/// The factorization has the form
///
/// A = U' * U if uplo = 'U'
/// A = L * L' if uplo = 'L'
///
/// where U is upper triangular, U' is the transpose of U, and L is lower triangular.
/// @return 0 if success
/// @return -i if the ith argument is invalid.
/// @return i+1 if the leading minor of order i is not positive definite.
/// @tparam real_t Floating point type.
/// @param uplo Indicates whether the symmetric matrix A is stored as upper triangular or lower triangular. The other triangular part of A is not referenced.
/// @param n Order of the matrix A. n >= 0
/// @param kd The number of super-diagonals of the matrix A if uplo = 'U' or the number of sub-diagonals if uplo = 'L'. kd >= 0
/// @param AB Real array size ldAB-by-n. On entry, the upper or lower triangle of the symmetric band matrix A, stored in the first kd+1 rows of the array. On exit, the triangular factor U or L from the Cholesky factorization A = U' * U or A = L * L' of the band matrix A in the same storage format as A.
/// @param ldAB Column length of the array AB. ldAB >= kd+1;
/// @ingroup COMP
template< typename real_t>
int_t PBTRF(const char uplo, const int_t n, const int_t kd, real_t * const AB, const int_t ldAB)
{
if (uplo != 'U' && uplo != 'L' && uplo != 'u' && uplo != 'l')
return -1;
if ( n < 0)
return -2;
if (kd < 0 )
return -3;
if (ldAB < kd+1)
return -5;
if ( n == 0)
return 0;
const real_t one(1.0);
const real_t zero(0.0);
int_t kn, kld = ldAB-1;
real_t ajj;
real_t * ABj = AB;
real_t * ABjp1 = AB+ldAB;
if (uplo == 'U' || uplo == 'u')
{
for (int_t j = 0; j < n; ++j)
{
ajj = ABj[kd];
if (ajj <= zero || std::isnan(ajj))
return j+1;
ABj[kd] = ajj = sqrt(ajj);
kn = std::min(kd, n-j-1);
if (kn > 0)
{
LATL::SCAL(kn, one/ajj, ABjp1+kd-1, kld);
LATL::SYR('U', kn, -one, ABjp1+kd-1, kld, ABjp1+kd, kld);
}
ABj += ldAB;
ABjp1 += ldAB;
}
}
else
{
for (int_t j = 0; j < n; ++j)
{
ajj = ABj[0];
if (ajj <= 0 || std::isnan(ajj))
return j+1;
ABj[0] = ajj = sqrt(ajj);
kn = std::min(kd, n-j-1);
if (kn > 0)
{
LATL::SCAL(kn, one/ajj, ABj+1, 1);
LATL::SYR('L', kn, -one, ABj+1, 1, ABjp1, kld);
}
ABj += ldAB;
ABjp1 += ldAB;
}
}
return 0;
}
/// @brief Computes the Cholesky factorization of a complex Hermitian positive definite band matrix A.
///
/// The factorization has the form
///
/// A = U^H * U if uplo = 'U'
/// A = L * L^H if uplo = 'L'
///
/// where U is upper triangular and U^H is the conjugate transpose of U, and L is lower triangular.
/// @return 0 if success
/// @return -i if the ith argument is invalid.
/// @return i+1 if the leading minor of order i is not positive definite.
/// @tparam real_t Floating point type.
/// @param uplo Indicates whether the Hermitian matrix A is stored as upper triangular or lower triangular. The other triangular part of A is not referenced.
/// @param n Order of the matrix A. n >= 0
/// @param kd The number of super-diagonals of the matrix A if uplo = 'U' or the number of sub-diagonals if uplo = 'L'. kd >= 0
/// @param AB Complex array size ldAB-by-n. On entry, the upper or lower triangle of the Hermitian band matrix A, stored in the first kd+1 rows of the array. On exit, the triangular factor U or L from the Cholesky factorization A = U^H * U or A = L * L^H of the band matrix A in the same storage format as A.
/// @param ldAB Column length of the array AB. ldAB >= kd+1;
/// @ingroup COMP
template< typename real_t>
int_t PBTRF(const char uplo, const int_t n, const int_t kd, complex<real_t> * const AB, const int_t ldAB)
{
if (uplo != 'U' && uplo != 'L' && uplo != 'u' && uplo != 'l')
return -1;
if ( n < 0)
return -2;
if (kd < 0 )
return -3;
if (ldAB < kd+1)
return -5;
if ( n == 0)
return 0;
const real_t one(1.0);
const real_t zero(0.0);
int_t kn, kld = ldAB-1;
real_t ajj;
complex<real_t> * ABj = AB;
complex<real_t> * ABjp1 = AB+ldAB;
if (uplo == 'U' || uplo == 'u')
{
for (int_t j = 0; j < n; ++j)
{
ajj = real(ABj[kd]);
if (ajj <= zero || std::isnan(ajj))
{
ABj[kd] = ajj;
return j+1;
}
ABj[kd] = ajj = sqrt(ajj);
kn = std::min(kd, n-j-1);
if (kn > 0)
{
LATL::SCAL(kn, one/ajj, ABjp1+kd-1, kld);
LATL::LACGV(kn, ABjp1+kd-1, kld);
LATL::HER('U', kn, -one, ABjp1+kd-1, kld, ABjp1+kd, kld);
LATL::LACGV(kn, ABjp1+kd, kld);
}
ABj += ldAB;
ABjp1 += ldAB;
}
}
else
{
for (int_t j = 0; j < n; ++j)
{
ajj = real(ABj[0]);
if (ajj <= 0 || std::isnan(ajj))
{
ABj[0] = ajj;
return j+1;
}
ABj[0] = ajj = sqrt(ajj);
kn = std::min(kd, n-j-1);
if (kn > 0)
{
LATL::SCAL(kn, one/ajj, ABj+1, 1);
LATL::HER('L', kn, -one, ABj+1, 1, ABjp1, kld);
}
ABj += ldAB;
ABjp1 += ldAB;
}
}
return 0;
}
/// @brief Computes the Cholesky factorization of a real symmetric positive definite band matrix A.
///
/// The factorization has the form
///
/// A = U' * U if uplo = 'U'
/// A = L * L' if uplo = 'L'
///
/// where U is upper triangular, U' is the transpose of U, and L is lower triangular.
/// @return 0 if success
/// @return -i if the ith argument is invalid.
/// @return i+1 if the leading minor of order i is not positive definite.
/// @tparam real_t Floating point type.
/// @param uplo Indicates whether the symmetric matrix A is stored as upper triangular or lower triangular. The other triangular part of A is not referenced.
/// @param n Order of the matrix A. n >= 0
/// @param kd The number of super-diagonals of the matrix A if uplo = 'U' or the number of sub-diagonals if uplo = 'L'. kd >= 0
/// @param AB Real array size ldAB-by-n. On entry, the upper or lower triangle of the symmetric band matrix A, stored in the first kd+1 rows of the array. On exit, the triangular factor U or L from the Cholesky factorization A = U' * U or A = L * L' of the band matrix A in the same storage format as A.
/// @param ldAB Column length of the array AB. ldAB >= kd+1;
/// @param nb Block size.
/// @ingroup COMP
template< typename real_t>
int_t PBTRF(const char uplo, const int_t n, const int_t kd, real_t * const AB, const int_t ldAB, const int_t nb)
{
if (uplo != 'U' && uplo != 'L' && uplo != 'u' && uplo != 'l')
return -1;
if ( n < 0)
return -2;
if (kd < 0 )
return -3;
if (ldAB < kd+1)
return -5;
if (n == 0)
return 0;
if (nb <= 1 || nb > kd)
return LATL::PBTRF(uplo, n, kd, AB, ldAB);
else
{
const real_t one(1.0);
const real_t zero(0.0);
const int_t ldWork = nb+1;
real_t * const Work = new real_t[ldWork*nb];
real_t * Worktemp = Work, *ABi = AB;
int_t i2, i3, ib, info = 0, kld = ldAB-1;
if (uplo == 'U' || uplo == 'u')
{
for (int_t j = 0; j < nb; ++j)
{
for (int_t i = 0; i < j; ++i)
{
Worktemp[i] = zero;
}
Worktemp += ldWork;
}
for (int_t i = 0; i < n; i += nb)
{
ib = std::min(nb, n-i);
info = LATL::POTRF(uplo, ib, ABi+kd, kld);
if (info != 0)
{
return info+i;
}
if ((i+ib) < n)
{
i2 = std::min(kd-ib, n-i-ib);
i3 = std::min(ib, n-i-kd);
if (i2 > 0)
{
LATL::TRSM('L', 'U', 'T', 'N', ib, i2, one, ABi+kd, kld, ABi+ldAB*ib+kd-ib, kld);
LATL::SYRK('U', 'T', i2, ib, -one, ABi+ldAB*ib+kd-ib, kld, one, ABi+ldAB*ib+kd, kld);
}
if (i3 > 0)
{
Worktemp = Work;
real_t * ABitemp;
for (int_t jj = 0; jj < i3; ++jj)
{
ABitemp = ABi+ldAB*(jj+kd);
for (int_t ii = jj; ii < ib; ++ii)
{
Worktemp[ii] = ABitemp[ii-jj];
}
Worktemp += ldWork;
}
LATL::TRSM('L', 'U', 'T', 'N', ib, i3, one, ABi+kd, kld, Work, ldWork);
if (i2 > 0)
LATL::GEMM('T', 'N', i2, i3, ib, -one, ABi+ldAB*ib+kd-ib, kld, Work, ldWork, one, ABi+ldAB*kd+ib, kld);
LATL::SYRK('U', 'T', i3, ib, -one, Work, ldWork, one, ABi+ldAB*kd+kd, kld);
Worktemp = Work;
for (int_t jj = 0; jj < i3; ++jj)
{
ABitemp = ABi+ldAB*(jj+kd);
for (int_t ii = jj; ii < ib; ++ii)
{
ABitemp[ii-jj] = Worktemp[ii];
}
Worktemp += ldWork;
}
}
}
ABi += ldAB*nb;
}
}
else //if lower
{
for (int_t j = 0; j < nb; ++j)
{
for (int_t i = j+1; i < nb; ++i)
{
Worktemp[i] = zero;
}
Worktemp += ldWork;
}
for (int_t i = 0; i < n; i += nb)
{
ib = std::min(nb, n-i);
info = LATL::POTRF(uplo, ib, ABi, kld);
if (info != 0)
{
return info+i;
}
if (i+ib < n)
{
i2 = std::min(kd-ib, n-i-ib);
i3 = std::min(ib, n-i-kd);
if (i2 > 0)
{
LATL::TRSM('R', 'L', 'T', 'N', i2, ib, one, ABi, kld, ABi+ib, kld);
LATL::SYRK('L', 'N', i2, ib, -one, ABi+ib, kld, one, ABi+ldAB*ib, kld);
}
if (i3 > 0)
{
Worktemp = Work;
real_t * ABitemp;
for (int_t jj = 0; jj < ib; ++jj)
{
ABitemp = ABi+ldAB*jj;
for (int_t ii = 0; ii <= std::min(jj, i3-1); ++ii)
{
Worktemp[ii] = ABitemp[kd-jj+ii];
}
Worktemp += ldWork;
}
LATL::TRSM('R', 'L', 'T', 'N', i3, ib, one, ABi, kld, Work, ldWork);
if (i2 > 0)
{
LATL::GEMM('N', 'T', i3, i2, ib, -one, Work, ldWork, ABi+ib, kld, one, ABi+ldAB*ib+kd-ib, kld);
}
LATL::SYRK('L', 'N', i3, ib, -one, Work, ldWork, one, ABi+ldAB*kd, kld);
Worktemp = Work;
for (int_t jj = 0; jj < ib; ++jj)
{
ABitemp = ABi+ldAB*jj;
for (int_t ii = 0; ii <= std::min(jj, i3-1); ++ii)
{
ABitemp[kd-jj+ii] = Worktemp[ii];
}
Worktemp += ldWork;
}
}
}
ABi += ldAB*nb;
}
}
delete [] Work;
}
}
/// @brief Computes the Cholesky factorization of a complex Hermitian positive definite band matrix A.
///
/// The factorization has the form
///
/// A = U' * U if uplo = 'U'
/// A = L * L' if uplo = 'L'
///
/// where U is upper triangular, U' is the transpose of U, and L is lower triangular.
/// @return 0 if success
/// @return -i if the ith argument is invalid.
/// @return i+1 if the leading minor of order i is not positive definite.
/// @tparam real_t Floating point type.
/// @param uplo Indicates whether the matrix A is stored as upper triangular or lower triangular. The other triangular part of A is not referenced.
/// @param n Order of the matrix A. n >= 0
/// @param kd The number of super-diagonals of the matrix A if uplo = 'U' or the number of sub-diagonals if uplo = 'L'. kd >= 0
/// @param AB Complex array size ldAB-by-n. On entry, the upper or lower triangle of the band matrix A, stored in the first kd+1 rows of the array. On exit, the triangular factor U or L from the Cholesky factorization A = U' * U or A = L * L' of the band matrix A in the same storage format as A.
/// @param ldAB Column length of the array AB. ldAB >= kd+1;
/// @param nb Block size.
/// @ingroup COMP
template< typename real_t>
int_t PBTRF(const char uplo, const int_t n, const int_t kd, complex<real_t> * const AB, const int_t ldAB, const int_t nb)
{
if (uplo != 'U' && uplo != 'L' && uplo != 'u' && uplo != 'l')
return -1;
if ( n < 0 )
return -2;
if (kd < 0 )
return -3;
if (ldAB < kd+1)
return -5;
if (n == 0)
return 0;
if (nb <= 1 || nb > kd)
return LATL::PBTRF(uplo, n, kd, AB, ldAB);
else
{
const real_t one(1.0);
const real_t zero(0.0);
const complex<real_t> onec(1.0);
const int_t ldWork = nb+1;
complex<real_t> * const Work = new complex<real_t>[ldWork*nb];
complex<real_t> * Worktemp = Work, *ABi = AB;
int_t i2, i3, ib, info = 0, kld = ldAB-1;
if (uplo == 'U' || uplo == 'u')
{
for (int_t j = 0; j < nb; ++j)
{
for (int_t i = 0; i < j; ++i)
{
Worktemp[i] = zero;
}
Worktemp += ldWork;
}
for (int_t i = 0; i < n; i += nb)
{
ib = std::min(nb, n-i);
info = LATL::POTRF(uplo, ib, ABi+kd, kld);
if (info != 0)
{
return info+i;
}
if (i+ib < n)
{
i2 = std::min(kd-ib, n-i-ib);
i3 = std::min(ib, n-i-kd);
if (i2 > 0)
{
LATL::TRSM('L', 'U', 'C', 'N', ib, i2, onec, ABi+kd, kld, ABi+ldAB*ib+kd-ib, kld);
LATL::HERK('U', 'C', i2, ib, -one, ABi+ldAB*ib+kd-ib, kld, one, ABi+ldAB*ib+kd, kld);
}
if (i3 > 0)
{
Worktemp = Work;
complex<real_t> * ABitemp;
for (int_t jj = 0; jj < i3; ++jj)
{
ABitemp = ABi+ldAB*(jj+kd);
for (int_t ii = jj; ii < ib; ++ii)
{
Worktemp[ii] = ABitemp[ii-jj];
}
Worktemp += ldWork;
}
LATL::TRSM('L', 'U', 'C', 'N', ib, i3, onec, ABi+kd, kld, Work, ldWork);
if (i2 > 0)
LATL::GEMM('C', 'N', i2, i3, ib, -onec, ABi+ldAB*ib+kd-ib, kld, Work, ldWork, onec, ABi+ldAB*kd+ib, kld);
LATL::HERK('U', 'C', i3, ib, -one, Work, ldWork, one, ABi+ldAB*kd+kd, kld);
Worktemp = Work;
for (int_t jj = 0; jj < i3; ++jj)
{
ABitemp = ABi+ldAB*(jj+kd);
for (int_t ii = jj; ii < ib; ++ii)
{
ABitemp[ii-jj] = Worktemp[ii];
}
Worktemp += ldWork;
}
}
}
ABi += ldAB*nb;
}
}
else
{
for (int_t j = 0; j < nb; ++j)
{
for (int_t i = j+1; i < nb; ++i)
{
Worktemp[i] = zero;
}
Worktemp += ldWork;
}
for (int_t i = 0; i < n; i += nb)
{
ib = std::min(nb, n-i);
info = LATL::POTRF(uplo, ib, ABi, kld);
if (info != 0)
{
return info+i;
}
if (i+ib < n)
{
i2 = std::min(kd-ib, n-i-ib);
i3 = std::min(ib, n-i-kd);
if (i2 > 0)
{
LATL::TRSM('R', 'L', 'C', 'N', i2, ib, onec, ABi, kld, ABi+ib, kld);
LATL::HERK('L', 'N', i2, ib, -one, ABi+ib, kld, one, ABi+ldAB*ib, kld);
}
if (i3 > 0)
{
Worktemp = Work;
complex<real_t> * ABitemp;
for (int_t jj = 0; jj < ib; ++jj)
{
ABitemp = ABi+ldAB*jj;
for (int_t ii = 0; ii <= std::min(jj, i3-1); ++ii)
{
Worktemp[ii] = ABitemp[kd-jj+ii];
}
Worktemp += ldWork;
}
LATL::TRSM('R', 'L', 'C', 'N', i3, ib, onec, ABi, kld, Work, ldWork);
if (i2 > 0)
{
LATL::GEMM('N', 'C', i3, i2, ib, -onec, Work, ldWork, ABi+ib, kld, onec, ABi+ldAB*ib+kd-ib, kld);
}
LATL::HERK('L', 'N', i3, ib, -one, Work, ldWork, one, ABi+ldAB*kd, kld);
Worktemp = Work;
for (int_t jj = 0; jj < ib; ++jj)
{
ABitemp = ABi+ldAB*jj;
for (int_t ii = 0; ii <= std::min(jj, i3-1); ++ii)
{
ABitemp[kd-jj+ii] = Worktemp[ii];
}
Worktemp += ldWork;
}
}
}
ABi += ldAB*nb;
}
}
delete [] Work;
}
}
}
#endif
| [
"[email protected]"
] | |
a92ef4a026eda0ec3564db35f500c997943dfc80 | 88eb6798d23b52ab13539ac4f31a735ea2d3cf0b | /lib/timer/timer.cpp | 8b3bdd8f1253a4126b02dda14693166d014af59e | [] | no_license | confrodog/Anti-Intruder-Detection | 4f28e43d95b956eb9b22c1489d866e26819ec525 | 9f8edc419105c167bf0941b99de55593a6024e2d | refs/heads/master | 2020-05-07T15:28:17.639499 | 2019-04-16T15:51:05 | 2019-04-16T15:51:05 | 180,637,536 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 594 | cpp |
#include "timer.h"
void initTimer1(){
// set timer to CTC mode
TCCR1A &= ~(1 << WGM10);
TCCR1A &= ~(1 << WGM11);
TCCR1B |= (1 << WGM12);
TCCR1B &= ~(1 << WGM13);
//sets prescaler to 64
TCCR1B |= (1 << CS11) | (1<<CS10);
//for millisecond timer
OCR1A = 250;
}
void delayMs(unsigned int delay){
unsigned int delayCnt = 0;
TIFR1 |= (1 << OCF1A);
TCNT1 = 0;
// counts 1us up until the inputted delay
while(delayCnt < delay){
if(TIFR1 & (1 << OCF1A)){
delayCnt++;
TIFR1 |= (1 << OCF1A);
}
}
} | [
"[email protected]"
] | |
ab3727bca0c13968c3012271a100b39b0b93d7d8 | 5a552d420ce16f986769dc36777e24e794438e58 | /rootscripts/k2pi.cpp | e6c40df86ca8b7bac05696c53f30a9385ba4ef5c | [] | no_license | francisnewson/hnuprocess | 1379ff7f6bd1db0c17ebeb898b16977b43cc37e4 | 6139a1d7d2c6e2dd975eaf7e33f39525b888a4f6 | refs/heads/master | 2020-04-01T19:34:10.863826 | 2016-09-27T19:36:38 | 2016-09-27T19:36:38 | 30,983,514 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,934 | cpp | #include "TMath.h"
#include <cmath>
#include "TFile.h"
#include "TTree.h"
#include "TCut.h"
#include "TH1F.h"
#include "TSystem.h"
#include <iostream>
void k2pi()
{
gSystem->AddLinkedLibs( "-L /afs/cern.ch/user/f/fnewson/"
"work/hnu/gopher/code/process/build03/k2pi"
" -lk2pivar");
double mpi = 0.139570;
double m2pi = std::pow( mpi, 2 );
TFile * tfile = new TFile( "output/k2pi_neutral_vertex_k2pi_tree.root");
TTree * k2pi = static_cast<TTree*>( tfile->Get("k2pi") );
TFile tfout( "output/k2pi_plots_sep.root", "RECREATE");
std::cerr << "Missing mass ... " << std::endl;
k2pi->Draw("data.p4pip.M2()>>hm2miss(1000, -0.3, 0.2)");
TH1F * hm2miss = static_cast<TH1F*>( gDirectory->Get("hm2miss") );
hm2miss->Write();
std::cerr << "Neutral vertex ... " << std::endl;
k2pi->Draw("data.neutral_vertex.Z()-mc.vertex.Z()>>hdz_neutral(1000, -1000, 1000 )");
TH1F * hdz_neutral = static_cast<TH1F*>( gDirectory->Get("hdz_neutral") );
hdz_neutral->Write();
std::cerr << "Neutral vertex (cut) ... " << std::endl;
TCut low_mass = "data.p4pip.M2() > 0.019479785 - 0.002";
TCut high_mass = "data.p4pip.M2() > 0.019479785 + 0.002";
k2pi->Draw("data.neutral_vertex.Z()-mc.vertex.Z()>>hdz_neutral_cut(1000, -1000, 1000 )",
low_mass && high_mass);
TH1F * hdz_neutral_cut = static_cast<TH1F*>( gDirectory->Get("hdz_neutral_cut") );
hdz_neutral_cut->Write();
std::cerr << "neutral vertex (2d) ... " << std::endl;
k2pi->Draw("data.neutral_vertex.Z()-mc.vertex.Z():mc.vertex.Z()>>hdzvsz_neutral(100, -5000, 10000, 100, -1000, 1000 )");
TH1F * hdzvsz_neutral = static_cast<TH1F*>( gDirectory->Get("hdzvsz_neutral") );
hdzvsz_neutral->Write();
std::cerr << "neutral vertex (E1) ... " << std::endl;
k2pi->Draw("data.neutral_vertex.Z()-mc.vertex.Z():mc.p4g1.E()>>hdzvsE1_neutral(100, 0, 100, 100, -1000, 1000 )");
TH1F * hdzvsE1_neutral = static_cast<TH1F*>( gDirectory->Get("hdzvsE1_neutral") );
hdzvsE1_neutral->Write();
std::cerr << "neutral vertex (E2) ... " << std::endl;
k2pi->Draw("data.neutral_vertex.Z()-mc.vertex.Z():mc.p4g2.E()>>hdzvsE2_neutral(100, 0, 100, 100, -1000, 1000 )");
TH1F * hdzvsE2_neutral = static_cast<TH1F*>( gDirectory->Get("hdzvsE2_neutral") );
hdzvsE2_neutral->Write();
std::cerr << "neutral vertex (C1) ... " << std::endl;
k2pi->Draw("data.neutral_vertex.Z()-mc.vertex.Z():data.E1>>hdzvsC1_neutral(100, 0, 100, 100, -1000, 1000 )");
TH1F * hdzvsC1_neutral = static_cast<TH1F*>( gDirectory->Get("hdzvsC1_neutral") );
hdzvsC1_neutral->Write();
std::cerr << "neutral vertex (c2) ... " << std::endl;
k2pi->Draw("data.neutral_vertex.Z()-mc.vertex.Z():data.E2>>hdzvsC2_neutral(100, 0, 100, 100, -1000, 1000 )");
TH1F * hdzvsC2_neutral = static_cast<TH1F*>( gDirectory->Get("hdzvsC2_neutral") );
hdzvsC2_neutral->Write();
std::cerr << "cluster 1 ... " << std::endl;
k2pi->Draw("data.E1 - mc.p4g1.E()>>hdE1( 1000, -50, 50)");
TH1F * hdE1 = static_cast<TH1F*>( gDirectory->Get("hdE1") );
hdE1->Write();
std::cerr << "cluster 2 ... " << std::endl;
k2pi->Draw("data.E2 - mc.p4g2.E()>>hdE2( 1000, -50, 50)");
TH1F * hdE2 = static_cast<TH1F*>( gDirectory->Get("hdE2") );
hdE2->Write();
std::cerr << "Cluster 1 and neutral dz... " << std::endl;
k2pi->Draw("data.E1 - mc.p4g1.E():data.neutral_vertex.Z()-mc.vertex.Z()"
">>hdE1vsdz( 100, -1000, 1000, 100, -50, 50)");
TH1F * hdE1vsdz = static_cast<TH1F*>( gDirectory->Get("hdE1vsdz") );
hdE1vsdz->Write();
std::cerr << "Cluster 2 and neutral dz... " << std::endl;
k2pi->Draw("data.E2 - mc.p4g2.E():data.neutral_vertex.Z()-mc.vertex.Z()"
">>hdE2vsdz( 100, -1000, 1000, 100, -50, 50)");
TH1F * hdE2vsdz = static_cast<TH1F*>( gDirectory->Get("hdE2vsdz") );
hdE2vsdz->Write();
std::cerr << "Charged vertex ... " << std::endl;
k2pi->Draw("data.charged_vertex.Z()-mc.vertex.Z()>>hdz_charged(1000, -1000, 1000 )");
TH1F * hdz_charged = static_cast<TH1F*>( gDirectory->Get("hdz_charged") );
hdz_charged->Write();
std::cerr << "Transverse momentum ... " << std::endl;
k2pi->Draw("data.dch_pt>>hdch_pt(1000, -0.1, 0.9 )");
TH1F * hdch_pt = static_cast<TH1F*>( gDirectory->Get("hdch_pt") );
hdch_pt->Write();
std::cerr << "Transverse momentum squared... " << std::endl;
k2pi->Draw("data.dch_pt*data.dch_pt>>hdch_pt2(1000, -0.1, 0.9 )");
TH1F * hdch_pt2 = static_cast<TH1F*>( gDirectory->Get("hdch_pt2") );
hdch_pt2->Write();
std::cerr << "Vertex and low energy clusters ... " << std::endl;
k2pi->Draw("data.neutral_vertex.Z()-mc.vertex.Z()>>hdz_dEcut( 100, -1000, 1000 )",
"( data.E1 + data.E2 - mc.p4g1.E() - mc.p4g2.E() ) <0" );
TH1F * hdz_dEcut = static_cast<TH1F*>( gDirectory->Get("hdz_dEcut") );
hdz_dEcut->Write();
}
| [
"[email protected]"
] | |
755d7fd50fcb2e185b90f90b59b0161325599a2d | 50f7c8bd719e5e6eea2cebe86a941d0ce6eef8f5 | /merge two sorted array wuthout extra space.cpp | b3f14ddb318a4285a7847e2f661cff6b1c3b4db8 | [] | no_license | harshfulzele987/DSA | e3cc8b622ba0b685dde617f55ed8e76bc9d79394 | 7001b5be3f12db1f6a793770c7d570238e5d30a2 | refs/heads/main | 2023-05-01T14:28:59.525177 | 2021-05-25T19:11:35 | 2021-05-25T19:11:35 | 318,527,967 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 693 | cpp | #include<bits/stdc++.h>
using namespace std;
int main() {
//code
int t;cin>>t;
while(t--){
int x,y;
cin>>x>>y;
int arr1[x];
int arr2[y];
for(int i=0; i<x; i++){
cin>>arr1[i];
}
for(int i=0; i<y; i++){
cin>>arr2[i];
}
int i=x-1;
int j=0;
for(;i>=0 && j<y; i--,j++){
if(arr1[i]>=arr2[j]){
swap(arr1[i],arr2[j]);
}
else{
break;
}
}
sort(arr1,arr1+x);
sort(arr2,arr2+y);
for(int i=0; i<x; i++){
cout<<arr1[i]<<" ";
}
for(int i=0; i<y; i++){
cout<<arr2[i]<<" ";
}
cout<<"\n";
}
return 0;
}
| [
"[email protected]"
] | |
e1346f55ce35342980fc2559109a65aa609f98b9 | c1e208cd1ddc960094c615844d8f11826e6daac9 | /examples/chip-tool/commands/clusters/Commands.h | 233cdf7db7d0965e99fe43da2c0c80f102f8d8dc | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | INNOTECH2020/connectedhomeip | 7e77552fed6fa6d44cc377be280052e03d31070b | 239153cf2a6bd13216002abd3bdcbb1f08dfed97 | refs/heads/master | 2023-03-16T09:41:50.476530 | 2021-03-08T17:40:03 | 2021-03-08T17:40:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 302,629 | h | /*
*
* Copyright (c) 2021 Project CHIP 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.
*/
// THIS FILE IS GENERATED BY ZAP
#pragma once
#include <cstdint>
#include "ModelCommand.h"
#include "gen/CHIPClientCallbacks.h"
#include <controller/CHIPClusters.h>
#include <lib/core/CHIPSafeCasts.h>
#include <lib/support/Span.h>
static void OnDefaultSuccessResponse(void * context)
{
ChipLogProgress(chipTool, "Default Success Response");
ModelCommand * command = reinterpret_cast<ModelCommand *>(context);
command->SetCommandExitStatus(true);
}
static void OnDefaultFailureResponse(void * context, uint8_t status)
{
ChipLogProgress(chipTool, "Default Failure Response: 0x%02x", status);
ModelCommand * command = reinterpret_cast<ModelCommand *>(context);
command->SetCommandExitStatus(false);
}
typedef void (*UnsupportedAttributeCallback)(void * context);
static void OnUnsupportedAttributeResponse(void * context)
{
ChipLogError(chipTool, "Unsupported attribute Response. This should never happen !");
}
static void OnBooleanAttributeResponse(void * context, bool value)
{
ChipLogProgress(chipTool, "Boolean attribute Response: %d", value);
ModelCommand * command = reinterpret_cast<ModelCommand *>(context);
command->SetCommandExitStatus(true);
}
static void OnInt8uAttributeResponse(void * context, uint8_t value)
{
ChipLogProgress(chipTool, "Int8u attribute Response: %" PRIu8, value);
ModelCommand * command = reinterpret_cast<ModelCommand *>(context);
command->SetCommandExitStatus(true);
}
static void OnInt16uAttributeResponse(void * context, uint16_t value)
{
ChipLogProgress(chipTool, "Int16u attribute Response: %" PRIu16, value);
ModelCommand * command = reinterpret_cast<ModelCommand *>(context);
command->SetCommandExitStatus(true);
}
static void OnInt16sAttributeResponse(void * context, int16_t value)
{
ChipLogProgress(chipTool, "Int16s attribute Response: %" PRId16, value);
ModelCommand * command = reinterpret_cast<ModelCommand *>(context);
command->SetCommandExitStatus(true);
}
static void OnInt64uAttributeResponse(void * context, uint64_t value)
{
ChipLogProgress(chipTool, "Int64u attribute Response: %" PRIu64, value);
ModelCommand * command = reinterpret_cast<ModelCommand *>(context);
command->SetCommandExitStatus(true);
}
static void OnContentLaunchClusterLaunchContentResponse(void * context, uint8_t contentLaunchStatus)
{
ChipLogProgress(chipTool, "ContentLaunchClusterLaunchContentResponse");
ModelCommand * command = reinterpret_cast<ModelCommand *>(context);
command->SetCommandExitStatus(true);
}
static void OnContentLaunchClusterLaunchURLResponse(void * context, uint8_t contentLaunchStatus)
{
ChipLogProgress(chipTool, "ContentLaunchClusterLaunchURLResponse");
ModelCommand * command = reinterpret_cast<ModelCommand *>(context);
command->SetCommandExitStatus(true);
}
static void OnDoorLockClusterClearAllPinsResponse(void * context)
{
ChipLogProgress(chipTool, "DoorLockClusterClearAllPinsResponse");
ModelCommand * command = reinterpret_cast<ModelCommand *>(context);
command->SetCommandExitStatus(true);
}
static void OnDoorLockClusterClearAllRfidsResponse(void * context)
{
ChipLogProgress(chipTool, "DoorLockClusterClearAllRfidsResponse");
ModelCommand * command = reinterpret_cast<ModelCommand *>(context);
command->SetCommandExitStatus(true);
}
static void OnDoorLockClusterClearHolidayScheduleResponse(void * context)
{
ChipLogProgress(chipTool, "DoorLockClusterClearHolidayScheduleResponse");
ModelCommand * command = reinterpret_cast<ModelCommand *>(context);
command->SetCommandExitStatus(true);
}
static void OnDoorLockClusterClearPinResponse(void * context)
{
ChipLogProgress(chipTool, "DoorLockClusterClearPinResponse");
ModelCommand * command = reinterpret_cast<ModelCommand *>(context);
command->SetCommandExitStatus(true);
}
static void OnDoorLockClusterClearRfidResponse(void * context)
{
ChipLogProgress(chipTool, "DoorLockClusterClearRfidResponse");
ModelCommand * command = reinterpret_cast<ModelCommand *>(context);
command->SetCommandExitStatus(true);
}
static void OnDoorLockClusterClearWeekdayScheduleResponse(void * context)
{
ChipLogProgress(chipTool, "DoorLockClusterClearWeekdayScheduleResponse");
ModelCommand * command = reinterpret_cast<ModelCommand *>(context);
command->SetCommandExitStatus(true);
}
static void OnDoorLockClusterClearYeardayScheduleResponse(void * context)
{
ChipLogProgress(chipTool, "DoorLockClusterClearYeardayScheduleResponse");
ModelCommand * command = reinterpret_cast<ModelCommand *>(context);
command->SetCommandExitStatus(true);
}
static void OnDoorLockClusterGetHolidayScheduleResponse(void * context, uint8_t scheduleId, uint32_t localStartTime,
uint32_t localEndTime, uint8_t operatingModeDuringHoliday)
{
ChipLogProgress(chipTool, "DoorLockClusterGetHolidayScheduleResponse");
ModelCommand * command = reinterpret_cast<ModelCommand *>(context);
command->SetCommandExitStatus(true);
}
static void OnDoorLockClusterGetLogRecordResponse(void * context, uint16_t logEntryId, uint32_t timestamp, uint8_t eventType,
uint8_t source, uint8_t eventIdOrAlarmCode, uint16_t userId, uint8_t * pin)
{
ChipLogProgress(chipTool, "DoorLockClusterGetLogRecordResponse");
ModelCommand * command = reinterpret_cast<ModelCommand *>(context);
command->SetCommandExitStatus(true);
}
static void OnDoorLockClusterGetPinResponse(void * context, uint16_t userId, uint8_t userStatus, uint8_t userType, uint8_t * pin)
{
ChipLogProgress(chipTool, "DoorLockClusterGetPinResponse");
ModelCommand * command = reinterpret_cast<ModelCommand *>(context);
command->SetCommandExitStatus(true);
}
static void OnDoorLockClusterGetRfidResponse(void * context, uint16_t userId, uint8_t userStatus, uint8_t userType, uint8_t * rfid)
{
ChipLogProgress(chipTool, "DoorLockClusterGetRfidResponse");
ModelCommand * command = reinterpret_cast<ModelCommand *>(context);
command->SetCommandExitStatus(true);
}
static void OnDoorLockClusterGetUserTypeResponse(void * context, uint16_t userId, uint8_t userType)
{
ChipLogProgress(chipTool, "DoorLockClusterGetUserTypeResponse");
ModelCommand * command = reinterpret_cast<ModelCommand *>(context);
command->SetCommandExitStatus(true);
}
static void OnDoorLockClusterGetWeekdayScheduleResponse(void * context, uint8_t scheduleId, uint16_t userId, uint8_t daysMask,
uint8_t startHour, uint8_t startMinute, uint8_t endHour, uint8_t endMinute)
{
ChipLogProgress(chipTool, "DoorLockClusterGetWeekdayScheduleResponse");
ModelCommand * command = reinterpret_cast<ModelCommand *>(context);
command->SetCommandExitStatus(true);
}
static void OnDoorLockClusterGetYeardayScheduleResponse(void * context, uint8_t scheduleId, uint16_t userId,
uint32_t localStartTime, uint32_t localEndTime)
{
ChipLogProgress(chipTool, "DoorLockClusterGetYeardayScheduleResponse");
ModelCommand * command = reinterpret_cast<ModelCommand *>(context);
command->SetCommandExitStatus(true);
}
static void OnDoorLockClusterLockDoorResponse(void * context)
{
ChipLogProgress(chipTool, "DoorLockClusterLockDoorResponse");
ModelCommand * command = reinterpret_cast<ModelCommand *>(context);
command->SetCommandExitStatus(true);
}
static void OnDoorLockClusterSetHolidayScheduleResponse(void * context)
{
ChipLogProgress(chipTool, "DoorLockClusterSetHolidayScheduleResponse");
ModelCommand * command = reinterpret_cast<ModelCommand *>(context);
command->SetCommandExitStatus(true);
}
static void OnDoorLockClusterSetPinResponse(void * context)
{
ChipLogProgress(chipTool, "DoorLockClusterSetPinResponse");
ModelCommand * command = reinterpret_cast<ModelCommand *>(context);
command->SetCommandExitStatus(true);
}
static void OnDoorLockClusterSetRfidResponse(void * context)
{
ChipLogProgress(chipTool, "DoorLockClusterSetRfidResponse");
ModelCommand * command = reinterpret_cast<ModelCommand *>(context);
command->SetCommandExitStatus(true);
}
static void OnDoorLockClusterSetUserTypeResponse(void * context)
{
ChipLogProgress(chipTool, "DoorLockClusterSetUserTypeResponse");
ModelCommand * command = reinterpret_cast<ModelCommand *>(context);
command->SetCommandExitStatus(true);
}
static void OnDoorLockClusterSetWeekdayScheduleResponse(void * context)
{
ChipLogProgress(chipTool, "DoorLockClusterSetWeekdayScheduleResponse");
ModelCommand * command = reinterpret_cast<ModelCommand *>(context);
command->SetCommandExitStatus(true);
}
static void OnDoorLockClusterSetYeardayScheduleResponse(void * context)
{
ChipLogProgress(chipTool, "DoorLockClusterSetYeardayScheduleResponse");
ModelCommand * command = reinterpret_cast<ModelCommand *>(context);
command->SetCommandExitStatus(true);
}
static void OnDoorLockClusterUnlockDoorResponse(void * context)
{
ChipLogProgress(chipTool, "DoorLockClusterUnlockDoorResponse");
ModelCommand * command = reinterpret_cast<ModelCommand *>(context);
command->SetCommandExitStatus(true);
}
static void OnDoorLockClusterUnlockWithTimeoutResponse(void * context)
{
ChipLogProgress(chipTool, "DoorLockClusterUnlockWithTimeoutResponse");
ModelCommand * command = reinterpret_cast<ModelCommand *>(context);
command->SetCommandExitStatus(true);
}
static void OnGeneralCommissioningClusterArmFailSafeResponse(void * context, uint8_t errorCode, uint8_t * debugText)
{
ChipLogProgress(chipTool, "GeneralCommissioningClusterArmFailSafeResponse");
ModelCommand * command = reinterpret_cast<ModelCommand *>(context);
command->SetCommandExitStatus(true);
}
static void OnGeneralCommissioningClusterCommissioningCompleteResponse(void * context, uint8_t errorCode, uint8_t * debugText)
{
ChipLogProgress(chipTool, "GeneralCommissioningClusterCommissioningCompleteResponse");
ModelCommand * command = reinterpret_cast<ModelCommand *>(context);
command->SetCommandExitStatus(true);
}
static void OnGeneralCommissioningClusterSetFabricResponse(void * context, uint8_t errorCode, uint8_t * debugText)
{
ChipLogProgress(chipTool, "GeneralCommissioningClusterSetFabricResponse");
ModelCommand * command = reinterpret_cast<ModelCommand *>(context);
command->SetCommandExitStatus(true);
}
static void OnGroupsClusterAddGroupResponse(void * context, uint16_t groupId)
{
ChipLogProgress(chipTool, "GroupsClusterAddGroupResponse");
ModelCommand * command = reinterpret_cast<ModelCommand *>(context);
command->SetCommandExitStatus(true);
}
static void OnGroupsClusterGetGroupMembershipResponse(void * context, uint8_t capacity, uint8_t groupCount,
/* TYPE WARNING: array array defaults to */ uint8_t * groupList)
{
ChipLogProgress(chipTool, "GroupsClusterGetGroupMembershipResponse");
ModelCommand * command = reinterpret_cast<ModelCommand *>(context);
command->SetCommandExitStatus(true);
}
static void OnGroupsClusterRemoveGroupResponse(void * context, uint16_t groupId)
{
ChipLogProgress(chipTool, "GroupsClusterRemoveGroupResponse");
ModelCommand * command = reinterpret_cast<ModelCommand *>(context);
command->SetCommandExitStatus(true);
}
static void OnGroupsClusterViewGroupResponse(void * context, uint16_t groupId, uint8_t * groupName)
{
ChipLogProgress(chipTool, "GroupsClusterViewGroupResponse");
ModelCommand * command = reinterpret_cast<ModelCommand *>(context);
command->SetCommandExitStatus(true);
}
static void OnIdentifyClusterIdentifyQueryResponse(void * context, uint16_t timeout)
{
ChipLogProgress(chipTool, "IdentifyClusterIdentifyQueryResponse");
ModelCommand * command = reinterpret_cast<ModelCommand *>(context);
command->SetCommandExitStatus(true);
}
static void OnScenesClusterAddSceneResponse(void * context, uint16_t groupId, uint8_t sceneId)
{
ChipLogProgress(chipTool, "ScenesClusterAddSceneResponse");
ModelCommand * command = reinterpret_cast<ModelCommand *>(context);
command->SetCommandExitStatus(true);
}
static void OnScenesClusterGetSceneMembershipResponse(void * context, uint8_t capacity, uint16_t groupId, uint8_t sceneCount,
/* TYPE WARNING: array array defaults to */ uint8_t * sceneList)
{
ChipLogProgress(chipTool, "ScenesClusterGetSceneMembershipResponse");
ModelCommand * command = reinterpret_cast<ModelCommand *>(context);
command->SetCommandExitStatus(true);
}
static void OnScenesClusterRemoveAllScenesResponse(void * context, uint16_t groupId)
{
ChipLogProgress(chipTool, "ScenesClusterRemoveAllScenesResponse");
ModelCommand * command = reinterpret_cast<ModelCommand *>(context);
command->SetCommandExitStatus(true);
}
static void OnScenesClusterRemoveSceneResponse(void * context, uint16_t groupId, uint8_t sceneId)
{
ChipLogProgress(chipTool, "ScenesClusterRemoveSceneResponse");
ModelCommand * command = reinterpret_cast<ModelCommand *>(context);
command->SetCommandExitStatus(true);
}
static void OnScenesClusterStoreSceneResponse(void * context, uint16_t groupId, uint8_t sceneId)
{
ChipLogProgress(chipTool, "ScenesClusterStoreSceneResponse");
ModelCommand * command = reinterpret_cast<ModelCommand *>(context);
command->SetCommandExitStatus(true);
}
static void OnScenesClusterViewSceneResponse(void * context, uint16_t groupId, uint8_t sceneId, uint16_t transitionTime,
uint8_t * sceneName,
/* TYPE WARNING: array array defaults to */ uint8_t * extensionFieldSets)
{
ChipLogProgress(chipTool, "ScenesClusterViewSceneResponse");
ModelCommand * command = reinterpret_cast<ModelCommand *>(context);
command->SetCommandExitStatus(true);
}
/*----------------------------------------------------------------------------*\
| Cluster Name | ID |
|---------------------------------------------------------------------+--------|
| ApplicationBasic | 0x050D |
| BarrierControl | 0x0103 |
| Basic | 0x0000 |
| Binding | 0xF000 |
| ColorControl | 0x0300 |
| ContentLaunch | 0xF002 |
| DoorLock | 0x0101 |
| GeneralCommissioning | 0x0030 |
| Groups | 0x0004 |
| Identify | 0x0003 |
| LevelControl | 0x0008 |
| MediaPlayback | 0xF001 |
| OnOff | 0x0006 |
| Scenes | 0x0005 |
| TemperatureMeasurement | 0x0402 |
\*----------------------------------------------------------------------------*/
constexpr chip::ClusterId kApplicationBasicClusterId = 0x050D;
constexpr chip::ClusterId kBarrierControlClusterId = 0x0103;
constexpr chip::ClusterId kBasicClusterId = 0x0000;
constexpr chip::ClusterId kBindingClusterId = 0xF000;
constexpr chip::ClusterId kColorControlClusterId = 0x0300;
constexpr chip::ClusterId kContentLaunchClusterId = 0xF002;
constexpr chip::ClusterId kDoorLockClusterId = 0x0101;
constexpr chip::ClusterId kGeneralCommissioningClusterId = 0x0030;
constexpr chip::ClusterId kGroupsClusterId = 0x0004;
constexpr chip::ClusterId kIdentifyClusterId = 0x0003;
constexpr chip::ClusterId kLevelControlClusterId = 0x0008;
constexpr chip::ClusterId kMediaPlaybackClusterId = 0xF001;
constexpr chip::ClusterId kOnOffClusterId = 0x0006;
constexpr chip::ClusterId kScenesClusterId = 0x0005;
constexpr chip::ClusterId kTemperatureMeasurementClusterId = 0x0402;
/*----------------------------------------------------------------------------*\
| Cluster ApplicationBasic | 0x050D |
|------------------------------------------------------------------------------|
| Commands: | |
|------------------------------------------------------------------------------|
| Attributes: | |
| * VendorName | 0x0000 |
| * VendorId | 0x0001 |
| * ApplicationName | 0x0002 |
| * ProductId | 0x0003 |
| * ApplicationId | 0x0005 |
| * CatalogVendorId | 0x0006 |
| * ApplicationSatus | 0x0007 |
| * ClusterRevision | 0xFFFD |
\*----------------------------------------------------------------------------*/
/*
* Discover Attributes
*/
class DiscoverApplicationBasicAttributes : public ModelCommand
{
public:
DiscoverApplicationBasicAttributes() : ModelCommand("discover") { ModelCommand::AddArguments(); }
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0000) command (0x0C) on endpoint %" PRIu16, endpointId);
chip::Controller::ApplicationBasicCluster cluster;
cluster.Associate(device, endpointId);
return cluster.DiscoverAttributes(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute VendorName
*/
class ReadApplicationBasicVendorName : public ModelCommand
{
public:
ReadApplicationBasicVendorName() : ModelCommand("read")
{
AddArgument("attr-name", "vendor-name");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x050D) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ApplicationBasicCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeVendorName(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<UnsupportedAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<UnsupportedAttributeCallback>(OnUnsupportedAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute VendorId
*/
class ReadApplicationBasicVendorId : public ModelCommand
{
public:
ReadApplicationBasicVendorId() : ModelCommand("read")
{
AddArgument("attr-name", "vendor-id");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x050D) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ApplicationBasicCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeVendorId(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute ApplicationName
*/
class ReadApplicationBasicApplicationName : public ModelCommand
{
public:
ReadApplicationBasicApplicationName() : ModelCommand("read")
{
AddArgument("attr-name", "application-name");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x050D) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ApplicationBasicCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeApplicationName(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<UnsupportedAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<UnsupportedAttributeCallback>(OnUnsupportedAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute ProductId
*/
class ReadApplicationBasicProductId : public ModelCommand
{
public:
ReadApplicationBasicProductId() : ModelCommand("read")
{
AddArgument("attr-name", "product-id");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x050D) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ApplicationBasicCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeProductId(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute ApplicationId
*/
class ReadApplicationBasicApplicationId : public ModelCommand
{
public:
ReadApplicationBasicApplicationId() : ModelCommand("read")
{
AddArgument("attr-name", "application-id");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x050D) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ApplicationBasicCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeApplicationId(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<UnsupportedAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<UnsupportedAttributeCallback>(OnUnsupportedAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute CatalogVendorId
*/
class ReadApplicationBasicCatalogVendorId : public ModelCommand
{
public:
ReadApplicationBasicCatalogVendorId() : ModelCommand("read")
{
AddArgument("attr-name", "catalog-vendor-id");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x050D) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ApplicationBasicCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeCatalogVendorId(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute ApplicationSatus
*/
class ReadApplicationBasicApplicationSatus : public ModelCommand
{
public:
ReadApplicationBasicApplicationSatus() : ModelCommand("read")
{
AddArgument("attr-name", "application-satus");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x050D) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ApplicationBasicCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeApplicationSatus(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int8uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int8uAttributeCallback>(OnInt8uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute ClusterRevision
*/
class ReadApplicationBasicClusterRevision : public ModelCommand
{
public:
ReadApplicationBasicClusterRevision() : ModelCommand("read")
{
AddArgument("attr-name", "cluster-revision");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x050D) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ApplicationBasicCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeClusterRevision(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*----------------------------------------------------------------------------*\
| Cluster BarrierControl | 0x0103 |
|------------------------------------------------------------------------------|
| Commands: | |
| * BarrierControlGoToPercent | 0x00 |
| * BarrierControlStop | 0x01 |
|------------------------------------------------------------------------------|
| Attributes: | |
| * BarrierMovingState | 0x0001 |
| * BarrierSafetyStatus | 0x0002 |
| * BarrierCapabilities | 0x0003 |
| * BarrierPosition | 0x000A |
| * ClusterRevision | 0xFFFD |
\*----------------------------------------------------------------------------*/
/*
* Command BarrierControlGoToPercent
*/
class BarrierControlBarrierControlGoToPercent : public ModelCommand
{
public:
BarrierControlBarrierControlGoToPercent() : ModelCommand("barrier-control-go-to-percent")
{
AddArgument("percentOpen", 0, UINT8_MAX, &mPercentOpen);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0103) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::BarrierControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.BarrierControlGoToPercent(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mPercentOpen);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint8_t mPercentOpen;
};
/*
* Command BarrierControlStop
*/
class BarrierControlBarrierControlStop : public ModelCommand
{
public:
BarrierControlBarrierControlStop() : ModelCommand("barrier-control-stop") { ModelCommand::AddArguments(); }
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0103) command (0x01) on endpoint %" PRIu16, endpointId);
chip::Controller::BarrierControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.BarrierControlStop(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Discover Attributes
*/
class DiscoverBarrierControlAttributes : public ModelCommand
{
public:
DiscoverBarrierControlAttributes() : ModelCommand("discover") { ModelCommand::AddArguments(); }
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0000) command (0x0C) on endpoint %" PRIu16, endpointId);
chip::Controller::BarrierControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.DiscoverAttributes(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute BarrierMovingState
*/
class ReadBarrierControlBarrierMovingState : public ModelCommand
{
public:
ReadBarrierControlBarrierMovingState() : ModelCommand("read")
{
AddArgument("attr-name", "barrier-moving-state");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0103) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::BarrierControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeBarrierMovingState(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int8uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int8uAttributeCallback>(OnInt8uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute BarrierSafetyStatus
*/
class ReadBarrierControlBarrierSafetyStatus : public ModelCommand
{
public:
ReadBarrierControlBarrierSafetyStatus() : ModelCommand("read")
{
AddArgument("attr-name", "barrier-safety-status");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0103) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::BarrierControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeBarrierSafetyStatus(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute BarrierCapabilities
*/
class ReadBarrierControlBarrierCapabilities : public ModelCommand
{
public:
ReadBarrierControlBarrierCapabilities() : ModelCommand("read")
{
AddArgument("attr-name", "barrier-capabilities");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0103) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::BarrierControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeBarrierCapabilities(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int8uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int8uAttributeCallback>(OnInt8uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute BarrierPosition
*/
class ReadBarrierControlBarrierPosition : public ModelCommand
{
public:
ReadBarrierControlBarrierPosition() : ModelCommand("read")
{
AddArgument("attr-name", "barrier-position");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0103) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::BarrierControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeBarrierPosition(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int8uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int8uAttributeCallback>(OnInt8uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute ClusterRevision
*/
class ReadBarrierControlClusterRevision : public ModelCommand
{
public:
ReadBarrierControlClusterRevision() : ModelCommand("read")
{
AddArgument("attr-name", "cluster-revision");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0103) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::BarrierControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeClusterRevision(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*----------------------------------------------------------------------------*\
| Cluster Basic | 0x0000 |
|------------------------------------------------------------------------------|
| Commands: | |
| * MfgSpecificPing | 0x00 |
| * ResetToFactoryDefaults | 0x00 |
|------------------------------------------------------------------------------|
| Attributes: | |
| * ZclVersion | 0x0000 |
| * PowerSource | 0x0007 |
| * ClusterRevision | 0xFFFD |
\*----------------------------------------------------------------------------*/
/*
* Command MfgSpecificPing
*/
class BasicMfgSpecificPing : public ModelCommand
{
public:
BasicMfgSpecificPing() : ModelCommand("mfg-specific-ping") { ModelCommand::AddArguments(); }
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0000) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::BasicCluster cluster;
cluster.Associate(device, endpointId);
return cluster.MfgSpecificPing(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Command ResetToFactoryDefaults
*/
class BasicResetToFactoryDefaults : public ModelCommand
{
public:
BasicResetToFactoryDefaults() : ModelCommand("reset-to-factory-defaults") { ModelCommand::AddArguments(); }
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0000) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::BasicCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ResetToFactoryDefaults(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Discover Attributes
*/
class DiscoverBasicAttributes : public ModelCommand
{
public:
DiscoverBasicAttributes() : ModelCommand("discover") { ModelCommand::AddArguments(); }
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0000) command (0x0C) on endpoint %" PRIu16, endpointId);
chip::Controller::BasicCluster cluster;
cluster.Associate(device, endpointId);
return cluster.DiscoverAttributes(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute ZclVersion
*/
class ReadBasicZclVersion : public ModelCommand
{
public:
ReadBasicZclVersion() : ModelCommand("read")
{
AddArgument("attr-name", "zcl-version");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0000) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::BasicCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeZclVersion(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int8uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int8uAttributeCallback>(OnInt8uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute PowerSource
*/
class ReadBasicPowerSource : public ModelCommand
{
public:
ReadBasicPowerSource() : ModelCommand("read")
{
AddArgument("attr-name", "power-source");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0000) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::BasicCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributePowerSource(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int8uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int8uAttributeCallback>(OnInt8uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute ClusterRevision
*/
class ReadBasicClusterRevision : public ModelCommand
{
public:
ReadBasicClusterRevision() : ModelCommand("read")
{
AddArgument("attr-name", "cluster-revision");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0000) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::BasicCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeClusterRevision(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*----------------------------------------------------------------------------*\
| Cluster Binding | 0xF000 |
|------------------------------------------------------------------------------|
| Commands: | |
| * Bind | 0x00 |
| * Unbind | 0x01 |
|------------------------------------------------------------------------------|
| Attributes: | |
| * ClusterRevision | 0xFFFD |
\*----------------------------------------------------------------------------*/
/*
* Command Bind
*/
class BindingBind : public ModelCommand
{
public:
BindingBind() : ModelCommand("bind")
{
AddArgument("nodeId", 0, UINT64_MAX, &mNodeId);
AddArgument("groupId", 0, UINT16_MAX, &mGroupId);
AddArgument("endpointId", 0, UINT8_MAX, &mEndpointId);
AddArgument("clusterId", 0, UINT16_MAX, &mClusterId);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0xF000) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::BindingCluster cluster;
cluster.Associate(device, endpointId);
return cluster.Bind(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mNodeId, mGroupId, mEndpointId, mClusterId);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
chip::NodeId mNodeId;
chip::GroupId mGroupId;
chip::EndpointId mEndpointId;
chip::ClusterId mClusterId;
};
/*
* Command Unbind
*/
class BindingUnbind : public ModelCommand
{
public:
BindingUnbind() : ModelCommand("unbind")
{
AddArgument("nodeId", 0, UINT64_MAX, &mNodeId);
AddArgument("groupId", 0, UINT16_MAX, &mGroupId);
AddArgument("endpointId", 0, UINT8_MAX, &mEndpointId);
AddArgument("clusterId", 0, UINT16_MAX, &mClusterId);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0xF000) command (0x01) on endpoint %" PRIu16, endpointId);
chip::Controller::BindingCluster cluster;
cluster.Associate(device, endpointId);
return cluster.Unbind(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mNodeId, mGroupId, mEndpointId, mClusterId);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
chip::NodeId mNodeId;
chip::GroupId mGroupId;
chip::EndpointId mEndpointId;
chip::ClusterId mClusterId;
};
/*
* Discover Attributes
*/
class DiscoverBindingAttributes : public ModelCommand
{
public:
DiscoverBindingAttributes() : ModelCommand("discover") { ModelCommand::AddArguments(); }
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0000) command (0x0C) on endpoint %" PRIu16, endpointId);
chip::Controller::BindingCluster cluster;
cluster.Associate(device, endpointId);
return cluster.DiscoverAttributes(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute ClusterRevision
*/
class ReadBindingClusterRevision : public ModelCommand
{
public:
ReadBindingClusterRevision() : ModelCommand("read")
{
AddArgument("attr-name", "cluster-revision");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0xF000) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::BindingCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeClusterRevision(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*----------------------------------------------------------------------------*\
| Cluster ColorControl | 0x0300 |
|------------------------------------------------------------------------------|
| Commands: | |
| * MoveColor | 0x08 |
| * MoveColorTemperature | 0x4B |
| * MoveHue | 0x01 |
| * MoveSaturation | 0x04 |
| * MoveToColor | 0x07 |
| * MoveToColorTemperature | 0x0A |
| * MoveToHue | 0x00 |
| * MoveToHueAndSaturation | 0x06 |
| * MoveToSaturation | 0x03 |
| * StepColor | 0x09 |
| * StepColorTemperature | 0x4C |
| * StepHue | 0x02 |
| * StepSaturation | 0x05 |
| * StopMoveStep | 0x47 |
|------------------------------------------------------------------------------|
| Attributes: | |
| * CurrentHue | 0x0000 |
| * CurrentSaturation | 0x0001 |
| * RemainingTime | 0x0002 |
| * CurrentX | 0x0003 |
| * CurrentY | 0x0004 |
| * DriftCompensation | 0x0005 |
| * CompensationText | 0x0006 |
| * ColorTemperature | 0x0007 |
| * ColorMode | 0x0008 |
| * ColorControlOptions | 0x000F |
| * NumberOfPrimaries | 0x0010 |
| * Primary1X | 0x0011 |
| * Primary1Y | 0x0012 |
| * Primary1Intensity | 0x0013 |
| * Primary2X | 0x0015 |
| * Primary2Y | 0x0016 |
| * Primary2Intensity | 0x0017 |
| * Primary3X | 0x0019 |
| * Primary3Y | 0x001A |
| * Primary3Intensity | 0x001B |
| * Primary4X | 0x0020 |
| * Primary4Y | 0x0021 |
| * Primary4Intensity | 0x0022 |
| * Primary5X | 0x0024 |
| * Primary5Y | 0x0025 |
| * Primary5Intensity | 0x0026 |
| * Primary6X | 0x0028 |
| * Primary6Y | 0x0029 |
| * Primary6Intensity | 0x002A |
| * WhitePointX | 0x0030 |
| * WhitePointY | 0x0031 |
| * ColorPointRX | 0x0032 |
| * ColorPointRY | 0x0033 |
| * ColorPointRIntensity | 0x0034 |
| * ColorPointGX | 0x0036 |
| * ColorPointGY | 0x0037 |
| * ColorPointGIntensity | 0x0038 |
| * ColorPointBX | 0x003A |
| * ColorPointBY | 0x003B |
| * ColorPointBIntensity | 0x003C |
| * EnhancedCurrentHue | 0x4000 |
| * EnhancedColorMode | 0x4001 |
| * ColorLoopActive | 0x4002 |
| * ColorLoopDirection | 0x4003 |
| * ColorLoopTime | 0x4004 |
| * ColorCapabilities | 0x400A |
| * ColorTempPhysicalMin | 0x400B |
| * ColorTempPhysicalMax | 0x400C |
| * CoupleColorTempToLevelMinMireds | 0x400D |
| * StartUpColorTemperatureMireds | 0x4010 |
| * ClusterRevision | 0xFFFD |
\*----------------------------------------------------------------------------*/
/*
* Command MoveColor
*/
class ColorControlMoveColor : public ModelCommand
{
public:
ColorControlMoveColor() : ModelCommand("move-color")
{
AddArgument("rateX", INT16_MIN, INT16_MAX, &mRateX);
AddArgument("rateY", INT16_MIN, INT16_MAX, &mRateY);
AddArgument("optionsMask", 0, UINT8_MAX, &mOptionsMask);
AddArgument("optionsOverride", 0, UINT8_MAX, &mOptionsOverride);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x08) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.MoveColor(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mRateX, mRateY, mOptionsMask,
mOptionsOverride);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
int16_t mRateX;
int16_t mRateY;
uint8_t mOptionsMask;
uint8_t mOptionsOverride;
};
/*
* Command MoveColorTemperature
*/
class ColorControlMoveColorTemperature : public ModelCommand
{
public:
ColorControlMoveColorTemperature() : ModelCommand("move-color-temperature")
{
AddArgument("moveMode", 0, UINT8_MAX, &mMoveMode);
AddArgument("rate", 0, UINT16_MAX, &mRate);
AddArgument("colorTemperatureMinimum", 0, UINT16_MAX, &mColorTemperatureMinimum);
AddArgument("colorTemperatureMaximum", 0, UINT16_MAX, &mColorTemperatureMaximum);
AddArgument("optionsMask", 0, UINT8_MAX, &mOptionsMask);
AddArgument("optionsOverride", 0, UINT8_MAX, &mOptionsOverride);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x4B) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.MoveColorTemperature(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mMoveMode, mRate,
mColorTemperatureMinimum, mColorTemperatureMaximum, mOptionsMask, mOptionsOverride);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint8_t mMoveMode;
uint16_t mRate;
uint16_t mColorTemperatureMinimum;
uint16_t mColorTemperatureMaximum;
uint8_t mOptionsMask;
uint8_t mOptionsOverride;
};
/*
* Command MoveHue
*/
class ColorControlMoveHue : public ModelCommand
{
public:
ColorControlMoveHue() : ModelCommand("move-hue")
{
AddArgument("moveMode", 0, UINT8_MAX, &mMoveMode);
AddArgument("rate", 0, UINT8_MAX, &mRate);
AddArgument("optionsMask", 0, UINT8_MAX, &mOptionsMask);
AddArgument("optionsOverride", 0, UINT8_MAX, &mOptionsOverride);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x01) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.MoveHue(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mMoveMode, mRate, mOptionsMask,
mOptionsOverride);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint8_t mMoveMode;
uint8_t mRate;
uint8_t mOptionsMask;
uint8_t mOptionsOverride;
};
/*
* Command MoveSaturation
*/
class ColorControlMoveSaturation : public ModelCommand
{
public:
ColorControlMoveSaturation() : ModelCommand("move-saturation")
{
AddArgument("moveMode", 0, UINT8_MAX, &mMoveMode);
AddArgument("rate", 0, UINT8_MAX, &mRate);
AddArgument("optionsMask", 0, UINT8_MAX, &mOptionsMask);
AddArgument("optionsOverride", 0, UINT8_MAX, &mOptionsOverride);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x04) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.MoveSaturation(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mMoveMode, mRate, mOptionsMask,
mOptionsOverride);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint8_t mMoveMode;
uint8_t mRate;
uint8_t mOptionsMask;
uint8_t mOptionsOverride;
};
/*
* Command MoveToColor
*/
class ColorControlMoveToColor : public ModelCommand
{
public:
ColorControlMoveToColor() : ModelCommand("move-to-color")
{
AddArgument("colorX", 0, UINT16_MAX, &mColorX);
AddArgument("colorY", 0, UINT16_MAX, &mColorY);
AddArgument("transitionTime", 0, UINT16_MAX, &mTransitionTime);
AddArgument("optionsMask", 0, UINT8_MAX, &mOptionsMask);
AddArgument("optionsOverride", 0, UINT8_MAX, &mOptionsOverride);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x07) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.MoveToColor(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mColorX, mColorY, mTransitionTime,
mOptionsMask, mOptionsOverride);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint16_t mColorX;
uint16_t mColorY;
uint16_t mTransitionTime;
uint8_t mOptionsMask;
uint8_t mOptionsOverride;
};
/*
* Command MoveToColorTemperature
*/
class ColorControlMoveToColorTemperature : public ModelCommand
{
public:
ColorControlMoveToColorTemperature() : ModelCommand("move-to-color-temperature")
{
AddArgument("colorTemperature", 0, UINT16_MAX, &mColorTemperature);
AddArgument("transitionTime", 0, UINT16_MAX, &mTransitionTime);
AddArgument("optionsMask", 0, UINT8_MAX, &mOptionsMask);
AddArgument("optionsOverride", 0, UINT8_MAX, &mOptionsOverride);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x0A) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.MoveToColorTemperature(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mColorTemperature,
mTransitionTime, mOptionsMask, mOptionsOverride);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint16_t mColorTemperature;
uint16_t mTransitionTime;
uint8_t mOptionsMask;
uint8_t mOptionsOverride;
};
/*
* Command MoveToHue
*/
class ColorControlMoveToHue : public ModelCommand
{
public:
ColorControlMoveToHue() : ModelCommand("move-to-hue")
{
AddArgument("hue", 0, UINT8_MAX, &mHue);
AddArgument("direction", 0, UINT8_MAX, &mDirection);
AddArgument("transitionTime", 0, UINT16_MAX, &mTransitionTime);
AddArgument("optionsMask", 0, UINT8_MAX, &mOptionsMask);
AddArgument("optionsOverride", 0, UINT8_MAX, &mOptionsOverride);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.MoveToHue(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mHue, mDirection, mTransitionTime,
mOptionsMask, mOptionsOverride);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint8_t mHue;
uint8_t mDirection;
uint16_t mTransitionTime;
uint8_t mOptionsMask;
uint8_t mOptionsOverride;
};
/*
* Command MoveToHueAndSaturation
*/
class ColorControlMoveToHueAndSaturation : public ModelCommand
{
public:
ColorControlMoveToHueAndSaturation() : ModelCommand("move-to-hue-and-saturation")
{
AddArgument("hue", 0, UINT8_MAX, &mHue);
AddArgument("saturation", 0, UINT8_MAX, &mSaturation);
AddArgument("transitionTime", 0, UINT16_MAX, &mTransitionTime);
AddArgument("optionsMask", 0, UINT8_MAX, &mOptionsMask);
AddArgument("optionsOverride", 0, UINT8_MAX, &mOptionsOverride);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x06) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.MoveToHueAndSaturation(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mHue, mSaturation,
mTransitionTime, mOptionsMask, mOptionsOverride);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint8_t mHue;
uint8_t mSaturation;
uint16_t mTransitionTime;
uint8_t mOptionsMask;
uint8_t mOptionsOverride;
};
/*
* Command MoveToSaturation
*/
class ColorControlMoveToSaturation : public ModelCommand
{
public:
ColorControlMoveToSaturation() : ModelCommand("move-to-saturation")
{
AddArgument("saturation", 0, UINT8_MAX, &mSaturation);
AddArgument("transitionTime", 0, UINT16_MAX, &mTransitionTime);
AddArgument("optionsMask", 0, UINT8_MAX, &mOptionsMask);
AddArgument("optionsOverride", 0, UINT8_MAX, &mOptionsOverride);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x03) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.MoveToSaturation(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mSaturation, mTransitionTime,
mOptionsMask, mOptionsOverride);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint8_t mSaturation;
uint16_t mTransitionTime;
uint8_t mOptionsMask;
uint8_t mOptionsOverride;
};
/*
* Command StepColor
*/
class ColorControlStepColor : public ModelCommand
{
public:
ColorControlStepColor() : ModelCommand("step-color")
{
AddArgument("stepX", INT16_MIN, INT16_MAX, &mStepX);
AddArgument("stepY", INT16_MIN, INT16_MAX, &mStepY);
AddArgument("transitionTime", 0, UINT16_MAX, &mTransitionTime);
AddArgument("optionsMask", 0, UINT8_MAX, &mOptionsMask);
AddArgument("optionsOverride", 0, UINT8_MAX, &mOptionsOverride);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x09) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.StepColor(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mStepX, mStepY, mTransitionTime,
mOptionsMask, mOptionsOverride);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
int16_t mStepX;
int16_t mStepY;
uint16_t mTransitionTime;
uint8_t mOptionsMask;
uint8_t mOptionsOverride;
};
/*
* Command StepColorTemperature
*/
class ColorControlStepColorTemperature : public ModelCommand
{
public:
ColorControlStepColorTemperature() : ModelCommand("step-color-temperature")
{
AddArgument("stepMode", 0, UINT8_MAX, &mStepMode);
AddArgument("stepSize", 0, UINT16_MAX, &mStepSize);
AddArgument("transitionTime", 0, UINT16_MAX, &mTransitionTime);
AddArgument("colorTemperatureMinimum", 0, UINT16_MAX, &mColorTemperatureMinimum);
AddArgument("colorTemperatureMaximum", 0, UINT16_MAX, &mColorTemperatureMaximum);
AddArgument("optionsMask", 0, UINT8_MAX, &mOptionsMask);
AddArgument("optionsOverride", 0, UINT8_MAX, &mOptionsOverride);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x4C) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.StepColorTemperature(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mStepMode, mStepSize,
mTransitionTime, mColorTemperatureMinimum, mColorTemperatureMaximum, mOptionsMask,
mOptionsOverride);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint8_t mStepMode;
uint16_t mStepSize;
uint16_t mTransitionTime;
uint16_t mColorTemperatureMinimum;
uint16_t mColorTemperatureMaximum;
uint8_t mOptionsMask;
uint8_t mOptionsOverride;
};
/*
* Command StepHue
*/
class ColorControlStepHue : public ModelCommand
{
public:
ColorControlStepHue() : ModelCommand("step-hue")
{
AddArgument("stepMode", 0, UINT8_MAX, &mStepMode);
AddArgument("stepSize", 0, UINT8_MAX, &mStepSize);
AddArgument("transitionTime", 0, UINT8_MAX, &mTransitionTime);
AddArgument("optionsMask", 0, UINT8_MAX, &mOptionsMask);
AddArgument("optionsOverride", 0, UINT8_MAX, &mOptionsOverride);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x02) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.StepHue(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mStepMode, mStepSize, mTransitionTime,
mOptionsMask, mOptionsOverride);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint8_t mStepMode;
uint8_t mStepSize;
uint8_t mTransitionTime;
uint8_t mOptionsMask;
uint8_t mOptionsOverride;
};
/*
* Command StepSaturation
*/
class ColorControlStepSaturation : public ModelCommand
{
public:
ColorControlStepSaturation() : ModelCommand("step-saturation")
{
AddArgument("stepMode", 0, UINT8_MAX, &mStepMode);
AddArgument("stepSize", 0, UINT8_MAX, &mStepSize);
AddArgument("transitionTime", 0, UINT8_MAX, &mTransitionTime);
AddArgument("optionsMask", 0, UINT8_MAX, &mOptionsMask);
AddArgument("optionsOverride", 0, UINT8_MAX, &mOptionsOverride);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x05) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.StepSaturation(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mStepMode, mStepSize,
mTransitionTime, mOptionsMask, mOptionsOverride);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint8_t mStepMode;
uint8_t mStepSize;
uint8_t mTransitionTime;
uint8_t mOptionsMask;
uint8_t mOptionsOverride;
};
/*
* Command StopMoveStep
*/
class ColorControlStopMoveStep : public ModelCommand
{
public:
ColorControlStopMoveStep() : ModelCommand("stop-move-step")
{
AddArgument("optionsMask", 0, UINT8_MAX, &mOptionsMask);
AddArgument("optionsOverride", 0, UINT8_MAX, &mOptionsOverride);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x47) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.StopMoveStep(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mOptionsMask, mOptionsOverride);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint8_t mOptionsMask;
uint8_t mOptionsOverride;
};
/*
* Discover Attributes
*/
class DiscoverColorControlAttributes : public ModelCommand
{
public:
DiscoverColorControlAttributes() : ModelCommand("discover") { ModelCommand::AddArguments(); }
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0000) command (0x0C) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.DiscoverAttributes(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute CurrentHue
*/
class ReadColorControlCurrentHue : public ModelCommand
{
public:
ReadColorControlCurrentHue() : ModelCommand("read")
{
AddArgument("attr-name", "current-hue");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeCurrentHue(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int8uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int8uAttributeCallback>(OnInt8uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
class ReportColorControlCurrentHue : public ModelCommand
{
public:
ReportColorControlCurrentHue() : ModelCommand("report")
{
AddArgument("attr-name", "current-hue");
AddArgument("min-interval", 0, UINT16_MAX, &mMinInterval);
AddArgument("max-interval", 0, UINT16_MAX, &mMaxInterval);
AddArgument("change", 0, UINT8_MAX, &mChange);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x06) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
CHIP_ERROR err = cluster.ReportAttributeCurrentHue(onReportCallback->Cancel());
if (err != CHIP_NO_ERROR)
{
return err;
}
return cluster.ConfigureAttributeCurrentHue(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mMinInterval,
mMaxInterval, mChange);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
chip::Callback::Callback<Int8uAttributeCallback> * onReportCallback =
new chip::Callback::Callback<Int8uAttributeCallback>(OnInt8uAttributeResponse, this);
uint16_t mMinInterval;
uint16_t mMaxInterval;
uint8_t mChange;
};
/*
* Attribute CurrentSaturation
*/
class ReadColorControlCurrentSaturation : public ModelCommand
{
public:
ReadColorControlCurrentSaturation() : ModelCommand("read")
{
AddArgument("attr-name", "current-saturation");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeCurrentSaturation(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int8uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int8uAttributeCallback>(OnInt8uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
class ReportColorControlCurrentSaturation : public ModelCommand
{
public:
ReportColorControlCurrentSaturation() : ModelCommand("report")
{
AddArgument("attr-name", "current-saturation");
AddArgument("min-interval", 0, UINT16_MAX, &mMinInterval);
AddArgument("max-interval", 0, UINT16_MAX, &mMaxInterval);
AddArgument("change", 0, UINT8_MAX, &mChange);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x06) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
CHIP_ERROR err = cluster.ReportAttributeCurrentSaturation(onReportCallback->Cancel());
if (err != CHIP_NO_ERROR)
{
return err;
}
return cluster.ConfigureAttributeCurrentSaturation(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mMinInterval,
mMaxInterval, mChange);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
chip::Callback::Callback<Int8uAttributeCallback> * onReportCallback =
new chip::Callback::Callback<Int8uAttributeCallback>(OnInt8uAttributeResponse, this);
uint16_t mMinInterval;
uint16_t mMaxInterval;
uint8_t mChange;
};
/*
* Attribute RemainingTime
*/
class ReadColorControlRemainingTime : public ModelCommand
{
public:
ReadColorControlRemainingTime() : ModelCommand("read")
{
AddArgument("attr-name", "remaining-time");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeRemainingTime(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute CurrentX
*/
class ReadColorControlCurrentX : public ModelCommand
{
public:
ReadColorControlCurrentX() : ModelCommand("read")
{
AddArgument("attr-name", "current-x");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeCurrentX(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
class ReportColorControlCurrentX : public ModelCommand
{
public:
ReportColorControlCurrentX() : ModelCommand("report")
{
AddArgument("attr-name", "current-x");
AddArgument("min-interval", 0, UINT16_MAX, &mMinInterval);
AddArgument("max-interval", 0, UINT16_MAX, &mMaxInterval);
AddArgument("change", 0, UINT16_MAX, &mChange);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x06) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
CHIP_ERROR err = cluster.ReportAttributeCurrentX(onReportCallback->Cancel());
if (err != CHIP_NO_ERROR)
{
return err;
}
return cluster.ConfigureAttributeCurrentX(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mMinInterval,
mMaxInterval, mChange);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
chip::Callback::Callback<Int16uAttributeCallback> * onReportCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
uint16_t mMinInterval;
uint16_t mMaxInterval;
uint16_t mChange;
};
/*
* Attribute CurrentY
*/
class ReadColorControlCurrentY : public ModelCommand
{
public:
ReadColorControlCurrentY() : ModelCommand("read")
{
AddArgument("attr-name", "current-y");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeCurrentY(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
class ReportColorControlCurrentY : public ModelCommand
{
public:
ReportColorControlCurrentY() : ModelCommand("report")
{
AddArgument("attr-name", "current-y");
AddArgument("min-interval", 0, UINT16_MAX, &mMinInterval);
AddArgument("max-interval", 0, UINT16_MAX, &mMaxInterval);
AddArgument("change", 0, UINT16_MAX, &mChange);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x06) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
CHIP_ERROR err = cluster.ReportAttributeCurrentY(onReportCallback->Cancel());
if (err != CHIP_NO_ERROR)
{
return err;
}
return cluster.ConfigureAttributeCurrentY(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mMinInterval,
mMaxInterval, mChange);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
chip::Callback::Callback<Int16uAttributeCallback> * onReportCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
uint16_t mMinInterval;
uint16_t mMaxInterval;
uint16_t mChange;
};
/*
* Attribute DriftCompensation
*/
class ReadColorControlDriftCompensation : public ModelCommand
{
public:
ReadColorControlDriftCompensation() : ModelCommand("read")
{
AddArgument("attr-name", "drift-compensation");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeDriftCompensation(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int8uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int8uAttributeCallback>(OnInt8uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute CompensationText
*/
class ReadColorControlCompensationText : public ModelCommand
{
public:
ReadColorControlCompensationText() : ModelCommand("read")
{
AddArgument("attr-name", "compensation-text");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeCompensationText(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<UnsupportedAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<UnsupportedAttributeCallback>(OnUnsupportedAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute ColorTemperature
*/
class ReadColorControlColorTemperature : public ModelCommand
{
public:
ReadColorControlColorTemperature() : ModelCommand("read")
{
AddArgument("attr-name", "color-temperature");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeColorTemperature(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
class ReportColorControlColorTemperature : public ModelCommand
{
public:
ReportColorControlColorTemperature() : ModelCommand("report")
{
AddArgument("attr-name", "color-temperature");
AddArgument("min-interval", 0, UINT16_MAX, &mMinInterval);
AddArgument("max-interval", 0, UINT16_MAX, &mMaxInterval);
AddArgument("change", 0, UINT16_MAX, &mChange);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x06) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
CHIP_ERROR err = cluster.ReportAttributeColorTemperature(onReportCallback->Cancel());
if (err != CHIP_NO_ERROR)
{
return err;
}
return cluster.ConfigureAttributeColorTemperature(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mMinInterval,
mMaxInterval, mChange);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
chip::Callback::Callback<Int16uAttributeCallback> * onReportCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
uint16_t mMinInterval;
uint16_t mMaxInterval;
uint16_t mChange;
};
/*
* Attribute ColorMode
*/
class ReadColorControlColorMode : public ModelCommand
{
public:
ReadColorControlColorMode() : ModelCommand("read")
{
AddArgument("attr-name", "color-mode");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeColorMode(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int8uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int8uAttributeCallback>(OnInt8uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute ColorControlOptions
*/
class ReadColorControlColorControlOptions : public ModelCommand
{
public:
ReadColorControlColorControlOptions() : ModelCommand("read")
{
AddArgument("attr-name", "color-control-options");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeColorControlOptions(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int8uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int8uAttributeCallback>(OnInt8uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
class WriteColorControlColorControlOptions : public ModelCommand
{
public:
WriteColorControlColorControlOptions() : ModelCommand("write")
{
AddArgument("attr-name", "color-control-options");
AddArgument("attr-value", 0, UINT8_MAX, &mValue);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x01) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.WriteAttributeColorControlOptions(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mValue);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint8_t mValue;
};
/*
* Attribute NumberOfPrimaries
*/
class ReadColorControlNumberOfPrimaries : public ModelCommand
{
public:
ReadColorControlNumberOfPrimaries() : ModelCommand("read")
{
AddArgument("attr-name", "number-of-primaries");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeNumberOfPrimaries(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int8uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int8uAttributeCallback>(OnInt8uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute Primary1X
*/
class ReadColorControlPrimary1X : public ModelCommand
{
public:
ReadColorControlPrimary1X() : ModelCommand("read")
{
AddArgument("attr-name", "primary1x");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributePrimary1X(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute Primary1Y
*/
class ReadColorControlPrimary1Y : public ModelCommand
{
public:
ReadColorControlPrimary1Y() : ModelCommand("read")
{
AddArgument("attr-name", "primary1y");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributePrimary1Y(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute Primary1Intensity
*/
class ReadColorControlPrimary1Intensity : public ModelCommand
{
public:
ReadColorControlPrimary1Intensity() : ModelCommand("read")
{
AddArgument("attr-name", "primary1intensity");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributePrimary1Intensity(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int8uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int8uAttributeCallback>(OnInt8uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute Primary2X
*/
class ReadColorControlPrimary2X : public ModelCommand
{
public:
ReadColorControlPrimary2X() : ModelCommand("read")
{
AddArgument("attr-name", "primary2x");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributePrimary2X(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute Primary2Y
*/
class ReadColorControlPrimary2Y : public ModelCommand
{
public:
ReadColorControlPrimary2Y() : ModelCommand("read")
{
AddArgument("attr-name", "primary2y");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributePrimary2Y(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute Primary2Intensity
*/
class ReadColorControlPrimary2Intensity : public ModelCommand
{
public:
ReadColorControlPrimary2Intensity() : ModelCommand("read")
{
AddArgument("attr-name", "primary2intensity");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributePrimary2Intensity(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int8uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int8uAttributeCallback>(OnInt8uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute Primary3X
*/
class ReadColorControlPrimary3X : public ModelCommand
{
public:
ReadColorControlPrimary3X() : ModelCommand("read")
{
AddArgument("attr-name", "primary3x");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributePrimary3X(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute Primary3Y
*/
class ReadColorControlPrimary3Y : public ModelCommand
{
public:
ReadColorControlPrimary3Y() : ModelCommand("read")
{
AddArgument("attr-name", "primary3y");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributePrimary3Y(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute Primary3Intensity
*/
class ReadColorControlPrimary3Intensity : public ModelCommand
{
public:
ReadColorControlPrimary3Intensity() : ModelCommand("read")
{
AddArgument("attr-name", "primary3intensity");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributePrimary3Intensity(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int8uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int8uAttributeCallback>(OnInt8uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute Primary4X
*/
class ReadColorControlPrimary4X : public ModelCommand
{
public:
ReadColorControlPrimary4X() : ModelCommand("read")
{
AddArgument("attr-name", "primary4x");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributePrimary4X(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute Primary4Y
*/
class ReadColorControlPrimary4Y : public ModelCommand
{
public:
ReadColorControlPrimary4Y() : ModelCommand("read")
{
AddArgument("attr-name", "primary4y");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributePrimary4Y(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute Primary4Intensity
*/
class ReadColorControlPrimary4Intensity : public ModelCommand
{
public:
ReadColorControlPrimary4Intensity() : ModelCommand("read")
{
AddArgument("attr-name", "primary4intensity");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributePrimary4Intensity(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int8uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int8uAttributeCallback>(OnInt8uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute Primary5X
*/
class ReadColorControlPrimary5X : public ModelCommand
{
public:
ReadColorControlPrimary5X() : ModelCommand("read")
{
AddArgument("attr-name", "primary5x");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributePrimary5X(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute Primary5Y
*/
class ReadColorControlPrimary5Y : public ModelCommand
{
public:
ReadColorControlPrimary5Y() : ModelCommand("read")
{
AddArgument("attr-name", "primary5y");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributePrimary5Y(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute Primary5Intensity
*/
class ReadColorControlPrimary5Intensity : public ModelCommand
{
public:
ReadColorControlPrimary5Intensity() : ModelCommand("read")
{
AddArgument("attr-name", "primary5intensity");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributePrimary5Intensity(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int8uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int8uAttributeCallback>(OnInt8uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute Primary6X
*/
class ReadColorControlPrimary6X : public ModelCommand
{
public:
ReadColorControlPrimary6X() : ModelCommand("read")
{
AddArgument("attr-name", "primary6x");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributePrimary6X(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute Primary6Y
*/
class ReadColorControlPrimary6Y : public ModelCommand
{
public:
ReadColorControlPrimary6Y() : ModelCommand("read")
{
AddArgument("attr-name", "primary6y");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributePrimary6Y(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute Primary6Intensity
*/
class ReadColorControlPrimary6Intensity : public ModelCommand
{
public:
ReadColorControlPrimary6Intensity() : ModelCommand("read")
{
AddArgument("attr-name", "primary6intensity");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributePrimary6Intensity(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int8uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int8uAttributeCallback>(OnInt8uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute WhitePointX
*/
class ReadColorControlWhitePointX : public ModelCommand
{
public:
ReadColorControlWhitePointX() : ModelCommand("read")
{
AddArgument("attr-name", "white-point-x");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeWhitePointX(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
class WriteColorControlWhitePointX : public ModelCommand
{
public:
WriteColorControlWhitePointX() : ModelCommand("write")
{
AddArgument("attr-name", "white-point-x");
AddArgument("attr-value", 0, UINT16_MAX, &mValue);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x01) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.WriteAttributeWhitePointX(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mValue);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint16_t mValue;
};
/*
* Attribute WhitePointY
*/
class ReadColorControlWhitePointY : public ModelCommand
{
public:
ReadColorControlWhitePointY() : ModelCommand("read")
{
AddArgument("attr-name", "white-point-y");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeWhitePointY(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
class WriteColorControlWhitePointY : public ModelCommand
{
public:
WriteColorControlWhitePointY() : ModelCommand("write")
{
AddArgument("attr-name", "white-point-y");
AddArgument("attr-value", 0, UINT16_MAX, &mValue);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x01) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.WriteAttributeWhitePointY(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mValue);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint16_t mValue;
};
/*
* Attribute ColorPointRX
*/
class ReadColorControlColorPointRX : public ModelCommand
{
public:
ReadColorControlColorPointRX() : ModelCommand("read")
{
AddArgument("attr-name", "color-point-rx");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeColorPointRX(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
class WriteColorControlColorPointRX : public ModelCommand
{
public:
WriteColorControlColorPointRX() : ModelCommand("write")
{
AddArgument("attr-name", "color-point-rx");
AddArgument("attr-value", 0, UINT16_MAX, &mValue);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x01) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.WriteAttributeColorPointRX(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mValue);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint16_t mValue;
};
/*
* Attribute ColorPointRY
*/
class ReadColorControlColorPointRY : public ModelCommand
{
public:
ReadColorControlColorPointRY() : ModelCommand("read")
{
AddArgument("attr-name", "color-point-ry");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeColorPointRY(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
class WriteColorControlColorPointRY : public ModelCommand
{
public:
WriteColorControlColorPointRY() : ModelCommand("write")
{
AddArgument("attr-name", "color-point-ry");
AddArgument("attr-value", 0, UINT16_MAX, &mValue);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x01) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.WriteAttributeColorPointRY(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mValue);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint16_t mValue;
};
/*
* Attribute ColorPointRIntensity
*/
class ReadColorControlColorPointRIntensity : public ModelCommand
{
public:
ReadColorControlColorPointRIntensity() : ModelCommand("read")
{
AddArgument("attr-name", "color-point-rintensity");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeColorPointRIntensity(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int8uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int8uAttributeCallback>(OnInt8uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
class WriteColorControlColorPointRIntensity : public ModelCommand
{
public:
WriteColorControlColorPointRIntensity() : ModelCommand("write")
{
AddArgument("attr-name", "color-point-rintensity");
AddArgument("attr-value", 0, UINT8_MAX, &mValue);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x01) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.WriteAttributeColorPointRIntensity(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mValue);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint8_t mValue;
};
/*
* Attribute ColorPointGX
*/
class ReadColorControlColorPointGX : public ModelCommand
{
public:
ReadColorControlColorPointGX() : ModelCommand("read")
{
AddArgument("attr-name", "color-point-gx");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeColorPointGX(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
class WriteColorControlColorPointGX : public ModelCommand
{
public:
WriteColorControlColorPointGX() : ModelCommand("write")
{
AddArgument("attr-name", "color-point-gx");
AddArgument("attr-value", 0, UINT16_MAX, &mValue);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x01) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.WriteAttributeColorPointGX(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mValue);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint16_t mValue;
};
/*
* Attribute ColorPointGY
*/
class ReadColorControlColorPointGY : public ModelCommand
{
public:
ReadColorControlColorPointGY() : ModelCommand("read")
{
AddArgument("attr-name", "color-point-gy");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeColorPointGY(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
class WriteColorControlColorPointGY : public ModelCommand
{
public:
WriteColorControlColorPointGY() : ModelCommand("write")
{
AddArgument("attr-name", "color-point-gy");
AddArgument("attr-value", 0, UINT16_MAX, &mValue);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x01) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.WriteAttributeColorPointGY(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mValue);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint16_t mValue;
};
/*
* Attribute ColorPointGIntensity
*/
class ReadColorControlColorPointGIntensity : public ModelCommand
{
public:
ReadColorControlColorPointGIntensity() : ModelCommand("read")
{
AddArgument("attr-name", "color-point-gintensity");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeColorPointGIntensity(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int8uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int8uAttributeCallback>(OnInt8uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
class WriteColorControlColorPointGIntensity : public ModelCommand
{
public:
WriteColorControlColorPointGIntensity() : ModelCommand("write")
{
AddArgument("attr-name", "color-point-gintensity");
AddArgument("attr-value", 0, UINT8_MAX, &mValue);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x01) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.WriteAttributeColorPointGIntensity(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mValue);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint8_t mValue;
};
/*
* Attribute ColorPointBX
*/
class ReadColorControlColorPointBX : public ModelCommand
{
public:
ReadColorControlColorPointBX() : ModelCommand("read")
{
AddArgument("attr-name", "color-point-bx");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeColorPointBX(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
class WriteColorControlColorPointBX : public ModelCommand
{
public:
WriteColorControlColorPointBX() : ModelCommand("write")
{
AddArgument("attr-name", "color-point-bx");
AddArgument("attr-value", 0, UINT16_MAX, &mValue);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x01) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.WriteAttributeColorPointBX(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mValue);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint16_t mValue;
};
/*
* Attribute ColorPointBY
*/
class ReadColorControlColorPointBY : public ModelCommand
{
public:
ReadColorControlColorPointBY() : ModelCommand("read")
{
AddArgument("attr-name", "color-point-by");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeColorPointBY(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
class WriteColorControlColorPointBY : public ModelCommand
{
public:
WriteColorControlColorPointBY() : ModelCommand("write")
{
AddArgument("attr-name", "color-point-by");
AddArgument("attr-value", 0, UINT16_MAX, &mValue);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x01) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.WriteAttributeColorPointBY(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mValue);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint16_t mValue;
};
/*
* Attribute ColorPointBIntensity
*/
class ReadColorControlColorPointBIntensity : public ModelCommand
{
public:
ReadColorControlColorPointBIntensity() : ModelCommand("read")
{
AddArgument("attr-name", "color-point-bintensity");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeColorPointBIntensity(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int8uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int8uAttributeCallback>(OnInt8uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
class WriteColorControlColorPointBIntensity : public ModelCommand
{
public:
WriteColorControlColorPointBIntensity() : ModelCommand("write")
{
AddArgument("attr-name", "color-point-bintensity");
AddArgument("attr-value", 0, UINT8_MAX, &mValue);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x01) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.WriteAttributeColorPointBIntensity(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mValue);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint8_t mValue;
};
/*
* Attribute EnhancedCurrentHue
*/
class ReadColorControlEnhancedCurrentHue : public ModelCommand
{
public:
ReadColorControlEnhancedCurrentHue() : ModelCommand("read")
{
AddArgument("attr-name", "enhanced-current-hue");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeEnhancedCurrentHue(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute EnhancedColorMode
*/
class ReadColorControlEnhancedColorMode : public ModelCommand
{
public:
ReadColorControlEnhancedColorMode() : ModelCommand("read")
{
AddArgument("attr-name", "enhanced-color-mode");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeEnhancedColorMode(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int8uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int8uAttributeCallback>(OnInt8uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute ColorLoopActive
*/
class ReadColorControlColorLoopActive : public ModelCommand
{
public:
ReadColorControlColorLoopActive() : ModelCommand("read")
{
AddArgument("attr-name", "color-loop-active");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeColorLoopActive(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int8uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int8uAttributeCallback>(OnInt8uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute ColorLoopDirection
*/
class ReadColorControlColorLoopDirection : public ModelCommand
{
public:
ReadColorControlColorLoopDirection() : ModelCommand("read")
{
AddArgument("attr-name", "color-loop-direction");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeColorLoopDirection(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int8uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int8uAttributeCallback>(OnInt8uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute ColorLoopTime
*/
class ReadColorControlColorLoopTime : public ModelCommand
{
public:
ReadColorControlColorLoopTime() : ModelCommand("read")
{
AddArgument("attr-name", "color-loop-time");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeColorLoopTime(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute ColorCapabilities
*/
class ReadColorControlColorCapabilities : public ModelCommand
{
public:
ReadColorControlColorCapabilities() : ModelCommand("read")
{
AddArgument("attr-name", "color-capabilities");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeColorCapabilities(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute ColorTempPhysicalMin
*/
class ReadColorControlColorTempPhysicalMin : public ModelCommand
{
public:
ReadColorControlColorTempPhysicalMin() : ModelCommand("read")
{
AddArgument("attr-name", "color-temp-physical-min");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeColorTempPhysicalMin(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute ColorTempPhysicalMax
*/
class ReadColorControlColorTempPhysicalMax : public ModelCommand
{
public:
ReadColorControlColorTempPhysicalMax() : ModelCommand("read")
{
AddArgument("attr-name", "color-temp-physical-max");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeColorTempPhysicalMax(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute CoupleColorTempToLevelMinMireds
*/
class ReadColorControlCoupleColorTempToLevelMinMireds : public ModelCommand
{
public:
ReadColorControlCoupleColorTempToLevelMinMireds() : ModelCommand("read")
{
AddArgument("attr-name", "couple-color-temp-to-level-min-mireds");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeCoupleColorTempToLevelMinMireds(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute StartUpColorTemperatureMireds
*/
class ReadColorControlStartUpColorTemperatureMireds : public ModelCommand
{
public:
ReadColorControlStartUpColorTemperatureMireds() : ModelCommand("read")
{
AddArgument("attr-name", "start-up-color-temperature-mireds");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeStartUpColorTemperatureMireds(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
class WriteColorControlStartUpColorTemperatureMireds : public ModelCommand
{
public:
WriteColorControlStartUpColorTemperatureMireds() : ModelCommand("write")
{
AddArgument("attr-name", "start-up-color-temperature-mireds");
AddArgument("attr-value", 0, UINT16_MAX, &mValue);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x01) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.WriteAttributeStartUpColorTemperatureMireds(onSuccessCallback->Cancel(), onFailureCallback->Cancel(),
mValue);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint16_t mValue;
};
/*
* Attribute ClusterRevision
*/
class ReadColorControlClusterRevision : public ModelCommand
{
public:
ReadColorControlClusterRevision() : ModelCommand("read")
{
AddArgument("attr-name", "cluster-revision");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0300) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ColorControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeClusterRevision(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*----------------------------------------------------------------------------*\
| Cluster ContentLaunch | 0xF002 |
|------------------------------------------------------------------------------|
| Commands: | |
| * LaunchContent | 0x00 |
| * LaunchURL | 0x01 |
|------------------------------------------------------------------------------|
| Attributes: | |
| * ClusterRevision | 0xFFFD |
\*----------------------------------------------------------------------------*/
/*
* Command LaunchContent
*/
class ContentLaunchLaunchContent : public ModelCommand
{
public:
ContentLaunchLaunchContent() : ModelCommand("launch-content") { ModelCommand::AddArguments(); }
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0xF002) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ContentLaunchCluster cluster;
cluster.Associate(device, endpointId);
return cluster.LaunchContent(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<ContentLaunchClusterLaunchContentResponseCallback> * onSuccessCallback =
new chip::Callback::Callback<ContentLaunchClusterLaunchContentResponseCallback>(OnContentLaunchClusterLaunchContentResponse,
this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Command LaunchURL
*/
class ContentLaunchLaunchURL : public ModelCommand
{
public:
ContentLaunchLaunchURL() : ModelCommand("launch-url") { ModelCommand::AddArguments(); }
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0xF002) command (0x01) on endpoint %" PRIu16, endpointId);
chip::Controller::ContentLaunchCluster cluster;
cluster.Associate(device, endpointId);
return cluster.LaunchURL(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<ContentLaunchClusterLaunchURLResponseCallback> * onSuccessCallback =
new chip::Callback::Callback<ContentLaunchClusterLaunchURLResponseCallback>(OnContentLaunchClusterLaunchURLResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Discover Attributes
*/
class DiscoverContentLaunchAttributes : public ModelCommand
{
public:
DiscoverContentLaunchAttributes() : ModelCommand("discover") { ModelCommand::AddArguments(); }
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0000) command (0x0C) on endpoint %" PRIu16, endpointId);
chip::Controller::ContentLaunchCluster cluster;
cluster.Associate(device, endpointId);
return cluster.DiscoverAttributes(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute ClusterRevision
*/
class ReadContentLaunchClusterRevision : public ModelCommand
{
public:
ReadContentLaunchClusterRevision() : ModelCommand("read")
{
AddArgument("attr-name", "cluster-revision");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0xF002) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ContentLaunchCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeClusterRevision(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*----------------------------------------------------------------------------*\
| Cluster DoorLock | 0x0101 |
|------------------------------------------------------------------------------|
| Commands: | |
| * ClearAllPins | 0x08 |
| * ClearAllRfids | 0x19 |
| * ClearHolidaySchedule | 0x13 |
| * ClearPin | 0x07 |
| * ClearRfid | 0x18 |
| * ClearWeekdaySchedule | 0x0D |
| * ClearYeardaySchedule | 0x10 |
| * GetHolidaySchedule | 0x12 |
| * GetLogRecord | 0x04 |
| * GetPin | 0x06 |
| * GetRfid | 0x17 |
| * GetUserType | 0x15 |
| * GetWeekdaySchedule | 0x0C |
| * GetYeardaySchedule | 0x0F |
| * LockDoor | 0x00 |
| * SetHolidaySchedule | 0x11 |
| * SetPin | 0x05 |
| * SetRfid | 0x16 |
| * SetUserType | 0x14 |
| * SetWeekdaySchedule | 0x0B |
| * SetYeardaySchedule | 0x0E |
| * UnlockDoor | 0x01 |
| * UnlockWithTimeout | 0x03 |
|------------------------------------------------------------------------------|
| Attributes: | |
| * LockState | 0x0000 |
| * LockType | 0x0001 |
| * ActuatorEnabled | 0x0002 |
| * ClusterRevision | 0xFFFD |
\*----------------------------------------------------------------------------*/
/*
* Command ClearAllPins
*/
class DoorLockClearAllPins : public ModelCommand
{
public:
DoorLockClearAllPins() : ModelCommand("clear-all-pins") { ModelCommand::AddArguments(); }
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0101) command (0x08) on endpoint %" PRIu16, endpointId);
chip::Controller::DoorLockCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ClearAllPins(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<DoorLockClusterClearAllPinsResponseCallback> * onSuccessCallback =
new chip::Callback::Callback<DoorLockClusterClearAllPinsResponseCallback>(OnDoorLockClusterClearAllPinsResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Command ClearAllRfids
*/
class DoorLockClearAllRfids : public ModelCommand
{
public:
DoorLockClearAllRfids() : ModelCommand("clear-all-rfids") { ModelCommand::AddArguments(); }
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0101) command (0x19) on endpoint %" PRIu16, endpointId);
chip::Controller::DoorLockCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ClearAllRfids(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<DoorLockClusterClearAllRfidsResponseCallback> * onSuccessCallback =
new chip::Callback::Callback<DoorLockClusterClearAllRfidsResponseCallback>(OnDoorLockClusterClearAllRfidsResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Command ClearHolidaySchedule
*/
class DoorLockClearHolidaySchedule : public ModelCommand
{
public:
DoorLockClearHolidaySchedule() : ModelCommand("clear-holiday-schedule")
{
AddArgument("scheduleId", 0, UINT8_MAX, &mScheduleId);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0101) command (0x13) on endpoint %" PRIu16, endpointId);
chip::Controller::DoorLockCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ClearHolidaySchedule(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mScheduleId);
}
private:
chip::Callback::Callback<DoorLockClusterClearHolidayScheduleResponseCallback> * onSuccessCallback =
new chip::Callback::Callback<DoorLockClusterClearHolidayScheduleResponseCallback>(
OnDoorLockClusterClearHolidayScheduleResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint8_t mScheduleId;
};
/*
* Command ClearPin
*/
class DoorLockClearPin : public ModelCommand
{
public:
DoorLockClearPin() : ModelCommand("clear-pin")
{
AddArgument("userId", 0, UINT16_MAX, &mUserId);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0101) command (0x07) on endpoint %" PRIu16, endpointId);
chip::Controller::DoorLockCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ClearPin(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mUserId);
}
private:
chip::Callback::Callback<DoorLockClusterClearPinResponseCallback> * onSuccessCallback =
new chip::Callback::Callback<DoorLockClusterClearPinResponseCallback>(OnDoorLockClusterClearPinResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint16_t mUserId;
};
/*
* Command ClearRfid
*/
class DoorLockClearRfid : public ModelCommand
{
public:
DoorLockClearRfid() : ModelCommand("clear-rfid")
{
AddArgument("userId", 0, UINT16_MAX, &mUserId);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0101) command (0x18) on endpoint %" PRIu16, endpointId);
chip::Controller::DoorLockCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ClearRfid(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mUserId);
}
private:
chip::Callback::Callback<DoorLockClusterClearRfidResponseCallback> * onSuccessCallback =
new chip::Callback::Callback<DoorLockClusterClearRfidResponseCallback>(OnDoorLockClusterClearRfidResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint16_t mUserId;
};
/*
* Command ClearWeekdaySchedule
*/
class DoorLockClearWeekdaySchedule : public ModelCommand
{
public:
DoorLockClearWeekdaySchedule() : ModelCommand("clear-weekday-schedule")
{
AddArgument("scheduleId", 0, UINT8_MAX, &mScheduleId);
AddArgument("userId", 0, UINT16_MAX, &mUserId);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0101) command (0x0D) on endpoint %" PRIu16, endpointId);
chip::Controller::DoorLockCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ClearWeekdaySchedule(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mScheduleId, mUserId);
}
private:
chip::Callback::Callback<DoorLockClusterClearWeekdayScheduleResponseCallback> * onSuccessCallback =
new chip::Callback::Callback<DoorLockClusterClearWeekdayScheduleResponseCallback>(
OnDoorLockClusterClearWeekdayScheduleResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint8_t mScheduleId;
uint16_t mUserId;
};
/*
* Command ClearYeardaySchedule
*/
class DoorLockClearYeardaySchedule : public ModelCommand
{
public:
DoorLockClearYeardaySchedule() : ModelCommand("clear-yearday-schedule")
{
AddArgument("scheduleId", 0, UINT8_MAX, &mScheduleId);
AddArgument("userId", 0, UINT16_MAX, &mUserId);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0101) command (0x10) on endpoint %" PRIu16, endpointId);
chip::Controller::DoorLockCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ClearYeardaySchedule(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mScheduleId, mUserId);
}
private:
chip::Callback::Callback<DoorLockClusterClearYeardayScheduleResponseCallback> * onSuccessCallback =
new chip::Callback::Callback<DoorLockClusterClearYeardayScheduleResponseCallback>(
OnDoorLockClusterClearYeardayScheduleResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint8_t mScheduleId;
uint16_t mUserId;
};
/*
* Command GetHolidaySchedule
*/
class DoorLockGetHolidaySchedule : public ModelCommand
{
public:
DoorLockGetHolidaySchedule() : ModelCommand("get-holiday-schedule")
{
AddArgument("scheduleId", 0, UINT8_MAX, &mScheduleId);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0101) command (0x12) on endpoint %" PRIu16, endpointId);
chip::Controller::DoorLockCluster cluster;
cluster.Associate(device, endpointId);
return cluster.GetHolidaySchedule(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mScheduleId);
}
private:
chip::Callback::Callback<DoorLockClusterGetHolidayScheduleResponseCallback> * onSuccessCallback =
new chip::Callback::Callback<DoorLockClusterGetHolidayScheduleResponseCallback>(OnDoorLockClusterGetHolidayScheduleResponse,
this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint8_t mScheduleId;
};
/*
* Command GetLogRecord
*/
class DoorLockGetLogRecord : public ModelCommand
{
public:
DoorLockGetLogRecord() : ModelCommand("get-log-record")
{
AddArgument("logIndex", 0, UINT16_MAX, &mLogIndex);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0101) command (0x04) on endpoint %" PRIu16, endpointId);
chip::Controller::DoorLockCluster cluster;
cluster.Associate(device, endpointId);
return cluster.GetLogRecord(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mLogIndex);
}
private:
chip::Callback::Callback<DoorLockClusterGetLogRecordResponseCallback> * onSuccessCallback =
new chip::Callback::Callback<DoorLockClusterGetLogRecordResponseCallback>(OnDoorLockClusterGetLogRecordResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint16_t mLogIndex;
};
/*
* Command GetPin
*/
class DoorLockGetPin : public ModelCommand
{
public:
DoorLockGetPin() : ModelCommand("get-pin")
{
AddArgument("userId", 0, UINT16_MAX, &mUserId);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0101) command (0x06) on endpoint %" PRIu16, endpointId);
chip::Controller::DoorLockCluster cluster;
cluster.Associate(device, endpointId);
return cluster.GetPin(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mUserId);
}
private:
chip::Callback::Callback<DoorLockClusterGetPinResponseCallback> * onSuccessCallback =
new chip::Callback::Callback<DoorLockClusterGetPinResponseCallback>(OnDoorLockClusterGetPinResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint16_t mUserId;
};
/*
* Command GetRfid
*/
class DoorLockGetRfid : public ModelCommand
{
public:
DoorLockGetRfid() : ModelCommand("get-rfid")
{
AddArgument("userId", 0, UINT16_MAX, &mUserId);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0101) command (0x17) on endpoint %" PRIu16, endpointId);
chip::Controller::DoorLockCluster cluster;
cluster.Associate(device, endpointId);
return cluster.GetRfid(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mUserId);
}
private:
chip::Callback::Callback<DoorLockClusterGetRfidResponseCallback> * onSuccessCallback =
new chip::Callback::Callback<DoorLockClusterGetRfidResponseCallback>(OnDoorLockClusterGetRfidResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint16_t mUserId;
};
/*
* Command GetUserType
*/
class DoorLockGetUserType : public ModelCommand
{
public:
DoorLockGetUserType() : ModelCommand("get-user-type")
{
AddArgument("userId", 0, UINT16_MAX, &mUserId);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0101) command (0x15) on endpoint %" PRIu16, endpointId);
chip::Controller::DoorLockCluster cluster;
cluster.Associate(device, endpointId);
return cluster.GetUserType(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mUserId);
}
private:
chip::Callback::Callback<DoorLockClusterGetUserTypeResponseCallback> * onSuccessCallback =
new chip::Callback::Callback<DoorLockClusterGetUserTypeResponseCallback>(OnDoorLockClusterGetUserTypeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint16_t mUserId;
};
/*
* Command GetWeekdaySchedule
*/
class DoorLockGetWeekdaySchedule : public ModelCommand
{
public:
DoorLockGetWeekdaySchedule() : ModelCommand("get-weekday-schedule")
{
AddArgument("scheduleId", 0, UINT8_MAX, &mScheduleId);
AddArgument("userId", 0, UINT16_MAX, &mUserId);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0101) command (0x0C) on endpoint %" PRIu16, endpointId);
chip::Controller::DoorLockCluster cluster;
cluster.Associate(device, endpointId);
return cluster.GetWeekdaySchedule(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mScheduleId, mUserId);
}
private:
chip::Callback::Callback<DoorLockClusterGetWeekdayScheduleResponseCallback> * onSuccessCallback =
new chip::Callback::Callback<DoorLockClusterGetWeekdayScheduleResponseCallback>(OnDoorLockClusterGetWeekdayScheduleResponse,
this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint8_t mScheduleId;
uint16_t mUserId;
};
/*
* Command GetYeardaySchedule
*/
class DoorLockGetYeardaySchedule : public ModelCommand
{
public:
DoorLockGetYeardaySchedule() : ModelCommand("get-yearday-schedule")
{
AddArgument("scheduleId", 0, UINT8_MAX, &mScheduleId);
AddArgument("userId", 0, UINT16_MAX, &mUserId);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0101) command (0x0F) on endpoint %" PRIu16, endpointId);
chip::Controller::DoorLockCluster cluster;
cluster.Associate(device, endpointId);
return cluster.GetYeardaySchedule(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mScheduleId, mUserId);
}
private:
chip::Callback::Callback<DoorLockClusterGetYeardayScheduleResponseCallback> * onSuccessCallback =
new chip::Callback::Callback<DoorLockClusterGetYeardayScheduleResponseCallback>(OnDoorLockClusterGetYeardayScheduleResponse,
this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint8_t mScheduleId;
uint16_t mUserId;
};
/*
* Command LockDoor
*/
class DoorLockLockDoor : public ModelCommand
{
public:
DoorLockLockDoor() : ModelCommand("lock-door")
{
AddArgument("pin", &mPin);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0101) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::DoorLockCluster cluster;
cluster.Associate(device, endpointId);
return cluster.LockDoor(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mPin);
}
private:
chip::Callback::Callback<DoorLockClusterLockDoorResponseCallback> * onSuccessCallback =
new chip::Callback::Callback<DoorLockClusterLockDoorResponseCallback>(OnDoorLockClusterLockDoorResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
char * mPin;
};
/*
* Command SetHolidaySchedule
*/
class DoorLockSetHolidaySchedule : public ModelCommand
{
public:
DoorLockSetHolidaySchedule() : ModelCommand("set-holiday-schedule")
{
AddArgument("scheduleId", 0, UINT8_MAX, &mScheduleId);
AddArgument("localStartTime", 0, UINT32_MAX, &mLocalStartTime);
AddArgument("localEndTime", 0, UINT32_MAX, &mLocalEndTime);
AddArgument("operatingModeDuringHoliday", 0, UINT8_MAX, &mOperatingModeDuringHoliday);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0101) command (0x11) on endpoint %" PRIu16, endpointId);
chip::Controller::DoorLockCluster cluster;
cluster.Associate(device, endpointId);
return cluster.SetHolidaySchedule(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mScheduleId, mLocalStartTime,
mLocalEndTime, mOperatingModeDuringHoliday);
}
private:
chip::Callback::Callback<DoorLockClusterSetHolidayScheduleResponseCallback> * onSuccessCallback =
new chip::Callback::Callback<DoorLockClusterSetHolidayScheduleResponseCallback>(OnDoorLockClusterSetHolidayScheduleResponse,
this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint8_t mScheduleId;
uint32_t mLocalStartTime;
uint32_t mLocalEndTime;
uint8_t mOperatingModeDuringHoliday;
};
/*
* Command SetPin
*/
class DoorLockSetPin : public ModelCommand
{
public:
DoorLockSetPin() : ModelCommand("set-pin")
{
AddArgument("userId", 0, UINT16_MAX, &mUserId);
AddArgument("userStatus", 0, UINT8_MAX, &mUserStatus);
AddArgument("userType", 0, UINT8_MAX, &mUserType);
AddArgument("pin", &mPin);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0101) command (0x05) on endpoint %" PRIu16, endpointId);
chip::Controller::DoorLockCluster cluster;
cluster.Associate(device, endpointId);
return cluster.SetPin(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mUserId, mUserStatus, mUserType, mPin);
}
private:
chip::Callback::Callback<DoorLockClusterSetPinResponseCallback> * onSuccessCallback =
new chip::Callback::Callback<DoorLockClusterSetPinResponseCallback>(OnDoorLockClusterSetPinResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint16_t mUserId;
uint8_t mUserStatus;
uint8_t mUserType;
char * mPin;
};
/*
* Command SetRfid
*/
class DoorLockSetRfid : public ModelCommand
{
public:
DoorLockSetRfid() : ModelCommand("set-rfid")
{
AddArgument("userId", 0, UINT16_MAX, &mUserId);
AddArgument("userStatus", 0, UINT8_MAX, &mUserStatus);
AddArgument("userType", 0, UINT8_MAX, &mUserType);
AddArgument("id", &mId);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0101) command (0x16) on endpoint %" PRIu16, endpointId);
chip::Controller::DoorLockCluster cluster;
cluster.Associate(device, endpointId);
return cluster.SetRfid(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mUserId, mUserStatus, mUserType, mId);
}
private:
chip::Callback::Callback<DoorLockClusterSetRfidResponseCallback> * onSuccessCallback =
new chip::Callback::Callback<DoorLockClusterSetRfidResponseCallback>(OnDoorLockClusterSetRfidResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint16_t mUserId;
uint8_t mUserStatus;
uint8_t mUserType;
char * mId;
};
/*
* Command SetUserType
*/
class DoorLockSetUserType : public ModelCommand
{
public:
DoorLockSetUserType() : ModelCommand("set-user-type")
{
AddArgument("userId", 0, UINT16_MAX, &mUserId);
AddArgument("userType", 0, UINT8_MAX, &mUserType);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0101) command (0x14) on endpoint %" PRIu16, endpointId);
chip::Controller::DoorLockCluster cluster;
cluster.Associate(device, endpointId);
return cluster.SetUserType(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mUserId, mUserType);
}
private:
chip::Callback::Callback<DoorLockClusterSetUserTypeResponseCallback> * onSuccessCallback =
new chip::Callback::Callback<DoorLockClusterSetUserTypeResponseCallback>(OnDoorLockClusterSetUserTypeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint16_t mUserId;
uint8_t mUserType;
};
/*
* Command SetWeekdaySchedule
*/
class DoorLockSetWeekdaySchedule : public ModelCommand
{
public:
DoorLockSetWeekdaySchedule() : ModelCommand("set-weekday-schedule")
{
AddArgument("scheduleId", 0, UINT8_MAX, &mScheduleId);
AddArgument("userId", 0, UINT16_MAX, &mUserId);
AddArgument("daysMask", 0, UINT8_MAX, &mDaysMask);
AddArgument("startHour", 0, UINT8_MAX, &mStartHour);
AddArgument("startMinute", 0, UINT8_MAX, &mStartMinute);
AddArgument("endHour", 0, UINT8_MAX, &mEndHour);
AddArgument("endMinute", 0, UINT8_MAX, &mEndMinute);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0101) command (0x0B) on endpoint %" PRIu16, endpointId);
chip::Controller::DoorLockCluster cluster;
cluster.Associate(device, endpointId);
return cluster.SetWeekdaySchedule(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mScheduleId, mUserId, mDaysMask,
mStartHour, mStartMinute, mEndHour, mEndMinute);
}
private:
chip::Callback::Callback<DoorLockClusterSetWeekdayScheduleResponseCallback> * onSuccessCallback =
new chip::Callback::Callback<DoorLockClusterSetWeekdayScheduleResponseCallback>(OnDoorLockClusterSetWeekdayScheduleResponse,
this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint8_t mScheduleId;
uint16_t mUserId;
uint8_t mDaysMask;
uint8_t mStartHour;
uint8_t mStartMinute;
uint8_t mEndHour;
uint8_t mEndMinute;
};
/*
* Command SetYeardaySchedule
*/
class DoorLockSetYeardaySchedule : public ModelCommand
{
public:
DoorLockSetYeardaySchedule() : ModelCommand("set-yearday-schedule")
{
AddArgument("scheduleId", 0, UINT8_MAX, &mScheduleId);
AddArgument("userId", 0, UINT16_MAX, &mUserId);
AddArgument("localStartTime", 0, UINT32_MAX, &mLocalStartTime);
AddArgument("localEndTime", 0, UINT32_MAX, &mLocalEndTime);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0101) command (0x0E) on endpoint %" PRIu16, endpointId);
chip::Controller::DoorLockCluster cluster;
cluster.Associate(device, endpointId);
return cluster.SetYeardaySchedule(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mScheduleId, mUserId,
mLocalStartTime, mLocalEndTime);
}
private:
chip::Callback::Callback<DoorLockClusterSetYeardayScheduleResponseCallback> * onSuccessCallback =
new chip::Callback::Callback<DoorLockClusterSetYeardayScheduleResponseCallback>(OnDoorLockClusterSetYeardayScheduleResponse,
this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint8_t mScheduleId;
uint16_t mUserId;
uint32_t mLocalStartTime;
uint32_t mLocalEndTime;
};
/*
* Command UnlockDoor
*/
class DoorLockUnlockDoor : public ModelCommand
{
public:
DoorLockUnlockDoor() : ModelCommand("unlock-door")
{
AddArgument("pin", &mPin);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0101) command (0x01) on endpoint %" PRIu16, endpointId);
chip::Controller::DoorLockCluster cluster;
cluster.Associate(device, endpointId);
return cluster.UnlockDoor(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mPin);
}
private:
chip::Callback::Callback<DoorLockClusterUnlockDoorResponseCallback> * onSuccessCallback =
new chip::Callback::Callback<DoorLockClusterUnlockDoorResponseCallback>(OnDoorLockClusterUnlockDoorResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
char * mPin;
};
/*
* Command UnlockWithTimeout
*/
class DoorLockUnlockWithTimeout : public ModelCommand
{
public:
DoorLockUnlockWithTimeout() : ModelCommand("unlock-with-timeout")
{
AddArgument("timeoutInSeconds", 0, UINT16_MAX, &mTimeoutInSeconds);
AddArgument("pin", &mPin);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0101) command (0x03) on endpoint %" PRIu16, endpointId);
chip::Controller::DoorLockCluster cluster;
cluster.Associate(device, endpointId);
return cluster.UnlockWithTimeout(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mTimeoutInSeconds, mPin);
}
private:
chip::Callback::Callback<DoorLockClusterUnlockWithTimeoutResponseCallback> * onSuccessCallback =
new chip::Callback::Callback<DoorLockClusterUnlockWithTimeoutResponseCallback>(OnDoorLockClusterUnlockWithTimeoutResponse,
this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint16_t mTimeoutInSeconds;
char * mPin;
};
/*
* Discover Attributes
*/
class DiscoverDoorLockAttributes : public ModelCommand
{
public:
DiscoverDoorLockAttributes() : ModelCommand("discover") { ModelCommand::AddArguments(); }
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0000) command (0x0C) on endpoint %" PRIu16, endpointId);
chip::Controller::DoorLockCluster cluster;
cluster.Associate(device, endpointId);
return cluster.DiscoverAttributes(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute LockState
*/
class ReadDoorLockLockState : public ModelCommand
{
public:
ReadDoorLockLockState() : ModelCommand("read")
{
AddArgument("attr-name", "lock-state");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0101) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::DoorLockCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeLockState(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int8uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int8uAttributeCallback>(OnInt8uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
class ReportDoorLockLockState : public ModelCommand
{
public:
ReportDoorLockLockState() : ModelCommand("report")
{
AddArgument("attr-name", "lock-state");
AddArgument("min-interval", 0, UINT16_MAX, &mMinInterval);
AddArgument("max-interval", 0, UINT16_MAX, &mMaxInterval);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0101) command (0x06) on endpoint %" PRIu16, endpointId);
chip::Controller::DoorLockCluster cluster;
cluster.Associate(device, endpointId);
CHIP_ERROR err = cluster.ReportAttributeLockState(onReportCallback->Cancel());
if (err != CHIP_NO_ERROR)
{
return err;
}
return cluster.ConfigureAttributeLockState(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mMinInterval,
mMaxInterval);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
chip::Callback::Callback<Int8uAttributeCallback> * onReportCallback =
new chip::Callback::Callback<Int8uAttributeCallback>(OnInt8uAttributeResponse, this);
uint16_t mMinInterval;
uint16_t mMaxInterval;
};
/*
* Attribute LockType
*/
class ReadDoorLockLockType : public ModelCommand
{
public:
ReadDoorLockLockType() : ModelCommand("read")
{
AddArgument("attr-name", "lock-type");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0101) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::DoorLockCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeLockType(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int8uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int8uAttributeCallback>(OnInt8uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute ActuatorEnabled
*/
class ReadDoorLockActuatorEnabled : public ModelCommand
{
public:
ReadDoorLockActuatorEnabled() : ModelCommand("read")
{
AddArgument("attr-name", "actuator-enabled");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0101) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::DoorLockCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeActuatorEnabled(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<BooleanAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<BooleanAttributeCallback>(OnBooleanAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute ClusterRevision
*/
class ReadDoorLockClusterRevision : public ModelCommand
{
public:
ReadDoorLockClusterRevision() : ModelCommand("read")
{
AddArgument("attr-name", "cluster-revision");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0101) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::DoorLockCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeClusterRevision(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*----------------------------------------------------------------------------*\
| Cluster GeneralCommissioning | 0x0030 |
|------------------------------------------------------------------------------|
| Commands: | |
| * ArmFailSafe | 0x02 |
| * CommissioningComplete | 0x06 |
| * SetFabric | 0x00 |
|------------------------------------------------------------------------------|
| Attributes: | |
| * FabricId | 0x0000 |
| * Breadcrumb | 0x0001 |
| * ClusterRevision | 0xFFFD |
\*----------------------------------------------------------------------------*/
/*
* Command ArmFailSafe
*/
class GeneralCommissioningArmFailSafe : public ModelCommand
{
public:
GeneralCommissioningArmFailSafe() : ModelCommand("arm-fail-safe")
{
AddArgument("expiryLengthSeconds", 0, UINT16_MAX, &mExpiryLengthSeconds);
AddArgument("breadcrumb", 0, UINT64_MAX, &mBreadcrumb);
AddArgument("timeoutMs", 0, UINT32_MAX, &mTimeoutMs);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0030) command (0x02) on endpoint %" PRIu16, endpointId);
chip::Controller::GeneralCommissioningCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ArmFailSafe(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mExpiryLengthSeconds, mBreadcrumb,
mTimeoutMs);
}
private:
chip::Callback::Callback<GeneralCommissioningClusterArmFailSafeResponseCallback> * onSuccessCallback =
new chip::Callback::Callback<GeneralCommissioningClusterArmFailSafeResponseCallback>(
OnGeneralCommissioningClusterArmFailSafeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint16_t mExpiryLengthSeconds;
uint64_t mBreadcrumb;
uint32_t mTimeoutMs;
};
/*
* Command CommissioningComplete
*/
class GeneralCommissioningCommissioningComplete : public ModelCommand
{
public:
GeneralCommissioningCommissioningComplete() : ModelCommand("commissioning-complete") { ModelCommand::AddArguments(); }
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0030) command (0x06) on endpoint %" PRIu16, endpointId);
chip::Controller::GeneralCommissioningCluster cluster;
cluster.Associate(device, endpointId);
return cluster.CommissioningComplete(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<GeneralCommissioningClusterCommissioningCompleteResponseCallback> * onSuccessCallback =
new chip::Callback::Callback<GeneralCommissioningClusterCommissioningCompleteResponseCallback>(
OnGeneralCommissioningClusterCommissioningCompleteResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Command SetFabric
*/
class GeneralCommissioningSetFabric : public ModelCommand
{
public:
GeneralCommissioningSetFabric() : ModelCommand("set-fabric")
{
AddArgument("fabricId", &mFabricId);
AddArgument("fabricSecret", &mFabricSecret);
AddArgument("breadcrumb", 0, UINT64_MAX, &mBreadcrumb);
AddArgument("timeoutMs", 0, UINT32_MAX, &mTimeoutMs);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0030) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::GeneralCommissioningCluster cluster;
cluster.Associate(device, endpointId);
return cluster.SetFabric(onSuccessCallback->Cancel(), onFailureCallback->Cancel(),
chip::ByteSpan(chip::Uint8::from_char(mFabricId), strlen(mFabricId)),
chip::ByteSpan(chip::Uint8::from_char(mFabricSecret), strlen(mFabricSecret)), mBreadcrumb,
mTimeoutMs);
}
private:
chip::Callback::Callback<GeneralCommissioningClusterSetFabricResponseCallback> * onSuccessCallback =
new chip::Callback::Callback<GeneralCommissioningClusterSetFabricResponseCallback>(
OnGeneralCommissioningClusterSetFabricResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
char * mFabricId;
char * mFabricSecret;
uint64_t mBreadcrumb;
uint32_t mTimeoutMs;
};
/*
* Discover Attributes
*/
class DiscoverGeneralCommissioningAttributes : public ModelCommand
{
public:
DiscoverGeneralCommissioningAttributes() : ModelCommand("discover") { ModelCommand::AddArguments(); }
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0000) command (0x0C) on endpoint %" PRIu16, endpointId);
chip::Controller::GeneralCommissioningCluster cluster;
cluster.Associate(device, endpointId);
return cluster.DiscoverAttributes(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute FabricId
*/
class ReadGeneralCommissioningFabricId : public ModelCommand
{
public:
ReadGeneralCommissioningFabricId() : ModelCommand("read")
{
AddArgument("attr-name", "fabric-id");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0030) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::GeneralCommissioningCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeFabricId(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<UnsupportedAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<UnsupportedAttributeCallback>(OnUnsupportedAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute Breadcrumb
*/
class ReadGeneralCommissioningBreadcrumb : public ModelCommand
{
public:
ReadGeneralCommissioningBreadcrumb() : ModelCommand("read")
{
AddArgument("attr-name", "breadcrumb");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0030) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::GeneralCommissioningCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeBreadcrumb(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int64uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int64uAttributeCallback>(OnInt64uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
class WriteGeneralCommissioningBreadcrumb : public ModelCommand
{
public:
WriteGeneralCommissioningBreadcrumb() : ModelCommand("write")
{
AddArgument("attr-name", "breadcrumb");
AddArgument("attr-value", 0, UINT64_MAX, &mValue);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0030) command (0x01) on endpoint %" PRIu16, endpointId);
chip::Controller::GeneralCommissioningCluster cluster;
cluster.Associate(device, endpointId);
return cluster.WriteAttributeBreadcrumb(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mValue);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint64_t mValue;
};
/*
* Attribute ClusterRevision
*/
class ReadGeneralCommissioningClusterRevision : public ModelCommand
{
public:
ReadGeneralCommissioningClusterRevision() : ModelCommand("read")
{
AddArgument("attr-name", "cluster-revision");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0030) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::GeneralCommissioningCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeClusterRevision(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*----------------------------------------------------------------------------*\
| Cluster Groups | 0x0004 |
|------------------------------------------------------------------------------|
| Commands: | |
| * AddGroup | 0x00 |
| * AddGroupIfIdentifying | 0x05 |
| * GetGroupMembership | 0x02 |
| * RemoveAllGroups | 0x04 |
| * RemoveGroup | 0x03 |
| * ViewGroup | 0x01 |
|------------------------------------------------------------------------------|
| Attributes: | |
| * NameSupport | 0x0000 |
| * ClusterRevision | 0xFFFD |
\*----------------------------------------------------------------------------*/
/*
* Command AddGroup
*/
class GroupsAddGroup : public ModelCommand
{
public:
GroupsAddGroup() : ModelCommand("add-group")
{
AddArgument("groupId", 0, UINT16_MAX, &mGroupId);
AddArgument("groupName", &mGroupName);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0004) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::GroupsCluster cluster;
cluster.Associate(device, endpointId);
return cluster.AddGroup(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mGroupId, mGroupName);
}
private:
chip::Callback::Callback<GroupsClusterAddGroupResponseCallback> * onSuccessCallback =
new chip::Callback::Callback<GroupsClusterAddGroupResponseCallback>(OnGroupsClusterAddGroupResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint16_t mGroupId;
char * mGroupName;
};
/*
* Command AddGroupIfIdentifying
*/
class GroupsAddGroupIfIdentifying : public ModelCommand
{
public:
GroupsAddGroupIfIdentifying() : ModelCommand("add-group-if-identifying")
{
AddArgument("groupId", 0, UINT16_MAX, &mGroupId);
AddArgument("groupName", &mGroupName);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0004) command (0x05) on endpoint %" PRIu16, endpointId);
chip::Controller::GroupsCluster cluster;
cluster.Associate(device, endpointId);
return cluster.AddGroupIfIdentifying(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mGroupId, mGroupName);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint16_t mGroupId;
char * mGroupName;
};
/*
* Command GetGroupMembership
*/
class GroupsGetGroupMembership : public ModelCommand
{
public:
GroupsGetGroupMembership() : ModelCommand("get-group-membership")
{
AddArgument("groupCount", 0, UINT8_MAX, &mGroupCount);
AddArgument("groupList", 0, UINT16_MAX, &mGroupList);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0004) command (0x02) on endpoint %" PRIu16, endpointId);
chip::Controller::GroupsCluster cluster;
cluster.Associate(device, endpointId);
return cluster.GetGroupMembership(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mGroupCount, mGroupList);
}
private:
chip::Callback::Callback<GroupsClusterGetGroupMembershipResponseCallback> * onSuccessCallback =
new chip::Callback::Callback<GroupsClusterGetGroupMembershipResponseCallback>(OnGroupsClusterGetGroupMembershipResponse,
this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint8_t mGroupCount;
uint16_t mGroupList;
};
/*
* Command RemoveAllGroups
*/
class GroupsRemoveAllGroups : public ModelCommand
{
public:
GroupsRemoveAllGroups() : ModelCommand("remove-all-groups") { ModelCommand::AddArguments(); }
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0004) command (0x04) on endpoint %" PRIu16, endpointId);
chip::Controller::GroupsCluster cluster;
cluster.Associate(device, endpointId);
return cluster.RemoveAllGroups(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Command RemoveGroup
*/
class GroupsRemoveGroup : public ModelCommand
{
public:
GroupsRemoveGroup() : ModelCommand("remove-group")
{
AddArgument("groupId", 0, UINT16_MAX, &mGroupId);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0004) command (0x03) on endpoint %" PRIu16, endpointId);
chip::Controller::GroupsCluster cluster;
cluster.Associate(device, endpointId);
return cluster.RemoveGroup(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mGroupId);
}
private:
chip::Callback::Callback<GroupsClusterRemoveGroupResponseCallback> * onSuccessCallback =
new chip::Callback::Callback<GroupsClusterRemoveGroupResponseCallback>(OnGroupsClusterRemoveGroupResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint16_t mGroupId;
};
/*
* Command ViewGroup
*/
class GroupsViewGroup : public ModelCommand
{
public:
GroupsViewGroup() : ModelCommand("view-group")
{
AddArgument("groupId", 0, UINT16_MAX, &mGroupId);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0004) command (0x01) on endpoint %" PRIu16, endpointId);
chip::Controller::GroupsCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ViewGroup(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mGroupId);
}
private:
chip::Callback::Callback<GroupsClusterViewGroupResponseCallback> * onSuccessCallback =
new chip::Callback::Callback<GroupsClusterViewGroupResponseCallback>(OnGroupsClusterViewGroupResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint16_t mGroupId;
};
/*
* Discover Attributes
*/
class DiscoverGroupsAttributes : public ModelCommand
{
public:
DiscoverGroupsAttributes() : ModelCommand("discover") { ModelCommand::AddArguments(); }
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0000) command (0x0C) on endpoint %" PRIu16, endpointId);
chip::Controller::GroupsCluster cluster;
cluster.Associate(device, endpointId);
return cluster.DiscoverAttributes(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute NameSupport
*/
class ReadGroupsNameSupport : public ModelCommand
{
public:
ReadGroupsNameSupport() : ModelCommand("read")
{
AddArgument("attr-name", "name-support");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0004) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::GroupsCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeNameSupport(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int8uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int8uAttributeCallback>(OnInt8uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute ClusterRevision
*/
class ReadGroupsClusterRevision : public ModelCommand
{
public:
ReadGroupsClusterRevision() : ModelCommand("read")
{
AddArgument("attr-name", "cluster-revision");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0004) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::GroupsCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeClusterRevision(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*----------------------------------------------------------------------------*\
| Cluster Identify | 0x0003 |
|------------------------------------------------------------------------------|
| Commands: | |
| * Identify | 0x00 |
| * IdentifyQuery | 0x01 |
|------------------------------------------------------------------------------|
| Attributes: | |
| * IdentifyTime | 0x0000 |
| * ClusterRevision | 0xFFFD |
\*----------------------------------------------------------------------------*/
/*
* Command Identify
*/
class IdentifyIdentify : public ModelCommand
{
public:
IdentifyIdentify() : ModelCommand("identify")
{
AddArgument("identifyTime", 0, UINT16_MAX, &mIdentifyTime);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0003) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::IdentifyCluster cluster;
cluster.Associate(device, endpointId);
return cluster.Identify(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mIdentifyTime);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint16_t mIdentifyTime;
};
/*
* Command IdentifyQuery
*/
class IdentifyIdentifyQuery : public ModelCommand
{
public:
IdentifyIdentifyQuery() : ModelCommand("identify-query") { ModelCommand::AddArguments(); }
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0003) command (0x01) on endpoint %" PRIu16, endpointId);
chip::Controller::IdentifyCluster cluster;
cluster.Associate(device, endpointId);
return cluster.IdentifyQuery(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<IdentifyClusterIdentifyQueryResponseCallback> * onSuccessCallback =
new chip::Callback::Callback<IdentifyClusterIdentifyQueryResponseCallback>(OnIdentifyClusterIdentifyQueryResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Discover Attributes
*/
class DiscoverIdentifyAttributes : public ModelCommand
{
public:
DiscoverIdentifyAttributes() : ModelCommand("discover") { ModelCommand::AddArguments(); }
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0000) command (0x0C) on endpoint %" PRIu16, endpointId);
chip::Controller::IdentifyCluster cluster;
cluster.Associate(device, endpointId);
return cluster.DiscoverAttributes(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute IdentifyTime
*/
class ReadIdentifyIdentifyTime : public ModelCommand
{
public:
ReadIdentifyIdentifyTime() : ModelCommand("read")
{
AddArgument("attr-name", "identify-time");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0003) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::IdentifyCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeIdentifyTime(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
class WriteIdentifyIdentifyTime : public ModelCommand
{
public:
WriteIdentifyIdentifyTime() : ModelCommand("write")
{
AddArgument("attr-name", "identify-time");
AddArgument("attr-value", 0, UINT16_MAX, &mValue);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0003) command (0x01) on endpoint %" PRIu16, endpointId);
chip::Controller::IdentifyCluster cluster;
cluster.Associate(device, endpointId);
return cluster.WriteAttributeIdentifyTime(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mValue);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint16_t mValue;
};
/*
* Attribute ClusterRevision
*/
class ReadIdentifyClusterRevision : public ModelCommand
{
public:
ReadIdentifyClusterRevision() : ModelCommand("read")
{
AddArgument("attr-name", "cluster-revision");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0003) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::IdentifyCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeClusterRevision(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*----------------------------------------------------------------------------*\
| Cluster LevelControl | 0x0008 |
|------------------------------------------------------------------------------|
| Commands: | |
| * Move | 0x01 |
| * MoveToLevel | 0x00 |
| * MoveToLevelWithOnOff | 0x04 |
| * MoveWithOnOff | 0x05 |
| * Step | 0x02 |
| * StepWithOnOff | 0x06 |
| * Stop | 0x03 |
| * StopWithOnOff | 0x07 |
|------------------------------------------------------------------------------|
| Attributes: | |
| * CurrentLevel | 0x0000 |
| * ClusterRevision | 0xFFFD |
\*----------------------------------------------------------------------------*/
/*
* Command Move
*/
class LevelControlMove : public ModelCommand
{
public:
LevelControlMove() : ModelCommand("move")
{
AddArgument("moveMode", 0, UINT8_MAX, &mMoveMode);
AddArgument("rate", 0, UINT8_MAX, &mRate);
AddArgument("optionMask", 0, UINT8_MAX, &mOptionMask);
AddArgument("optionOverride", 0, UINT8_MAX, &mOptionOverride);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0008) command (0x01) on endpoint %" PRIu16, endpointId);
chip::Controller::LevelControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.Move(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mMoveMode, mRate, mOptionMask,
mOptionOverride);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint8_t mMoveMode;
uint8_t mRate;
uint8_t mOptionMask;
uint8_t mOptionOverride;
};
/*
* Command MoveToLevel
*/
class LevelControlMoveToLevel : public ModelCommand
{
public:
LevelControlMoveToLevel() : ModelCommand("move-to-level")
{
AddArgument("level", 0, UINT8_MAX, &mLevel);
AddArgument("transitionTime", 0, UINT16_MAX, &mTransitionTime);
AddArgument("optionMask", 0, UINT8_MAX, &mOptionMask);
AddArgument("optionOverride", 0, UINT8_MAX, &mOptionOverride);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0008) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::LevelControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.MoveToLevel(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mLevel, mTransitionTime, mOptionMask,
mOptionOverride);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint8_t mLevel;
uint16_t mTransitionTime;
uint8_t mOptionMask;
uint8_t mOptionOverride;
};
/*
* Command MoveToLevelWithOnOff
*/
class LevelControlMoveToLevelWithOnOff : public ModelCommand
{
public:
LevelControlMoveToLevelWithOnOff() : ModelCommand("move-to-level-with-on-off")
{
AddArgument("level", 0, UINT8_MAX, &mLevel);
AddArgument("transitionTime", 0, UINT16_MAX, &mTransitionTime);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0008) command (0x04) on endpoint %" PRIu16, endpointId);
chip::Controller::LevelControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.MoveToLevelWithOnOff(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mLevel, mTransitionTime);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint8_t mLevel;
uint16_t mTransitionTime;
};
/*
* Command MoveWithOnOff
*/
class LevelControlMoveWithOnOff : public ModelCommand
{
public:
LevelControlMoveWithOnOff() : ModelCommand("move-with-on-off")
{
AddArgument("moveMode", 0, UINT8_MAX, &mMoveMode);
AddArgument("rate", 0, UINT8_MAX, &mRate);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0008) command (0x05) on endpoint %" PRIu16, endpointId);
chip::Controller::LevelControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.MoveWithOnOff(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mMoveMode, mRate);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint8_t mMoveMode;
uint8_t mRate;
};
/*
* Command Step
*/
class LevelControlStep : public ModelCommand
{
public:
LevelControlStep() : ModelCommand("step")
{
AddArgument("stepMode", 0, UINT8_MAX, &mStepMode);
AddArgument("stepSize", 0, UINT8_MAX, &mStepSize);
AddArgument("transitionTime", 0, UINT16_MAX, &mTransitionTime);
AddArgument("optionMask", 0, UINT8_MAX, &mOptionMask);
AddArgument("optionOverride", 0, UINT8_MAX, &mOptionOverride);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0008) command (0x02) on endpoint %" PRIu16, endpointId);
chip::Controller::LevelControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.Step(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mStepMode, mStepSize, mTransitionTime,
mOptionMask, mOptionOverride);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint8_t mStepMode;
uint8_t mStepSize;
uint16_t mTransitionTime;
uint8_t mOptionMask;
uint8_t mOptionOverride;
};
/*
* Command StepWithOnOff
*/
class LevelControlStepWithOnOff : public ModelCommand
{
public:
LevelControlStepWithOnOff() : ModelCommand("step-with-on-off")
{
AddArgument("stepMode", 0, UINT8_MAX, &mStepMode);
AddArgument("stepSize", 0, UINT8_MAX, &mStepSize);
AddArgument("transitionTime", 0, UINT16_MAX, &mTransitionTime);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0008) command (0x06) on endpoint %" PRIu16, endpointId);
chip::Controller::LevelControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.StepWithOnOff(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mStepMode, mStepSize,
mTransitionTime);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint8_t mStepMode;
uint8_t mStepSize;
uint16_t mTransitionTime;
};
/*
* Command Stop
*/
class LevelControlStop : public ModelCommand
{
public:
LevelControlStop() : ModelCommand("stop")
{
AddArgument("optionMask", 0, UINT8_MAX, &mOptionMask);
AddArgument("optionOverride", 0, UINT8_MAX, &mOptionOverride);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0008) command (0x03) on endpoint %" PRIu16, endpointId);
chip::Controller::LevelControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.Stop(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mOptionMask, mOptionOverride);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint8_t mOptionMask;
uint8_t mOptionOverride;
};
/*
* Command StopWithOnOff
*/
class LevelControlStopWithOnOff : public ModelCommand
{
public:
LevelControlStopWithOnOff() : ModelCommand("stop-with-on-off") { ModelCommand::AddArguments(); }
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0008) command (0x07) on endpoint %" PRIu16, endpointId);
chip::Controller::LevelControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.StopWithOnOff(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Discover Attributes
*/
class DiscoverLevelControlAttributes : public ModelCommand
{
public:
DiscoverLevelControlAttributes() : ModelCommand("discover") { ModelCommand::AddArguments(); }
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0000) command (0x0C) on endpoint %" PRIu16, endpointId);
chip::Controller::LevelControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.DiscoverAttributes(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute CurrentLevel
*/
class ReadLevelControlCurrentLevel : public ModelCommand
{
public:
ReadLevelControlCurrentLevel() : ModelCommand("read")
{
AddArgument("attr-name", "current-level");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0008) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::LevelControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeCurrentLevel(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int8uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int8uAttributeCallback>(OnInt8uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
class ReportLevelControlCurrentLevel : public ModelCommand
{
public:
ReportLevelControlCurrentLevel() : ModelCommand("report")
{
AddArgument("attr-name", "current-level");
AddArgument("min-interval", 0, UINT16_MAX, &mMinInterval);
AddArgument("max-interval", 0, UINT16_MAX, &mMaxInterval);
AddArgument("change", 0, UINT8_MAX, &mChange);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0008) command (0x06) on endpoint %" PRIu16, endpointId);
chip::Controller::LevelControlCluster cluster;
cluster.Associate(device, endpointId);
CHIP_ERROR err = cluster.ReportAttributeCurrentLevel(onReportCallback->Cancel());
if (err != CHIP_NO_ERROR)
{
return err;
}
return cluster.ConfigureAttributeCurrentLevel(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mMinInterval,
mMaxInterval, mChange);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
chip::Callback::Callback<Int8uAttributeCallback> * onReportCallback =
new chip::Callback::Callback<Int8uAttributeCallback>(OnInt8uAttributeResponse, this);
uint16_t mMinInterval;
uint16_t mMaxInterval;
uint8_t mChange;
};
/*
* Attribute ClusterRevision
*/
class ReadLevelControlClusterRevision : public ModelCommand
{
public:
ReadLevelControlClusterRevision() : ModelCommand("read")
{
AddArgument("attr-name", "cluster-revision");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0008) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::LevelControlCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeClusterRevision(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*----------------------------------------------------------------------------*\
| Cluster MediaPlayback | 0xF001 |
|------------------------------------------------------------------------------|
| Commands: | |
| * FastForwardRequest | 0x07 |
| * NextRequest | 0x05 |
| * PauseRequest | 0x01 |
| * PlayRequest | 0x00 |
| * PreviousRequest | 0x04 |
| * RewindRequest | 0x06 |
| * SkipBackwardRequest | 0x09 |
| * SkipForwardRequest | 0x08 |
| * StartOverRequest | 0x03 |
| * StopRequest | 0x02 |
|------------------------------------------------------------------------------|
| Attributes: | |
| * CurrentState | 0x0000 |
| * ClusterRevision | 0xFFFD |
\*----------------------------------------------------------------------------*/
/*
* Command FastForwardRequest
*/
class MediaPlaybackFastForwardRequest : public ModelCommand
{
public:
MediaPlaybackFastForwardRequest() : ModelCommand("fast-forward-request") { ModelCommand::AddArguments(); }
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0xF001) command (0x07) on endpoint %" PRIu16, endpointId);
chip::Controller::MediaPlaybackCluster cluster;
cluster.Associate(device, endpointId);
return cluster.FastForwardRequest(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Command NextRequest
*/
class MediaPlaybackNextRequest : public ModelCommand
{
public:
MediaPlaybackNextRequest() : ModelCommand("next-request") { ModelCommand::AddArguments(); }
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0xF001) command (0x05) on endpoint %" PRIu16, endpointId);
chip::Controller::MediaPlaybackCluster cluster;
cluster.Associate(device, endpointId);
return cluster.NextRequest(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Command PauseRequest
*/
class MediaPlaybackPauseRequest : public ModelCommand
{
public:
MediaPlaybackPauseRequest() : ModelCommand("pause-request") { ModelCommand::AddArguments(); }
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0xF001) command (0x01) on endpoint %" PRIu16, endpointId);
chip::Controller::MediaPlaybackCluster cluster;
cluster.Associate(device, endpointId);
return cluster.PauseRequest(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Command PlayRequest
*/
class MediaPlaybackPlayRequest : public ModelCommand
{
public:
MediaPlaybackPlayRequest() : ModelCommand("play-request") { ModelCommand::AddArguments(); }
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0xF001) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::MediaPlaybackCluster cluster;
cluster.Associate(device, endpointId);
return cluster.PlayRequest(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Command PreviousRequest
*/
class MediaPlaybackPreviousRequest : public ModelCommand
{
public:
MediaPlaybackPreviousRequest() : ModelCommand("previous-request") { ModelCommand::AddArguments(); }
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0xF001) command (0x04) on endpoint %" PRIu16, endpointId);
chip::Controller::MediaPlaybackCluster cluster;
cluster.Associate(device, endpointId);
return cluster.PreviousRequest(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Command RewindRequest
*/
class MediaPlaybackRewindRequest : public ModelCommand
{
public:
MediaPlaybackRewindRequest() : ModelCommand("rewind-request") { ModelCommand::AddArguments(); }
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0xF001) command (0x06) on endpoint %" PRIu16, endpointId);
chip::Controller::MediaPlaybackCluster cluster;
cluster.Associate(device, endpointId);
return cluster.RewindRequest(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Command SkipBackwardRequest
*/
class MediaPlaybackSkipBackwardRequest : public ModelCommand
{
public:
MediaPlaybackSkipBackwardRequest() : ModelCommand("skip-backward-request") { ModelCommand::AddArguments(); }
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0xF001) command (0x09) on endpoint %" PRIu16, endpointId);
chip::Controller::MediaPlaybackCluster cluster;
cluster.Associate(device, endpointId);
return cluster.SkipBackwardRequest(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Command SkipForwardRequest
*/
class MediaPlaybackSkipForwardRequest : public ModelCommand
{
public:
MediaPlaybackSkipForwardRequest() : ModelCommand("skip-forward-request") { ModelCommand::AddArguments(); }
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0xF001) command (0x08) on endpoint %" PRIu16, endpointId);
chip::Controller::MediaPlaybackCluster cluster;
cluster.Associate(device, endpointId);
return cluster.SkipForwardRequest(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Command StartOverRequest
*/
class MediaPlaybackStartOverRequest : public ModelCommand
{
public:
MediaPlaybackStartOverRequest() : ModelCommand("start-over-request") { ModelCommand::AddArguments(); }
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0xF001) command (0x03) on endpoint %" PRIu16, endpointId);
chip::Controller::MediaPlaybackCluster cluster;
cluster.Associate(device, endpointId);
return cluster.StartOverRequest(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Command StopRequest
*/
class MediaPlaybackStopRequest : public ModelCommand
{
public:
MediaPlaybackStopRequest() : ModelCommand("stop-request") { ModelCommand::AddArguments(); }
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0xF001) command (0x02) on endpoint %" PRIu16, endpointId);
chip::Controller::MediaPlaybackCluster cluster;
cluster.Associate(device, endpointId);
return cluster.StopRequest(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Discover Attributes
*/
class DiscoverMediaPlaybackAttributes : public ModelCommand
{
public:
DiscoverMediaPlaybackAttributes() : ModelCommand("discover") { ModelCommand::AddArguments(); }
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0000) command (0x0C) on endpoint %" PRIu16, endpointId);
chip::Controller::MediaPlaybackCluster cluster;
cluster.Associate(device, endpointId);
return cluster.DiscoverAttributes(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute CurrentState
*/
class ReadMediaPlaybackCurrentState : public ModelCommand
{
public:
ReadMediaPlaybackCurrentState() : ModelCommand("read")
{
AddArgument("attr-name", "current-state");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0xF001) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::MediaPlaybackCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeCurrentState(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute ClusterRevision
*/
class ReadMediaPlaybackClusterRevision : public ModelCommand
{
public:
ReadMediaPlaybackClusterRevision() : ModelCommand("read")
{
AddArgument("attr-name", "cluster-revision");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0xF001) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::MediaPlaybackCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeClusterRevision(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*----------------------------------------------------------------------------*\
| Cluster OnOff | 0x0006 |
|------------------------------------------------------------------------------|
| Commands: | |
| * Off | 0x00 |
| * On | 0x01 |
| * Toggle | 0x02 |
|------------------------------------------------------------------------------|
| Attributes: | |
| * OnOff | 0x0000 |
| * ClusterRevision | 0xFFFD |
\*----------------------------------------------------------------------------*/
/*
* Command Off
*/
class OnOffOff : public ModelCommand
{
public:
OnOffOff() : ModelCommand("off") { ModelCommand::AddArguments(); }
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0006) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::OnOffCluster cluster;
cluster.Associate(device, endpointId);
return cluster.Off(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Command On
*/
class OnOffOn : public ModelCommand
{
public:
OnOffOn() : ModelCommand("on") { ModelCommand::AddArguments(); }
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0006) command (0x01) on endpoint %" PRIu16, endpointId);
chip::Controller::OnOffCluster cluster;
cluster.Associate(device, endpointId);
return cluster.On(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Command Toggle
*/
class OnOffToggle : public ModelCommand
{
public:
OnOffToggle() : ModelCommand("toggle") { ModelCommand::AddArguments(); }
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0006) command (0x02) on endpoint %" PRIu16, endpointId);
chip::Controller::OnOffCluster cluster;
cluster.Associate(device, endpointId);
return cluster.Toggle(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Discover Attributes
*/
class DiscoverOnOffAttributes : public ModelCommand
{
public:
DiscoverOnOffAttributes() : ModelCommand("discover") { ModelCommand::AddArguments(); }
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0000) command (0x0C) on endpoint %" PRIu16, endpointId);
chip::Controller::OnOffCluster cluster;
cluster.Associate(device, endpointId);
return cluster.DiscoverAttributes(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute OnOff
*/
class ReadOnOffOnOff : public ModelCommand
{
public:
ReadOnOffOnOff() : ModelCommand("read")
{
AddArgument("attr-name", "on-off");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0006) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::OnOffCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeOnOff(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<BooleanAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<BooleanAttributeCallback>(OnBooleanAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
class ReportOnOffOnOff : public ModelCommand
{
public:
ReportOnOffOnOff() : ModelCommand("report")
{
AddArgument("attr-name", "on-off");
AddArgument("min-interval", 0, UINT16_MAX, &mMinInterval);
AddArgument("max-interval", 0, UINT16_MAX, &mMaxInterval);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0006) command (0x06) on endpoint %" PRIu16, endpointId);
chip::Controller::OnOffCluster cluster;
cluster.Associate(device, endpointId);
CHIP_ERROR err = cluster.ReportAttributeOnOff(onReportCallback->Cancel());
if (err != CHIP_NO_ERROR)
{
return err;
}
return cluster.ConfigureAttributeOnOff(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mMinInterval,
mMaxInterval);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
chip::Callback::Callback<BooleanAttributeCallback> * onReportCallback =
new chip::Callback::Callback<BooleanAttributeCallback>(OnBooleanAttributeResponse, this);
uint16_t mMinInterval;
uint16_t mMaxInterval;
};
/*
* Attribute ClusterRevision
*/
class ReadOnOffClusterRevision : public ModelCommand
{
public:
ReadOnOffClusterRevision() : ModelCommand("read")
{
AddArgument("attr-name", "cluster-revision");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0006) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::OnOffCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeClusterRevision(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*----------------------------------------------------------------------------*\
| Cluster Scenes | 0x0005 |
|------------------------------------------------------------------------------|
| Commands: | |
| * AddScene | 0x00 |
| * GetSceneMembership | 0x06 |
| * RecallScene | 0x05 |
| * RemoveAllScenes | 0x03 |
| * RemoveScene | 0x02 |
| * StoreScene | 0x04 |
| * ViewScene | 0x01 |
|------------------------------------------------------------------------------|
| Attributes: | |
| * SceneCount | 0x0000 |
| * CurrentScene | 0x0001 |
| * CurrentGroup | 0x0002 |
| * SceneValid | 0x0003 |
| * NameSupport | 0x0004 |
| * ClusterRevision | 0xFFFD |
\*----------------------------------------------------------------------------*/
/*
* Command AddScene
*/
class ScenesAddScene : public ModelCommand
{
public:
ScenesAddScene() : ModelCommand("add-scene")
{
AddArgument("groupId", 0, UINT16_MAX, &mGroupId);
AddArgument("sceneId", 0, UINT8_MAX, &mSceneId);
AddArgument("transitionTime", 0, UINT16_MAX, &mTransitionTime);
AddArgument("sceneName", &mSceneName);
AddArgument("clusterId", 0, UINT16_MAX, &mClusterId);
AddArgument("length", 0, UINT8_MAX, &mLength);
AddArgument("value", 0, UINT8_MAX, &mValue);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0005) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ScenesCluster cluster;
cluster.Associate(device, endpointId);
return cluster.AddScene(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mGroupId, mSceneId, mTransitionTime,
mSceneName, mClusterId, mLength, mValue);
}
private:
chip::Callback::Callback<ScenesClusterAddSceneResponseCallback> * onSuccessCallback =
new chip::Callback::Callback<ScenesClusterAddSceneResponseCallback>(OnScenesClusterAddSceneResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint16_t mGroupId;
uint8_t mSceneId;
uint16_t mTransitionTime;
char * mSceneName;
chip::ClusterId mClusterId;
uint8_t mLength;
uint8_t mValue;
};
/*
* Command GetSceneMembership
*/
class ScenesGetSceneMembership : public ModelCommand
{
public:
ScenesGetSceneMembership() : ModelCommand("get-scene-membership")
{
AddArgument("groupId", 0, UINT16_MAX, &mGroupId);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0005) command (0x06) on endpoint %" PRIu16, endpointId);
chip::Controller::ScenesCluster cluster;
cluster.Associate(device, endpointId);
return cluster.GetSceneMembership(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mGroupId);
}
private:
chip::Callback::Callback<ScenesClusterGetSceneMembershipResponseCallback> * onSuccessCallback =
new chip::Callback::Callback<ScenesClusterGetSceneMembershipResponseCallback>(OnScenesClusterGetSceneMembershipResponse,
this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint16_t mGroupId;
};
/*
* Command RecallScene
*/
class ScenesRecallScene : public ModelCommand
{
public:
ScenesRecallScene() : ModelCommand("recall-scene")
{
AddArgument("groupId", 0, UINT16_MAX, &mGroupId);
AddArgument("sceneId", 0, UINT8_MAX, &mSceneId);
AddArgument("transitionTime", 0, UINT16_MAX, &mTransitionTime);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0005) command (0x05) on endpoint %" PRIu16, endpointId);
chip::Controller::ScenesCluster cluster;
cluster.Associate(device, endpointId);
return cluster.RecallScene(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mGroupId, mSceneId, mTransitionTime);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint16_t mGroupId;
uint8_t mSceneId;
uint16_t mTransitionTime;
};
/*
* Command RemoveAllScenes
*/
class ScenesRemoveAllScenes : public ModelCommand
{
public:
ScenesRemoveAllScenes() : ModelCommand("remove-all-scenes")
{
AddArgument("groupId", 0, UINT16_MAX, &mGroupId);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0005) command (0x03) on endpoint %" PRIu16, endpointId);
chip::Controller::ScenesCluster cluster;
cluster.Associate(device, endpointId);
return cluster.RemoveAllScenes(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mGroupId);
}
private:
chip::Callback::Callback<ScenesClusterRemoveAllScenesResponseCallback> * onSuccessCallback =
new chip::Callback::Callback<ScenesClusterRemoveAllScenesResponseCallback>(OnScenesClusterRemoveAllScenesResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint16_t mGroupId;
};
/*
* Command RemoveScene
*/
class ScenesRemoveScene : public ModelCommand
{
public:
ScenesRemoveScene() : ModelCommand("remove-scene")
{
AddArgument("groupId", 0, UINT16_MAX, &mGroupId);
AddArgument("sceneId", 0, UINT8_MAX, &mSceneId);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0005) command (0x02) on endpoint %" PRIu16, endpointId);
chip::Controller::ScenesCluster cluster;
cluster.Associate(device, endpointId);
return cluster.RemoveScene(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mGroupId, mSceneId);
}
private:
chip::Callback::Callback<ScenesClusterRemoveSceneResponseCallback> * onSuccessCallback =
new chip::Callback::Callback<ScenesClusterRemoveSceneResponseCallback>(OnScenesClusterRemoveSceneResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint16_t mGroupId;
uint8_t mSceneId;
};
/*
* Command StoreScene
*/
class ScenesStoreScene : public ModelCommand
{
public:
ScenesStoreScene() : ModelCommand("store-scene")
{
AddArgument("groupId", 0, UINT16_MAX, &mGroupId);
AddArgument("sceneId", 0, UINT8_MAX, &mSceneId);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0005) command (0x04) on endpoint %" PRIu16, endpointId);
chip::Controller::ScenesCluster cluster;
cluster.Associate(device, endpointId);
return cluster.StoreScene(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mGroupId, mSceneId);
}
private:
chip::Callback::Callback<ScenesClusterStoreSceneResponseCallback> * onSuccessCallback =
new chip::Callback::Callback<ScenesClusterStoreSceneResponseCallback>(OnScenesClusterStoreSceneResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint16_t mGroupId;
uint8_t mSceneId;
};
/*
* Command ViewScene
*/
class ScenesViewScene : public ModelCommand
{
public:
ScenesViewScene() : ModelCommand("view-scene")
{
AddArgument("groupId", 0, UINT16_MAX, &mGroupId);
AddArgument("sceneId", 0, UINT8_MAX, &mSceneId);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0005) command (0x01) on endpoint %" PRIu16, endpointId);
chip::Controller::ScenesCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ViewScene(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mGroupId, mSceneId);
}
private:
chip::Callback::Callback<ScenesClusterViewSceneResponseCallback> * onSuccessCallback =
new chip::Callback::Callback<ScenesClusterViewSceneResponseCallback>(OnScenesClusterViewSceneResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
uint16_t mGroupId;
uint8_t mSceneId;
};
/*
* Discover Attributes
*/
class DiscoverScenesAttributes : public ModelCommand
{
public:
DiscoverScenesAttributes() : ModelCommand("discover") { ModelCommand::AddArguments(); }
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0000) command (0x0C) on endpoint %" PRIu16, endpointId);
chip::Controller::ScenesCluster cluster;
cluster.Associate(device, endpointId);
return cluster.DiscoverAttributes(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute SceneCount
*/
class ReadScenesSceneCount : public ModelCommand
{
public:
ReadScenesSceneCount() : ModelCommand("read")
{
AddArgument("attr-name", "scene-count");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0005) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ScenesCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeSceneCount(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int8uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int8uAttributeCallback>(OnInt8uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute CurrentScene
*/
class ReadScenesCurrentScene : public ModelCommand
{
public:
ReadScenesCurrentScene() : ModelCommand("read")
{
AddArgument("attr-name", "current-scene");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0005) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ScenesCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeCurrentScene(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int8uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int8uAttributeCallback>(OnInt8uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute CurrentGroup
*/
class ReadScenesCurrentGroup : public ModelCommand
{
public:
ReadScenesCurrentGroup() : ModelCommand("read")
{
AddArgument("attr-name", "current-group");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0005) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ScenesCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeCurrentGroup(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute SceneValid
*/
class ReadScenesSceneValid : public ModelCommand
{
public:
ReadScenesSceneValid() : ModelCommand("read")
{
AddArgument("attr-name", "scene-valid");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0005) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ScenesCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeSceneValid(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<BooleanAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<BooleanAttributeCallback>(OnBooleanAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute NameSupport
*/
class ReadScenesNameSupport : public ModelCommand
{
public:
ReadScenesNameSupport() : ModelCommand("read")
{
AddArgument("attr-name", "name-support");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0005) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ScenesCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeNameSupport(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int8uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int8uAttributeCallback>(OnInt8uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute ClusterRevision
*/
class ReadScenesClusterRevision : public ModelCommand
{
public:
ReadScenesClusterRevision() : ModelCommand("read")
{
AddArgument("attr-name", "cluster-revision");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0005) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::ScenesCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeClusterRevision(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*----------------------------------------------------------------------------*\
| Cluster TemperatureMeasurement | 0x0402 |
|------------------------------------------------------------------------------|
| Commands: | |
|------------------------------------------------------------------------------|
| Attributes: | |
| * MeasuredValue | 0x0000 |
| * MinMeasuredValue | 0x0001 |
| * MaxMeasuredValue | 0x0002 |
| * ClusterRevision | 0xFFFD |
\*----------------------------------------------------------------------------*/
/*
* Discover Attributes
*/
class DiscoverTemperatureMeasurementAttributes : public ModelCommand
{
public:
DiscoverTemperatureMeasurementAttributes() : ModelCommand("discover") { ModelCommand::AddArguments(); }
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0000) command (0x0C) on endpoint %" PRIu16, endpointId);
chip::Controller::TemperatureMeasurementCluster cluster;
cluster.Associate(device, endpointId);
return cluster.DiscoverAttributes(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute MeasuredValue
*/
class ReadTemperatureMeasurementMeasuredValue : public ModelCommand
{
public:
ReadTemperatureMeasurementMeasuredValue() : ModelCommand("read")
{
AddArgument("attr-name", "measured-value");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0402) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::TemperatureMeasurementCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeMeasuredValue(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16sAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16sAttributeCallback>(OnInt16sAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
class ReportTemperatureMeasurementMeasuredValue : public ModelCommand
{
public:
ReportTemperatureMeasurementMeasuredValue() : ModelCommand("report")
{
AddArgument("attr-name", "measured-value");
AddArgument("min-interval", 0, UINT16_MAX, &mMinInterval);
AddArgument("max-interval", 0, UINT16_MAX, &mMaxInterval);
AddArgument("change", INT16_MIN, INT16_MAX, &mChange);
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0402) command (0x06) on endpoint %" PRIu16, endpointId);
chip::Controller::TemperatureMeasurementCluster cluster;
cluster.Associate(device, endpointId);
CHIP_ERROR err = cluster.ReportAttributeMeasuredValue(onReportCallback->Cancel());
if (err != CHIP_NO_ERROR)
{
return err;
}
return cluster.ConfigureAttributeMeasuredValue(onSuccessCallback->Cancel(), onFailureCallback->Cancel(), mMinInterval,
mMaxInterval, mChange);
}
private:
chip::Callback::Callback<DefaultSuccessCallback> * onSuccessCallback =
new chip::Callback::Callback<DefaultSuccessCallback>(OnDefaultSuccessResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
chip::Callback::Callback<Int16sAttributeCallback> * onReportCallback =
new chip::Callback::Callback<Int16sAttributeCallback>(OnInt16sAttributeResponse, this);
uint16_t mMinInterval;
uint16_t mMaxInterval;
int16_t mChange;
};
/*
* Attribute MinMeasuredValue
*/
class ReadTemperatureMeasurementMinMeasuredValue : public ModelCommand
{
public:
ReadTemperatureMeasurementMinMeasuredValue() : ModelCommand("read")
{
AddArgument("attr-name", "min-measured-value");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0402) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::TemperatureMeasurementCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeMinMeasuredValue(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16sAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16sAttributeCallback>(OnInt16sAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute MaxMeasuredValue
*/
class ReadTemperatureMeasurementMaxMeasuredValue : public ModelCommand
{
public:
ReadTemperatureMeasurementMaxMeasuredValue() : ModelCommand("read")
{
AddArgument("attr-name", "max-measured-value");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0402) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::TemperatureMeasurementCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeMaxMeasuredValue(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16sAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16sAttributeCallback>(OnInt16sAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*
* Attribute ClusterRevision
*/
class ReadTemperatureMeasurementClusterRevision : public ModelCommand
{
public:
ReadTemperatureMeasurementClusterRevision() : ModelCommand("read")
{
AddArgument("attr-name", "cluster-revision");
ModelCommand::AddArguments();
}
CHIP_ERROR SendCommand(ChipDevice * device, uint8_t endpointId) override
{
ChipLogProgress(chipTool, "Sending cluster (0x0402) command (0x00) on endpoint %" PRIu16, endpointId);
chip::Controller::TemperatureMeasurementCluster cluster;
cluster.Associate(device, endpointId);
return cluster.ReadAttributeClusterRevision(onSuccessCallback->Cancel(), onFailureCallback->Cancel());
}
private:
chip::Callback::Callback<Int16uAttributeCallback> * onSuccessCallback =
new chip::Callback::Callback<Int16uAttributeCallback>(OnInt16uAttributeResponse, this);
chip::Callback::Callback<DefaultFailureCallback> * onFailureCallback =
new chip::Callback::Callback<DefaultFailureCallback>(OnDefaultFailureResponse, this);
};
/*----------------------------------------------------------------------------*\
| Register all Clusters commands |
\*----------------------------------------------------------------------------*/
void registerClusterApplicationBasic(Commands & commands)
{
const char * clusterName = "ApplicationBasic";
commands_list clusterCommands = {
make_unique<DiscoverApplicationBasicAttributes>(), make_unique<ReadApplicationBasicVendorName>(),
make_unique<ReadApplicationBasicVendorId>(), make_unique<ReadApplicationBasicApplicationName>(),
make_unique<ReadApplicationBasicProductId>(), make_unique<ReadApplicationBasicApplicationId>(),
make_unique<ReadApplicationBasicCatalogVendorId>(), make_unique<ReadApplicationBasicApplicationSatus>(),
make_unique<ReadApplicationBasicClusterRevision>(),
};
commands.Register(clusterName, clusterCommands);
}
void registerClusterBarrierControl(Commands & commands)
{
const char * clusterName = "BarrierControl";
commands_list clusterCommands = {
make_unique<BarrierControlBarrierControlGoToPercent>(), make_unique<BarrierControlBarrierControlStop>(),
make_unique<DiscoverBarrierControlAttributes>(), make_unique<ReadBarrierControlBarrierMovingState>(),
make_unique<ReadBarrierControlBarrierSafetyStatus>(), make_unique<ReadBarrierControlBarrierCapabilities>(),
make_unique<ReadBarrierControlBarrierPosition>(), make_unique<ReadBarrierControlClusterRevision>(),
};
commands.Register(clusterName, clusterCommands);
}
void registerClusterBasic(Commands & commands)
{
const char * clusterName = "Basic";
commands_list clusterCommands = {
make_unique<BasicMfgSpecificPing>(), make_unique<BasicResetToFactoryDefaults>(), make_unique<DiscoverBasicAttributes>(),
make_unique<ReadBasicZclVersion>(), make_unique<ReadBasicPowerSource>(), make_unique<ReadBasicClusterRevision>(),
};
commands.Register(clusterName, clusterCommands);
}
void registerClusterBinding(Commands & commands)
{
const char * clusterName = "Binding";
commands_list clusterCommands = {
make_unique<BindingBind>(),
make_unique<BindingUnbind>(),
make_unique<DiscoverBindingAttributes>(),
make_unique<ReadBindingClusterRevision>(),
};
commands.Register(clusterName, clusterCommands);
}
void registerClusterColorControl(Commands & commands)
{
const char * clusterName = "ColorControl";
commands_list clusterCommands = {
make_unique<ColorControlMoveColor>(),
make_unique<ColorControlMoveColorTemperature>(),
make_unique<ColorControlMoveHue>(),
make_unique<ColorControlMoveSaturation>(),
make_unique<ColorControlMoveToColor>(),
make_unique<ColorControlMoveToColorTemperature>(),
make_unique<ColorControlMoveToHue>(),
make_unique<ColorControlMoveToHueAndSaturation>(),
make_unique<ColorControlMoveToSaturation>(),
make_unique<ColorControlStepColor>(),
make_unique<ColorControlStepColorTemperature>(),
make_unique<ColorControlStepHue>(),
make_unique<ColorControlStepSaturation>(),
make_unique<ColorControlStopMoveStep>(),
make_unique<DiscoverColorControlAttributes>(),
make_unique<ReadColorControlCurrentHue>(),
make_unique<ReportColorControlCurrentHue>(),
make_unique<ReadColorControlCurrentSaturation>(),
make_unique<ReportColorControlCurrentSaturation>(),
make_unique<ReadColorControlRemainingTime>(),
make_unique<ReadColorControlCurrentX>(),
make_unique<ReportColorControlCurrentX>(),
make_unique<ReadColorControlCurrentY>(),
make_unique<ReportColorControlCurrentY>(),
make_unique<ReadColorControlDriftCompensation>(),
make_unique<ReadColorControlCompensationText>(),
make_unique<ReadColorControlColorTemperature>(),
make_unique<ReportColorControlColorTemperature>(),
make_unique<ReadColorControlColorMode>(),
make_unique<ReadColorControlColorControlOptions>(),
make_unique<WriteColorControlColorControlOptions>(),
make_unique<ReadColorControlNumberOfPrimaries>(),
make_unique<ReadColorControlPrimary1X>(),
make_unique<ReadColorControlPrimary1Y>(),
make_unique<ReadColorControlPrimary1Intensity>(),
make_unique<ReadColorControlPrimary2X>(),
make_unique<ReadColorControlPrimary2Y>(),
make_unique<ReadColorControlPrimary2Intensity>(),
make_unique<ReadColorControlPrimary3X>(),
make_unique<ReadColorControlPrimary3Y>(),
make_unique<ReadColorControlPrimary3Intensity>(),
make_unique<ReadColorControlPrimary4X>(),
make_unique<ReadColorControlPrimary4Y>(),
make_unique<ReadColorControlPrimary4Intensity>(),
make_unique<ReadColorControlPrimary5X>(),
make_unique<ReadColorControlPrimary5Y>(),
make_unique<ReadColorControlPrimary5Intensity>(),
make_unique<ReadColorControlPrimary6X>(),
make_unique<ReadColorControlPrimary6Y>(),
make_unique<ReadColorControlPrimary6Intensity>(),
make_unique<ReadColorControlWhitePointX>(),
make_unique<WriteColorControlWhitePointX>(),
make_unique<ReadColorControlWhitePointY>(),
make_unique<WriteColorControlWhitePointY>(),
make_unique<ReadColorControlColorPointRX>(),
make_unique<WriteColorControlColorPointRX>(),
make_unique<ReadColorControlColorPointRY>(),
make_unique<WriteColorControlColorPointRY>(),
make_unique<ReadColorControlColorPointRIntensity>(),
make_unique<WriteColorControlColorPointRIntensity>(),
make_unique<ReadColorControlColorPointGX>(),
make_unique<WriteColorControlColorPointGX>(),
make_unique<ReadColorControlColorPointGY>(),
make_unique<WriteColorControlColorPointGY>(),
make_unique<ReadColorControlColorPointGIntensity>(),
make_unique<WriteColorControlColorPointGIntensity>(),
make_unique<ReadColorControlColorPointBX>(),
make_unique<WriteColorControlColorPointBX>(),
make_unique<ReadColorControlColorPointBY>(),
make_unique<WriteColorControlColorPointBY>(),
make_unique<ReadColorControlColorPointBIntensity>(),
make_unique<WriteColorControlColorPointBIntensity>(),
make_unique<ReadColorControlEnhancedCurrentHue>(),
make_unique<ReadColorControlEnhancedColorMode>(),
make_unique<ReadColorControlColorLoopActive>(),
make_unique<ReadColorControlColorLoopDirection>(),
make_unique<ReadColorControlColorLoopTime>(),
make_unique<ReadColorControlColorCapabilities>(),
make_unique<ReadColorControlColorTempPhysicalMin>(),
make_unique<ReadColorControlColorTempPhysicalMax>(),
make_unique<ReadColorControlCoupleColorTempToLevelMinMireds>(),
make_unique<ReadColorControlStartUpColorTemperatureMireds>(),
make_unique<WriteColorControlStartUpColorTemperatureMireds>(),
make_unique<ReadColorControlClusterRevision>(),
};
commands.Register(clusterName, clusterCommands);
}
void registerClusterContentLaunch(Commands & commands)
{
const char * clusterName = "ContentLaunch";
commands_list clusterCommands = {
make_unique<ContentLaunchLaunchContent>(),
make_unique<ContentLaunchLaunchURL>(),
make_unique<DiscoverContentLaunchAttributes>(),
make_unique<ReadContentLaunchClusterRevision>(),
};
commands.Register(clusterName, clusterCommands);
}
void registerClusterDoorLock(Commands & commands)
{
const char * clusterName = "DoorLock";
commands_list clusterCommands = {
make_unique<DoorLockClearAllPins>(),
make_unique<DoorLockClearAllRfids>(),
make_unique<DoorLockClearHolidaySchedule>(),
make_unique<DoorLockClearPin>(),
make_unique<DoorLockClearRfid>(),
make_unique<DoorLockClearWeekdaySchedule>(),
make_unique<DoorLockClearYeardaySchedule>(),
make_unique<DoorLockGetHolidaySchedule>(),
make_unique<DoorLockGetLogRecord>(),
make_unique<DoorLockGetPin>(),
make_unique<DoorLockGetRfid>(),
make_unique<DoorLockGetUserType>(),
make_unique<DoorLockGetWeekdaySchedule>(),
make_unique<DoorLockGetYeardaySchedule>(),
make_unique<DoorLockLockDoor>(),
make_unique<DoorLockSetHolidaySchedule>(),
make_unique<DoorLockSetPin>(),
make_unique<DoorLockSetRfid>(),
make_unique<DoorLockSetUserType>(),
make_unique<DoorLockSetWeekdaySchedule>(),
make_unique<DoorLockSetYeardaySchedule>(),
make_unique<DoorLockUnlockDoor>(),
make_unique<DoorLockUnlockWithTimeout>(),
make_unique<DiscoverDoorLockAttributes>(),
make_unique<ReadDoorLockLockState>(),
make_unique<ReportDoorLockLockState>(),
make_unique<ReadDoorLockLockType>(),
make_unique<ReadDoorLockActuatorEnabled>(),
make_unique<ReadDoorLockClusterRevision>(),
};
commands.Register(clusterName, clusterCommands);
}
void registerClusterGeneralCommissioning(Commands & commands)
{
const char * clusterName = "GeneralCommissioning";
commands_list clusterCommands = {
make_unique<GeneralCommissioningArmFailSafe>(), make_unique<GeneralCommissioningCommissioningComplete>(),
make_unique<GeneralCommissioningSetFabric>(), make_unique<DiscoverGeneralCommissioningAttributes>(),
make_unique<ReadGeneralCommissioningFabricId>(), make_unique<ReadGeneralCommissioningBreadcrumb>(),
make_unique<WriteGeneralCommissioningBreadcrumb>(), make_unique<ReadGeneralCommissioningClusterRevision>(),
};
commands.Register(clusterName, clusterCommands);
}
void registerClusterGroups(Commands & commands)
{
const char * clusterName = "Groups";
commands_list clusterCommands = {
make_unique<GroupsAddGroup>(),
make_unique<GroupsAddGroupIfIdentifying>(),
make_unique<GroupsGetGroupMembership>(),
make_unique<GroupsRemoveAllGroups>(),
make_unique<GroupsRemoveGroup>(),
make_unique<GroupsViewGroup>(),
make_unique<DiscoverGroupsAttributes>(),
make_unique<ReadGroupsNameSupport>(),
make_unique<ReadGroupsClusterRevision>(),
};
commands.Register(clusterName, clusterCommands);
}
void registerClusterIdentify(Commands & commands)
{
const char * clusterName = "Identify";
commands_list clusterCommands = {
make_unique<IdentifyIdentify>(), make_unique<IdentifyIdentifyQuery>(),
make_unique<DiscoverIdentifyAttributes>(), make_unique<ReadIdentifyIdentifyTime>(),
make_unique<WriteIdentifyIdentifyTime>(), make_unique<ReadIdentifyClusterRevision>(),
};
commands.Register(clusterName, clusterCommands);
}
void registerClusterLevelControl(Commands & commands)
{
const char * clusterName = "LevelControl";
commands_list clusterCommands = {
make_unique<LevelControlMove>(),
make_unique<LevelControlMoveToLevel>(),
make_unique<LevelControlMoveToLevelWithOnOff>(),
make_unique<LevelControlMoveWithOnOff>(),
make_unique<LevelControlStep>(),
make_unique<LevelControlStepWithOnOff>(),
make_unique<LevelControlStop>(),
make_unique<LevelControlStopWithOnOff>(),
make_unique<DiscoverLevelControlAttributes>(),
make_unique<ReadLevelControlCurrentLevel>(),
make_unique<ReportLevelControlCurrentLevel>(),
make_unique<ReadLevelControlClusterRevision>(),
};
commands.Register(clusterName, clusterCommands);
}
void registerClusterMediaPlayback(Commands & commands)
{
const char * clusterName = "MediaPlayback";
commands_list clusterCommands = {
make_unique<MediaPlaybackFastForwardRequest>(), make_unique<MediaPlaybackNextRequest>(),
make_unique<MediaPlaybackPauseRequest>(), make_unique<MediaPlaybackPlayRequest>(),
make_unique<MediaPlaybackPreviousRequest>(), make_unique<MediaPlaybackRewindRequest>(),
make_unique<MediaPlaybackSkipBackwardRequest>(), make_unique<MediaPlaybackSkipForwardRequest>(),
make_unique<MediaPlaybackStartOverRequest>(), make_unique<MediaPlaybackStopRequest>(),
make_unique<DiscoverMediaPlaybackAttributes>(), make_unique<ReadMediaPlaybackCurrentState>(),
make_unique<ReadMediaPlaybackClusterRevision>(),
};
commands.Register(clusterName, clusterCommands);
}
void registerClusterOnOff(Commands & commands)
{
const char * clusterName = "OnOff";
commands_list clusterCommands = {
make_unique<OnOffOff>(),
make_unique<OnOffOn>(),
make_unique<OnOffToggle>(),
make_unique<DiscoverOnOffAttributes>(),
make_unique<ReadOnOffOnOff>(),
make_unique<ReportOnOffOnOff>(),
make_unique<ReadOnOffClusterRevision>(),
};
commands.Register(clusterName, clusterCommands);
}
void registerClusterScenes(Commands & commands)
{
const char * clusterName = "Scenes";
commands_list clusterCommands = {
make_unique<ScenesAddScene>(), make_unique<ScenesGetSceneMembership>(), make_unique<ScenesRecallScene>(),
make_unique<ScenesRemoveAllScenes>(), make_unique<ScenesRemoveScene>(), make_unique<ScenesStoreScene>(),
make_unique<ScenesViewScene>(), make_unique<DiscoverScenesAttributes>(), make_unique<ReadScenesSceneCount>(),
make_unique<ReadScenesCurrentScene>(), make_unique<ReadScenesCurrentGroup>(), make_unique<ReadScenesSceneValid>(),
make_unique<ReadScenesNameSupport>(), make_unique<ReadScenesClusterRevision>(),
};
commands.Register(clusterName, clusterCommands);
}
void registerClusterTemperatureMeasurement(Commands & commands)
{
const char * clusterName = "TemperatureMeasurement";
commands_list clusterCommands = {
make_unique<DiscoverTemperatureMeasurementAttributes>(), make_unique<ReadTemperatureMeasurementMeasuredValue>(),
make_unique<ReportTemperatureMeasurementMeasuredValue>(), make_unique<ReadTemperatureMeasurementMinMeasuredValue>(),
make_unique<ReadTemperatureMeasurementMaxMeasuredValue>(), make_unique<ReadTemperatureMeasurementClusterRevision>(),
};
commands.Register(clusterName, clusterCommands);
}
void registerClusters(Commands & commands)
{
registerClusterApplicationBasic(commands);
registerClusterBarrierControl(commands);
registerClusterBasic(commands);
registerClusterBinding(commands);
registerClusterColorControl(commands);
registerClusterContentLaunch(commands);
registerClusterDoorLock(commands);
registerClusterGeneralCommissioning(commands);
registerClusterGroups(commands);
registerClusterIdentify(commands);
registerClusterLevelControl(commands);
registerClusterMediaPlayback(commands);
registerClusterOnOff(commands);
registerClusterScenes(commands);
registerClusterTemperatureMeasurement(commands);
}
| [
"[email protected]"
] | |
790cac105484b8878af338527d0fea9eff7c9910 | cde82a3e0173514b868f8b07e7767e6802c43d14 | /Projects/Project02/testgraph.cpp | d7d3fd1c9e65c24f78eb32ad7eca127f080f554a | [] | no_license | gerardogtn/Algorithms | aaa84f1249cd4bc217a6250fa0c647d0d50ff589 | 31a774001fe64328e9135c6ccbc0bdcb8bd6918e | refs/heads/master | 2020-05-17T19:30:41.490383 | 2015-11-20T03:11:42 | 2015-11-20T03:11:42 | 41,504,729 | 0 | 0 | null | 2015-09-30T17:11:05 | 2015-08-27T18:43:24 | C++ | UTF-8 | C++ | false | false | 13,823 | cpp | #include <iostream>
#include <iomanip>
#include <chrono>
#include <utility>
#include <vector>
#include <deque>
#include <string>
#include <fstream>
#include <stack>
#include <algorithm>
#include <utility>
#include <limits>
#include "stdafx.h"
#undef max
class myVis {
public:
myVis() { }
myVis(const int& Nodes){ }
void DiscoverNode(int NId) { printf("%i\n",NId); }
void FinishNode(const int& NId) { }
void ExamineEdge(const int& NId1, const int& NId2) { }
void TreeEdge(const int& NId1, const int& NId2) { }
void BackEdge(const int& NId1, const int& NId2) { }
void FwdEdge(const int& NId1, const int& NId2) { }
};
bool sortFunction(int a, int b,std::vector<float> distancias);
bool sortFunction2(std::pair<int, int> a, std::pair<int, int> b, std::vector<float> distancias);
class sorter {
std::vector<float> type_;
public:
sorter(std::vector<float> type) : type_(type) {}
bool operator()(int o1, int o2) const
{
return sortFunction(o1, o2, type_ );
}
};
class sorter2 {
std::vector<float> type_;
public:
sorter2(std::vector<float> type) : type_(type) {}
bool operator()(std::pair<int, int> o1,std::pair<int, int> o2) const
{
return sortFunction2(o1, o2, type_ );
}
};
//DECLARACIÓN OF DIJKSTRA'S ALGORITHM
//dijkstra (Grafo,Nodo origen)
void dijkstra(TPt<TNodeEDatNet<TInt, TFlt> > graph, const int &SrcNId);
void prim(TPt<TNodeEDatNet<TInt, TFlt> > graph, const int &v);
void printVector(std::vector<int> vector);
void menu(TPt<TNodeEDatNet<TInt, TFlt> > graph);
void kruskal(TPt<TNodeEDatNet<TInt, TFlt> > graph);
void fw(TPt<TNodeEDatNet<TInt, TFlt> > graph);
int main(int argc, char* argv[]) {
//Declaración del grafo dirigido
TPt<TNodeEDatNet<TInt, TFlt> > grafo = TNodeEDatNet<TInt, TFlt>::New();
// menu(grafo);
//Codigo comentado para test
//ADD NODES
//AddNode(id)
for (int i = 1; i<15; i++)
{
grafo->AddNode(i);
}
//ADD EDGES
//(Origen, Desitno, Weight)
grafo->AddEdge(1,4,8);
grafo->AddEdge(1,3,8);
grafo->AddEdge(2,5,7);
grafo->AddEdge(3,10,4);
grafo->AddEdge(3,5,8);
grafo->AddEdge(3,2,7);
grafo->AddEdge(4,7,3);
grafo->AddEdge(4,5,1);
grafo->AddEdge(4,8,2);
grafo->AddEdge(5,6,9);
grafo->AddEdge(6,13,4);
grafo->AddEdge(7,4,6);
grafo->AddEdge(8,9,3);
grafo->AddEdge(8,7,3);
grafo->AddEdge(9,10,2);
grafo->AddEdge(9,12,4);
grafo->AddEdge(10,3,10);
grafo->AddEdge(10,6,6);
grafo->AddEdge(11,12,6);
grafo->AddEdge(12,11,8);
grafo->AddEdge(12,9,2);
grafo->AddEdge(12,14,9);
grafo->AddEdge(13,14,6);
grafo->AddEdge(14,13,2);
// Floyd warshall.
std::cout << "++++++FLOYD-WARSHALL: " << std::endl;
auto rbt_ib = std::chrono::high_resolution_clock::now();
fw(grafo);
auto rbt_ie = std::chrono::high_resolution_clock::now();
auto rbt_i = std::chrono::duration_cast<std::chrono::microseconds>(rbt_ie-rbt_ib);
std::cout << "Tiempo en microsegundos: " << rbt_i.count() << std::endl;
//BFS
std::cout << "++++++BFS: " << std::endl;
rbt_ib = std::chrono::high_resolution_clock::now();
PNGraph GBFS =TSnap::GetBfsTree(grafo, 1, true, true);
rbt_ie = std::chrono::high_resolution_clock::now();
rbt_i = std::chrono::duration_cast<std::chrono::microseconds>(rbt_ie-rbt_ib);
std::cout << "Tiempo en microsegundos: " << rbt_i.count() << std::endl;
for (TNGraph::TNodeI NI = GBFS->BegNI(); NI < GBFS->EndNI(); NI++)
{
printf("%d\n", NI.GetId());
}
//DFS
std::cout << "++++++DFS: " << std::endl;
rbt_ib = std::chrono::high_resolution_clock::now();
myVis vis(grafo->GetNodes());
TCnCom::GetDfsVisitor(grafo, vis);
rbt_ie = std::chrono::high_resolution_clock::now();
rbt_i = std::chrono::duration_cast<std::chrono::microseconds>(rbt_ie-rbt_ib);
std::cout << "Tiempo en microsegundos: " << rbt_i.count() << std::endl;
//Dijkstra
std::cout << "++++++DJIKSTRA: " << std::endl;
rbt_ib = std::chrono::high_resolution_clock::now();
dijkstra(grafo, 1);
rbt_ie = std::chrono::high_resolution_clock::now();
rbt_i = std::chrono::duration_cast<std::chrono::microseconds>(rbt_ie-rbt_ib);
std::cout << "Tiempo en microsegundos: " << rbt_i.count() << std::endl;
//Prim
std::cout << "++++++PRIM: " << std::endl;
rbt_ib = std::chrono::high_resolution_clock::now();
prim(grafo, 1);
rbt_ie = std::chrono::high_resolution_clock::now();
rbt_i = std::chrono::duration_cast<std::chrono::microseconds>(rbt_ie-rbt_ib);
std::cout << "Tiempo en microsegundos: " << rbt_i.count() << std::endl;
//Kruskal
std::cout << "++++++KRUSKAL: " << std::endl;
rbt_ib = std::chrono::high_resolution_clock::now();
kruskal(grafo);
rbt_ie = std::chrono::high_resolution_clock::now();
rbt_i = std::chrono::duration_cast<std::chrono::microseconds>(rbt_ie-rbt_ib);
std::cout << "Tiempo en microsegundos: " << rbt_i.count() << std::endl;
return 0;
}
//IMPLEMENTATION OF DIJKSTRA'S ALGORITHM
//dijkstra (Grafo,Nodo origen)
void dijkstra(TPt<TNodeEDatNet<TInt, TFlt> > graph, const int &v)
{
int size = graph->GetNodes();
std::vector<float> distances (size,INFINITY);
std::vector<int> parents (size,-1);
std::deque<int> noVisitados;
std::vector<int> visitados;
for(int i=0; i<size; i++)
{
noVisitados.push_back(i+1);
}
distances[v-1] = 0;
while(!noVisitados.empty())
{
//Ordenar los no visitados en base a su distancia
std::sort(noVisitados.begin(), noVisitados.end(), sorter(distances));
int u = noVisitados[0];//El primero de los no visitados es el de la distancia mas corta
noVisitados.pop_front();//Sacar al mas corto de la cola
visitados.push_back(u); //Meterlo en la lista de los que ya se visitaron
int sourceNode = u; //Asignar este con el siguiente nodo de inicio
TNodeEDatNet<TInt, TFlt>::TNodeI NI = graph->GetNI(sourceNode);
//Iterar por cada arista que sale de el nodo
for (int e = 0; e < NI.GetOutDeg(); e++)
{
int destNode = NI.GetOutNId(e);//Sacar el nodo destino
TNodeEDatNet<TInt, TFlt>::TEdgeI EI = graph->GetEI(sourceNode,destNode);//Sacar la arista
float edgeWeight = (float)EI.GetDat(); //Sacar el dato de la arista (peso)
//Si la distancia es menor susituir, si no se deja igual
if(distances[destNode-1] > distances[sourceNode-1] + edgeWeight)
{
distances[destNode-1] = distances[sourceNode-1] + edgeWeight;
parents[destNode-1] = sourceNode;
}
}
}
int node = 1;
//Impresión de el camino mas corto
for (int i = 0 ; i< parents.size(); i++)
{
std::cout << parents[node-1] << " -> " << node << " distance: " << distances[node-1] << std::endl;
node++;
}
}
//Función para imprimir un vector de ints
void printVector(std::vector<int> vector)
{
printf("[ ");
for (int i = 0; i < vector.size(); i++)
{
printf("%d ",vector[i]);
}
printf("] \n");
}
//Función para poder ordenar el vector de noVisitados en relación a su distancia
bool sortFunction(int a, int b, std::vector<float> distancias)
{
return distancias[a-1] < distancias[b-1];
}
bool sortFunction2(std::pair<int, int> a, std::pair<int, int> b, std::vector<float> distancias)
{
return distancias[a.first-1] < distancias [b.first-1];
}
//Función del algoritmo de prim
void prim(TPt<TNodeEDatNet<TInt, TFlt> > graph, const int &v)
{
int size = graph->GetNodes();
int tam = size;
int graphMatrix[tam][tam];
int peso = 0;
for (int i = 0; i<size; i++)
{
for (int j = 0; j<size; j++)
{
peso = graph->GetEDat(i+1, j+1);
if (peso > 0)
{
graphMatrix[i][j] = peso;
}
else
{
graphMatrix[i][j] = INFINITY;
}
}
}
//Código para poder imprimir la matriz de el gráfo
// for (int i = 0; i<size; i++)
// {
// for (int j = 0; j<size; j++)
// {
// std::cout << graphMatrix[i][j] << " ";
// }
// std::cout << std::endl;
// }
int selected[tam], i, j,ne;
int min, x, y;
for (i = 0; i<tam; i++)
{
selected[i] = false;
}
selected[0] = true;
ne = 0;
while (ne < tam-1)
{
min=INFINITY;
for(i=0;i<tam;i++)
{
if(selected[i]==true)
{
for(j=0;j<tam;j++)
{
if(selected[j]==false)
{
if(min > graphMatrix[i][j])
{
min=graphMatrix[i][j];
x=i;
y=j;
}
}
}
}
}
selected[y]=true;
//Imprimir padre y su hijo
std::cout<<x+1<<" --> "<<y+1 << "\n";
ne=ne+1;
}
}
void kruskal(TPt<TNodeEDatNet<TInt, TFlt> > graph)
{
const int N = graph->GetNodes();
std::vector<std::pair<int, int>> connections;
std::vector<std::pair<int, int>> tree;
std::vector<float> distances;
std::vector<int> visited;
for (int i = 0; i < N; i++){
for (int j = 0; j < N; j++){
int peso = graph->GetEDat(i+1, j+1);
if (peso != 0){
connections.push_back(std::make_pair(i, j));
distances.push_back(peso);
}
}
}
std::sort(connections.begin(), connections.end(), sorter2(distances));
tree.push_back(connections[0]);
visited.push_back(connections[0].first);
visited.push_back(connections[0].second);
int i = 1;
while(i < connections.size() || tree.size() < N){
bool firstFound = false;
bool secondFound = false;
for (int j = 0; j < visited.size(); j++){
if (visited[i] == connections[i].first){
firstFound = true;
}
if (visited[i] == connections[i].second){
secondFound = true;
}
}
if (!firstFound || !firstFound){
tree.push_back(connections[i]);
if (!firstFound){
visited.push_back(connections[i].first);
}
if (!secondFound){
visited.push_back(connections[i].second);
}
}
i++;
}
for (int i = 0; i < tree.size(); i++){
printf("parent[%d] = %d\n", tree[i].first, tree[i].second);
}
}
void fw(TPt<TNodeEDatNet<TInt, TFlt> > graph)
{
std::cout << "Entering Floyd Warshall: " << std::endl;
const int N = graph->GetNodes();
int size = N;
int distances[N][N];
int peso = 0;
for (int i = 0; i<size; i++)
{
for (int j = 0; j<size; j++)
{
peso = graph->GetEDat(i+1, j+1);
if(i==j)
{
distances[i][j]=0;
}
else if (peso > 0)
{
distances[i][j] = peso;
}
else
{
distances[i][j] = 999999999;
}
std::cout << std::setw(9) << distances[i][j] << " ";
}
std::cout << "\n";
}
for (int k = 0; k < N; k++)
{
std::cout << "Distance matrix after iteration " << k + 1 << "\n";
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
if (distances[i][j] > distances[i][k] + distances[k][j])
{
distances[i][j] = distances[i][k] + distances[k][j];
}
std::cout << std::setw(9) << distances[i][j] << " ";
}
std::cout << "\n";
}
}
}
void menu(TPt<TNodeEDatNet<TInt, TFlt> > graph)
{
int cont = 1;
int opcion=0;
int nodoOrigen;
int nodoDestino;
int v;
while (opcion !=9)
{
std::cout << "\tBienvenido" << std::endl;
std::cout << "Dame una opción" << std::endl;
std::cout << std::endl;
std::cout << "1. Añade un nodo" << std::endl;
std::cout << "2. Añade una arista" << std::endl;
std::cout << "3. Borra un nodo" << std::endl;
std::cout << "4. Borra una arista" << std::endl;
std::cout << "5. Dijkstra" << std::endl;
std::cout << "6. Prim" << std::endl;
std::cout << "7. BFS" << std::endl;
std::cout << "8. DFS" << std::endl;
std::cout << "9. Salir" << std::endl;
std::cin >> opcion;
std::cout << std::endl;
switch (opcion)
{
case 1:
graph->AddNode(cont);
cont++;
break;
case 2:
std::cout << "Dame el id del nodo origen" << std::endl;
std::cin >> nodoOrigen;
std::cout << std::endl;
std::cout << "Dame el id del nodo destino" << std::endl;
std::cin >> nodoDestino;
std::cout << std::endl;
graph->AddEdge(nodoOrigen, nodoDestino);
break;
case 3:
std::cout << "Dame el id del nodo que quieres borrar" << std::endl;
std::cin >> v;
graph->DelNode(v);
break;
case 4:
std::cout << "Dame el id del nodo origen de la arista que quieres borrar" << std::endl;
std::cin >> nodoOrigen;
std::cout << std::endl;
std::cout << "Dame el id del nodo destino de la arista que quieres borrar" << std::endl;
std::cin >> nodoDestino;
std::cout << std::endl;
graph->DelEdge(nodoOrigen, nodoDestino);
break;
case 5:
std::cout << "Dame el id del nodo del que quieres encontrar el camino mas corto" << std::endl;
std::cin >> v;
dijkstra(graph, v);
break;
case 6:
prim(graph, 1);
break;
case 7:
break;
case 8:
break;
case 9:
opcion=9;
break;
default:
break;
}
}
}
| [
"[email protected]"
] | |
34db4154b4298fd07f40ad73a9a8f572f2953d52 | 6115a3c414fd806dc4a8877c83a466f7d0f7acf2 | /bankAccount.h | 375b2ae118d05886b24b84b692a79fca97d1476a | [] | no_license | mike-b88/CS285Wk2 | 58e6779a45dcf460f61db5afad9cd20e5e621588 | 1d6c51dc0486001224df768d357f5bf656662615 | refs/heads/master | 2020-04-01T20:45:39.671186 | 2018-11-29T04:02:30 | 2018-11-29T04:02:30 | 153,619,345 | 0 | 0 | null | 2018-11-29T04:02:31 | 2018-10-18T12:21:58 | C++ | UTF-8 | C++ | false | false | 898 | h | #pragma once
#include <string>
//Class definition
//with extra features, password implementation is user program is optional
class bankAccount
{
public:
void printAll() const;
void getName() const;
int getAccNum()const;
void storeAccNum();
void getIntRate() const;
void getAccTypes() const;
//void compare(int&, string&);
void depositMon();
void withDraw();
void getBal() const;
void enterAccountName();
void storeAccNum(int&);
static int genAccountNum();
//void deposit();
void secretKey();
//string getKey()const;
// void X9.17KeyGen();
int chooseAccTypes();
std::string getKey()const;
bankAccount(); //use as default constructor!!!
private:
std::string accountName;
int accountNumber;
std::string checkingsAcc;
std::string savingsAcc;
std::string passWord;
double checkingBal;
double savingsBal;
double interestRate = 0.0001;
int userChoice;
}; | [
"[email protected]"
] | |
88bb68b8028def4c8edd7820ef6c874a613b4eea | 1af49694004c6fbc31deada5618dae37255ce978 | /content/browser/accessibility/browser_accessibility_state_impl_android.cc | 03f81c3078f129014e022cb4bc4198c74583c1f3 | [
"BSD-3-Clause"
] | permissive | sadrulhc/chromium | 59682b173a00269ed036eee5ebfa317ba3a770cc | a4b950c23db47a0fdd63549cccf9ac8acd8e2c41 | refs/heads/master | 2023-02-02T07:59:20.295144 | 2020-12-01T21:32:32 | 2020-12-01T21:32:32 | 317,678,056 | 3 | 0 | BSD-3-Clause | 2020-12-01T21:56:26 | 2020-12-01T21:56:25 | null | UTF-8 | C++ | false | false | 2,913 | cc | // Copyright 2018 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 "content/browser/accessibility/browser_accessibility_state_impl.h"
#include "base/android/jni_android.h"
#include "base/metrics/histogram_macros.h"
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/public/android/content_jni_headers/BrowserAccessibilityState_jni.h"
#include "content/public/browser/browser_thread.h"
#include "ui/gfx/animation/animation.h"
using base::android::AttachCurrentThread;
namespace content {
void BrowserAccessibilityStateImpl::PlatformInitialize() {
// Setup the listener for the prefers reduced motion setting changing, so we
// can inform the renderer about changes.
JNIEnv* env = AttachCurrentThread();
Java_BrowserAccessibilityState_registerAnimatorDurationScaleObserver(env);
}
void BrowserAccessibilityStateImpl::
UpdatePlatformSpecificHistogramsOnUIThread() {}
void BrowserAccessibilityStateImpl::
UpdatePlatformSpecificHistogramsOnOtherThread() {
// NOTE: this method is run from another thread to reduce jank, since
// there's no guarantee these system calls will return quickly. Be careful
// not to add any code that isn't safe to run from a non-main thread!
DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::UI));
// Screen reader metric.
ui::AXMode mode =
BrowserAccessibilityStateImpl::GetInstance()->GetAccessibilityMode();
UMA_HISTOGRAM_BOOLEAN("Accessibility.Android.ScreenReader",
mode.has_mode(ui::AXMode::kScreenReader));
}
void BrowserAccessibilityStateImpl::UpdateUniqueUserHistograms() {
ui::AXMode mode = GetAccessibilityMode();
UMA_HISTOGRAM_BOOLEAN("Accessibility.Android.ScreenReader.EveryReport",
mode.has_mode(ui::AXMode::kScreenReader));
}
void BrowserAccessibilityStateImpl::SetImageLabelsModeForProfile(
bool enabled,
BrowserContext* profile) {
std::vector<WebContentsImpl*> web_contents_vector =
WebContentsImpl::GetAllWebContents();
for (size_t i = 0; i < web_contents_vector.size(); ++i) {
if (web_contents_vector[i]->GetBrowserContext() != profile)
continue;
ui::AXMode ax_mode = web_contents_vector[i]->GetAccessibilityMode();
ax_mode.set_mode(ui::AXMode::kLabelImages, enabled);
web_contents_vector[i]->SetAccessibilityMode(ax_mode);
}
}
// static
void JNI_BrowserAccessibilityState_OnAnimatorDurationScaleChanged(JNIEnv* env) {
// We need to call into gfx::Animation and WebContentsImpl on the UI thread,
// so ensure that we setup the notification on the correct thread.
DCHECK_CURRENTLY_ON(BrowserThread::UI);
gfx::Animation::UpdatePrefersReducedMotion();
for (WebContentsImpl* wc : WebContentsImpl::GetAllWebContents()) {
wc->OnWebPreferencesChanged();
}
}
} // namespace content
| [
"[email protected]"
] | |
3c976f9ceda5c0788495f4c51be155e6d2553cd5 | 417f3c5f1df10a43fedde4600b141e5f850d7d6c | /424 - Integer Inquiry.cpp | e916a0b99c3dd59af4cf8b07dd14235b253c5463 | [] | no_license | HSAkash/UVA | 56ce6f7af2ab6186f3fbb153ab2473f3392677b0 | 849414cb8c3a4892df5bcdc8f2a444a6ad01b61a | refs/heads/master | 2021-12-14T18:56:08.037131 | 2021-12-03T02:40:04 | 2021-12-03T02:40:04 | 250,986,090 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 761 | cpp | #include<stdio.h>
int b[200];
int main()
{
int i,j,k,sum,a[200],l,temp,r,t=0,r2=0,r3;
char s[250];
while(scanf("%s",s)){
for(i=0;i<200;i++)a[i]=0;
for(i=0;s[i]>='0'&&s[i]<='9';i++){
a[i]=s[i]-'0';
}
l=i;
if(l==1&&s[0]=='0'){
for(i=r2-1;i>=0;i--)printf("%d",b[i]);
printf("\n");
return 0;
}
if(t==0)r2=l;
if(l>r2)r2=l;
for(i=0;i<l/2;i++){
temp=a[i];
a[i]=a[l-i-1];
a[l-i-1]=temp;
}
r=0;
for(i=0;i<r2;i++){
r3=r+a[i]+b[i];
b[i]=r3%10;
r=r3/10;
}
if(r>0)b[r2++]=r;
t=1;
}
}
| [
"[email protected]"
] | |
96677fe5bf707b79b74cbb874ea2239549791a89 | 18bb98bfd36f63fd3b6f3443fc3f04b0a9228a59 | /BackupDialog.h | cb47c62025ae2707023d00bee7464c23d2f9c3bd | [] | no_license | anzhsoft/Readings | c0909b540957aab9a8172a300d31e4c8c445dd56 | 72795df2556273ac168e8729ecae87b25e46d6c1 | refs/heads/master | 2020-04-06T05:21:43.719490 | 2014-01-04T11:18:39 | 2014-01-04T11:18:39 | 15,630,264 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,526 | h | #if !defined(AFX_BACKUPDIALOG_H__E53238C0_9F1C_49D2_AC3E_0AB50882319A__INCLUDED_)
#define AFX_BACKUPDIALOG_H__E53238C0_9F1C_49D2_AC3E_0AB50882319A__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// BackupDialog.h : header file
//
/////////////////////////////////////////////////////////////////////////////
// CBackupDialog dialog
class CBackupDialog : public CDialog
{
// Construction
public:
static UINT _Thread(LPVOID pParam);
CBackupDialog(CWnd* pParent = NULL); // standard constructor
void PowerCopy(CString src, CString dst, BOOL& quit);
CString sourcePath;
CString destPath;
__int64 used;
__int64 finished;
BOOL q;
CWinThread* th;
DWORD start;
// Dialog Data
//{{AFX_DATA(CBackupDialog)
enum { IDD = IDD_DIALOG_BACKUP };
CStatic m_tm;
CStatic m_tip;
CProgressCtrl m_progress;
//}}AFX_DATA
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CBackupDialog)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
// Generated message map functions
//{{AFX_MSG(CBackupDialog)
virtual BOOL OnInitDialog();
afx_msg void OnTimer(UINT nIDEvent);
afx_msg LRESULT OnFinished(WPARAM,LPARAM);
virtual void OnOK();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_BACKUPDIALOG_H__E53238C0_9F1C_49D2_AC3E_0AB50882319A__INCLUDED_)
| [
"[email protected]"
] | |
26efe7c68a457e2da81f9d270ef36611796b4722 | 1957f86d4539255fe7ffbcfe40ffbc4589b0a33c | /compileAttributes/PLNmodels/src/RcppExports.cpp | 8ef0f1a0dc85d3ee4af33fe715445c8dd17b5ea5 | [] | no_license | NAU-CS/RcppExports | fd9dc77f481bc50fec174f42f426535f49dcce3a | 87d1b597283aa458c53110ade228b33cd95545ff | refs/heads/master | 2022-07-26T10:32:13.235183 | 2022-07-08T16:56:58 | 2022-07-08T16:56:58 | 237,045,789 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,455 | cpp | // Generated by using Rcpp::compileAttributes() -> do not edit by hand
// Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393
#include <RcppArmadillo.h>
#include <Rcpp.h>
using namespace Rcpp;
// optim_spherical
Rcpp::List optim_spherical(arma::vec par, const arma::mat& Y, const arma::mat& X, const arma::mat& O, const arma::vec& w, Rcpp::List options);
RcppExport SEXP _PLNmodels_optim_spherical(SEXP parSEXP, SEXP YSEXP, SEXP XSEXP, SEXP OSEXP, SEXP wSEXP, SEXP optionsSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< arma::vec >::type par(parSEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type Y(YSEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type X(XSEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type O(OSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type w(wSEXP);
Rcpp::traits::input_parameter< Rcpp::List >::type options(optionsSEXP);
rcpp_result_gen = Rcpp::wrap(optim_spherical(par, Y, X, O, w, options));
return rcpp_result_gen;
END_RCPP
}
// optim_diagonal
Rcpp::List optim_diagonal(arma::vec par, const arma::mat& Y, const arma::mat& X, const arma::mat& O, const arma::vec& w, Rcpp::List options);
RcppExport SEXP _PLNmodels_optim_diagonal(SEXP parSEXP, SEXP YSEXP, SEXP XSEXP, SEXP OSEXP, SEXP wSEXP, SEXP optionsSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< arma::vec >::type par(parSEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type Y(YSEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type X(XSEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type O(OSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type w(wSEXP);
Rcpp::traits::input_parameter< Rcpp::List >::type options(optionsSEXP);
rcpp_result_gen = Rcpp::wrap(optim_diagonal(par, Y, X, O, w, options));
return rcpp_result_gen;
END_RCPP
}
// optim_full
Rcpp::List optim_full(arma::vec par, const arma::mat& Y, const arma::mat& X, const arma::mat& O, const arma::vec& w, Rcpp::List options);
RcppExport SEXP _PLNmodels_optim_full(SEXP parSEXP, SEXP YSEXP, SEXP XSEXP, SEXP OSEXP, SEXP wSEXP, SEXP optionsSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< arma::vec >::type par(parSEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type Y(YSEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type X(XSEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type O(OSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type w(wSEXP);
Rcpp::traits::input_parameter< Rcpp::List >::type options(optionsSEXP);
rcpp_result_gen = Rcpp::wrap(optim_full(par, Y, X, O, w, options));
return rcpp_result_gen;
END_RCPP
}
// optim_rank
Rcpp::List optim_rank(arma::vec par, const arma::mat& Y, const arma::mat& X, const arma::mat& O, const arma::vec& w, Rcpp::List options);
RcppExport SEXP _PLNmodels_optim_rank(SEXP parSEXP, SEXP YSEXP, SEXP XSEXP, SEXP OSEXP, SEXP wSEXP, SEXP optionsSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< arma::vec >::type par(parSEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type Y(YSEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type X(XSEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type O(OSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type w(wSEXP);
Rcpp::traits::input_parameter< Rcpp::List >::type options(optionsSEXP);
rcpp_result_gen = Rcpp::wrap(optim_rank(par, Y, X, O, w, options));
return rcpp_result_gen;
END_RCPP
}
// optim_sparse
Rcpp::List optim_sparse(arma::vec par, const arma::mat& Y, const arma::mat& X, const arma::mat& O, const arma::vec& w, Rcpp::List options);
RcppExport SEXP _PLNmodels_optim_sparse(SEXP parSEXP, SEXP YSEXP, SEXP XSEXP, SEXP OSEXP, SEXP wSEXP, SEXP optionsSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< arma::vec >::type par(parSEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type Y(YSEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type X(XSEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type O(OSEXP);
Rcpp::traits::input_parameter< const arma::vec& >::type w(wSEXP);
Rcpp::traits::input_parameter< Rcpp::List >::type options(optionsSEXP);
rcpp_result_gen = Rcpp::wrap(optim_sparse(par, Y, X, O, w, options));
return rcpp_result_gen;
END_RCPP
}
// optimization_VEstep_PLN
Rcpp::List optimization_VEstep_PLN(arma::vec par, const arma::mat& Y, const arma::mat& X, const arma::mat& O, const arma::mat& Theta, const arma::mat& Sigma, Rcpp::List options);
RcppExport SEXP _PLNmodels_optimization_VEstep_PLN(SEXP parSEXP, SEXP YSEXP, SEXP XSEXP, SEXP OSEXP, SEXP ThetaSEXP, SEXP SigmaSEXP, SEXP optionsSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< arma::vec >::type par(parSEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type Y(YSEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type X(XSEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type O(OSEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type Theta(ThetaSEXP);
Rcpp::traits::input_parameter< const arma::mat& >::type Sigma(SigmaSEXP);
Rcpp::traits::input_parameter< Rcpp::List >::type options(optionsSEXP);
rcpp_result_gen = Rcpp::wrap(optimization_VEstep_PLN(par, Y, X, O, Theta, Sigma, options));
return rcpp_result_gen;
END_RCPP
}
static const R_CallMethodDef CallEntries[] = {
{"_PLNmodels_optim_spherical", (DL_FUNC) &_PLNmodels_optim_spherical, 6},
{"_PLNmodels_optim_diagonal", (DL_FUNC) &_PLNmodels_optim_diagonal, 6},
{"_PLNmodels_optim_full", (DL_FUNC) &_PLNmodels_optim_full, 6},
{"_PLNmodels_optim_rank", (DL_FUNC) &_PLNmodels_optim_rank, 6},
{"_PLNmodels_optim_sparse", (DL_FUNC) &_PLNmodels_optim_sparse, 6},
{"_PLNmodels_optimization_VEstep_PLN", (DL_FUNC) &_PLNmodels_optimization_VEstep_PLN, 7},
{NULL, NULL, 0}
};
RcppExport void R_init_PLNmodels(DllInfo *dll) {
R_registerRoutines(dll, NULL, CallEntries, NULL, NULL);
R_useDynamicSymbols(dll, FALSE);
}
| [
"[email protected]"
] | |
950fc376b44e0bbff000b7d1b86a8d6836cf8809 | 252ed0371ecc0685a5027780b702fb864ae6a1b1 | /Samples/Shared/CameraKsPropertyHelper/BackgroundSegmentationConfigCaps.cpp | ea979040af4eeefccfb450691d353db2a3c69f52 | [
"LicenseRef-scancode-generic-cla",
"MIT"
] | permissive | microsoft/Windows-Camera | 64a6236ccdea904e1e962d6ac1abe18b637cc5e4 | eb7bfd7b02fd3985ab4a187feb1187a0b0d56d94 | refs/heads/master | 2023-08-21T05:56:02.289672 | 2023-06-07T18:14:21 | 2023-06-07T18:14:21 | 128,274,185 | 134 | 58 | MIT | 2023-04-08T00:31:00 | 2018-04-05T23:09:58 | C# | UTF-8 | C++ | false | false | 164 | cpp | // Copyright (c) Microsoft. All rights reserved.
#include "pch.h"
#include "BackgroundSegmentationConfigCaps.h"
#include "BackgroundSegmentationConfigCaps.g.cpp"
| [
"[email protected]"
] | |
f6af95fbe69e838f035e56f089ce400075f407d3 | 4fcf2967da46f37c831b72b7b97f705d3364306d | /problems/acmicpc_11773.cpp | 5f895c621c2f5b01237e9ba550aa0017acc81ba3 | [
"MIT"
] | permissive | qawbecrdtey/BOJ-sol | e2be11e60c3c19e88439665d586cb69234f2e5db | 249b988225a8b4f52d27c5f526d7c8d3f4de557c | refs/heads/master | 2023-08-03T15:04:50.837332 | 2023-07-30T08:25:58 | 2023-07-30T08:25:58 | 205,078,469 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 498 | cpp | #include <iostream>
#include <string>
#include <queue>
using namespace std;
int main(){
int a,b;
scanf("%d%d",&a,&b);
queue<string> q;
q.push("");
int cnt=0;
int const m=(a<(b/2)?(b/2):a);
while(cnt<m){
string const now=q.front();
q.pop();
if(now.length()&&now.length()<16){
printf("%s ",now.c_str());
cnt++;
}
if(q.size()<b)
for(char i='a';i<='z';i++){
q.push(now+i);
}
}
} | [
"[email protected]"
] | |
d55f451d21153c4cb32f973d51232c100151f298 | 587e191159ab12e577940251d14558939e602614 | /verwrite/stockIT/app/src/main/include/Fuse.TranslationModes.WidthMode.h | ea0ec89cc67fea59f73e380e341bf37a4f2c61b1 | [] | no_license | hazimayesh/stockIT | cefcaa402e61108294f8db178ee807faf6b14d61 | 809381e7e32df270f0b007a6afc7b394453d1668 | refs/heads/master | 2021-04-09T16:10:23.318883 | 2017-07-31T21:28:05 | 2017-07-31T21:28:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,118 | h | // This file was generated based on 'C:\Users\Emenike pc\AppData\Local\Fusetools\Packages\FuseCore\0.43.11\$.uno'.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Fuse.ITransformMode.h>
#include <Fuse.ITranslationMode.h>
#include <Fuse.TranslationModes.SizeMode.h>
namespace g{namespace Fuse{struct Translation;}}
namespace g{namespace Fuse{struct TranslationModes__WidthMode;}}
namespace g{namespace Uno{struct Float3;}}
namespace g{
namespace Fuse{
// private sealed class TranslationModes.WidthMode :10312
// {
::g::Fuse::TranslationModes__SizeMode_type* TranslationModes__WidthMode_typeof();
void TranslationModes__WidthMode__ctor_1_fn(TranslationModes__WidthMode* __this);
void TranslationModes__WidthMode__GetAbsVector_fn(TranslationModes__WidthMode* __this, ::g::Fuse::Translation* t, ::g::Uno::Float3* __retval);
void TranslationModes__WidthMode__New2_fn(TranslationModes__WidthMode** __retval);
struct TranslationModes__WidthMode : ::g::Fuse::TranslationModes__SizeMode
{
void ctor_1();
static TranslationModes__WidthMode* New2();
};
// }
}} // ::g::Fuse
| [
"[email protected]"
] | |
aa3ab3f7750e7bf10708a08a57a560f61ac5fa69 | b7d10ca34603bd4781202b816fe5eec201708094 | /clean_ogre_cmake_project/Firefighters/GameObject.cpp | 400b6b6fa0e8f96b9d8fd301b2524611b96ae164 | [] | no_license | vic347/FireFighter | 05af8d5dd84c5527c30d2a2963b860c355fb61f7 | 720531f46d8c82fc36ff9832a6b7853e535afc1b | refs/heads/master | 2021-01-20T14:29:53.118705 | 2017-05-09T12:52:38 | 2017-05-09T12:52:38 | 90,620,470 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,251 | cpp | //|||||||||||||||||||||||||||||||||||||||||||||||
#include "GameObject.hpp"
#include "ObjectManagement.hpp"
//|||||||||||||||||||||||||||||||||||||||||||||||
using namespace Ogre;
//|||||||||||||||||||||||||||||||||||||||||||||||
/** Default constructor for GameObject
*
* \param mesh
* \param materialName
* \param position
*/
GameObject::GameObject(std::string mesh, std::string materialName, Ogre::Vector3 position, Ogre::Vector2 gridPosition)
{
m_pSceneMgr = OgreFramework::getSingletonPtr()->m_pRoot->getSceneManager("GameSceneMgr");
gameObjectEntity = m_pSceneMgr->createEntity(mesh);
if (materialName == "RockWall")
{
gameObjectNode = m_pSceneMgr->getRootSceneNode()->createChildSceneNode();
}
else if (materialName == "FireFighter")
{
gameObjectNode = m_pSceneMgr->getRootSceneNode()->createChildSceneNode();
}
else
{
gameObjectNode = m_pSceneMgr->createSceneNode();
}
gameObjectNode->setPosition(position);
gameObjectNode->setUserAny(Ogre::Any(this)); // Attach GameObject on the node
gameObjectEntity->setUserAny(Ogre::Any(this));
if (materialName == "Fire")
gameObjectNode->setScale(0.5, 0.5, 0.5);
gameObjectNode->attachObject(gameObjectEntity);
gameObjectEntity->setMaterialName(materialName);
setGridPosition(gridPosition);
ObjectManagement::getSingletonPtr()->addObject(this);
}
GameObject::GameObject(std::string mesh, std::string materialName, Ogre::Vector3 position, float startingRotation, Vector2 gridPosition)
{
m_pSceneMgr = OgreFramework::getSingletonPtr()->m_pRoot->getSceneManager("GameSceneMgr");
if (materialName == "RockWall")
{
gameObjectNode = m_pSceneMgr->getRootSceneNode()->createChildSceneNode();
}
else if (materialName == "FireFighter")
{
gameObjectNode = m_pSceneMgr->getRootSceneNode();
}
else
{
gameObjectNode = m_pSceneMgr->createSceneNode();
}
gameObjectEntity = m_pSceneMgr->createEntity(mesh);
//gameObjectNode = m_pSceneMgr->getRootSceneNode()->createChildSceneNode();
gameObjectNode->setPosition(position);
gameObjectNode->setUserAny(Ogre::Any(this)); // Attach GameObject on the node
gameObjectEntity->setUserAny(Ogre::Any(this));
if (materialName == "Fire")
gameObjectNode->setScale(0.5, 0.5, 0.5);
gameObjectNode->attachObject(gameObjectEntity);
gameObjectEntity->setMaterialName(materialName);
setGridPosition(gridPosition);
gameObjectNode->rotate(Ogre::Vector3::NEGATIVE_UNIT_Y, Ogre::Degree(startingRotation));
ObjectManagement::getSingletonPtr()->addObject(this);
}
GameObject::GameObject()
{
m_pSceneMgr = OgreFramework::getSingletonPtr()->m_pRoot->getSceneManager("GameSceneMgr");
gameObjectEntity = nullptr;
gameObjectNode = nullptr;
}
//void GameObject::update()
//{
//}
void GameObject::draw()
{
}
std::string GameObject::getTag()
{
return tag;
}
//|||||||||||||||||||||||||||||||||||||||||||||||
GameObject::~GameObject()
{
ObjectManagement::getSingletonPtr()->deleteObject(this);
//delete m_pSceneMgr;
}
//|||||||||||||||||||||||||||||||||||||||||||||||
/**
* Setter for @Param gridPosition
*/
void GameObject::setGridPosition(Ogre::Vector2 newGridPosition)
{
gridPosition = newGridPosition;
}
/**
* Getter for @Param gridPosition
*/
Ogre::Vector2 GameObject::getGridPosition()
{
return gridPosition;
}
| [
"[email protected]"
] | |
90013220f6e3e2dbd42669fe1648b9bc30da3089 | 406fe3543dc160f046eac9a6fde40732e1b19b0a | /src/randoms/sobol.H | 305caa230b757ff73a441b1f7d2e0340198e0ee9 | [] | no_license | simw/opacity | 16598883db92ca4d5b7ec565a5abab52fa39ea66 | dee6408d5f9c2849a9c28d90282b4eb18520ab0c | refs/heads/master | 2020-05-27T05:40:05.696142 | 2014-08-19T23:20:09 | 2014-08-19T23:20:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,103 | h |
namespace Sobol
{
//
// 32 bit integer routines.
//
int i4_bit_hi1 ( int n );
int i4_bit_lo0 ( int n );
int i4_max ( int i1, int i2 );
int i4_min ( int i1, int i2 );
void i4_sobol ( int dim_num, int *seed, float quasi[ ] );
int i4_uniform ( int b, int c, int *seed );
unsigned int i4_xor ( unsigned int i, unsigned int j );
//
// 64 bit integer routines.
//
int i8_bit_hi1 ( long long int n );
int i8_bit_lo0 ( long long int n );
long long int i8_max ( long long int i1, long long int i2 );
long long int i8_min ( long long int i1, long long int i2 );
void i8_sobol ( int dim_num, long long int *seed, double quasi[ ] );
long long int i8_uniform ( long long int b, long long int c, int *seed );
unsigned long long int i8_xor ( unsigned long long int i,
unsigned long long int j );
//
// 32 bit real rotuines.
//
float r4_abs ( float x );
int r4_nint ( float x );
float r4_uniform_01 ( int *seed );
//
// 64 bit real routines.
//
double r8_abs ( double x );
int r8_nint ( double x );
double r8_uniform_01 ( int *seed );
//
// Utilities.
//
void timestamp ( void );
} // End of Sobol namespace
| [
"[email protected]"
] | |
3b19d36902bec8d2af2155507b3b6e8af5ad2438 | e1c1a66df2844a73b8590df873693b6b6daaefd3 | /(C++)ProblemSolving/ProblemSolving/[BOJ_2805]나무 자르기.cpp | 58d30f2002acc3ce8bd13c6ffe67243bfc47659c | [] | no_license | SwimmingLee/ProblemSolving | 0c61dc5ea7aa9e46319d3f02dca023f60ff869a7 | 21bcb6c526342b124c2ff74858f3cec9ac4577a5 | refs/heads/master | 2021-11-24T21:13:10.687022 | 2021-11-18T15:10:00 | 2021-11-18T15:10:00 | 244,309,231 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 568 | cpp | #include <iostream>
#include <algorithm>
using namespace std;
int arr[1000000];
int main(void) {
int n, length;
cin >> n >> length;
for (int i = 0; i < n; i++)
cin >> arr[i];
int total = -987987987;
int left, right, mid;
left = 0;
right = 1e9;
while (left <= right) {
mid = (left + right) / 2;
long long sum = 0;
for (int i = 0; i < n; i++) {
int part = arr[i] - mid;
sum += part > 0 ? part : 0;
}
if (sum >= length) {
total = max(total, mid);
left = mid + 1;
}
else right = mid - 1;
}
cout << total << '\n';
return 0;
} | [
"[email protected]"
] | |
a4c2b9920cb9351d2242df8c6d1c89c4679ea313 | d1a8325badc20c344a586793593692c201c3f5e8 | /sem1-2-cource1/QUEUE-CHEAT-DOC.cpp | f325c0b698bbc13e72a13832412879d988ba3948 | [
"MIT"
] | permissive | yokkidack/bmstu | 6aa378edcf5bcb191a7997b7155b0373dbd93e56 | 3533ac4cd5376b25c1f236ce606e3e2c28944244 | refs/heads/master | 2021-07-03T23:44:38.420172 | 2020-09-04T08:55:48 | 2020-09-04T08:55:48 | 165,707,061 | 1 | 3 | MIT | 2019-01-20T15:06:56 | 2019-01-14T17:47:01 | null | UTF-8 | C++ | false | false | 6,613 | cpp |
/*
так реализована очередь в std
*/
template <class _Tp, class _Container /*= deque<_Tp>*/>
class _LIBCPP_TEMPLATE_VIS queue
{
public:
typedef _Container container_type;
typedef typename container_type::value_type value_type;
typedef typename container_type::reference reference;
typedef typename container_type::const_reference const_reference;
typedef typename container_type::size_type size_type;
static_assert((is_same<_Tp, value_type>::value), "" );
protected:
container_type c;
public:
_LIBCPP_INLINE_VISIBILITY
queue()
_NOEXCEPT_(is_nothrow_default_constructible<container_type>::value)
: c() {}
_LIBCPP_INLINE_VISIBILITY
queue(const queue& __q) : c(__q.c) {}
#ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES
_LIBCPP_INLINE_VISIBILITY
queue(queue&& __q)
_NOEXCEPT_(is_nothrow_move_constructible<container_type>::value)
: c(_VSTD::move(__q.c)) {}
#endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES
_LIBCPP_INLINE_VISIBILITY
queue& operator=(const queue& __q) {c = __q.c; return *this;}
#ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES
_LIBCPP_INLINE_VISIBILITY
queue& operator=(queue&& __q)
_NOEXCEPT_(is_nothrow_move_assignable<container_type>::value)
{c = _VSTD::move(__q.c); return *this;}
#endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES
_LIBCPP_INLINE_VISIBILITY
explicit queue(const container_type& __c) : c(__c) {}
#ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES
_LIBCPP_INLINE_VISIBILITY
explicit queue(container_type&& __c) : c(_VSTD::move(__c)) {}
#endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES
template <class _Alloc>
_LIBCPP_INLINE_VISIBILITY
explicit queue(const _Alloc& __a,
typename enable_if<uses_allocator<container_type,
_Alloc>::value>::type* = 0)
: c(__a) {}
template <class _Alloc>
_LIBCPP_INLINE_VISIBILITY
queue(const queue& __q, const _Alloc& __a,
typename enable_if<uses_allocator<container_type,
_Alloc>::value>::type* = 0)
: c(__q.c, __a) {}
template <class _Alloc>
_LIBCPP_INLINE_VISIBILITY
queue(const container_type& __c, const _Alloc& __a,
typename enable_if<uses_allocator<container_type,
_Alloc>::value>::type* = 0)
: c(__c, __a) {}
#ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES
template <class _Alloc>
_LIBCPP_INLINE_VISIBILITY
queue(container_type&& __c, const _Alloc& __a,
typename enable_if<uses_allocator<container_type,
_Alloc>::value>::type* = 0)
: c(_VSTD::move(__c), __a) {}
template <class _Alloc>
_LIBCPP_INLINE_VISIBILITY
queue(queue&& __q, const _Alloc& __a,
typename enable_if<uses_allocator<container_type,
_Alloc>::value>::type* = 0)
: c(_VSTD::move(__q.c), __a) {}
#endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES
_LIBCPP_INLINE_VISIBILITY
bool empty() const {return c.empty();}
_LIBCPP_INLINE_VISIBILITY
size_type size() const {return c.size();}
_LIBCPP_INLINE_VISIBILITY
reference front() {return c.front();}
_LIBCPP_INLINE_VISIBILITY
const_reference front() const {return c.front();}
_LIBCPP_INLINE_VISIBILITY
reference back() {return c.back();}
_LIBCPP_INLINE_VISIBILITY
const_reference back() const {return c.back();}
_LIBCPP_INLINE_VISIBILITY
void push(const value_type& __v) {c.push_back(__v);}
#ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES
_LIBCPP_INLINE_VISIBILITY
void push(value_type&& __v) {c.push_back(_VSTD::move(__v));}
#ifndef _LIBCPP_HAS_NO_VARIADICS
template <class... _Args>
_LIBCPP_INLINE_VISIBILITY
#if _LIBCPP_STD_VER > 14
reference emplace(_Args&&... __args)
{ return c.emplace_back(_VSTD::forward<_Args>(__args)...);}
#else
void emplace(_Args&&... __args)
{ c.emplace_back(_VSTD::forward<_Args>(__args)...);}
#endif
#endif // _LIBCPP_HAS_NO_VARIADICS
#endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES
_LIBCPP_INLINE_VISIBILITY
void pop() {c.pop_front();}
_LIBCPP_INLINE_VISIBILITY
void swap(queue& __q)
_NOEXCEPT_(__is_nothrow_swappable<container_type>::value)
{
using _VSTD::swap;
swap(c, __q.c);
}
template <class _T1, class _C1>
friend
_LIBCPP_INLINE_VISIBILITY
bool
operator==(const queue<_T1, _C1>& __x,const queue<_T1, _C1>& __y);
template <class _T1, class _C1>
friend
_LIBCPP_INLINE_VISIBILITY
bool
operator< (const queue<_T1, _C1>& __x,const queue<_T1, _C1>& __y);
};
template <class _Tp, class _Container>
inline _LIBCPP_INLINE_VISIBILITY
bool
operator==(const queue<_Tp, _Container>& __x,const queue<_Tp, _Container>& __y)
{
return __x.c == __y.c;
}
template <class _Tp, class _Container>
inline _LIBCPP_INLINE_VISIBILITY
bool
operator< (const queue<_Tp, _Container>& __x,const queue<_Tp, _Container>& __y)
{
return __x.c < __y.c;
}
template <class _Tp, class _Container>
inline _LIBCPP_INLINE_VISIBILITY
bool
operator!=(const queue<_Tp, _Container>& __x,const queue<_Tp, _Container>& __y)
{
return !(__x == __y);
}
template <class _Tp, class _Container>
inline _LIBCPP_INLINE_VISIBILITY
bool
operator> (const queue<_Tp, _Container>& __x,const queue<_Tp, _Container>& __y)
{
return __y < __x;
}
template <class _Tp, class _Container>
inline _LIBCPP_INLINE_VISIBILITY
bool
operator>=(const queue<_Tp, _Container>& __x,const queue<_Tp, _Container>& __y)
{
return !(__x < __y);
}
template <class _Tp, class _Container>
inline _LIBCPP_INLINE_VISIBILITY
bool
operator<=(const queue<_Tp, _Container>& __x,const queue<_Tp, _Container>& __y)
{
return !(__y < __x);
}
template <class _Tp, class _Container>
inline _LIBCPP_INLINE_VISIBILITY
typename enable_if<
__is_swappable<_Container>::value,
void
>::type
swap(queue<_Tp, _Container>& __x, queue<_Tp, _Container>& __y)
_NOEXCEPT_(_NOEXCEPT_(__x.swap(__y)))
{
__x.swap(__y);
}
template <class _Tp, class _Container, class _Alloc>
struct _LIBCPP_TEMPLATE_VIS uses_allocator<queue<_Tp, _Container>, _Alloc>
: public uses_allocator<_Container, _Alloc>
{
};
| [
"[email protected]"
] | |
39cc51102c80b0fd6f724870a91e5a8f757dac04 | 1001817eed1a9e1dc8bbb89df8c52592dc5792e1 | /src/codes/w_07/prng_util/20180423_2147/dist_test_beta.cc | d31ec2590471592eff4937bdced03530fe101ddf | [] | no_license | ninjalp/gtu-elec-433-631 | 031d736da72d9eaa5e1dee90bdfafaa0d0c47bd0 | 47ac2f31f14dab9a4b6877dac19e6a6bdf2ca8bf | refs/heads/main | 2023-05-13T06:03:59.660704 | 2021-06-08T12:33:39 | 2021-06-08T12:33:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,389 | cc | /*
* This file is part of the "dev-in-place" repository located at:
* https://github.com/osuvak/dev-in-place
*
* Copyright (C) 2018 Onder Suvak
*
* For licensing information check the above url.
* Please do not remove this header.
* */
#include "prng_static_ctor.hh"
#include <iostream>
#include <iomanip>
#include <algorithm>
// #define USE_STATIC_IMPL
int main ()
{
#ifdef HAVE_BOOST
using namespace os_prng_sc;
const int nRolls = 100000 ; // number of experiments
#ifndef USE_STATIC_IMPL
PRNG_COMMON rgen;
#endif
std::vector<double> numbers;
std::string heading;
unsigned int ch = 3;
switch ( ch )
{
case 1 :
numbers =
#ifndef USE_STATIC_IMPL
rgen.randn
#else
PRNG_Static::randn
#endif
( nRolls , 5.0 , 2.0 );
heading = "normal_distribution (5.0,2.0):";
break;
case 2 :
numbers =
#ifndef USE_STATIC_IMPL
rgen.rand
#else
PRNG_Static::rand
#endif
( nRolls , 0.0 , 10.0 );
heading = "uniform_distribution (0.0,10.0):";
break;
case 3 :
numbers =
#ifndef USE_STATIC_IMPL
rgen.randbeta
#else
PRNG_Static::randbeta
#endif
( nRolls , 5.0 , 2.0 , 10.0 , 20.0 );
heading = "beta_distribution (5.0, 2.0):";
break;
}
plot_histogram( numbers , 10.0 , 20.0 , heading , 500 , 40 );
#endif
return 0;
}
| [
"[email protected]"
] | |
cb8791836a71b4d3a39c1fe30aeb2a429c2d0b05 | 47c25c6e4d6c6435b750207f741eb65015662669 | /branches/build-system/arch/win32/include/pch.h | d338a2861073f7e7505a3af075cd6dc96f2b7852 | [] | no_license | paud/d2x-xl | 0e1ea14fa060e46503d0328692451da65d561192 | 7b5b1089a856647962e636c9d4bc8d2e977e5ddb | refs/heads/master | 2021-01-21T02:11:13.027136 | 2009-08-23T12:13:44 | 2009-08-23T12:13:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 665 | h | #define D3D_OVERLOADS
#define WIN32_MEAN_AND_LEAN
#if 0
class _Lockit
{
public:
_Lockit () {}
~_Lockit () {}
};
#define _Lockit ___Lockit
#include <yvals.h>
#undef _Lockit
#endif
#include <windows.h>
#include <windowsx.h>
#include <ddraw.h>
#include <dinput.h>
#include <d3d.h>
#include <d3dtypes.h>
#include <dsound.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <double.h>
#include <tchar.h>
#include <assert.h>
#include <list>
#include <queue>
#include <set>
#include <map>
#include <atlbase.h>
extern CComModule _Module;
#include <atlcom.h>
#include "resource.h"
#define ASSERT(x) _ASSERTE(x)
#pragma warning (disable: 4786)
| [
"[email protected]"
] | |
fc0364accda07d63b0c9af4ff2b4d304194d5b58 | 7d5537f9562461770451aead76ec1589a219cca2 | /catkin_ws/devel/include/darknet_ros_msgs/BoundingBox.h | c39e51e38314a684922e21579889005f738abf9d | [] | no_license | sinsinsin00/KSS | 5606820dde032abf424c43cc33264343a1b531cf | 26393be824150b5fc6ace51e543da58b09468d74 | refs/heads/master | 2021-07-07T00:03:41.002098 | 2020-07-27T05:02:45 | 2020-07-27T05:02:45 | 156,021,380 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,583 | h | // Generated by gencpp from file darknet_ros_msgs/BoundingBox.msg
// DO NOT EDIT!
#ifndef DARKNET_ROS_MSGS_MESSAGE_BOUNDINGBOX_H
#define DARKNET_ROS_MSGS_MESSAGE_BOUNDINGBOX_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>
namespace darknet_ros_msgs
{
template <class ContainerAllocator>
struct BoundingBox_
{
typedef BoundingBox_<ContainerAllocator> Type;
BoundingBox_()
: Class()
, probability(0.0)
, xmin(0)
, ymin(0)
, xmax(0)
, ymax(0) {
}
BoundingBox_(const ContainerAllocator& _alloc)
: Class(_alloc)
, probability(0.0)
, xmin(0)
, ymin(0)
, xmax(0)
, ymax(0) {
(void)_alloc;
}
typedef std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > _Class_type;
_Class_type Class;
typedef double _probability_type;
_probability_type probability;
typedef int64_t _xmin_type;
_xmin_type xmin;
typedef int64_t _ymin_type;
_ymin_type ymin;
typedef int64_t _xmax_type;
_xmax_type xmax;
typedef int64_t _ymax_type;
_ymax_type ymax;
typedef boost::shared_ptr< ::darknet_ros_msgs::BoundingBox_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::darknet_ros_msgs::BoundingBox_<ContainerAllocator> const> ConstPtr;
}; // struct BoundingBox_
typedef ::darknet_ros_msgs::BoundingBox_<std::allocator<void> > BoundingBox;
typedef boost::shared_ptr< ::darknet_ros_msgs::BoundingBox > BoundingBoxPtr;
typedef boost::shared_ptr< ::darknet_ros_msgs::BoundingBox const> BoundingBoxConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::darknet_ros_msgs::BoundingBox_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::darknet_ros_msgs::BoundingBox_<ContainerAllocator> >::stream(s, "", v);
return s;
}
} // namespace darknet_ros_msgs
namespace ros
{
namespace message_traits
{
// BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': False}
// {'sensor_msgs': ['/opt/ros/kinetic/share/sensor_msgs/cmake/../msg'], 'darknet_ros_msgs': ['/home/ksshin/catkin_ws/src/darknet_ros/darknet_ros_msgs/msg', '/home/ksshin/catkin_ws/devel/share/darknet_ros_msgs/msg'], 'actionlib_msgs': ['/opt/ros/kinetic/share/actionlib_msgs/cmake/../msg'], 'geometry_msgs': ['/opt/ros/kinetic/share/geometry_msgs/cmake/../msg'], 'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../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< ::darknet_ros_msgs::BoundingBox_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::darknet_ros_msgs::BoundingBox_<ContainerAllocator> const>
: FalseType
{ };
template <class ContainerAllocator>
struct IsMessage< ::darknet_ros_msgs::BoundingBox_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::darknet_ros_msgs::BoundingBox_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::darknet_ros_msgs::BoundingBox_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct HasHeader< ::darknet_ros_msgs::BoundingBox_<ContainerAllocator> const>
: FalseType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::darknet_ros_msgs::BoundingBox_<ContainerAllocator> >
{
static const char* value()
{
return "8434cf5c7ed632005efa1b05bb45ca2a";
}
static const char* value(const ::darknet_ros_msgs::BoundingBox_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0x8434cf5c7ed63200ULL;
static const uint64_t static_value2 = 0x5efa1b05bb45ca2aULL;
};
template<class ContainerAllocator>
struct DataType< ::darknet_ros_msgs::BoundingBox_<ContainerAllocator> >
{
static const char* value()
{
return "darknet_ros_msgs/BoundingBox";
}
static const char* value(const ::darknet_ros_msgs::BoundingBox_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::darknet_ros_msgs::BoundingBox_<ContainerAllocator> >
{
static const char* value()
{
return "string Class\n\
float64 probability\n\
int64 xmin\n\
int64 ymin\n\
int64 xmax\n\
int64 ymax\n\
\n\
";
}
static const char* value(const ::darknet_ros_msgs::BoundingBox_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::darknet_ros_msgs::BoundingBox_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)
{
stream.next(m.Class);
stream.next(m.probability);
stream.next(m.xmin);
stream.next(m.ymin);
stream.next(m.xmax);
stream.next(m.ymax);
}
ROS_DECLARE_ALLINONE_SERIALIZER
}; // struct BoundingBox_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::darknet_ros_msgs::BoundingBox_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::darknet_ros_msgs::BoundingBox_<ContainerAllocator>& v)
{
s << indent << "Class: ";
Printer<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::stream(s, indent + " ", v.Class);
s << indent << "probability: ";
Printer<double>::stream(s, indent + " ", v.probability);
s << indent << "xmin: ";
Printer<int64_t>::stream(s, indent + " ", v.xmin);
s << indent << "ymin: ";
Printer<int64_t>::stream(s, indent + " ", v.ymin);
s << indent << "xmax: ";
Printer<int64_t>::stream(s, indent + " ", v.xmax);
s << indent << "ymax: ";
Printer<int64_t>::stream(s, indent + " ", v.ymax);
}
};
} // namespace message_operations
} // namespace ros
#endif // DARKNET_ROS_MSGS_MESSAGE_BOUNDINGBOX_H
| [
"[email protected]"
] | |
6313a3fafa61360afb3d09623651a3f4b1e6a066 | 40a6ea8f4890c60a903b5051d861d8b26c3851e2 | /BOJAlgorithm/1152단어개수.cpp | a0a24f13a456bf070af831970956064ff1ab3231 | [] | no_license | golborneville/BOJAlgorithm | 82acd3273a57f226efed09ac1fc0f4cb9f0e6deb | a19614d5d82cb1f73a8762bdf5600dcd5fcaa179 | refs/heads/master | 2021-07-20T02:22:44.853694 | 2021-05-06T11:02:06 | 2021-05-06T11:02:06 | 248,513,580 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 590 | cpp | #include <iostream>
using namespace std;
int main() {
char string[1000003];
cin.getline(string, 1000003, '\n');
int i = 0, cnt =0;
while (string[i] != '\0') {
if (string[i] == ' ') {
if (i > 0) { //b_ -> 1
cnt++;
}
else { // (blank) char ~~
//1. (only blank)
if (string[i + 1] == '\0') {
cnt = 0;
break;
}
//2. _a_b => 2
// else pass
}
}
i++;
}
if (string[i - 1] != ' ') {
//_b(end)
cnt++;
}
if (string[0] == ' ' && string[1] == '\0') {
cnt = 0;
}
if (string[0] == '\0') {
cnt = 0;
}
cout << cnt;
return 0;
} | [
"[email protected]"
] | |
fb917bb52e29c5d2344b094b2620948521b8ac2d | 03bfe3a2d1bfa51c79582adbdb655ef2235c0118 | /tests/tinytemplate_tests.cpp | fbdcef30a87749b582205f4294f02dd5c9967678 | [
"MIT"
] | permissive | comargo/tinytemplate | 0b37900adb6f30515192cb3c58cc29fd4dcca868 | 0182eb7acb029ce85eaf668323a24e71034f87bf | refs/heads/master | 2021-01-19T23:19:32.493518 | 2017-04-21T12:59:38 | 2017-04-21T12:59:38 | 88,948,875 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,790 | cpp | // This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
#include <tinytemplate.hpp>
#include <gtest/gtest.h>
TEST(TinyTemplate, SimplePass)
{
std::string input = "test";
std::string expected = input;
std::map<std::string, std::string> vars;
std::string output = tinytemplate::render(input, vars);
EXPECT_EQ(expected, output);
}
TEST(TinyTemplate, SimpleVar)
{
std::string input = "t{{var}}t";
std::string expected = "test";
std::map<std::string, std::string> vars;
vars["var"] = "es";
std::string output = tinytemplate::render(input, vars);
EXPECT_EQ(expected, output);
}
TEST(TinyTemplate, ComposedVar)
{
std::string input = "t{{v{{var2}}}}t";
std::string expected = "test";
std::map<std::string, std::string> vars;
vars["var"] = "es";
vars["var2"] = "ar";
std::string output = tinytemplate::render(input, vars);
EXPECT_EQ(expected, output);
}
TEST(TinyTemplate, ComposedVar2)
{
std::string input = "t{{v{{var1}}{{var2}}}}t";
std::string expected = "test";
std::map<std::string, std::string> vars;
vars["var"] = "es";
vars["var1"] = "a";
vars["var2"] = "r";
std::string output = tinytemplate::render(input, vars);
EXPECT_EQ(expected, output);
}
TEST(TinyTemplate, LostVar)
{
std::string input = "t{{var}}t";
std::string expected = input;
std::map<std::string, std::string> vars;
std::string output = tinytemplate::render(input, vars);
EXPECT_EQ(expected, output);
}
TEST(TinyTemplate, Escaped)
{
std::string input = "t\\{est\\}";
std::string expected = input;
std::map<std::string, std::string> vars;
std::string output;
EXPECT_NO_THROW(
output = tinytemplate::render(input, vars, true);
);
EXPECT_EQ(expected, input);
}
TEST(TinyTemplate, UnbalancedOpenBracesError)
{
std::string input = "t{{var";
std::map<std::string, std::string> vars;
vars["var"] = "es";
EXPECT_THROW(
std::string output = tinytemplate::render(input, vars);
, tinytemplate::render_error);
}
TEST(TinyTemplate, UnbalancedOpenBracesNoError)
{
std::string input = "t{{var";
std::string expected = input;
std::string output;
std::map<std::string, std::string> vars;
vars["var"] = "es";
EXPECT_NO_THROW(
output = tinytemplate::render(input, vars, true);
);
EXPECT_EQ(expected, input);
}
TEST(TinyTemplate, UnbalancedCloseBracesError)
{
std::string input = "tvar}}";
std::map<std::string, std::string> vars;
vars["var"] = "es";
EXPECT_THROW(
std::string output = tinytemplate::render(input, vars);
, tinytemplate::render_error);
}
TEST(TinyTemplate, UnbalancedCloseBracesNoError)
{
std::string input = "tvar}}";
std::string expected = input;
std::string output;
std::map<std::string, std::string> vars;
vars["var"] = "es";
EXPECT_NO_THROW(
output = tinytemplate::render(input, vars, true);
);
EXPECT_EQ(expected, input);
}
TEST(TinyTemplate, Unescaped)
{
std::string input = "t{var}";
std::map<std::string, std::string> vars;
vars["var"] = "es";
EXPECT_THROW(
std::string output = tinytemplate::render(input, vars);
, tinytemplate::render_error);
}
TEST(TinyTemplate, UnescapedNoError)
{
std::string input = "t{var}";
std::string expected = input;
std::map<std::string, std::string> vars;
vars["var"] = "es";
std::string output;
EXPECT_NO_THROW(
output = tinytemplate::render(input, vars, true);
);
EXPECT_EQ(expected, input);
}
| [
"[email protected]"
] | |
47168d97cf72b8d697e34c82f65c6295a60de4ad | 200b310a18514177117cda1d1faed81dbfaa3a3e | /devel/.private/bwi_msgs/include/bwi_msgs/SaveImageResponseResponse.h | 18a781521effbc3b57923147d9af42f1d7b7cc6b | [] | no_license | YoheiHayamizu/rl_ws | c63aedd2dc539bd56398dd19eafe9932bc598040 | 7fdde2f72a3b9cbef585e218d568e8c44c2e374e | refs/heads/main | 2023-08-16T09:29:33.289334 | 2021-10-23T20:59:08 | 2021-10-23T20:59:08 | 420,521,618 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,646 | h | // Generated by gencpp from file bwi_msgs/SaveImageResponseResponse.msg
// DO NOT EDIT!
#ifndef BWI_MSGS_MESSAGE_SAVEIMAGERESPONSERESPONSE_H
#define BWI_MSGS_MESSAGE_SAVEIMAGERESPONSERESPONSE_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>
namespace bwi_msgs
{
template <class ContainerAllocator>
struct SaveImageResponseResponse_
{
typedef SaveImageResponseResponse_<ContainerAllocator> Type;
SaveImageResponseResponse_()
: success(false) {
}
SaveImageResponseResponse_(const ContainerAllocator& _alloc)
: success(false) {
(void)_alloc;
}
typedef uint8_t _success_type;
_success_type success;
typedef boost::shared_ptr< ::bwi_msgs::SaveImageResponseResponse_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::bwi_msgs::SaveImageResponseResponse_<ContainerAllocator> const> ConstPtr;
}; // struct SaveImageResponseResponse_
typedef ::bwi_msgs::SaveImageResponseResponse_<std::allocator<void> > SaveImageResponseResponse;
typedef boost::shared_ptr< ::bwi_msgs::SaveImageResponseResponse > SaveImageResponseResponsePtr;
typedef boost::shared_ptr< ::bwi_msgs::SaveImageResponseResponse const> SaveImageResponseResponseConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::bwi_msgs::SaveImageResponseResponse_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::bwi_msgs::SaveImageResponseResponse_<ContainerAllocator> >::stream(s, "", v);
return s;
}
} // namespace bwi_msgs
namespace ros
{
namespace message_traits
{
// BOOLTRAITS {'IsFixedSize': True, 'IsMessage': True, 'HasHeader': False}
// {'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg'], 'actionlib_msgs': ['/opt/ros/kinetic/share/actionlib_msgs/cmake/../msg'], 'sensor_msgs': ['/opt/ros/kinetic/share/sensor_msgs/cmake/../msg'], 'bwi_msgs': ['/home/yohei/rl_ws/src/bwi_common/bwi_msgs/msg', '/home/yohei/rl_ws/devel/.private/bwi_msgs/share/bwi_msgs/msg'], 'bwi_planning_common': ['/home/yohei/rl_ws/src/bwi_common/bwi_planning_common/msg'], 'geometry_msgs': ['/opt/ros/kinetic/share/geometry_msgs/cmake/../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< ::bwi_msgs::SaveImageResponseResponse_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::bwi_msgs::SaveImageResponseResponse_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::bwi_msgs::SaveImageResponseResponse_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::bwi_msgs::SaveImageResponseResponse_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::bwi_msgs::SaveImageResponseResponse_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct HasHeader< ::bwi_msgs::SaveImageResponseResponse_<ContainerAllocator> const>
: FalseType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::bwi_msgs::SaveImageResponseResponse_<ContainerAllocator> >
{
static const char* value()
{
return "358e233cde0c8a8bcfea4ce193f8fc15";
}
static const char* value(const ::bwi_msgs::SaveImageResponseResponse_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0x358e233cde0c8a8bULL;
static const uint64_t static_value2 = 0xcfea4ce193f8fc15ULL;
};
template<class ContainerAllocator>
struct DataType< ::bwi_msgs::SaveImageResponseResponse_<ContainerAllocator> >
{
static const char* value()
{
return "bwi_msgs/SaveImageResponseResponse";
}
static const char* value(const ::bwi_msgs::SaveImageResponseResponse_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::bwi_msgs::SaveImageResponseResponse_<ContainerAllocator> >
{
static const char* value()
{
return "bool success\n\
\n\
";
}
static const char* value(const ::bwi_msgs::SaveImageResponseResponse_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::bwi_msgs::SaveImageResponseResponse_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)
{
stream.next(m.success);
}
ROS_DECLARE_ALLINONE_SERIALIZER
}; // struct SaveImageResponseResponse_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::bwi_msgs::SaveImageResponseResponse_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::bwi_msgs::SaveImageResponseResponse_<ContainerAllocator>& v)
{
s << indent << "success: ";
Printer<uint8_t>::stream(s, indent + " ", v.success);
}
};
} // namespace message_operations
} // namespace ros
#endif // BWI_MSGS_MESSAGE_SAVEIMAGERESPONSERESPONSE_H
| [
"[email protected]"
] | |
c7370eb221a46a55dae7e07e0726b26ed2723b00 | bbfaf10487116a517a008d8520a312a1e593bd1c | /QT Creator/Practica 01 Email/Practica_01_email/mainwindow.h | e24f8149de0aeaed45671b282d99013e8df87881 | [] | no_license | aldov500/CPP | e5256ce08df863a0fa73a383cdc56b95bb0735b2 | 350ebe5774bb13a583f7d57049c8b2ac4140c895 | refs/heads/master | 2023-04-10T03:31:21.742678 | 2021-04-04T23:13:49 | 2021-04-04T23:13:49 | 114,075,065 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 867 | h | #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "mat2qimage.h"
#include<qdebug.h>
#include<opencv2/core/core.hpp>
#include<opencv2/ml/ml.hpp>
#include<opencv/cv.h>
#include<opencv2/imgproc/imgproc.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/video/background_segm.hpp>
#include<opencv2/videoio.hpp>
#include<opencv2/imgcodecs.hpp>
#include<QTimer>
#include<QDirIterator>
#include<QFileInfo>
#include<unistd.h>
using namespace cv;
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
public slots:
void loop();
void loop2();
private slots:
void on_radioButton_3_clicked();
void on_pushButton_3_clicked();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
| [
"[email protected]"
] | |
e24e17bfd2bce86cccaa386dbc21182da2c3c043 | a0ec1d598e37fd2ed253076b2dfa3b06d1c10ece | /hw_pong/hw_pong.cpp | b72b4636da2bc543b5781257eab38c24dfb0d3c5 | [] | no_license | kevinlin592/CS3113 | b1d40f85401f21392d920e6f3aa77a73430ea052 | d7aef5a3568ab99715629972e74a4c6ab64ae2ae | refs/heads/master | 2020-12-24T14:56:21.903696 | 2015-01-02T22:22:45 | 2015-01-02T22:22:45 | 23,716,492 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,081 | cpp | //Simple 2 player pong imitation where the ball moves at a 45 degree angle
//Use w and s to control player 1
//Use up and down to control player 2
//A trophy will signify the winner of the game
//Press space whenever to reset the game
#include "Header.h"
GLuint LoadTexture(const char *image_path, GLenum format) {
SDL_Surface *surface = IMG_Load(image_path);
GLuint textureID;
glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_2D, textureID);
glTexImage2D(GL_TEXTURE_2D, 0, 4, surface->w, surface->h, 0, format, GL_UNSIGNED_BYTE, surface->pixels);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
SDL_FreeSurface(surface);
return textureID;
}
void DrawSprite(GLint texture, float x, float y, float xscale, float yscale, float rotation) {
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(x, y, 0.0);
glScalef(xscale, yscale, 1.0);
glRotatef(rotation, 0.0, 0.0, 1.0);
GLfloat quad[] = { -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f };
glVertexPointer(2, GL_FLOAT, 0, quad);
glEnableClientState(GL_VERTEX_ARRAY);
GLfloat quadUVs[] = { 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0 };
glTexCoordPointer(2, GL_FLOAT, 0, quadUVs);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDrawArrays(GL_QUADS, 0, 4);
glDisable(GL_TEXTURE_2D);
}
void Setup(){
SDL_Init(SDL_INIT_VIDEO);
displayWindow = SDL_CreateWindow("My Game", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, SDL_WINDOW_OPENGL);
SDL_GLContext context = SDL_GL_CreateContext(displayWindow);
SDL_GL_MakeCurrent(displayWindow, context);
}
void PreProcesses(){
glViewport(0, 0, 800, 600);
glMatrixMode(GL_PROJECTION);
glOrtho(-1.33, 1.33, -1.0, 1.0, -1.0, 1.0);
}
void Update(Ball& b){
b.x += b.d_x*b.speed;
b.y += b.d_y*b.speed;
}
bool CollisionX(Ball b){
if (abs(b.y) + b.size > 1){
return true;
}
else {
return false;
}
}
bool CollisionY(Ball b, Paddle p1, Paddle p2){
if (((b.x + b.size<p1.x - p1.w) || (b.x - b.size>p1.x + p1.w) || (b.y + b.size<p1.y - p1.h) || (b.y - b.size>p1.y + p1.h)) && ((b.x + b.size<p2.x - p2.w) || (b.x - b.size>p2.x + p2.w) || (b.y + b.size<p2.y - p2.h) || (b.y - b.size>p2.y + p2.h))){
return false;
}
else{
return true;
}
}
void Render(Paddle p1, Paddle p2, Ball b, GLuint wins){
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
p1.Draw();
p2.Draw();
b.Draw();
if (b.x + b.size < p1.x - p1.w){
DrawSprite(wins, 1.1, 0.8, 0.1, 0.08, 0);
}
else if (b.x - b.size > p2.x + p2.w){
DrawSprite(wins, -1.1, 0.8, 0.1, 0.08, 0);
}
}
void PaddleMovement(const Uint8* keys, float& pos1, float& pos2){
if (keys[SDL_SCANCODE_W]){
pos1 += 0.0005;
}
else if (keys[SDL_SCANCODE_S]){
pos1 -= 0.0005;
}
if (keys[SDL_SCANCODE_UP]){
pos2 += 0.0005;
}
else if (keys[SDL_SCANCODE_DOWN]){
pos2 -= 0.0005;
}
}
int main(int argc, char *argv[])
{
Setup();
bool done = false;
SDL_Event event;
PreProcesses();
const Uint8* keys = SDL_GetKeyboardState(NULL);
Paddle p1(-0.9);
Paddle p2(0.9);
float angle[] = { 45, 135, 225, 315 };
int choice = floor(rand() % 4);
Ball ball(0.0005, angle[choice]);
GLuint wins = LoadTexture("wins.png", GL_RGBA);
while (!done) {
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT || event.type == SDL_WINDOWEVENT_CLOSE) {
done = true;
}
else if (event.type == SDL_KEYDOWN){
if (event.key.keysym.scancode == SDL_SCANCODE_SPACE){
p1.Reset(-0.9);
p2.Reset(0.9);
choice = floor(rand() % 4);
ball.Reset(angle[choice]);
}
}
}
if (CollisionX(ball)){
ball.d_y = -ball.d_y;
}
if (CollisionY(ball, p1, p2)){
if (ball.x > 0){
ball.d_x = -abs(ball.d_x);
}
else {
ball.d_x = abs(ball.d_x);
}
}
PaddleMovement(keys, p1.y, p2.y);
Update(ball);
Render(p1, p2, ball, wins);
SDL_GL_SwapWindow(displayWindow);
}
SDL_Quit();
return 0;
} | [
"[email protected]"
] | |
4a705b66d3f1d935cf40fe2bec35f3c9c8e31b97 | 9e7de3802e71b31eba3547d17372edc9c52b8029 | /referenceswapping.cpp | f576a289d8b39f4f48e355df840982bdd794025e | [] | no_license | Sanket-landge/C-CPP-Hands-on | 38253a5b8bb835d03cf9b930504b56d23c343c87 | a409b27356cc40908190a957210c47d097925467 | refs/heads/master | 2023-07-18T01:26:44.709766 | 2021-08-25T11:47:29 | 2021-08-25T11:47:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 209 | cpp | #include<iostream>
using namespace std;
void swap(int &, int &);
main()
{
int a=20;
int b=30;
swap(a,b);
cout<<"a="<<a<<"\tb="<<b<<endl;
}
void swap(int &p,int&q)
{
int temp;
temp=p;
p=q;
q=temp;
}
| [
"[email protected]"
] | |
8784b52a76649350e92a4643e56687c4ec64f8c0 | 308c249a4fd0f452c7dc76337cffb8a03153b43e | /GameObject.cpp | a657d80457435209ae4f2e7859c9bec36b7d08a6 | [] | no_license | LeeSamuel14/VietnameseRunner | 407b69cd01d98e89ed2b8a4b3ba250d254218bb9 | 7d02dd1c45cc42dc79c30383295165208e29d407 | refs/heads/master | 2023-08-17T10:05:01.716435 | 2021-10-12T06:01:11 | 2021-10-12T06:01:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 308 | cpp | #include "GameObject.h"
Engine::GameObject::GameObject()
: point {}
{
}
Engine::GameObject::GameObject(int x, int y)
{
set_point(x, y);
}
Engine::Point Engine::GameObject::get_point()
{
return point;
}
void Engine::GameObject::set_point(int x, int y)
{
point.x = x;
point.y = y;
}
| [
"[email protected]"
] | |
1612fd9dbd1acaeda50f8142fe75cbaf13266f96 | 8ff9613a68aa8e03e74bc1598f468d8b4a1f2056 | /每日一题/day_1.cpp | 3c9b41e8efa5822bb258eb0e2638ec1bb77bf3fe | [] | no_license | Angelsufeiya/CPP | d3a93ca5663db8c043c6069925f7cb54fa06504b | f65266a40bb9b71a5317c069c25e5022a227f801 | refs/heads/master | 2022-12-08T01:09:00.454190 | 2020-08-25T15:23:40 | 2020-08-25T15:23:40 | 204,861,646 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,578 | cpp | //标题:组队竞赛
//牛牛举办了一次编程比赛, 参加比赛的有3*n个选手, 每个选手都有一个水平值a_i.
//现在要将这些选手进行组队, 一 共组成n个队伍, 即每个队伍3人.
//牛牛发现队伍的水平值等于该队伍队员中第二高水平值。
//例如 :
//一个队伍三个队员的水平值分别是3, 3, 3.那么队伍的水平值是3
//一个队伍三个队员的水平值分别是3, 2, 3.那么队伍的水平值是3
//一个队伍三个队员的水平值分别是1, 5, 2.那么队伍的水平值是2
//为了让比赛更有看点, 牛牛想安排队伍使所有队伍的水平值总和最大。 如样例所示 :
//如果牛牛把6个队员划分到两个队伍
//如果方案为 :
//team1 : {1, 2, 5}, team2 : {5, 5, 8}, 这时候水平值总和为7.
//而如果方案为 :
//team1 : {2, 5, 8}, team2 : {1, 5, 5}, 这时候水平值总和为10.
//输入描述 :
// 输入的第一行为一个正整数n(1 ≤ n ≤ 10 ^ 5)
// 第二行包括3*n个整数a_i(1 ≤ a_i ≤ 10 ^ 9), 表示每个参赛选手的水平值.
//输出描述 :
// 输出一个整数表示所有队伍的水平值总和最大值.
//示例1 :
// 输入
// 2
// 5 2 8 5 1 5
// 输出
// 10
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main_0() {
int n;
while (cin >> n) {
int i;
long long sum = 0;
vector<int> a_i;
a_i.resize(3 * n);
for (i = 0; i < 3 * n; i++) {
cin >> a_i[i];
}
std::sort(a_i.begin(), a_i.end());
for (i = n; i < 3 * n; i += 2)
{
sum += a_i[n];
}
cout << sum << endl;
}
return 0;
}
//标题:删除公共字符
//输入两个字符串,从第一字符串中删除第二个字符串中所有的字符。例如,输入”They are students.”和”aeiou”,
//则删除之后的第一个字符串变成”Thy r stdnts.”
//输入描述 :
//每个测试输入包含2个字符串
//输出描述 : 输出删除后的字符串
//示例1 :
//输入
//They are students.
//aeiou
//输出
//Thy r stdnts.
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1, s2;
getline(cin, s1);
getline(cin, s2);
// 使用哈希映射思想先str2统计字符出现的次数
char arr[256] = { 0 };
for (auto i : s2) {
arr[i] = 1;
}
string str;
//注意这里最好不要str1.erases(i) (因为边遍历,边erase,容易出错。)
for (auto i : s1) {
if (!arr[i]) {
str += i;
}
}
cout << str;
return 0;
}
| [
"[email protected]"
] | |
9a4b1c8ad121b8247f0e43e3c1139a1bf3976d04 | 21fb876e8ef8ff2ee56d7c7e7c836fcf2a00058f | /s1_designation.cpp | e1162698befea3a2ecc326b9f9593f3919f79742 | [] | no_license | u2015s/EMS | 4e6ea4181c0010584388fde9bc3d5da9fd6e5b04 | a99692478075f18bd222120c8856e7b1ac4508ab | refs/heads/master | 2021-03-27T06:50:01.889363 | 2020-04-06T12:03:24 | 2020-04-06T12:03:24 | 247,798,183 | 0 | 0 | null | 2020-04-01T13:00:06 | 2020-03-16T19:19:30 | C++ | UTF-8 | C++ | false | false | 12,329 | cpp | #include "s1_designation.h"
#include "ui_s1_designation.h"
#include <QMessageBox>
S1_Designation::S1_Designation(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::S1_Designation)
{
ui->setupUi(this);
if( (ui->stackedWidget->currentIndex()==0) || (ui->stackedWidget->currentIndex()==1) )
{ ui->signout_button->setVisible(false); ui->changepass_button->setVisible(false);}
else ui->signout_button->setVisible(true);//actually this condition never reaches because when compiler read this at that time, page index is 0.
}
S1_Designation::~S1_Designation()
{
delete ui;
}
char ch1;
void S1_Designation::on_pushButton_7_clicked()//login button
{
QString username = ui->comboBox_input_username->currentText();
QString password = ui->comboBox_input_password->currentText();
if(username == "admin" && password == "admin") {ch1='A';
QMessageBox::information(this,"Login Status", "you are logged in successfully");
ui->stackedWidget->setCurrentIndex(2);
}
else if(username == "receptionist" && password == "receptionist") {ch1='R';
QMessageBox::information(this,"Login Status", "you are logged in successfully");
ui->stackedWidget->setCurrentIndex(5);
}
else if(username == "staff" && password == "staff") {ch1='S';
QMessageBox::information(this,"Login Status", "you are logged in successfully");
ui->stackedWidget->setCurrentIndex(3);
}
else if(username == "eventmanager" && password == "eventmanager") {ch1='E';
QMessageBox::information(this,"Login Status", "you are logged in successfully");
ui->stackedWidget->setCurrentIndex(6);
}
else if(username == "inventory" && password == "inventory") {ch1='I';
QMessageBox::information(this,"Login Status", "you are logged in successfully");
ui->stackedWidget->setCurrentIndex(4);
}
else {
QMessageBox::warning(this,"Login Status", "Either Username or password is not valid");
}
ui->comboBox_input_username->clearEditText();
ui->comboBox_input_password->clearEditText();
ui->comboBox_input_username->clear();
ui->comboBox_input_password->clear();
if( (ui->stackedWidget->currentIndex()!=0) && (ui->stackedWidget->currentIndex()!=1) )
{ ui->signout_button->setVisible(true); ui->changepass_button->setVisible(true);}
}
void S1_Designation::on_pushButton_ok_clicked()//designation submit button
{
if(ui->comboBox_designation->currentText()=="Admin"){
ui->comboBox_input_username->addItem("admin");
ui->comboBox_input_username->addItem("admin1");
ui->comboBox_input_username->addItem("admin2");
ui->stackedWidget->setCurrentIndex(1);
}
else if(ui->comboBox_designation->currentText()=="Receptionist"){
ui->comboBox_input_username->addItem("receptionist");
ui->stackedWidget->setCurrentIndex(1);
}
else if(ui->comboBox_designation->currentText()=="Staff Manager"){
ui->comboBox_input_username->addItem("staff");
ui->stackedWidget->setCurrentIndex(1);
}
else if(ui->comboBox_designation->currentText()=="Event Manager"){
ui->comboBox_input_username->addItem("eventmanager");
ui->stackedWidget->setCurrentIndex(1);
}
else if(ui->comboBox_designation->currentText()=="Inventory Manager"){
ui->comboBox_input_username->addItem("inventory");
ui->stackedWidget->setCurrentIndex(1);
}
else {
QMessageBox::warning(this,"User Type Selection", "choose any one designation");
}
}
//--------------------------------------------------------------------------------------------------------------------------
//below are extra functions not for use but compiler made them
//--------------------------------------------------------------------------------------------------------------------------
//below are pushbuttons under afterlogin screens(i.e.,chosing tables by different users)
char ch;
void S1_Designation::on_admin_login_eventbutton_clicked() {ch='E'; ui->stackedWidget->setCurrentIndex(7);}
void S1_Designation::on_admin_login_userbutton_clicked() {ch='U'; ui->stackedWidget->setCurrentIndex(8);}//options screen is diff. for user table
void S1_Designation::on_admin_login_staffbutton_clicked() {ch='S'; ui->stackedWidget->setCurrentIndex(7);}
void S1_Designation::on_admin_login_inventorybutton_clicked() {ch='I'; ui->stackedWidget->setCurrentIndex(7);}
void S1_Designation::on_admin_login_venuebutton_clicked() {ch='V'; ui->stackedWidget->setCurrentIndex(7);}
void S1_Designation::on_admin_login_clientbutton_clicked() {ch='C'; ui->stackedWidget->setCurrentIndex(7);}
void S1_Designation::on_staff_login_eventbutton_clicked() {ch='E'; ui->stackedWidget->setCurrentIndex(7);}
void S1_Designation::on_staff_login_staffbutton_clicked() {ch='S'; ui->stackedWidget->setCurrentIndex(7);}
void S1_Designation::on_Inventory_login_eventbutton_clicked() {ch='E'; ui->stackedWidget->setCurrentIndex(7);}
void S1_Designation::on_Inventory_login_inventorybutton_clicked() {ch='I'; ui->stackedWidget->setCurrentIndex(7);}
void S1_Designation::on_R_login_eventbutton_clicked() {ch='E'; ui->stackedWidget->setCurrentIndex(7);}
void S1_Designation::on_R_login_clientbutton_clicked() {ch='C'; ui->stackedWidget->setCurrentIndex(7);}
void S1_Designation::on_EM_login_eventbutton_clicked() {ch='E'; ui->stackedWidget->setCurrentIndex(25);}//only EM is having no option page,so directly linked to view page
void S1_Designation::on_EM_login_staffbutton_clicked() {ch='S'; ui->stackedWidget->setCurrentIndex(25);}
void S1_Designation::on_EM_login_inventorybutton_clicked() {ch='I'; ui->stackedWidget->setCurrentIndex(25);}
void S1_Designation::on_EM_login_venuebutton_clicked() {ch='V'; ui->stackedWidget->setCurrentIndex(25);}
//--------------------------------------------------------------------------------------------------------------------------
//below are pushbuttons under options screen for tables(except user table)
void S1_Designation::on_user_login_table_viewbutton_clicked() {ui->stackedWidget->setCurrentIndex(24);}
void S1_Designation::on_user_login_table_deletebutton_clicked() {ui->stackedWidget->setCurrentIndex(17);}
void S1_Designation::on_user_login_table_printbutton_clicked() {ui->stackedWidget->setCurrentIndex(16);}
void S1_Designation::on_user_login_table_updatebutton_clicked() {
if(ch=='E') ui->stackedWidget->setCurrentIndex(18);
else if(ch=='I') ui->stackedWidget->setCurrentIndex(20);
else if(ch=='S') ui->stackedWidget->setCurrentIndex(19);
else if(ch=='V') ui->stackedWidget->setCurrentIndex(21);
else if(ch=='C') ui->stackedWidget->setCurrentIndex(22);
//else if(ch=='U') {ui->stackedWidget->setCurrentIndex(15);}
else
QMessageBox::warning(this,"ERROR", "No table is choosed before in afterlogin(tables) screen, which cann't be happen");
}
void S1_Designation::on_user_login_table_addbutton_clicked() {
if(ch=='E') ui->stackedWidget->setCurrentIndex(10);
else if(ch=='I') ui->stackedWidget->setCurrentIndex(12);
else if(ch=='S') ui->stackedWidget->setCurrentIndex(11);
else if(ch=='V') ui->stackedWidget->setCurrentIndex(14);
else if(ch=='C') ui->stackedWidget->setCurrentIndex(13);
else if(ch=='U') {ui->stackedWidget->setCurrentIndex(15);}
else
QMessageBox::warning(this,"ERROR", "No table is choosed before in afterlogin(tables) screen, which cann't be happen");
}
//--------------------------------------------------------------------------------------------------------------------------
//below are pushbuttons under option screen for USER table
void S1_Designation::on_admin_login_table_viewbutton_clicked() {ui->stackedWidget->setCurrentIndex(24);}
void S1_Designation::on_admin_login_table_createuserbutton_clicked() {ui->stackedWidget->setCurrentIndex(15);}
void S1_Designation::on_admin_login_table_removeuserbutton_clicked() {ui->stackedWidget->setCurrentIndex(17);}
void S1_Designation::on_admin_login_table_changeUserPassbutton_clicked() {ui->stackedWidget->setCurrentIndex(23);}
//--------------------------------------------------------------------------------------------------------------------------
//print button on EM-view page
void S1_Designation::on_EM_login_table_printbutton_clicked() {ui->stackedWidget->setCurrentIndex(16);}
//--------------------------------------------------------------------------------------------------------------------------
//all page's back buttons below
void S1_Designation::on_loginpage_backbutton_clicked() {
ui->comboBox_input_username->clearEditText();
ui->comboBox_input_password->clearEditText();
ui->comboBox_input_username->clear();
ui->comboBox_input_password->clear();
ui->stackedWidget->setCurrentIndex(0); }
void S1_Designation::on_user_login_table_backbutton_clicked() {
if(ch1=='A') ui->stackedWidget->setCurrentIndex(2);
else if(ch1=='R') ui->stackedWidget->setCurrentIndex(5);
else if(ch1=='S') ui->stackedWidget->setCurrentIndex(3);
else if(ch1=='E') ui->stackedWidget->setCurrentIndex(6);
else if(ch1=='I') ui->stackedWidget->setCurrentIndex(4);
else
QMessageBox::warning(this,"ERROR", "No table is choosed before in afterlogin(tables) screen, which cann't be happen");
}
void S1_Designation::on_admin_login_table_backbutton_clicked() {ui->stackedWidget->setCurrentIndex(2);}
void S1_Designation::on_event_addform_backbutton_clicked() {ui->stackedWidget->setCurrentIndex(7);}
void S1_Designation::on_staff_addform_backbutton_clicked() {ui->stackedWidget->setCurrentIndex(7);}
void S1_Designation::on_inventory_addform_backbutton_clicked() {ui->stackedWidget->setCurrentIndex(7);}
void S1_Designation::on_client_addform_backbutton_clicked() {ui->stackedWidget->setCurrentIndex(7);}
void S1_Designation::on_venue_addform_backbutton_clicked() {ui->stackedWidget->setCurrentIndex(7);}
void S1_Designation::on_user_addform_backbutton_clicked() {ui->stackedWidget->setCurrentIndex(8);}
void S1_Designation::on_print_backbutton_clicked() {ui->stackedWidget->setCurrentIndex(7);}
void S1_Designation::on_delete_backbutton_clicked() {
if(ch=='U') ui->stackedWidget->setCurrentIndex(8);
else ui->stackedWidget->setCurrentIndex(7); }
void S1_Designation::on_update_backbutton_clicked() {ui->stackedWidget->setCurrentIndex(7);}//this is for Event table
void S1_Designation::on_updateStaff_backbutton_clicked() {ui->stackedWidget->setCurrentIndex(7);}
void S1_Designation::on_updateInventory_backbutton_clicked() {ui->stackedWidget->setCurrentIndex(7);}
void S1_Designation::on_updateVenue_backbutton_clicked() {ui->stackedWidget->setCurrentIndex(7);}
void S1_Designation::on_updateClient_backbutton_clicked() {ui->stackedWidget->setCurrentIndex(7);}
void S1_Designation::on_changeUserPass_backbutton_clicked() {ui->stackedWidget->setCurrentIndex(8);}
void S1_Designation::on_view_backbutton_clicked() {
if(ch=='U') ui->stackedWidget->setCurrentIndex(8);
else ui->stackedWidget->setCurrentIndex(7); }
void S1_Designation::on_EM_viewpage_backbutton_clicked() {ui->stackedWidget->setCurrentIndex(6);}
//----------------------------------------------------------------------------------------------------------------------------
//common buttons
void S1_Designation::on_signout_button_clicked() { ui->stackedWidget->setCurrentIndex(0);
if( (ui->stackedWidget->currentIndex()==0) || (ui->stackedWidget->currentIndex()==1) )
{ ui->signout_button->setVisible(false); ui->changepass_button->setVisible(false);} }
void S1_Designation::on_changepass_button_clicked() { ui->stackedWidget->setCurrentIndex(9);}
void S1_Designation::on_changepass_okbutton_clicked() {ui->stackedWidget->setCurrentIndex(0);
if( (ui->stackedWidget->currentIndex()==0) || (ui->stackedWidget->currentIndex()==1) )
{ ui->signout_button->setVisible(false); ui->changepass_button->setVisible(false);} }
//----------------------------------------------------------------------------------------------------------------------------
| [
"[email protected]"
] | |
e4a1e493b91e3d1f7da5e15d94759e977a5e9e3e | 996126a2ed07ab381b625c92be916f2607804db1 | /プロジェクト/マスター版プロジェクト/source.ver.0.1/tutorial.cpp | 52e454b0a8c23e9efaf89080e0b89d9699f062a0 | [] | no_license | ReiKishida/KishidaStudio_Front_Line | 10630cc57274b73d22d78639e7c53ae0c8a8dfc8 | 93694415975d032c27bd7d81a5d8ad2763c4687a | refs/heads/master | 2020-09-10T00:58:36.353818 | 2020-02-06T00:40:50 | 2020-02-06T00:40:50 | 221,608,377 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 64,493 | cpp | //=============================================================================
//
// ゲーム処理 [game.cpp]
// Author : Takuto Ishida & Rei Kishida
//
//=============================================================================
#define _CRT_SECURE_NO_WARNINGS
#include "tutorial.h"
#include "camera.h"
#include "renderer.h"
#include "fade.h"
#include "input.h"
#include "manager.h"
#include "scene.h"
#include "camera.h"
#include "debugProc.h"
#include "result.h"
#include "sound.h"
#include "life.h"
#include "modelSet.h"
#include "player.h"
#include "meshField.h"
#include "motion.h"
#include "pause.h"
#include "meshField.h"
#include "number.h"
#include "bullet.h"
#include "button.h"
#include "mouseCursor.h"
#include "UI_Number.h"
#include "UI_Texture.h"
#include "texture.h"
#include <stdio.h>
#include "model.h"
#include "gauge.h"
#include "server.h"
#include "serverfunction.h"
#include "collisionSet.h"
#include "scene3D.h"
#include "menu.h"
#include "particle.h"
#include "AI.h"
#include "tutorialmenu.h"
#include "nodeDataFiler.h"
//*****************************************************************************
// マクロ定義
//*****************************************************************************
#define FIELD_MODEL_NAME "data/MODEL/map_tutorial.x"
#define CLEAR_MODEL_NAME "data/MODEL/tutorial_marker.x"
#define CLEARMARK_MODEL_NAME "data/MODEL/tutorial_marker_2.x"
#define SKY_MODEL_NAME "data/MODEL/sky_dome.x"
#define NUMTEX_UV_X (1)
#define NUMTEX_UV_Y (3)
#define TUTORIAL_INI "data/TEXT/tutorial.ini"
#define GAME_SCRIPT "SCRIPT"
#define GAME_END_SCRIPT "END_SCRIPT"
#define GAME_BLUE "BLUE"
#define GAME_BLUE_END "BLUE_END"
#define GAME_RED "RED"
#define GAME_RED_END "RED_END"
#define GAME_SPAWN_A "A"
#define GAME_SPAWN_B "B"
#define GAME_SPAWN_C "C"
#define GAME_SPAWN_D "D"
#define NUMTEX_GAUGE_WIDTH (430.0f)
#define NUMTEX_GAUGE_HEIGHT (30.0f)
#define TUTORIAL_TITLE_WIDTH (450.0f) //チュートリアル項目の幅
#define TUTORIAL_TITLE_HEIGHT (140.0f) //チュートリアル項目の高さ
#define TUTORIAL_STEPS_WIDTH (50.0f) //チュートリアル進行度の幅
#define TUTORIAL_STEPS_HEIGHT (50.0f) //チュートリアル進行度の高さ
#define TUTORIAL_SUCCESS_WIDTH (520.0f) //項目達成の幅
#define TUTORIAL_SUCCESS_HEIGHT (120.0f) //項目達成の高さ
#define TUTORIAL_MISSION_WIDTH (750.0f) //チュートリアル目標の幅
#define TUTORIAL_MISSION_HEIGHT (85.0f) //チュートリアル目標の高さ
#define TUTORIAL_INST_WIDTH (350.0f) //チュートリアル目標の幅
#define TUTORIAL_INST_HEIGHT (180.0f) //チュートリアル目標の高さ
#define TUTORIAL_BASIC_STEPS_NUM (3) //基本操作の項目数
#define TUTORIAL_ACTION_STEPS_NUM (3) //アクションパートの項目数
#define TUTORIAL_STRATEGY_STEPS_NUM (3) //ストラテジーパートの項目数
#define TUTORIAL_BASIC_INST_NUM (2) //基本操作の操作項目数
#define TUTORIAL_ACTION_INST_NUM (3) //アクションパートの操作項目数
#define TUTORIAL_STRATEGY_INST_NUM (3) //アクションパートの操作項目数
//*****************************************************************************
// 静的メンバ変数
//*****************************************************************************
CTutorial::STATE CTutorial::m_state = CTutorial::STATE_NONE;
int CTutorial::m_nCurStage = 0;
CPlayer *CTutorial::m_pPlayer[MAX_PLAYER_TUTORIAL] = {};
CMechaSelect::MECHATYPE CTutorial::m_aMechaType[MAX_PLAYER_TUTORIAL] = { CMechaSelect::MECHATYPE_EMPTY,CMechaSelect::MECHATYPE_EMPTY };
int CTutorial::m_nType = 0; //チュートリアルの種類
int CTutorial::m_nSteps = 0; //進行度
int CTutorial::m_nStepsMax = 0; //進行度の最大数
int CTutorial::m_nInstMax = 0;
CTutorial::TUTORIALSTATE CTutorial::m_TutorialState = TUTORIALSTATE_NONE;
CNodeDataFiler *CTutorial::m_pNodeFiler = NULL; // マップデータクラスのポインタ変数
//=============================================================================
// コンストラクタ
//=============================================================================
CTutorial::CTutorial(int nPriority, CScene::OBJTYPE objType) : CScene(nPriority, objType)
{
m_modeCounter = 0;
m_pMouseCursor = NULL;
m_pPause = NULL;
m_bPause = false;
m_pButtonManager = NULL;
m_part = PART_ACTION;
m_pField = NULL;
m_pClearMarker = NULL;
m_pSky = NULL;
m_pMouse = NULL;
m_nBlueLinkEnergy = 0;
m_nRedLinkEnergy = 0;
//チュートリアルの状態
m_TutorialState = TUTORIALSTATE_NONE;
//基本操作のチュートリアル
m_R_CameraState = CLEARSTATE_NONE;
m_L_CameraState = CLEARSTATE_NONE;
m_U_CameraState = CLEARSTATE_NONE;
m_D_CameraState = CLEARSTATE_NONE;
m_Move_State = CLEARSTATE_NONE;
//アクションパートのチュートリアル
m_AttackState = CLEARSTATE_NONE;
m_ReloadState = CLEARSTATE_NONE;
//ストラテジーのチュートリアル
m_Ai_Move_State = CLEARSTATE_NONE; //移動のクリア状態
m_Ai_Attack_State = CLEARSTATE_NONE; //攻撃のクリア状態
m_nDisp = 0;
m_nType = 0;
m_nSteps = 0;
m_nStepsMax = 0;
m_nInstMax = 0;
for (int nCntConnect = 0; nCntConnect < MAX_PLAYER_TUTORIAL; nCntConnect++)
{
m_bConnect[nCntConnect] = false;
}
for (int nCntTeam = 0; nCntTeam < NUM_TEAM; nCntTeam++)
{
for (int nCntRespawn = 0; nCntRespawn < NUM_RESPAWN_POS; nCntRespawn++)
{
m_aRespawnPos[nCntTeam][nCntRespawn] = D3DXVECTOR3(0.0f, 0.0f, 0.0f);
}
}
for (int nCntConnect = 0; nCntConnect < 2; nCntConnect++)
{
for (int nCntPlayer = 0; nCntPlayer < MAX_PLAYER_TUTORIAL; nCntPlayer++)
{
m_bAIDeath[nCntConnect][nCntPlayer] = false;
}
}
for (int nCntSteps = 0; nCntSteps < 3; nCntSteps++)
{
m_apSteps[nCntSteps] = NULL;
}
}
//=============================================================================
// デストラクタ
//=============================================================================
CTutorial::~CTutorial()
{
}
//=============================================================================
// 初期化処理
//=============================================================================
HRESULT CTutorial::Init(void)
{
m_nType = CTutorialMenu::GetMode();
//チュートリアルの状態
m_TutorialState = TUTORIALSTATE_NORMAL;
//リスポーン位置の読み込み
LoadRespawnPos();
//// 読み込み
CMotionManager::Load();
m_pField = CModel::Create();
m_pField->SetModel(FIELD_MODEL_NAME,false);
//=====================================================================================
// マップデータファイラーの生成
//=====================================================================================
if (m_pNodeFiler == NULL)
{// NULLチェック
m_pNodeFiler = CNodeDataFiler::Create();
}
//// 弾の当たり判定クラスの生成
CBulletCollision::Create();
//// マップの当たり判定の読み込み
CCollision::Load();
//====================================================
//チュートリアルのテクスチャ
//====================================================
switch (m_nType)
{
case 0:
CUI_TEXTURE::Create(D3DXVECTOR3(SCREEN_WIDTH / 2, 80.0f, 0.0f), TUTORIAL_TITLE_WIDTH, TUTORIAL_TITLE_HEIGHT, CUI_TEXTURE::UIFLAME_TUTORIAL_TITLE_BASIC); // チュートリアルの項目
m_nStepsMax = TUTORIAL_BASIC_STEPS_NUM;
m_nInstMax = TUTORIAL_BASIC_INST_NUM;
for (int nCntSteps = 0; nCntSteps < m_nStepsMax; nCntSteps++)
{
m_apSteps[nCntSteps] = CUI_TEXTURE::Create(D3DXVECTOR3((SCREEN_WIDTH / 2 - 80.0f) + (70.0f * nCntSteps), 180.0f, 0.0f), TUTORIAL_STEPS_WIDTH, TUTORIAL_STEPS_HEIGHT, CUI_TEXTURE::UIFLAME_TUTORIAL_NUMBER); // チュートリアルの項目
m_apSteps[nCntSteps]->SetTex(nCntSteps + 1, 10, 1);
m_apSteps[nCntSteps]->SetObjType(OBJTYPE_UI_TUTORIAL);
}
m_pMission = CUI_TEXTURE::Create(D3DXVECTOR3(SCREEN_WIDTH / 2, 250.0f, 0.0f), TUTORIAL_MISSION_WIDTH, TUTORIAL_MISSION_HEIGHT, CUI_TEXTURE::UIFLAME_TUTORIAL_LESSON_BASICMOVEMENT); // 基本操作の目標
m_pMission->SetObjType(OBJTYPE_UI_TUTORIAL);
m_pInst = CUI_TEXTURE::Create(D3DXVECTOR3(SCREEN_WIDTH - 180.0f, 450.0f, 0.0f), TUTORIAL_INST_WIDTH, TUTORIAL_INST_HEIGHT, CUI_TEXTURE::UIFLAME_TUTORIAL_INST_BASICMOVEMENT); // 基本操作の目標
m_pInst->SetObjType(OBJTYPE_UI_TUTORIAL);
break;
case 1:
CUI_TEXTURE::Create(D3DXVECTOR3(SCREEN_WIDTH / 2, 80.0f, 0.0f), TUTORIAL_TITLE_WIDTH, TUTORIAL_TITLE_HEIGHT, CUI_TEXTURE::UIFLAME_TUTORIAL_TITLE_ACTION); // チュートリアルの項目
m_nStepsMax = TUTORIAL_ACTION_STEPS_NUM;
m_nInstMax = TUTORIAL_ACTION_INST_NUM;
for (int nCntSteps = 0; nCntSteps < m_nStepsMax; nCntSteps++)
{
m_apSteps[nCntSteps] = CUI_TEXTURE::Create(D3DXVECTOR3((SCREEN_WIDTH / 2 - 80.0f) + (70.0f * nCntSteps), 180.0f, 0.0f), TUTORIAL_STEPS_WIDTH, TUTORIAL_STEPS_HEIGHT, CUI_TEXTURE::UIFLAME_TUTORIAL_NUMBER); // チュートリアルの項目
m_apSteps[nCntSteps]->SetTex(nCntSteps + 1, 10, 1);
m_apSteps[nCntSteps]->SetObjType(OBJTYPE_UI_TUTORIAL);
}
m_pMission = CUI_TEXTURE::Create(D3DXVECTOR3(SCREEN_WIDTH / 2, 250.0f, 0.0f), TUTORIAL_MISSION_WIDTH, TUTORIAL_MISSION_HEIGHT, CUI_TEXTURE::UIFLAME_TUTORIAL_LESSON_ACTION); // 基本操作の目標
m_pMission->SetObjType(OBJTYPE_UI_TUTORIAL);
m_pInst = CUI_TEXTURE::Create(D3DXVECTOR3(SCREEN_WIDTH - 180.0f, 450.0f, 0.0f), TUTORIAL_INST_WIDTH, TUTORIAL_INST_HEIGHT, CUI_TEXTURE::UIFLAME_TUTORIAL_INST_ACTION); // 基本操作の目標
m_pInst->SetObjType(OBJTYPE_UI_TUTORIAL);
break;
case 2:
CUI_TEXTURE::Create(D3DXVECTOR3(SCREEN_WIDTH / 2, 80.0f, 0.0f), TUTORIAL_TITLE_WIDTH, TUTORIAL_TITLE_HEIGHT, CUI_TEXTURE::UIFLAME_TUTORIAL_TITLE_STRATEGY); // チュートリアルの項目
m_nStepsMax = TUTORIAL_STRATEGY_STEPS_NUM;
m_nInstMax = TUTORIAL_STRATEGY_INST_NUM;
for (int nCntSteps = 0; nCntSteps < m_nStepsMax; nCntSteps++)
{
m_apSteps[nCntSteps] = CUI_TEXTURE::Create(D3DXVECTOR3((SCREEN_WIDTH / 2 - 80.0f) + (70.0f * nCntSteps), 180.0f, 0.0f), TUTORIAL_STEPS_WIDTH, TUTORIAL_STEPS_HEIGHT, CUI_TEXTURE::UIFLAME_TUTORIAL_NUMBER); // チュートリアルの項目
m_apSteps[nCntSteps]->SetTex(nCntSteps + 1, 10, 1);
m_apSteps[nCntSteps]->SetObjType(OBJTYPE_UI_TUTORIAL);
}
m_pMission = CUI_TEXTURE::Create(D3DXVECTOR3(SCREEN_WIDTH / 2, 250.0f, 0.0f), 850.0f, 90.0f, CUI_TEXTURE::UIFLAME_TUTORIAL_LESSON_STRATEGY); // 基本操作の目標
m_pMission->SetObjType(OBJTYPE_UI_TUTORIAL);
m_pInst = CUI_TEXTURE::Create(D3DXVECTOR3(SCREEN_WIDTH - 180.0f, 450.0f, 0.0f), TUTORIAL_INST_WIDTH, TUTORIAL_INST_HEIGHT, CUI_TEXTURE::UIFLAME_TUTORIAL_INST_STRATEGY); // 基本操作の目標
m_pInst->SetObjType(OBJTYPE_UI_TUTORIAL);
break;
}
//====================================================
//プレイヤーの生成
//====================================================
switch (m_nType)
{
case 0:
m_pPlayer[0] = CPlayer::Create(0, CMechaSelect::MECHATYPE_LIGHT, m_aRespawnPos[0][2], true);
break;
case 1:
m_pPlayer[0] = CPlayer::Create(0, CMechaSelect::MECHATYPE_LIGHT, m_aRespawnPos[0][2], true);
m_pPlayer[1] = CPlayer::Create(2, CMechaSelect::MECHATYPE_LIGHT, D3DXVECTOR3(-30.0f, 0.0f, -40.0f), false);
m_pPlayer[1]->SetLife(50);
m_pPlayer[1]->SetRot(D3DXVECTOR3(0.0f, D3DX_PI * 0.5f, 0.0f));
//****************************************
// 2DUI生成(フレーム)
//****************************************
// 武器フレーム
CUI_TEXTURE::Create(D3DXVECTOR3(1100.0f, 650.0f, 0.0f), 350.0f, 120.0f, CUI_TEXTURE::UIFLAME_WEAPON); // 武器
// プレイヤー体力フレーム
CUI_TEXTURE::Create(D3DXVECTOR3(180.0f, 650.0f, 0.0f), 350.0f, 125.0f, CUI_TEXTURE::UIFLAME_PLAYER_HP); // 胴体
//****************************************
// UI生成(数字)
//****************************************
CUI_NUMBER::Create(D3DXVECTOR3(970.0f, 660.0f, 0.0f), 150.0f, 90.0f, 60.0f, CUI_NUMBER::UI_NUMTYPE_REMAINBULLET, 0, NUMTEX_UV_X, NUMTEX_UV_Y); // 残弾
CUI_NUMBER::Create(D3DXVECTOR3(195.0f, 650.0f, 0.0f), 170.0f, 110.0f, 70.0f, CUI_NUMBER::UI_NUMTYPE_PLAYER_HP, 0, NUMTEX_UV_X, NUMTEX_UV_Y); // プレイヤーライフ
break;
case 2:
m_pPlayer[0] = CPlayer::Create(0, CMechaSelect::MECHATYPE_LIGHT, m_aRespawnPos[0][2], true);
//****************************************
// 2DUI生成(フレーム)
//****************************************
// 武器フレーム
// プレイヤー体力フレーム
CUI_TEXTURE::Create(D3DXVECTOR3(180.0f, 650.0f, 0.0f), 350.0f, 125.0f, CUI_TEXTURE::UIFLAME_PLAYER_HP); // 胴体
CUI_TEXTURE::Create(D3DXVECTOR3(125.0f, 530.0f, 0.0f), 230.0f, 100.0f, CUI_TEXTURE::UIFLAME_DRONE); // AI01
//****************************************
// UI生成(数字)
//****************************************
CUI_NUMBER::Create(D3DXVECTOR3(195.0f, 650.0f, 0.0f), 170.0f, 110.0f, 70.0f, CUI_NUMBER::UI_NUMTYPE_PLAYER_HP, 0, NUMTEX_UV_X, NUMTEX_UV_Y); // プレイヤーライフ
break;
}
return S_OK;
}
//=============================================================================
// 終了処理
//=============================================================================
void CTutorial::Uninit(void)
{
// データの破棄
CMotionManager::Unload();
for (int nCntPlayer = 0; nCntPlayer < MAX_PLAYER_TUTORIAL; nCntPlayer++)
{
if (NULL != m_pPlayer[nCntPlayer])
{// プレイヤークラスの破棄
m_pPlayer[nCntPlayer]->Uninit();
m_pPlayer[nCntPlayer] = NULL;
}
}
for (int nCntSteps = 0; nCntSteps < m_nStepsMax; nCntSteps++)
{
if (NULL != m_apSteps[nCntSteps])
{
m_apSteps[nCntSteps]->Uninit();
m_apSteps[nCntSteps] = NULL;
}
}
if (NULL != m_pField)
{// 地面の破棄
m_pField->Uninit();
delete m_pField;
m_pField = NULL;
}
if (m_pClearMarker != NULL)
{
m_pClearMarker->Uninit();
delete m_pClearMarker;
m_pClearMarker = NULL;
}
if (NULL != m_pMouseCursor)
{// マウスカーソルの破棄
m_pMouseCursor->Uninit();
m_pMouseCursor = NULL;
}
if (NULL != m_pMouse)
{// マウスカーソルの破棄
m_pMouse->Uninit();
m_pMouse = NULL;
}
if (m_pNodeFiler != NULL)
{// マップデータファイラーの破棄
m_pNodeFiler->Uninit();
m_pNodeFiler = NULL;
}
if (NULL != m_pButtonManager)
{// ボタン管理クラスの破棄
m_pButtonManager->Uninit();
m_pButtonManager = NULL;
}
// オブジェクトを破棄
CScene::Release();
}
//=============================================================================
// ゲーム更新処理
//=============================================================================
void CTutorial::Update(void)
{
CInputKeyboard *pKeyboard = CManager::GetInputKeyboard(); // キーボードの取得
CXInput *pXInput = CManager::GetXInput(); // XInputの取得
CSound *pSound = CManager::GetSound(); // サウンドの取得
CInputMouse *pMouse = CManager::GetInputMouse();
CDirectInput *pDirectInput = CManager::GetDirectInput(); //DirectInputの取得
CDirectInput::GamePad *DirectInputStick = pDirectInput->GetgamePadStick();
if (m_pPlayer[0]->GetRespawn() == CPlayer::RESPAWN_NONE)
{
//パートの切り替え処理
SwicthPart();
}
#ifdef _DEBUG
if (pKeyboard->GetTrigger(DIK_O))
{
CFade::Create(CManager::MODE_MENU);
}
if (pKeyboard->GetTrigger(DIK_L))
{
m_nSteps++;
}
#endif
switch (m_TutorialState)
{
case TUTORIALSTATE_NONE:
break;
case TUTORIALSTATE_NORMAL:
break;
case TUTORIALSTATE_CLEAR:
m_nDisp--;
if (m_nDisp <= 0)
{
m_nDisp = 0;
if (m_nSteps == m_nStepsMax - 1)
{
if (CFade::GetFade() == CFade::FADE_NONE)
{// フェードがないとき
CManager::MODE mode;
mode = CManager::MODE_TUTORIALMENU;
CFade::Create(mode);
}
}
else
{
if (m_Succes != NULL)
{
m_Succes->Uninit();
}
m_nSteps++;
m_TutorialState = TUTORIALSTATE_NORMAL;
}
}
break;
}
CDebugProc::Print("現在のステップ : %d / %d", m_nSteps, m_nStepsMax);
CDebugProc::Print("m_nDisp : %d", m_nDisp);
CDebugProc::Print("m_TutorialState : %d", m_TutorialState);
switch (m_nType)
{
case 0:
TutorialBasicMovement();
break;
case 1:
TutorialAction();
break;
case 2:
TutorialStrategy();
break;
}
// フェードの取得
//CFade::FADE fade = CFade::GetFade();
CDebugProc::Print("チュートリアル");
//CDebugProc::Print("機種:%d %d %d %d", m_aMechaType[0], m_aMechaType[1], m_aMechaType[2], m_aMechaType[3]);
switch (m_nType)
{
case 0:
CDebugProc::Print("BASIC_MOVE");
break;
case 1:
CDebugProc::Print("ACTION_PART");
break;
case 2:
CDebugProc::Print("STRATEGY_PART");
break;
}
}
//=============================================================================
// ゲーム描画処理
//=============================================================================
void CTutorial::Draw(void)
{
//// デバイスの取得
CRenderer *pRenderer = CManager::GetRenderer();
LPDIRECT3DDEVICE9 pDevice;
pDevice = pRenderer->GetDevice();
if (NULL != m_pField)
{// 地面の描画
m_pField->Draw();
}
if (NULL != m_pField)
{// 地面の破棄
m_pField->Draw();
}
if (m_pClearMarker != NULL)
{
m_pClearMarker->Draw();
}
// ライティングOFF
pDevice->SetRenderState(D3DRS_LIGHTING, FALSE);
//if (NULL != m_pSky)
//{// スカイドームの描画
// m_pSky->Draw();
//}
//// ライティングON
pDevice->SetRenderState(D3DRS_LIGHTING, TRUE);
}
//=============================================================================
// ゲームの状態の設定
//=============================================================================
const void CTutorial::SetGameState(STATE state)
{
m_state = state;
}
//=============================================================================
// ステージの設定
//=============================================================================
void CTutorial::SetStage(int nStage)
{
// 現在のステージを設定
m_nCurStage = nStage;
}
//=============================================================================
// パートの切り替え処理
//=============================================================================
void CTutorial::SwicthPart(void)
{
CInputKeyboard *pKeyboard = CManager::GetInputKeyboard(); // キーボードの取得
CXInput *pXInput = CManager::GetXInput(); // XInputの取得
CInputMouse *pMouse = CManager::GetInputMouse();
CDirectInput *pDirectInput = CManager::GetDirectInput(); //DirectInputの取得
CDirectInput::GamePad *DirectInputStick = pDirectInput->GetgamePadStick();
if (CTutorialMenu::GetMode() == CTutorialMenu::TYPE_STRATEGY)
{
if (pKeyboard->GetTrigger(DIK_Z) || pDirectInput->GetGamePadTrigger(0))
{// パート切り替え
m_part = (PART)((m_part + 1) % PART_MAX);
CScene::UIUninit();
if (PART_STRATEGY == m_part)
{
CreateStrategyUI();
}
else
{
CreateActionUI();
}
}
}
}
//=============================================================================
// アクションパートのUI生成処理
//=============================================================================
void CTutorial::CreateActionUI(void)
{
if (NULL != m_pButtonManager)
{// ボタン管理クラスの破棄
m_pButtonManager->Uninit();
m_pButtonManager = NULL;
}
if (NULL != m_pMouseCursor)
{// マウスカーソルの破棄
m_pMouseCursor->Uninit();
m_pMouseCursor = NULL;
}
if (NULL != m_pMouse)
{
//m_pMouse->Uninit();
//m_pMouse = NULL;
m_pMouse->SetDisp(false);
}
//****************************************
// 2DUI生成(フレーム)
//****************************************
CUI_TEXTURE::Create(D3DXVECTOR3(SCREEN_WIDTH / 2, 80.0f, 0.0f), TUTORIAL_TITLE_WIDTH, TUTORIAL_TITLE_HEIGHT, CUI_TEXTURE::UIFLAME_TUTORIAL_TITLE_STRATEGY); // チュートリアルの項目
m_nStepsMax = TUTORIAL_STRATEGY_STEPS_NUM;
m_nInstMax = TUTORIAL_STRATEGY_INST_NUM;
for (int nCntSteps = 0; nCntSteps < m_nStepsMax; nCntSteps++)
{
m_apSteps[nCntSteps] = CUI_TEXTURE::Create(D3DXVECTOR3((SCREEN_WIDTH / 2 - 80.0f) + (70.0f * nCntSteps), 180.0f, 0.0f), TUTORIAL_STEPS_WIDTH, TUTORIAL_STEPS_HEIGHT, CUI_TEXTURE::UIFLAME_TUTORIAL_NUMBER); // チュートリアルの項目
m_apSteps[nCntSteps]->SetTex(nCntSteps + 1, 10, 1);
m_apSteps[nCntSteps]->SetObjType(OBJTYPE_UI_TUTORIAL);
}
if (m_pMission != NULL)
{
m_pMission->Uninit();
m_pMission = NULL;
}
m_pMission = CUI_TEXTURE::Create(D3DXVECTOR3(SCREEN_WIDTH / 2, 250.0f, 0.0f), 850.0f, 90.0f, CUI_TEXTURE::UIFLAME_TUTORIAL_LESSON_STRATEGY); // 基本操作の目標
m_pMission->SetObjType(OBJTYPE_UI_TUTORIAL);
if (m_pInst != NULL)
{
m_pInst->Uninit();
m_pInst = NULL;
}
m_pInst = CUI_TEXTURE::Create(D3DXVECTOR3(SCREEN_WIDTH - 180.0f, 450.0f, 0.0f), TUTORIAL_INST_WIDTH, TUTORIAL_INST_HEIGHT, CUI_TEXTURE::UIFLAME_TUTORIAL_INST_STRATEGY); // 基本操作の目標
m_pInst->SetObjType(OBJTYPE_UI_TUTORIAL);
// 武器フレーム
// プレイヤー体力フレーム
CUI_TEXTURE::Create(D3DXVECTOR3(180.0f, 650.0f, 0.0f), 350.0f, 125.0f, CUI_TEXTURE::UIFLAME_PLAYER_HP); // 胴体
CUI_TEXTURE::Create(D3DXVECTOR3(125.0f, 530.0f, 0.0f), 230.0f, 100.0f, CUI_TEXTURE::UIFLAME_DRONE); // AI01
//****************************************
// UI生成(数字)
//****************************************
CUI_NUMBER::Create(D3DXVECTOR3(195.0f, 650.0f, 0.0f), 170.0f, 110.0f, 70.0f, CUI_NUMBER::UI_NUMTYPE_PLAYER_HP, 0, NUMTEX_UV_X, NUMTEX_UV_Y); // プレイヤーライフ
}
//=============================================================================
// ストラテジーパートのUI生成処理
//=============================================================================
void CTutorial::CreateStrategyUI(void)
{
//****************************************
// 2DUI生成(フレーム)
//****************************************
// 背景
CUI_TEXTURE::Create(D3DXVECTOR3(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, 0.0f), SCREEN_WIDTH, SCREEN_HEIGHT, CUI_TEXTURE::UIFLAME_STRATEGY_BG); // 背景
// フレーム
CUI_TEXTURE::Create(D3DXVECTOR3(785.0f, 420.0f, 0.0f), 990.0f, 590.0f, CUI_TEXTURE::UIFLAME_FLAME_BLUE); // 大枠
CUI_TEXTURE::Create(D3DXVECTOR3(790.0f, 190.0f, 0.0f), 970.0f, 100.0f, CUI_TEXTURE::UIFLAME_FLAME_WHITE); // ロジックライン
CUI_TEXTURE::Create(D3DXVECTOR3(405.0f, 470.0f, 0.0f), 200.0f, 450.0f, CUI_TEXTURE::UIFLAME_FLAME_WHITE); // AI表示
CUI_TEXTURE::Create(D3DXVECTOR3(895.0f, 470.0f, 0.0f), 760.0f, 450.0f, CUI_TEXTURE::UIFLAME_FLAME_WHITE); // ロジック部分
//****************************************
// 1P小隊情報
//****************************************
CUI_TEXTURE::Create(D3DXVECTOR3(150.0f, 325.0f, 0.0f), 280.0f, 260.0f, CUI_TEXTURE::UIFLAME_1P_INFO);
// プレイヤー体力フレーム
CUI_TEXTURE::Create(D3DXVECTOR3(150.0f, 260.0f, 0.0f), 255.0f, 80.0f, CUI_TEXTURE::UIFLAME_PLAYER_HP);
// AIチケット数フレーム
CUI_TEXTURE::Create(D3DXVECTOR3(150.0f, 410.0f, 0.0f), 255.0f, 80.0f, CUI_TEXTURE::UIFLAME_DRONE); // ドローン
if (NULL == m_pButtonManager)
{// ボタン管理クラスの生成
m_pButtonManager = CButtonManagerStrategy::Create();
}
if (NULL == m_pMouseCursor)
{// マウスカーソルの生成
m_pMouseCursor = CMouseCursor2D::Create();
}
if (NULL == m_pMouse)
{
m_pMouse = CMouseCursor::Create();
}
if (NULL != m_pMouse)
{
m_pMouse->SetDisp(true);
}
}
//=============================================================================
// 必要な情報を書き込む処理
//=============================================================================
void CTutorial::PrintData(void)
{
//クライアントの取得
CClient *pClient = CManager::GetClient();
#if 1
if (pClient != NULL && pClient->GetConnect() == true)
{//NULLではない場合
if (m_pPlayer[pClient->GetPlayerIdx()] != NULL)
{//NULLではない場合
pClient->Printf(SERVER_PLAYER_DATA);
//プレイヤー番号を書き込む
pClient->Printf("%d", CManager::GetClient()->GetPlayerIdx());
pClient->Printf(" ");
//チームの番号を書き込む
pClient->Printf("%d", CManager::GetClient()->GetTeam());
pClient->Printf(" ");
//プレイヤーのx,y軸の位置を書き込む
pClient->Printf("%.1f %.1f", m_pPlayer[pClient->GetPlayerIdx()]->GetPos().x, m_pPlayer[pClient->GetPlayerIdx()]->GetPos().z);
pClient->Printf(" ");
//プレイヤーのy軸の向きを書き込む
pClient->Printf("%.1f", m_pPlayer[pClient->GetPlayerIdx()]->GetRot().y);
pClient->Printf(" ");
//モデル0番のy軸の向きを書き込む
pClient->Printf("%.1f", m_pPlayer[pClient->GetPlayerIdx()]->GetModel(0)->GetRot().y);
pClient->Printf(" ");
//モデル1番の向きを書き込む
pClient->Printf("%.1f %.1f %.1f", m_pPlayer[pClient->GetPlayerIdx()]->GetModel(1)->GetRot().x, m_pPlayer[pClient->GetPlayerIdx()]->GetModel(1)->GetRot().y, m_pPlayer[pClient->GetPlayerIdx()]->GetModel(1)->GetRot().z);
pClient->Printf(" ");
//カメラの向きを書き込む
pClient->Printf("%.1f %.1f %.1f", CManager::GetCamera()->GetRot().x, CManager::GetCamera()->GetRot().y, CManager::GetCamera()->GetRot().z);
pClient->Printf(" ");
//死亡しているかどうか
if (m_pPlayer[pClient->GetPlayerIdx()]->GetDeath() == true)
{
pClient->Printf("1");
pClient->Printf(" ");
}
else
{
pClient->Printf("0");
pClient->Printf(" ");
//体力の表示
pClient->Printf("%d", m_pPlayer[pClient->GetPlayerIdx()]->GetLife());
pClient->Printf(" ");
}
//弾を発射しているかどうかを書き込む
if (m_pPlayer[pClient->GetPlayerIdx()]->GetShoot() == true)
{//発射されている場合
pClient->Printf("1");
pClient->Printf(" ");
//弾の同時発射数を書き込む
pClient->Printf("%d", m_pPlayer[pClient->GetPlayerIdx()]->GetNumShoot());
pClient->Printf(" ");
pClient->Printf("%d", m_pPlayer[pClient->GetPlayerIdx()]->GetAttack());
pClient->Printf(" ");
//水平角度の情報を書き込む
for (int nCntShoot = 0; nCntShoot < m_pPlayer[pClient->GetPlayerIdx()]->GetNumShoot() * 2; nCntShoot++)
{
pClient->Printf("%.2f %.2f", m_pPlayer[pClient->GetPlayerIdx()]->GetAngle(nCntShoot), m_pPlayer[pClient->GetPlayerIdx()]->GetAngleV(nCntShoot));
pClient->Printf(" ");
}
//発射していない状態に戻す
m_pPlayer[pClient->GetPlayerIdx()]->SetShoot(false);
}
else
{
pClient->Printf("0");
pClient->Printf(" ");
}
//チャットをしているかどうかを書き込む
if (m_pPlayer[pClient->GetPlayerIdx()]->GetChat() == true)
{//チャットをしている場合
pClient->Printf("1");
pClient->Printf(" ");
//チャットの番号を書き込む
pClient->Printf("%d", m_pPlayer[pClient->GetPlayerIdx()]->GetRadioChat());
pClient->Printf(" ");
}
else
{
pClient->Printf("0");
pClient->Printf(" ");
}
//AIの位置を書き込む
pClient->Printf("%.1f %.1f %.1f", m_pPlayer[pClient->GetPlayerIdx()]->GetMyAI(0)->GetPos().x, m_pPlayer[pClient->GetPlayerIdx()]->GetMyAI(0)->GetPos().y, m_pPlayer[pClient->GetPlayerIdx()]->GetMyAI(0)->GetPos().z);
pClient->Printf(" ");
//AIの向きを書き込む
pClient->Printf("%.1f", m_pPlayer[pClient->GetPlayerIdx()]->GetMyAI(0)->GetRot().y);
pClient->Printf(" ");
//AIの死亡しているかどうかを書き込む
if (m_pPlayer[pClient->GetPlayerIdx()]->GetMyAI(0)->GetDeath() == true)
{
pClient->Printf("1");
pClient->Printf(" ");
}
else
{
pClient->Printf("0");
pClient->Printf(" ");
}
if (pClient->GetPlayerIdx() == 0)
{//ホストの場合
if (m_state == STATE_END)
{
pClient->Printf("1");
pClient->Printf(" ");
pClient->Printf("%d", CResult::GetTeamWin());
pClient->Printf(" ");
}
else
{
pClient->Printf("0");
pClient->Printf(" ");
}
//CPUのデータ情報を書き込む処理
//PrintCPUData();
}
}
}
#endif
}
//=============================================================================
// CPUのデータ情報を書き込む処理
//=============================================================================
void CTutorial::PrintCPUData(void)
{
CClient *pClient = CManager::GetClient();
if (pClient != NULL)
{
for (int nCntPlayer = 0; nCntPlayer < MAX_PLAYER_TUTORIAL; nCntPlayer++)
{
if (pClient->GetPlayerIdx() != nCntPlayer)
{
if (m_bConnect[nCntPlayer] == false)
{
//プレイヤー番号を書き込む
pClient->Printf("%d", nCntPlayer);
pClient->Printf(" ");
//チームの番号を書き込む
pClient->Printf("%d", m_pPlayer[nCntPlayer]->GetTeam());
pClient->Printf(" ");
//プレイヤーのx,y軸の位置を書き込む
pClient->Printf("%.1f %.1f", m_pPlayer[nCntPlayer]->GetPos().x, m_pPlayer[nCntPlayer]->GetPos().z);
pClient->Printf(" ");
//プレイヤーのy軸の向きを書き込む
pClient->Printf("%.1f", m_pPlayer[nCntPlayer]->GetRot().y);
pClient->Printf(" ");
//死亡しているかどうか
if (m_pPlayer[nCntPlayer]->GetDeath() == true)
{
pClient->Printf("1");
pClient->Printf(" ");
}
else
{
pClient->Printf("0");
pClient->Printf(" ");
}
//弾を発射しているかどうかを書き込む
if (m_pPlayer[nCntPlayer]->GetShoot() == true)
{//発射されている場合
pClient->Printf("1");
pClient->Printf(" ");
//弾の同時発射数を書き込む
pClient->Printf("%d", m_pPlayer[nCntPlayer]->GetNumShoot());
pClient->Printf(" ");
pClient->Printf("%d", m_pPlayer[nCntPlayer]->GetAttack());
pClient->Printf(" ");
//水平角度の情報を書き込む
for (int nCntShoot = 0; nCntShoot < m_pPlayer[nCntPlayer]->GetNumShoot() * 2; nCntShoot++)
{
pClient->Printf("%.2f %.2f", m_pPlayer[nCntPlayer]->GetAngle(nCntShoot), m_pPlayer[nCntPlayer]->GetAngleV(nCntShoot));
pClient->Printf(" ");
}
//発射していない状態に戻す
m_pPlayer[nCntPlayer]->SetShoot(false);
}
else
{
pClient->Printf("0");
pClient->Printf(" ");
}
}
}
}
}
}
//=============================================================================
// 情報を読み取る処理
//=============================================================================
void CTutorial::ReadMessage(void)
{
CClient *pClient = CManager::GetClient(); //クライアントのポインタ情報
char *pStr = pClient->GetReceiveData(); //サーバーから受け取ったメッセージ情報
if (pClient != NULL && pClient->GetConnect() == true)
{
//頭出し処理
pStr = CServerFunction::HeadPutout(pStr, "");
if (CServerFunction::Memcmp(pStr, SERVER_CONNECT_DATA) == 0)
{//接続総数を示している場合
pStr += strlen(SERVER_CONNECT_DATA); //頭出し
//接続情報の読み取り処理
pStr = ReadConnectData(pStr);
}
if (CServerFunction::Memcmp(pStr, SERVER_PLAYER_START) == 0)
{//プレイヤーの開始を示している場合
pStr += strlen(SERVER_PLAYER_START); //頭出し
pStr += strlen(" ");
for (int nCntClient = 0; nCntClient < pClient->GetNumConnect() - 1; nCntClient++)
{
if (CServerFunction::Memcmp(pStr, SERVER_PLAYER_DATA) == 0)
{
pStr += strlen(SERVER_PLAYER_DATA);
pStr = ReadPlayerData(pStr);
}
}
}
}
}
//=============================================================================
// 接続の情報を読み取る処理
//=============================================================================
char *CTutorial::ReadConnectData(char *pStr)
{
//クライアントの取得
CClient *pClient = CManager::GetClient();
if (pClient != NULL)
{
if (pClient->GetConnect() == true)
{
int nWord = 0; //文字の頭出し用
//接続総数の設置処理
pClient->SetNumConnect(CServerFunction::ReadInt(pStr, ""));
nWord = CServerFunction::PopString(pStr, ""); //文字数カウント
pStr += nWord; //頭出し
//最小の番号の設置処理
pClient->SetMinIdx(CServerFunction::ReadInt(pStr, ""));
nWord = CServerFunction::PopString(pStr, ""); //文字数カウント
pStr += nWord; //頭出し
//最大の番号の設置処理
pClient->SetMaxIdx(CServerFunction::ReadInt(pStr, ""));
nWord = CServerFunction::PopString(pStr, ""); //文字数カウント
pStr += nWord; //頭出し
}
}
return pStr;
}
//=============================================================================
// プレイヤーの情報を読み取る処理
//=============================================================================
char *CTutorial::ReadPlayerData(char *pStr)
{
D3DXVECTOR3 pos = D3DXVECTOR3(0.0f, 0.0f, 0.0f); //位置
D3DXVECTOR3 rot = D3DXVECTOR3(0.0f, 0.0f, 0.0f);
D3DXVECTOR3 modelRotDown = D3DXVECTOR3(0.0f, 0.0f, 0.0f), modelRotUp = D3DXVECTOR3(0.0f, 0.0f, 0.0f); //モデルの上半身と下半身の向き
D3DXVECTOR3 cameraRot; //カメラの向き
int nPlayerIdx = 0; //プレイヤーの番号
int nNumConnect = 0; //接続総数
int nWord = 0; //文字の頭出し用
int nCntClient = 0; //クライアントのカウンター
int nTeam = 0;
float *pAngle = NULL;
float *pAngleV = NULL;
bool bShoot = false;
int nNumShoot = 0;
int nAttack = 0;
bool bChat = false;
CPlayer::RADIOCHAT radioChat = CPlayer::RADIOCHAT_OK;
int nBlueLinkEnergy = 0;
int nRedLinkEnergy = 0;
int nState = 0;
int nLife = 0;
D3DXVECTOR3 AIPos = D3DXVECTOR3(0.0f, 0.0f, 0.0f);
D3DXVECTOR3 AIRot = D3DXVECTOR3(0.0f, 0.0f, 0.0f);
bool bAIDeath = false;
//クライアントの取得
CClient *pClient = CManager::GetClient();
if (pClient != NULL)
{
if (pClient->GetConnect() == true)
{
//プレイヤー番号を代入
nPlayerIdx = CServerFunction::ReadInt(pStr, "");
nWord = CServerFunction::PopString(pStr, ""); //文字数カウント
pStr += nWord; //頭出し
//チーム情報の代入
nTeam = CServerFunction::ReadInt(pStr, "");
nWord = CServerFunction::PopString(pStr, "");
pStr += nWord;
//プレイヤーの位置を代入
pos.x = CServerFunction::ReadFloat(pStr, "");
nWord = CServerFunction::PopString(pStr, "");
pStr += nWord;
pos.z = CServerFunction::ReadFloat(pStr, "");
nWord = CServerFunction::PopString(pStr, "");
pStr += nWord;
//プレイヤーの向きを代入
rot.y = CServerFunction::ReadFloat(pStr, "");
nWord = CServerFunction::PopString(pStr, "");
pStr += nWord;
//モデル0版の向きを代入
modelRotDown.y = CServerFunction::ReadFloat(pStr, "");
nWord = CServerFunction::PopString(pStr, "");
pStr += nWord;
//モデル1番の向きを代入
modelRotUp.x = CServerFunction::ReadFloat(pStr, "");
nWord = CServerFunction::PopString(pStr, "");
pStr += nWord;
modelRotUp.y = CServerFunction::ReadFloat(pStr, "");
nWord = CServerFunction::PopString(pStr, "");
pStr += nWord;
modelRotUp.z = CServerFunction::ReadFloat(pStr, "");
nWord = CServerFunction::PopString(pStr, "");
pStr += nWord;
//カメラの向きを代入
cameraRot.x = CServerFunction::ReadFloat(pStr, "");
nWord = CServerFunction::PopString(pStr, "");
pStr += nWord;
cameraRot.y = CServerFunction::ReadFloat(pStr, "");
nWord = CServerFunction::PopString(pStr, "");
pStr += nWord;
cameraRot.z = CServerFunction::ReadFloat(pStr, "");
nWord = CServerFunction::PopString(pStr, "");
pStr += nWord;
//死亡しているかしているかどうかを代入
bool bDeath = CServerFunction::ReadBool(pStr, "");
nWord = CServerFunction::PopString(pStr, "");
pStr += nWord;
if (bDeath == false)
{
nLife = CServerFunction::ReadInt(pStr, "");
nWord = CServerFunction::PopString(pStr, "");
pStr += nWord;
}
//弾を発射しているかどうかを代入
bShoot = CServerFunction::ReadBool(pStr, "");
nWord = CServerFunction::PopString(pStr, "");
pStr += nWord;
if (bShoot == true)
{
nNumShoot = CServerFunction::ReadInt(pStr, "");
nWord = CServerFunction::PopString(pStr, "");
pStr += nWord;
pAngle = new float[nNumShoot * 2];
pAngleV = new float[nNumShoot * 2];
nAttack = CServerFunction::ReadInt(pStr, "");
nWord = CServerFunction::PopString(pStr, "");
pStr += nWord;
for (int nCntShoot = 0; nCntShoot < nNumShoot * 2; nCntShoot++)
{
pAngle[nCntShoot] = CServerFunction::ReadFloat(pStr, "");
nWord = CServerFunction::PopString(pStr, "");
pStr += nWord;
pAngleV[nCntShoot] = CServerFunction::ReadFloat(pStr, "");
nWord = CServerFunction::PopString(pStr, "");
pStr += nWord;
}
}
//チャットをしているかどうかを代入
bChat = CServerFunction::ReadBool(pStr, "");
nWord = CServerFunction::PopString(pStr, "");
pStr += nWord;
if (bChat == true)
{
radioChat = (CPlayer::RADIOCHAT)CServerFunction::ReadInt(pStr, "");
nWord = CServerFunction::PopString(pStr, "");
pStr += nWord;
}
//AIの位置を代入
AIPos.x = CServerFunction::ReadFloat(pStr, "");
nWord = CServerFunction::PopString(pStr, "");
pStr += nWord;
AIPos.y = CServerFunction::ReadFloat(pStr, "");
nWord = CServerFunction::PopString(pStr, "");
pStr += nWord;
AIPos.z = CServerFunction::ReadFloat(pStr, "");
nWord = CServerFunction::PopString(pStr, "");
pStr += nWord;
//AIの向きを代入
AIRot.y = CServerFunction::ReadFloat(pStr, "");
nWord = CServerFunction::PopString(pStr, "");
pStr += nWord;
//AIの死亡しているかどうかを代入
bAIDeath = CServerFunction::ReadBool(pStr, "");
nWord = CServerFunction::PopString(pStr, "");
pStr += nWord;
if (nPlayerIdx == 0)
{//ホストの場合
nState = CServerFunction::ReadInt(pStr, "");
nWord = CServerFunction::PopString(pStr, "");
pStr += nWord;
if (nState == 1)
{
CResult::SetTeamWin((CResult::TEAM_WIN)CServerFunction::ReadInt(pStr, ""));
}
else
{
//m_nBlueLinkEnergy = CServerFunction::ReadInt(pStr, "");
//nWord = CServerFunction::PopString(pStr, "");
//pStr += nWord;
//m_nRedLinkEnergy = CServerFunction::ReadInt(pStr, "");
//nWord = CServerFunction::PopString(pStr, "");
//pStr += nWord;
}
//pStr = ReadCPUData(pStr);
}
if (bDeath == true)
{
m_pPlayer[nPlayerIdx]->GetDeath() = true;
if (m_bPlayerDeath[nPlayerIdx] == false)
{
m_bPlayerDeath[nPlayerIdx] = true;
if (m_bPlayerDeath[nPlayerIdx] == true)
{
switch (nTeam)
{
case 0:
m_nBlueLinkEnergy -= 30;
break;
case 1:
m_nRedLinkEnergy -= 30;
break;
}
}
}
}
else
{
m_bPlayerDeath[nPlayerIdx] = false;
}
if (bAIDeath == true)
{
m_pPlayer[nPlayerIdx]->GetMyAI(0)->SetDeath(bAIDeath);
if (m_bAIDeath[0][nPlayerIdx] == false)
{
m_bAIDeath[0][nPlayerIdx] = true;
if (m_bAIDeath[0][nPlayerIdx] == true)
{
switch (nTeam)
{
case 0:
m_nBlueLinkEnergy -= 20;
break;
case 1:
m_nRedLinkEnergy -= 20;
break;
}
}
}
}
else
{
if (m_bAIDeath[0][nPlayerIdx] == true)
{
m_bAIDeath[0][nPlayerIdx] = false;
m_pPlayer[nPlayerIdx]->GetMyAI(0)->SetDeath(bAIDeath);
}
}
if (nPlayerIdx != pClient->GetPlayerIdx())
{//プレイヤーの番号がクライアント番号と違う場合
if (m_pPlayer[nPlayerIdx] != NULL)
{
//チーム情報をの設置処理
//m_pPlayer[nPlayerIdx]->SetTeam(nTeam);
SetPlayerData(nPlayerIdx, pos, rot, modelRotUp, modelRotDown, cameraRot);
m_pPlayer[nPlayerIdx]->SetLife(nLife);
m_pPlayer[nPlayerIdx]->GetMyAI(0)->SetPos(AIPos);
m_pPlayer[nPlayerIdx]->GetMyAI(0)->SetRot(AIRot);
if (bShoot == true)
{//弾を発射していintる場合
CreatePlayerBullet(nPlayerIdx, nNumShoot, nAttack, cameraRot, pAngle, pAngleV);
}
if (bChat == true && m_pPlayer[pClient->GetPlayerIdx()]->GetTeam() == nTeam)
{
SetChatData(nPlayerIdx, (int)radioChat);
}
if (nState == 1)
{
m_state = STATE_END;
}
}
}
}
}
if (pAngle != NULL)
{
delete[] pAngle;
pAngle = NULL;
}
if (pAngleV != NULL)
{
delete[] pAngleV;
pAngleV = NULL;
}
return pStr;
}
//=============================================================================
// CPUプレイヤー情報を読み取る処理
//=============================================================================
char *CTutorial::ReadCPUData(char *pStr)
{
for (int nCntPlayer = 0; nCntPlayer < MAX_PLAYER_TUTORIAL; nCntPlayer++)
{
if (m_bConnect[nCntPlayer] == false)
{
D3DXVECTOR3 pos = D3DXVECTOR3(0.0f, 0.0f, 0.0f); //位置
D3DXVECTOR3 rot = D3DXVECTOR3(0.0f, 0.0f, 0.0f);
D3DXVECTOR3 modelRotDown = D3DXVECTOR3(0.0f, 0.0f, 0.0f), modelRotUp = D3DXVECTOR3(0.0f, 0.0f, 0.0f); //モデルの上半身と下半身の向き
D3DXVECTOR3 cameraRot; //カメラの向き
int nPlayerIdx = 0; //プレイヤーの番号
int nNumConnect = 0; //接続総数
int nWord = 0; //文字の頭出し用
int nCntClient = 0; //クライアントのカウンター
int nTeam = 0;
float *pAngle = NULL;
float *pAngleV = NULL;
bool bShoot = false;
int nNumShoot = 0;
int nAttack = 0;
//番号を代入
nPlayerIdx = CServerFunction::ReadInt(pStr, "");
nWord = CServerFunction::PopString(pStr, ""); //文字数カウント
pStr += nWord; //頭出し
//チーム情報の代入
nTeam = CServerFunction::ReadInt(pStr, "");
nWord = CServerFunction::PopString(pStr, "");
pStr += nWord;
//プレイヤーの位置を代入
pos.x = CServerFunction::ReadFloat(pStr, "");
nWord = CServerFunction::PopString(pStr, "");
pStr += nWord;
pos.z = CServerFunction::ReadFloat(pStr, "");
nWord = CServerFunction::PopString(pStr, "");
pStr += nWord;
//プレイヤーの向きを代入
rot.y = CServerFunction::ReadFloat(pStr, "");
nWord = CServerFunction::PopString(pStr, "");
pStr += nWord;
//死亡しているかどうかを代入
bool bDeath = CServerFunction::ReadBool(pStr, "");
nWord = CServerFunction::PopString(pStr, "");
pStr += nWord;
//弾を発射しているかどうかを代入
bShoot = CServerFunction::ReadBool(pStr, "");
nWord = CServerFunction::PopString(pStr, "");
pStr += nWord;
if (bShoot == true)
{
nNumShoot = CServerFunction::ReadInt(pStr, "");
nWord = CServerFunction::PopString(pStr, "");
pStr += nWord;
pAngle = new float[nNumShoot * 2];
pAngleV = new float[nNumShoot * 2];
nAttack = CServerFunction::ReadInt(pStr, "");
nWord = CServerFunction::PopString(pStr, "");
pStr += nWord;
for (int nCntShoot = 0; nCntShoot < nNumShoot * 2; nCntShoot++)
{
pAngle[nCntShoot] = CServerFunction::ReadFloat(pStr, "");
nWord = CServerFunction::PopString(pStr, "");
pStr += nWord;
pAngleV[nCntShoot] = CServerFunction::ReadFloat(pStr, "");
nWord = CServerFunction::PopString(pStr, "");
pStr += nWord;
}
}
SetCPUData(nPlayerIdx, pos, rot);
if (bShoot == true)
{
CreateCPUBullet(nPlayerIdx, nNumShoot, nAttack, cameraRot, pAngle, pAngleV);
}
}
}
return pStr;
}
//=============================================================================
// プレイヤーの情報の設置処理
//=============================================================================
void CTutorial::SetPlayerData(int nPlayerIdx, D3DXVECTOR3 pos, D3DXVECTOR3 rot, D3DXVECTOR3 modelRotUp, D3DXVECTOR3 modelRotDown, D3DXVECTOR3 cameraRot)
{
//プレイヤーの位置の設置処理
m_pPlayer[nPlayerIdx]->SetPos(pos);
float fDiffRot;
float fAngle = D3DX_PI + cameraRot.y;
float fRotDest = m_pPlayer[nPlayerIdx]->GetRotDest();
// 目的の角度の調節
if (fRotDest > D3DX_PI) { fRotDest -= D3DX_PI * 2.0f; }
if (fRotDest < -D3DX_PI) { fRotDest += D3DX_PI * 2.0f; }
// 目的の角度への差分
fDiffRot = fRotDest - rot.y;
if (fDiffRot > D3DX_PI) { fDiffRot -= D3DX_PI * 2.0f; }
if (fDiffRot < -D3DX_PI) { fDiffRot += D3DX_PI * 2.0f; }
// 角度の更新
rot.y += fDiffRot * 0.05f;
if (rot.y > D3DX_PI) { rot.y -= D3DX_PI * 2.0f; }
if (rot.y < -D3DX_PI) { rot.y += D3DX_PI * 2.0f; }
float fCameraAngle = fAngle - rot.y;
// 差分の調節
if (fCameraAngle > D3DX_PI) { fCameraAngle -= D3DX_PI * 2.0f; }
if (fCameraAngle < -D3DX_PI) { fCameraAngle += D3DX_PI * 2.0f; }
if (fRotDest <= D3DX_PI * 0.5f && fRotDest >= D3DX_PI * -0.5f)
{// 下半身の動きを進行方向に合わせる
m_pPlayer[nPlayerIdx]->GetModel(0)->SetRot(D3DXVECTOR3(modelRotDown.x, rot.y + fCameraAngle, modelRotDown.z));
m_pPlayer[nPlayerIdx]->GetModel(1)->SetRot(D3DXVECTOR3(-cameraRot.x + (D3DX_PI * 0.5f), fCameraAngle - fAngle, modelRotUp.z));
}
else
{// 斜め後ろ向きのとき
m_pPlayer[nPlayerIdx]->GetModel(1)->SetRot(D3DXVECTOR3(-cameraRot.x + (D3DX_PI * 0.5f), fCameraAngle - (fAngle - D3DX_PI), modelRotUp.z));
}
//プレイヤーの向きの設置処理
m_pPlayer[nPlayerIdx]->SetRot(rot);
//プレイヤーの目的の角度の設置処理
m_pPlayer[nPlayerIdx]->SetRotDest(fRotDest);
}
//=============================================================================
// プレイヤーの弾の生成処理
//=============================================================================
void CTutorial::CreatePlayerBullet(int nPlayerIdx, int nNumShoot, int nAttack, D3DXVECTOR3 cameraRot, float *pAngle, float *pAngleV)
{
//for (int nCntShoot = 0; nCntShoot < nNumShoot; nCntShoot++)
//{
// // 弾の生成
// D3DXMATRIX mtxCanon = m_pPlayer[nPlayerIdx]->GetModel(2)->GetMtxWorld();
// D3DXVECTOR3 posCanon = D3DXVECTOR3(mtxCanon._41, mtxCanon._42, mtxCanon._43) + D3DXVECTOR3(sinf(cameraRot.y) * 30.0f, cosf(cameraRot.x) * 30.0f, cosf(cameraRot.y) * 30.0f);
// CBulletPlayer::Create(posCanon, pAngle[nCntShoot * 2], pAngleV[nCntShoot * 2], nAttack, m_pPlayer[nPlayerIdx]->GetTeam(), this);
// mtxCanon = m_pPlayer[nPlayerIdx]->GetModel(3)->GetMtxWorld();
// posCanon = D3DXVECTOR3(mtxCanon._41, mtxCanon._42, mtxCanon._43) + D3DXVECTOR3(sinf(cameraRot.y) * 30.0f, cosf(cameraRot.x) * 30.0f, cosf(cameraRot.y) * 30.0f);
// CBulletPlayer::Create(posCanon, pAngle[nCntShoot * 2 + 1], pAngleV[nCntShoot * 2 + 1], nAttack, m_pPlayer[nPlayerIdx]->GetTeam(), this);
// //弾を発射しているかどうかの設置処理
// m_pPlayer[nPlayerIdx]->SetShoot(false);
//}
}
//=============================================================================
// チャット情報の設置処理
//=============================================================================
void CTutorial::SetChatData(int nPlayerIdx, int radioChat)
{
switch (nPlayerIdx)
{
case 0:
m_pPlayer[1]->SetAllyRadioChat((CPlayer::RADIOCHAT)radioChat);
m_pPlayer[1]->SetAllyChat(true);
break;
case 1:
m_pPlayer[0]->SetAllyRadioChat((CPlayer::RADIOCHAT)radioChat);
m_pPlayer[0]->SetAllyChat(true);
break;
case 2:
m_pPlayer[3]->SetAllyRadioChat((CPlayer::RADIOCHAT)radioChat);
m_pPlayer[3]->SetAllyChat(true);
break;
case 3:
m_pPlayer[2]->SetAllyRadioChat((CPlayer::RADIOCHAT)radioChat);
m_pPlayer[2]->SetAllyChat(true);
break;
}
}
//=============================================================================
// CPUプレイヤーの情報設置処理
//=============================================================================
void CTutorial::SetCPUData(int nPlayerIdx, D3DXVECTOR3 pos, D3DXVECTOR3 rot)
{
//プレイヤーの位置の設置処理
m_pPlayer[nPlayerIdx]->SetPos(pos);
//プレイヤーの向きの設置処理
m_pPlayer[nPlayerIdx]->SetRot(rot);
}
//=============================================================================
// CPUプレイヤーの弾の生成処理
//=============================================================================
void CTutorial::CreateCPUBullet(int nPlayerIdx, int nNumShoot, int nAttack, D3DXVECTOR3 cameraRot, float *pAngle, float *pAngleV)
{
for (int nCntShoot = 0; nCntShoot < nNumShoot; nCntShoot++)
{
//// 弾の生成
//D3DXMATRIX mtxCanon = m_pPlayer[nPlayerIdx]->GetModel(2)->GetMtxWorld();
//D3DXVECTOR3 posCanon = D3DXVECTOR3(mtxCanon._41, mtxCanon._42, mtxCanon._43) + D3DXVECTOR3(sinf(cameraRot.y) * 30.0f, cosf(cameraRot.x) * 30.0f, cosf(cameraRot.y) * 30.0f);
//CBulletPlayer::Create(posCanon, pAngle[nCntShoot * 2], pAngleV[nCntShoot * 2], nAttack, m_pPlayer[nPlayerIdx]->GetTeam(), this);
//mtxCanon = m_pPlayer[nPlayerIdx]->GetModel(3)->GetMtxWorld();
//posCanon = D3DXVECTOR3(mtxCanon._41, mtxCanon._42, mtxCanon._43) + D3DXVECTOR3(sinf(cameraRot.y) * 30.0f, cosf(cameraRot.x) * 30.0f, cosf(cameraRot.y) * 30.0f);
//CBulletPlayer::Create(posCanon, pAngle[nCntShoot * 2 + 1], pAngleV[nCntShoot * 2 + 1], nAttack, m_pPlayer[nPlayerIdx]->GetTeam(), this);
////弾を発射しているかどうかの設置処理
//m_pPlayer[nPlayerIdx]->SetShoot(false);
}
}
//=============================================================================
// 基本操作のチュートリアル
//=============================================================================
void CTutorial::TutorialBasicMovement(void)
{
// サウンドの取得
CSound *pSound = CManager::GetSound();
CPlayer *pPlayer = CTutorial::GetPlayer(0);
D3DXVECTOR3 posPlayer = pPlayer->GetPos();
CCamera *pCamera = CManager::GetCamera();
D3DXVECTOR3 CameraRot = pCamera->GetRot();
D3DXVECTOR3 posClear = D3DXVECTOR3(-30.0f, 0.0f, -40.0f);
float fradius = 50.0f;
float fcol = ((posPlayer.x - posClear.x) *(posPlayer.x - posClear.x)) + ((posPlayer.z - posClear.z) *(posPlayer.z - posClear.z));
float fDiameter = fradius * fradius;
switch (m_nSteps)
{
case 0:
if (CameraRot.y >= 2.6f && CameraRot.y <= 3.0f)
{
if (m_R_CameraState == CLEARSTATE_NONE && m_R_CameraState != CLEARSTATE_TRUE)
{
pSound->PlaySound(CSound::SOUND_LABEL_SUCCESS);
m_R_CameraState = CLEARSTATE_TRUE;
}
}
else if (m_L_CameraState == CLEARSTATE_NONE && m_L_CameraState != CLEARSTATE_TRUE)
{
if (CameraRot.y <= 0.8f && CameraRot.y >= -1.5f)
{
pSound->PlaySound(CSound::SOUND_LABEL_SUCCESS);
m_L_CameraState = CLEARSTATE_TRUE;
}
}
if (m_R_CameraState == CLEARSTATE_TRUE && m_L_CameraState == CLEARSTATE_TRUE)
{
if (m_TutorialState == TUTORIALSTATE_NORMAL && m_TutorialState != TUTORIALSTATE_CLEAR)
{
pSound->PlaySound(CSound::SOUND_LABEL_STEPCLEAR);
m_Succes = CUI_TEXTURE::Create(D3DXVECTOR3(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, 0.0f), TUTORIAL_SUCCESS_WIDTH, TUTORIAL_SUCCESS_HEIGHT, CUI_TEXTURE::UIFLAME_TUTORIAL_SUCCESS); // チュートリアルの達成
m_nDisp = 60;
m_TutorialState = TUTORIALSTATE_CLEAR;
}
}
CDebugProc::Print("クリア[R]:%d", m_R_CameraState);
CDebugProc::Print("クリア[L]:%d", m_L_CameraState);
break;
case 1:
if (CameraRot.x <= 1.3f && CameraRot.x >= 1.0f)
{
if (m_U_CameraState == CLEARSTATE_NONE && m_U_CameraState != CLEARSTATE_TRUE)
{
pSound->PlaySound(CSound::SOUND_LABEL_SUCCESS);
m_U_CameraState = CLEARSTATE_TRUE;
}
}
if (m_U_CameraState == CLEARSTATE_TRUE)
{
if (CameraRot.x <= 1.6f && CameraRot.x >= 1.4f)
{
if (m_D_CameraState == CLEARSTATE_NONE && m_D_CameraState != CLEARSTATE_TRUE)
{
pSound->PlaySound(CSound::SOUND_LABEL_SUCCESS);
m_D_CameraState = CLEARSTATE_TRUE;
}
}
}
if (m_D_CameraState == CLEARSTATE_TRUE && m_U_CameraState == CLEARSTATE_TRUE)
{
if (m_TutorialState == TUTORIALSTATE_NORMAL && m_TutorialState != TUTORIALSTATE_CLEAR)
{
pSound->PlaySound(CSound::SOUND_LABEL_STEPCLEAR);
m_Succes = CUI_TEXTURE::Create(D3DXVECTOR3(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, 0.0f), TUTORIAL_SUCCESS_WIDTH, TUTORIAL_SUCCESS_HEIGHT, CUI_TEXTURE::UIFLAME_TUTORIAL_SUCCESS); // チュートリアルの達成
m_nDisp = 60;
m_TutorialState = TUTORIALSTATE_CLEAR;
}
}
CDebugProc::Print("クリア[U]:%d", m_U_CameraState);
CDebugProc::Print("クリア[D]:%d", m_D_CameraState);
break;
case 2:
if (m_pClearMarker == NULL)
{
m_pClearMarker = CModel::Create();
m_pClearMarker->SetModel(CLEAR_MODEL_NAME);
m_pClearMarker->SetPos(D3DXVECTOR3(-30.0f, 0.5f, -40.0f));
}
if (fcol <= fDiameter)
{
if (m_Move_State == CLEARSTATE_NONE && m_Move_State != CLEARSTATE_TRUE)
{
pSound->PlaySound(CSound::SOUND_LABEL_SUCCESS);
m_Move_State = CLEARSTATE_TRUE;
}
}
if (m_Move_State == CLEARSTATE_TRUE)
{
if (m_TutorialState == TUTORIALSTATE_NORMAL && m_TutorialState != TUTORIALSTATE_CLEAR)
{
pSound->PlaySound(CSound::SOUND_LABEL_STEPCLEAR);
m_Succes = CUI_TEXTURE::Create(D3DXVECTOR3(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, 0.0f), TUTORIAL_SUCCESS_WIDTH, TUTORIAL_SUCCESS_HEIGHT, CUI_TEXTURE::UIFLAME_TUTORIAL_SUCCESS); // チュートリアルの達成
m_nDisp = 60;
m_TutorialState = TUTORIALSTATE_CLEAR;
}
}
break;
}
SetTexTutorial(m_nType, m_nSteps);
}
//=============================================================================
// アクションパートのチュートリアル
//=============================================================================
void CTutorial::TutorialAction(void)
{
// サウンドの取得
CSound *pSound = CManager::GetSound();
D3DXVECTOR3 posClear = D3DXVECTOR3(-30.0f, 0.0f, -40.0f);
CPlayer *pPlayer = CTutorial::GetPlayer(0);
D3DXVECTOR3 posPlayer = pPlayer->GetPos();
float fradius = 50.0f;
float fcol = ((posPlayer.x - posClear.x) *(posPlayer.x - posClear.x)) + ((posPlayer.z - posClear.z) *(posPlayer.z - posClear.z));
float fDiameter = fradius * fradius;
switch (m_nSteps)
{
case 0:
int nLife;
nLife = m_pPlayer[1]->GetLife();
if (nLife == 0)
{
if (m_AttackState == CLEARSTATE_NONE && m_AttackState != CLEARSTATE_TRUE)
{
m_AttackState = CLEARSTATE_TRUE;
pSound->PlaySound(CSound::SOUND_LABEL_STEPCLEAR);
m_Succes = CUI_TEXTURE::Create(D3DXVECTOR3(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, 0.0f), TUTORIAL_SUCCESS_WIDTH, TUTORIAL_SUCCESS_HEIGHT, CUI_TEXTURE::UIFLAME_TUTORIAL_SUCCESS); // チュートリアルの達成
m_nDisp = 60;
m_TutorialState = TUTORIALSTATE_CLEAR;
}
}
break;
case 1:
if (m_pPlayer[0]->GetReload() == true)
{
if (m_ReloadState == CLEARSTATE_NONE && m_ReloadState != CLEARSTATE_TRUE)
{
m_ReloadState = CLEARSTATE_TRUE;
pSound->PlaySound(CSound::SOUND_LABEL_STEPCLEAR);
m_Succes = CUI_TEXTURE::Create(D3DXVECTOR3(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, 0.0f), TUTORIAL_SUCCESS_WIDTH, TUTORIAL_SUCCESS_HEIGHT, CUI_TEXTURE::UIFLAME_TUTORIAL_SUCCESS); // チュートリアルの達成
m_nDisp = 60;
m_TutorialState = TUTORIALSTATE_CLEAR;
}
}
break;
case 2:
if (m_pClearMarker == NULL)
{
m_pClearMarker = CModel::Create();
m_pClearMarker->SetModel(CLEAR_MODEL_NAME);
m_pClearMarker->SetPos(D3DXVECTOR3(-30.0f, 0.5f, -40.0f));
}
if (fcol <= fDiameter)
{
if (m_Move_State == CLEARSTATE_NONE && m_Move_State != CLEARSTATE_TRUE)
{
pSound->PlaySound(CSound::SOUND_LABEL_SUCCESS);
m_Move_State = CLEARSTATE_TRUE;
}
}
if (m_Move_State == CLEARSTATE_TRUE)
{
if (m_TutorialState == TUTORIALSTATE_NORMAL && m_TutorialState != TUTORIALSTATE_CLEAR)
{
pSound->PlaySound(CSound::SOUND_LABEL_STEPCLEAR);
m_Succes = CUI_TEXTURE::Create(D3DXVECTOR3(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, 0.0f), TUTORIAL_SUCCESS_WIDTH, TUTORIAL_SUCCESS_HEIGHT, CUI_TEXTURE::UIFLAME_TUTORIAL_SUCCESS); // チュートリアルの達成
m_nDisp = 60;
m_TutorialState = TUTORIALSTATE_CLEAR;
}
}
break;
}
SetTexTutorial(m_nType, m_nSteps);
}
//=============================================================================
// ストラテジーパートのチュートリアル
//=============================================================================
void CTutorial::TutorialStrategy(void)
{
// サウンドの取得
CSound *pSound = CManager::GetSound();
D3DXVECTOR3 posClear = D3DXVECTOR3(-30.0f, 0.0f, -40.0f);
D3DXVECTOR3 posClear_AI = D3DXVECTOR3(0.0f, 0.0f, 330.0f);
CPlayer *pPlayer = CTutorial::GetPlayer(0);
D3DXVECTOR3 posPlayer = pPlayer->GetPos();
CAIMecha *pAimecha = pPlayer->GetMyAI(0);
D3DXVECTOR3 posAi = pAimecha->GetPos();
float fradius = 50.0f;
float fcol = ((posPlayer.x - posClear.x) *(posPlayer.x - posClear.x)) + ((posPlayer.z - posClear.z) *(posPlayer.z - posClear.z));
float fcol_AI = ((posAi.x - posClear_AI.x) *(posAi.x - posClear_AI.x)) + ((posAi.z - posClear_AI.z) *(posAi.z - posClear_AI.z));
float fDiameter = fradius * fradius;
switch (m_nSteps)
{
case 0:
if (m_pClearMarker == NULL)
{
m_pClearMarker = CModel::Create();
m_pClearMarker->SetModel(CLEAR_MODEL_NAME);
m_pClearMarker->SetPos(posClear_AI);
}
if (fcol_AI <= fDiameter)
{
if (m_Ai_Move_State == CLEARSTATE_NONE && m_Ai_Move_State != CLEARSTATE_TRUE)
{
m_Ai_Move_State = CLEARSTATE_TRUE;
pSound->PlaySound(CSound::SOUND_LABEL_STEPCLEAR);
m_Succes = CUI_TEXTURE::Create(D3DXVECTOR3(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, 0.0f), TUTORIAL_SUCCESS_WIDTH, TUTORIAL_SUCCESS_HEIGHT, CUI_TEXTURE::UIFLAME_TUTORIAL_SUCCESS); // チュートリアルの達成
m_nDisp = 60;
m_TutorialState = TUTORIALSTATE_CLEAR;
}
}
break;
case 1:
if (m_pClearMarker != NULL)
{
m_pClearMarker->Uninit();
delete m_pClearMarker;
m_pClearMarker = NULL;
}
if (m_pPlayer[1] == NULL)
{
m_pPlayer[1] = CPlayer::Create(2, CMechaSelect::MECHATYPE_LIGHT, D3DXVECTOR3(-30.0f, 0.0f, -40.0f), false);
m_pPlayer[1]->SetLife(20);
m_pPlayer[1]->SetRot(D3DXVECTOR3(0.0f, D3DX_PI * 0.5f, 0.0f));
}
int nLife;
nLife = m_pPlayer[1]->GetLife();
if (nLife == 0)
{
if (m_Ai_Attack_State == CLEARSTATE_NONE && m_Ai_Attack_State != CLEARSTATE_TRUE)
{
m_Ai_Attack_State = CLEARSTATE_TRUE;
pSound->PlaySound(CSound::SOUND_LABEL_STEPCLEAR);
m_Succes = CUI_TEXTURE::Create(D3DXVECTOR3(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, 0.0f), TUTORIAL_SUCCESS_WIDTH, TUTORIAL_SUCCESS_HEIGHT, CUI_TEXTURE::UIFLAME_TUTORIAL_SUCCESS); // チュートリアルの達成
m_nDisp = 60;
m_TutorialState = TUTORIALSTATE_CLEAR;
}
}
break;
case 2:
if (m_pClearMarker == NULL)
{
m_pClearMarker = CModel::Create();
m_pClearMarker->SetModel(CLEAR_MODEL_NAME);
m_pClearMarker->SetPos(D3DXVECTOR3(-30.0f, 0.5f, -40.0f));
}
if (fcol <= fDiameter)
{
if (m_Move_State == CLEARSTATE_NONE && m_Move_State != CLEARSTATE_TRUE)
{
pSound->PlaySound(CSound::SOUND_LABEL_SUCCESS);
m_Move_State = CLEARSTATE_TRUE;
}
}
if (m_Move_State == CLEARSTATE_TRUE)
{
if (m_TutorialState == TUTORIALSTATE_NORMAL && m_TutorialState != TUTORIALSTATE_CLEAR)
{
pSound->PlaySound(CSound::SOUND_LABEL_STEPCLEAR);
m_Succes = CUI_TEXTURE::Create(D3DXVECTOR3(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, 0.0f), TUTORIAL_SUCCESS_WIDTH, TUTORIAL_SUCCESS_HEIGHT, CUI_TEXTURE::UIFLAME_TUTORIAL_SUCCESS); // チュートリアルの達成
m_nDisp = 60;
m_TutorialState = TUTORIALSTATE_CLEAR;
}
}
break;
}
SetTexTutorial(m_nType, m_nSteps);
}
//=============================================================================
// 基本操作のテクスチャ座標ずらし
//=============================================================================
void CTutorial::SetTexTutorial(int nType, int nSteps)
{
switch (nSteps)
{
case 0:
m_apSteps[0]->SetColor(D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f));
m_apSteps[1]->SetColor(D3DXCOLOR(0.4f, 0.4f, 0.4f, 1.0f));
m_apSteps[2]->SetColor(D3DXCOLOR(0.4f, 0.4f, 0.4f, 1.0f));
m_pMission->SetTex(nSteps, 1, m_nStepsMax);
m_pInst->SetTex(0, 1, m_nInstMax);
break;
case 1:
m_apSteps[0]->SetColor(D3DXCOLOR(0.4f, 0.4f, 0.4f, 1.0f));
m_apSteps[1]->SetColor(D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f));
m_apSteps[2]->SetColor(D3DXCOLOR(0.4f, 0.4f, 0.4f, 1.0f));
m_pMission->SetTex(nSteps, 1, m_nStepsMax);
switch (nType)
{
case 0:
m_pInst->SetTex(0, 1, m_nInstMax);
break;
case 1:
m_pInst->SetTex(nSteps, 1, m_nInstMax);
break;
case 2:
m_pInst->SetTex(nSteps, 1, m_nInstMax);
break;
} break;
case 2:
m_apSteps[0]->SetColor(D3DXCOLOR(0.4f, 0.4f, 0.4f, 1.0f));
m_apSteps[1]->SetColor(D3DXCOLOR(0.4f, 0.4f, 0.4f, 1.0f));
m_apSteps[2]->SetColor(D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f));
m_pMission->SetTex(nSteps, 1, m_nStepsMax);
switch (nType)
{
case 0:
m_pInst->SetTex(1, 1, m_nInstMax);
break;
case 1:
m_pInst->SetTex(nSteps, 1, m_nInstMax);
break;
case 2:
m_pInst->SetTex(nSteps, 1, m_nInstMax);
break;
}
break;
}
}
//=============================================================================
// リスポーン位置の読み込み
//=============================================================================
void CTutorial::LoadRespawnPos(void)
{
FILE *pFile; //ファイルのポインタ
//ファイルの読み込み
pFile = fopen(TUTORIAL_INI, "r");
if (pFile == NULL)
{//ファイルが読み込めていない場合
return;
}
else if (pFile != NULL)
{//ファイルが読み込めた場合
char aStr[128] = "\0";
while (1)
{//ループ
fscanf(pFile, "%s", aStr);
if (strcmp(aStr, GAME_SCRIPT) == 0)
{//スクリプトの開始を示している場合
while (strcmp(aStr, GAME_END_SCRIPT) != 0)
{//スクリプトの終了を示すまでループ
fscanf(pFile, "%s", aStr);
if (strcmp(aStr, GAME_BLUE) == 0)
{//サーバーのIPアドレスを示している場合
while (strcmp(aStr, GAME_BLUE_END) != 0)
{
fscanf(pFile, "%s", aStr);
if (strcmp(aStr, GAME_SPAWN_A) == 0)
{
fscanf(pFile, " = %f %f %f", &m_aRespawnPos[0][0].x, &m_aRespawnPos[0][0].y, &m_aRespawnPos[0][0].z);
}
if (strcmp(aStr, GAME_SPAWN_B) == 0)
{
fscanf(pFile, " = %f %f %f", &m_aRespawnPos[0][1].x, &m_aRespawnPos[0][1].y, &m_aRespawnPos[0][1].z);
}
if (strcmp(aStr, GAME_SPAWN_C) == 0)
{
fscanf(pFile, " = %f %f %f", &m_aRespawnPos[0][2].x, &m_aRespawnPos[0][2].y, &m_aRespawnPos[0][2].z);
}
if (strcmp(aStr, GAME_SPAWN_D) == 0)
{
fscanf(pFile, " = %f %f %f", &m_aRespawnPos[0][3].x, &m_aRespawnPos[0][3].y, &m_aRespawnPos[0][3].z);
}
}
}
if (strcmp(aStr, GAME_RED) == 0)
{//サーバーのIPアドレスを示している場合
while (strcmp(aStr, GAME_RED_END) != 0)
{
fscanf(pFile, "%s", aStr);
if (strcmp(aStr, GAME_SPAWN_A) == 0)
{
fscanf(pFile, " = %f %f %f", &m_aRespawnPos[1][0].x, &m_aRespawnPos[1][0].y, &m_aRespawnPos[1][0].z);
}
if (strcmp(aStr, GAME_SPAWN_B) == 0)
{
fscanf(pFile, " = %f %f %f", &m_aRespawnPos[1][1].x, &m_aRespawnPos[1][1].y, &m_aRespawnPos[1][1].z);
}
if (strcmp(aStr, GAME_SPAWN_C) == 0)
{
fscanf(pFile, " = %f %f %f", &m_aRespawnPos[1][2].x, &m_aRespawnPos[1][2].y, &m_aRespawnPos[1][2].z);
}
if (strcmp(aStr, GAME_SPAWN_D) == 0)
{
fscanf(pFile, " = %f %f %f", &m_aRespawnPos[1][3].x, &m_aRespawnPos[1][3].y, &m_aRespawnPos[1][3].z);
}
}
}
}
break;
}
}
}
}
| [
"[email protected]"
] | |
0a73ef7030c7eba3e10775d8f57cbd0eb69a70fd | 40c63e5b02391ef15b651a46c4119a5f76090b2a | /completed/Book02/Scene.cpp | f51395569181a66ea5fc2267decd372de235950b | [
"CC0-1.0"
] | permissive | mslinklater/GamePhysicsWeekend | 48852d73b2ca1caaf41d002e4bb702a1eaedc8a0 | 9321befb1cf446884dd3dac3969e161a2d80385f | refs/heads/main | 2023-07-03T11:15:27.666780 | 2021-08-08T20:36:59 | 2021-08-08T20:36:59 | 383,081,745 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 22,654 | cpp | //
// Scene.cpp
//
#include "Scene.h"
#include "Physics/GJK.h"
#include "Physics/Contact.h"
#include "Physics/Broadphase.h"
#include "Physics/Intersections.h"
/*
========================================================================================================
Scene
========================================================================================================
*/
/*
====================================================
Scene::~Scene
====================================================
*/
Scene::~Scene() {
for ( int i = 0; i < m_bodies.size(); i++ ) {
delete m_bodies[ i ].m_shape;
}
m_bodies.clear();
}
/*
====================================================
Scene::Reset
====================================================
*/
void Scene::Reset() {
for ( int i = 0; i < m_bodies.size(); i++ ) {
delete m_bodies[ i ].m_shape;
}
m_bodies.clear();
for ( int i = 0; i < m_constraints.size(); i++ ) {
delete m_constraints[ i ];
}
m_constraints.clear();
Initialize();
}
/*
====================================================
AddStandardSandBox
====================================================
*/
void AddStandardSandBox( std::vector< Body > & bodies ) {
Body body;
body.m_position = Vec3( 0, 0, 0 );
body.m_orientation = Quat( 0, 0, 0, 1 );
body.m_linearVelocity.Zero();
body.m_angularVelocity.Zero();
body.m_invMass = 0.0f;
body.m_elasticity = 0.5f;
body.m_friction = 0.5f;
body.m_shape = new ShapeBox( g_boxGround, sizeof( g_boxGround ) / sizeof( Vec3 ) );
bodies.push_back( body );
body.m_position = Vec3( 50, 0, 0 );
body.m_orientation = Quat( 0, 0, 0, 1 );
body.m_linearVelocity.Zero();
body.m_angularVelocity.Zero();
body.m_invMass = 0.0f;
body.m_elasticity = 0.5f;
body.m_friction = 0.0f;
body.m_shape = new ShapeBox( g_boxWall0, sizeof( g_boxWall0 ) / sizeof( Vec3 ) );
bodies.push_back( body );
body.m_position = Vec3(-50, 0, 0 );
body.m_orientation = Quat( 0, 0, 0, 1 );
body.m_linearVelocity.Zero();
body.m_angularVelocity.Zero();
body.m_invMass = 0.0f;
body.m_elasticity = 0.5f;
body.m_friction = 0.0f;
body.m_shape = new ShapeBox( g_boxWall0, sizeof( g_boxWall0 ) / sizeof( Vec3 ) );
bodies.push_back( body );
body.m_position = Vec3( 0, 25, 0 );
body.m_orientation = Quat( 0, 0, 0, 1 );
body.m_linearVelocity.Zero();
body.m_angularVelocity.Zero();
body.m_invMass = 0.0f;
body.m_elasticity = 0.5f;
body.m_friction = 0.0f;
body.m_shape = new ShapeBox( g_boxWall1, sizeof( g_boxWall1 ) / sizeof( Vec3 ) );
bodies.push_back( body );
body.m_position = Vec3( 0,-25, 0 );
body.m_orientation = Quat( 0, 0, 0, 1 );
body.m_linearVelocity.Zero();
body.m_angularVelocity.Zero();
body.m_invMass = 0.0f;
body.m_elasticity = 0.5f;
body.m_friction = 0.0f;
body.m_shape = new ShapeBox( g_boxWall1, sizeof( g_boxWall1 ) / sizeof( Vec3 ) );
bodies.push_back( body );
}
/*
====================================================
Scene::Initialize
====================================================
*/
void Scene::Initialize() {
const float pi = acosf( -1.0f );
Body body;
//
// Build a ragdoll
//
{
Vec3 offset = Vec3( -5, 0, 0 );
// head
body.m_position = Vec3( 0, 0, 5.5f ) + offset;
body.m_orientation = Quat( 0, 0, 0, 1 );
body.m_shape = new ShapeBox( g_boxSmall, sizeof( g_boxSmall ) / sizeof( Vec3 ) );
body.m_invMass = 2.0f;
body.m_elasticity = 1.0f;
body.m_friction = 1.0f;
m_bodies.push_back( body );
// torso
body.m_position = Vec3( 0, 0, 4 ) + offset;
body.m_orientation = Quat( 0, 0, 0, 1 );
body.m_shape = new ShapeBox( g_boxBody, sizeof( g_boxBody ) / sizeof( Vec3 ) );
body.m_invMass = 0.5f;
body.m_elasticity = 1.0f;
body.m_friction = 1.0f;
m_bodies.push_back( body );
// left arm
body.m_position = Vec3( 0.0f, 2.0f, 4.75f ) + offset;
body.m_orientation = Quat( Vec3( 0, 0, 1 ), -3.1415f / 2.0f );
body.m_shape = new ShapeBox( g_boxLimb, sizeof( g_boxLimb ) / sizeof( Vec3 ) );
body.m_invMass = 1.0f;
body.m_elasticity = 1.0f;
body.m_friction = 1.0f;
m_bodies.push_back( body );
// right arm
body.m_position = Vec3( 0.0f, -2.0f, 4.75f ) + offset;
body.m_orientation = Quat( Vec3( 0, 0, 1 ), 3.1415f / 2.0f );
body.m_shape = new ShapeBox( g_boxLimb, sizeof( g_boxLimb ) / sizeof( Vec3 ) );
body.m_invMass = 1.0f;
body.m_elasticity = 1.0f;
body.m_friction = 1.0f;
m_bodies.push_back( body );
// left leg
body.m_position = Vec3( 0.0f, 1.0f, 2.5f ) + offset;
body.m_orientation = Quat( Vec3( 0, 1, 0 ), 3.1415f / 2.0f );
body.m_shape = new ShapeBox( g_boxLimb, sizeof( g_boxLimb ) / sizeof( Vec3 ) );
body.m_invMass = 1.0f;
body.m_elasticity = 1.0f;
body.m_friction = 1.0f;
m_bodies.push_back( body );
// right leg
body.m_position = Vec3( 0.0f, -1.0f, 2.5f ) + offset;
body.m_orientation = Quat( Vec3( 0, 1, 0 ), 3.1415f / 2.0f );
body.m_shape = new ShapeBox( g_boxLimb, sizeof( g_boxLimb ) / sizeof( Vec3 ) );
body.m_invMass = 1.0f;
body.m_elasticity = 1.0f;
body.m_friction = 1.0f;
m_bodies.push_back( body );
const int idxHead = 0;
const int idxTorso = 1;
const int idxArmLeft = 2;
const int idxArmRight = 3;
const int idxLegLeft = 4;
const int idxLegRight = 5;
// Neck
{
ConstraintHingeQuatLimited * joint = new ConstraintHingeQuatLimited();
joint->m_bodyA = &m_bodies[ idxHead ];
joint->m_bodyB = &m_bodies[ idxTorso ];
const Vec3 jointWorldSpaceAnchor = joint->m_bodyA->m_position + Vec3( 0, 0, -0.5f );
joint->m_anchorA = joint->m_bodyA->WorldSpaceToBodySpace( jointWorldSpaceAnchor );
joint->m_anchorB = joint->m_bodyB->WorldSpaceToBodySpace( jointWorldSpaceAnchor );
joint->m_axisA = joint->m_bodyA->m_orientation.Inverse().RotatePoint( Vec3( 0, 1, 0 ) );
// Set the initial relative orientation
joint->m_q0 = joint->m_bodyA->m_orientation.Inverse() * joint->m_bodyB->m_orientation;
m_constraints.push_back( joint );
}
// Shoulder Left
{
ConstraintConstantVelocityLimited * joint = new ConstraintConstantVelocityLimited();
joint->m_bodyB = &m_bodies[ idxArmLeft ];
joint->m_bodyA = &m_bodies[ idxTorso ];
const Vec3 jointWorldSpaceAnchor = joint->m_bodyB->m_position + Vec3( 0, -1.0f, 0.0f );
joint->m_anchorA = joint->m_bodyA->WorldSpaceToBodySpace( jointWorldSpaceAnchor );
joint->m_anchorB = joint->m_bodyB->WorldSpaceToBodySpace( jointWorldSpaceAnchor );
joint->m_axisA = joint->m_bodyA->m_orientation.Inverse().RotatePoint( Vec3( 0, 1, 0 ) );
// Set the initial relative orientation
joint->m_q0 = joint->m_bodyA->m_orientation.Inverse() * joint->m_bodyB->m_orientation;
m_constraints.push_back( joint );
}
// Shoulder Right
{
ConstraintConstantVelocityLimited * joint = new ConstraintConstantVelocityLimited();
joint->m_bodyB = &m_bodies[ idxArmRight ];
joint->m_bodyA = &m_bodies[ idxTorso ];
const Vec3 jointWorldSpaceAnchor = joint->m_bodyB->m_position + Vec3( 0, 1.0f, 0.0f );
joint->m_anchorA = joint->m_bodyA->WorldSpaceToBodySpace( jointWorldSpaceAnchor );
joint->m_anchorB = joint->m_bodyB->WorldSpaceToBodySpace( jointWorldSpaceAnchor );
joint->m_axisA = joint->m_bodyA->m_orientation.Inverse().RotatePoint( Vec3( 0, -1, 0 ) );
// Set the initial relative orientation
joint->m_q0 = joint->m_bodyA->m_orientation.Inverse() * joint->m_bodyB->m_orientation;
m_constraints.push_back( joint );
}
// Hip Left
{
ConstraintHingeQuatLimited * joint = new ConstraintHingeQuatLimited();
joint->m_bodyB = &m_bodies[ idxLegLeft ];
joint->m_bodyA = &m_bodies[ idxTorso ];
const Vec3 jointWorldSpaceAnchor = joint->m_bodyB->m_position + Vec3( 0, 0, 0.5f );
joint->m_anchorA = joint->m_bodyA->WorldSpaceToBodySpace( jointWorldSpaceAnchor );
joint->m_anchorB = joint->m_bodyB->WorldSpaceToBodySpace( jointWorldSpaceAnchor );
joint->m_axisA = joint->m_bodyA->m_orientation.Inverse().RotatePoint( Vec3( 0, 1, 0 ) );
// Set the initial relative orientation
joint->m_q0 = joint->m_bodyA->m_orientation.Inverse() * joint->m_bodyB->m_orientation;
m_constraints.push_back( joint );
}
// Hip Right
{
ConstraintHingeQuatLimited * joint = new ConstraintHingeQuatLimited();
joint->m_bodyB = &m_bodies[ idxLegRight ];
joint->m_bodyA = &m_bodies[ idxTorso ];
const Vec3 jointWorldSpaceAnchor = joint->m_bodyB->m_position + Vec3( 0, 0, 0.5f );
joint->m_anchorA = joint->m_bodyA->WorldSpaceToBodySpace( jointWorldSpaceAnchor );
joint->m_anchorB = joint->m_bodyB->WorldSpaceToBodySpace( jointWorldSpaceAnchor );
joint->m_axisA = joint->m_bodyA->m_orientation.Inverse().RotatePoint( Vec3( 0, 1, 0 ) );
// Set the initial relative orientation
joint->m_q0 = joint->m_bodyA->m_orientation.Inverse() * joint->m_bodyB->m_orientation;
m_constraints.push_back( joint );
}
}
//
// Build a chain for funsies
//
const int numJoints = 5;
for ( int i = 0; i < numJoints; i++ ) {
if ( i == 0 ) {
body.m_position = Vec3( 0.0f, 5.0f, (float)numJoints + 3.0f );
body.m_orientation = Quat( 0, 0, 0, 1 );
body.m_shape = new ShapeBox( g_boxSmall, sizeof( g_boxSmall ) / sizeof( Vec3 ) );
body.m_invMass = 0.0f;
body.m_elasticity = 1.0f;
m_bodies.push_back( body );
} else {
body.m_invMass = 1.0f;
}
body.m_linearVelocity = Vec3( 0, 0, 0 );
Body * bodyA = &m_bodies[ m_bodies.size() - 1 ];
const Vec3 jointWorldSpaceAnchor = bodyA->m_position;
const Vec3 jointWorldSpaceAxis = Vec3( 0, 0, 1 ).Normalize();
Mat3 jointWorldSpaceMatrix;
jointWorldSpaceMatrix.rows[ 0 ] = jointWorldSpaceAxis;
jointWorldSpaceMatrix.rows[ 0 ].GetOrtho( jointWorldSpaceMatrix.rows[ 1 ], jointWorldSpaceMatrix.rows[ 2 ] );
jointWorldSpaceMatrix.rows[ 2 ] = jointWorldSpaceAxis;
jointWorldSpaceMatrix.rows[ 2 ].GetOrtho( jointWorldSpaceMatrix.rows[ 0 ], jointWorldSpaceMatrix.rows[ 1 ] );
Vec3 jointWorldSpaceAxisLimited = Vec3( 0, 1, -1 );
jointWorldSpaceAxisLimited.Normalize();
ConstraintDistance * joint = new ConstraintDistance();
const float pi = acosf( -1.0f );
joint->m_bodyA = &m_bodies[ m_bodies.size() - 1 ];
joint->m_anchorA = joint->m_bodyA->WorldSpaceToBodySpace( jointWorldSpaceAnchor );
joint->m_axisA = joint->m_bodyA->m_orientation.Inverse().RotatePoint( jointWorldSpaceAxis );
body.m_position = joint->m_bodyA->m_position - jointWorldSpaceAxis * 1.0f;
body.m_position = joint->m_bodyA->m_position + Vec3( 1, 0, 0 );
body.m_orientation = Quat( 0, 0, 0, 1 );
body.m_shape = new ShapeBox( g_boxSmall, sizeof( g_boxSmall ) / sizeof( Vec3 ) );
body.m_invMass = 1.0f;
body.m_elasticity = 1.0f;
m_bodies.push_back( body );
joint->m_bodyB = &m_bodies[ m_bodies.size() - 1 ];
joint->m_anchorB = joint->m_bodyB->WorldSpaceToBodySpace( jointWorldSpaceAnchor );
joint->m_axisB = joint->m_bodyB->m_orientation.Inverse().RotatePoint( jointWorldSpaceAxis );
m_constraints.push_back( joint );
}
//
// Stack of Boxes
//
const int stackHeight = 5;
for ( int x = 0; x < 1; x++ ) {
for ( int y = 0; y < 1; y++ ) {
for ( int z = 0; z < stackHeight; z++ ) {
float offset = ( ( z & 1 ) == 0 ) ? 0.0f : 0.15f;
float xx = (float)x + offset;
float yy = (float)y + offset;
float delta = 0.04f;
float scaleHeight = 2.0f + delta;
float deltaHeight = 1.0f + delta;
body.m_position = Vec3( (float)xx * scaleHeight, (float)yy * scaleHeight, deltaHeight + (float)z * scaleHeight );
body.m_orientation = Quat( 0, 0, 0, 1 );
body.m_shape = new ShapeBox( g_boxUnit, sizeof( g_boxUnit ) / sizeof( Vec3 ) );
body.m_invMass = 1.0f;
body.m_elasticity = 0.5f;
body.m_friction = 0.5f;
m_bodies.push_back( body );
}
}
}
//
// Sphere and Convex Hull
//
body.m_position = Vec3( -10.0f, 0.0f, 5.0f );
body.m_linearVelocity = Vec3( 0.0f, 0.0f, 0.0f );
body.m_orientation = Quat( 0, 0, 0, 1 );
body.m_shape = new ShapeSphere( 1.0f );
body.m_invMass = 1.0f;
body.m_elasticity = 0.9f;
body.m_friction = 0.5f;
m_bodies.push_back( body );
body.m_position = Vec3( -10.0f, 0.0f, 10.0f );
body.m_linearVelocity = Vec3( 0.0f, 0.0f, 0.0f );
body.m_orientation = Quat( 0, 0, 0, 1 );
body.m_shape = new ShapeConvex( g_diamond, sizeof( g_diamond ) / sizeof( Vec3 ) );
body.m_invMass = 1.0f;
body.m_elasticity = 1.0f;
body.m_friction = 0.5f;
m_bodies.push_back( body );
//
// Motor
//
Vec3 motorPos = Vec3( 5, 0, 2 );
Vec3 motorAxis = Vec3( 0, 0, 1 ).Normalize();
Quat motorOrient = Quat( 1, 0, 0, 0 );
body.m_position = motorPos;
body.m_linearVelocity = Vec3( 0.0f, 0.0f, 0.0f );
body.m_orientation = Quat( 0, 0, 0, 1 );
body.m_shape = new ShapeBox( g_boxSmall, sizeof( g_boxSmall ) / sizeof( Vec3 ) );
body.m_invMass = 0.0f;
body.m_elasticity = 0.9f;
body.m_friction = 0.5f;
m_bodies.push_back( body );
body.m_position = motorPos - motorAxis;
body.m_linearVelocity = Vec3( 0.0f, 0.0f, 0.0f );
body.m_orientation = motorOrient;
body.m_shape = new ShapeBox( g_boxBeam, sizeof( g_boxBeam ) / sizeof( Vec3 ) );
body.m_invMass = 0.01f;
body.m_elasticity = 1.0f;
body.m_friction = 0.5f;
m_bodies.push_back( body );
{
ConstraintMotor * joint = new ConstraintMotor();
joint->m_bodyA = &m_bodies[ m_bodies.size() - 2 ];
joint->m_bodyB = &m_bodies[ m_bodies.size() - 1 ];
const Vec3 jointWorldSpaceAnchor = joint->m_bodyA->m_position;
joint->m_anchorA = joint->m_bodyA->WorldSpaceToBodySpace( jointWorldSpaceAnchor );
joint->m_anchorB = joint->m_bodyB->WorldSpaceToBodySpace( jointWorldSpaceAnchor );
joint->m_motorSpeed = 2.0f;
joint->m_motorAxis = joint->m_bodyA->m_orientation.Inverse().RotatePoint( motorAxis );
// Set the initial relative orientation (in bodyA's space)
joint->m_q0 = joint->m_bodyA->m_orientation.Inverse() * joint->m_bodyB->m_orientation;
m_constraints.push_back( joint );
}
//
// Mover
//
body.m_position = Vec3( 10, 0, 5 );
body.m_linearVelocity = Vec3( 0, 0, 0 );
body.m_orientation = Quat( 0, 0, 0, 1 );
body.m_shape = new ShapeBox( g_boxPlatform, sizeof( g_boxPlatform ) / sizeof( Vec3 ) );
body.m_invMass = 0.0f;
body.m_elasticity = 0.1f;
body.m_friction = 0.9f;
m_bodies.push_back( body );
{
ConstraintMoverSimple * mover = new ConstraintMoverSimple();
mover->m_bodyA = &m_bodies[ m_bodies.size() - 1 ];
m_constraints.push_back( mover );
}
body.m_position = Vec3( 10, 0, 6.3f );
body.m_linearVelocity = Vec3( 0, 0, 0 );
body.m_orientation = Quat( 0, 0, 0, 1 );
body.m_shape = new ShapeBox( g_boxUnit, sizeof( g_boxUnit ) / sizeof( Vec3 ) );
body.m_invMass = 1.0f;
body.m_elasticity = 0.1f;
body.m_friction = 0.9f;
m_bodies.push_back( body );
//
// Hinge Constraint
//
body.m_position = Vec3( -2, -5, 6 );
body.m_linearVelocity = Vec3( 0.0f, 0.0f, 0.0f );
body.m_orientation = Quat( 0, 0, 0, 1 );
body.m_orientation = Quat( Vec3( 1, 1, 1 ), pi * 0.25f );
body.m_shape = new ShapeBox( g_boxSmall, sizeof( g_boxSmall ) / sizeof( Vec3 ) );
body.m_invMass = 0.0f;
body.m_elasticity = 0.9f;
body.m_friction = 0.5f;
m_bodies.push_back( body );
body.m_position = Vec3( -2, -5, 5 );
body.m_linearVelocity = Vec3( 0.0f, 0.0f, 0.0f );
body.m_orientation = Quat( Vec3( 0, 1, 1 ), pi * 0.5f );
body.m_shape = new ShapeBox( g_boxSmall, sizeof( g_boxSmall ) / sizeof( Vec3 ) );
body.m_invMass = 1.0f;
body.m_elasticity = 1.0f;
body.m_friction = 0.5f;
m_bodies.push_back( body );
{
ConstraintHingeQuatLimited * joint = new ConstraintHingeQuatLimited();
joint->m_bodyA = &m_bodies[ m_bodies.size() - 2 ];
joint->m_bodyB = &m_bodies[ m_bodies.size() - 1 ];
const Vec3 jointWorldSpaceAnchor = joint->m_bodyA->m_position;
joint->m_anchorA = joint->m_bodyA->WorldSpaceToBodySpace( jointWorldSpaceAnchor );
joint->m_anchorB = joint->m_bodyB->WorldSpaceToBodySpace( jointWorldSpaceAnchor );
joint->m_axisA = joint->m_bodyA->m_orientation.Inverse().RotatePoint( Vec3( 1, 0, 0 ) );
// Set the initial relative orientation
joint->m_q0 = joint->m_bodyA->m_orientation.Inverse() * joint->m_bodyB->m_orientation;
m_constraints.push_back( joint );
}
//
// Constant Velocity Constraint
//
body.m_position = Vec3( 2, -5, 6 );
body.m_linearVelocity = Vec3( 0.0f, 0.0f, 0.0f );
body.m_orientation = Quat( 0, 0, 0, 1 );
body.m_orientation = Quat( Vec3( 1, 1, 1 ), pi * 0.5f );
body.m_shape = new ShapeBox( g_boxSmall, sizeof( g_boxSmall ) / sizeof( Vec3 ) );
body.m_invMass = 0.0f;
body.m_elasticity = 0.9f;
body.m_friction = 0.5f;
m_bodies.push_back( body );
body.m_position = Vec3( 2, -5, 5 );
body.m_linearVelocity = Vec3( 0.0f, 0.0f, 0.0f );
body.m_orientation = Quat( Vec3( 0, 1, 1 ), pi * 0.5f );
body.m_shape = new ShapeBox( g_boxSmall, sizeof( g_boxSmall ) / sizeof( Vec3 ) );
body.m_invMass = 1.0f;
body.m_elasticity = 1.0f;
body.m_friction = 0.5f;
m_bodies.push_back( body );
{
ConstraintConstantVelocityLimited * joint = new ConstraintConstantVelocityLimited();
joint->m_bodyA = &m_bodies[ m_bodies.size() - 2 ];
joint->m_bodyB = &m_bodies[ m_bodies.size() - 1 ];
const Vec3 jointWorldSpaceAnchor = joint->m_bodyA->m_position;
joint->m_anchorA = joint->m_bodyA->WorldSpaceToBodySpace( jointWorldSpaceAnchor );
joint->m_anchorB = joint->m_bodyB->WorldSpaceToBodySpace( jointWorldSpaceAnchor );
joint->m_axisA = joint->m_bodyA->m_orientation.Inverse().RotatePoint( Vec3( 0, 0, 1 ) );
// Set the initial relative orientation
joint->m_q0 = joint->m_bodyA->m_orientation.Inverse() * joint->m_bodyB->m_orientation;
m_constraints.push_back( joint );
}
//
// Teleportation Bug Fix
//
body.m_position = Vec3( 10, -10, 3 );
body.m_orientation = Quat( 0, 0, 0, 1 );
body.m_linearVelocity = Vec3( -100, 0, 0 );
body.m_angularVelocity = Vec3( 0.0f, 0.0f, 0.0f );
body.m_invMass = 1.0f;
body.m_elasticity = 0.5f;
body.m_friction = 0.5f;
body.m_shape = new ShapeSphere( 0.5f );
m_bodies.push_back( body );
body.m_position = Vec3( -10, -10, 3 );
body.m_orientation = Quat( 0, 0, 0, 1 );
body.m_linearVelocity = Vec3( 100, 0, 0 );
body.m_angularVelocity = Vec3( 0, 10, 0 );
body.m_invMass = 1.0f;
body.m_elasticity = 0.5f;
body.m_friction = 0.5f;
body.m_shape = new ShapeConvex( g_diamond, sizeof( g_diamond ) / sizeof( Vec3 ) );
m_bodies.push_back( body );
//
// Orientation Constraint
//
body.m_position = Vec3( 5, 0, 5 );
body.m_linearVelocity = Vec3( 0.0f, 0.0f, 0.0f );
body.m_angularVelocity = Vec3( 0.0f, 0.0f, 0.0f );
body.m_orientation = Quat( 0, 0, 0, 1 );
body.m_shape = new ShapeBox( g_boxSmall, sizeof( g_boxSmall ) / sizeof( Vec3 ) );
body.m_invMass = 0.0f;
body.m_elasticity = 0.9f;
body.m_friction = 0.5f;
m_bodies.push_back( body );
body.m_position = Vec3( 6, 0, 5 );
body.m_linearVelocity = Vec3( 0.0f, 0.0f, 0.0f );
body.m_angularVelocity = Vec3( 0.0f, 0.0f, 0.0f );
body.m_orientation = Quat( 0, 0, 0, 1 );
body.m_shape = new ShapeBox( g_boxSmall, sizeof( g_boxSmall ) / sizeof( Vec3 ) );
body.m_invMass = 0.001f;
body.m_elasticity = 1.0f;
body.m_friction = 0.5f;
m_bodies.push_back( body );
{
ConstraintOrientation * joint = new ConstraintOrientation();
joint->m_bodyA = &m_bodies[ m_bodies.size() - 2 ];
joint->m_bodyB = &m_bodies[ m_bodies.size() - 1 ];
const Vec3 jointWorldSpaceAnchor = joint->m_bodyA->m_position;
joint->m_anchorA = joint->m_bodyA->WorldSpaceToBodySpace( jointWorldSpaceAnchor );
joint->m_anchorB = joint->m_bodyB->WorldSpaceToBodySpace( jointWorldSpaceAnchor );
// Set the initial relative orientation
joint->m_q0 = joint->m_bodyA->m_orientation.Inverse() * joint->m_bodyB->m_orientation;
m_constraints.push_back( joint );
}
//
// Standard floor and walls
//
AddStandardSandBox( m_bodies );
}
/*
====================================================
CompareContacts
====================================================
*/
int CompareContacts( const void * p1, const void * p2 ) {
contact_t a = *(contact_t*)p1;
contact_t b = *(contact_t*)p2;
if ( a.timeOfImpact < b.timeOfImpact ) {
return -1;
}
if ( a.timeOfImpact == b.timeOfImpact ) {
return 0;
}
return 1;
}
/*
====================================================
Scene::Update
====================================================
*/
void Scene::Update( const float dt_sec ) {
m_manifolds.RemoveExpired();
// Gravity impulse
for ( int i = 0; i < m_bodies.size(); i++ ) {
Body * body = &m_bodies[ i ];
float mass = 1.0f / body->m_invMass;
Vec3 impulseGravity = Vec3( 0, 0, -10 ) * mass * dt_sec;
body->ApplyImpulseLinear( impulseGravity );
}
//
// Broadphase (build potential collision pairs)
//
std::vector< collisionPair_t > collisionPairs;
BroadPhase( m_bodies.data(), (int)m_bodies.size(), collisionPairs, dt_sec );
//
// NarrowPhase (perform actual collision detection)
//
int numContacts = 0;
contact_t * contacts = (contact_t *)alloca( sizeof( contact_t ) * collisionPairs.size() );
for ( int i = 0; i < collisionPairs.size(); i++ ) {
const collisionPair_t & pair = collisionPairs[ i ];
Body * bodyA = &m_bodies[ pair.a ];
Body * bodyB = &m_bodies[ pair.b ];
// Skip body pairs with infinite mass
if ( 0.0f == bodyA->m_invMass && 0.0f == bodyB->m_invMass ) {
continue;
}
// Check for intersection
contact_t contact;
if ( Intersect( bodyA, bodyB, dt_sec, contact ) ) {
if ( 0.0f == contact.timeOfImpact ) {
// Static contact
m_manifolds.AddContact( contact );
} else {
// Ballistic contact
contacts[ numContacts ] = contact;
numContacts++;
}
}
}
// Sort the times of impact from first to last
if ( numContacts > 1 ) {
qsort( contacts, numContacts, sizeof( contact_t ), CompareContacts );
}
//
// Solve Constraints
//
for ( int i = 0; i < m_constraints.size(); i++ ) {
m_constraints[ i ]->PreSolve( dt_sec );
}
m_manifolds.PreSolve( dt_sec );
const int maxIters = 5;
for ( int iters = 0; iters < maxIters; iters++ ) {
for ( int i = 0; i < m_constraints.size(); i++ ) {
m_constraints[ i ]->Solve();
}
m_manifolds.Solve();
}
for ( int i = 0; i < m_constraints.size(); i++ ) {
m_constraints[ i ]->PostSolve();
}
m_manifolds.PostSolve();
//
// Apply ballistic impulses
//
float accumulatedTime = 0.0f;
for ( int i = 0; i < numContacts; i++ ) {
contact_t & contact = contacts[ i ];
const float dt = contact.timeOfImpact - accumulatedTime;
// Position update
for ( int j = 0; j < m_bodies.size(); j++ ) {
m_bodies[ j ].Update( dt );
}
ResolveContact( contact );
accumulatedTime += dt;
}
// Update the positions for the rest of this frame's time
const float timeRemaining = dt_sec - accumulatedTime;
if ( timeRemaining > 0.0f ) {
for ( int i = 0; i < m_bodies.size(); i++ ) {
m_bodies[ i ].Update( timeRemaining );
}
}
} | [
"[email protected]"
] | |
55cf134dacde92fecb32c10f64aed9eb64771c0b | 6a185b29cadec3dd0d41223183de656bee2a9c66 | /VoltmeterArduino/VoltmeterArduino.ino | 595d9a9f103c49ea57f21a93cc7ce3259ef217ba | [
"MIT"
] | permissive | 16paulob/VoltmeterArduino | 736c412df1c2532339c59285743e451497ae061f | 8dc326e2b6d7d0c490080cd76f128d9174f5c57c | refs/heads/master | 2020-03-27T23:58:17.936864 | 2018-09-04T15:05:25 | 2018-09-04T15:05:25 | 147,093,348 | 0 | 0 | MIT | 2018-09-04T14:54:19 | 2018-09-02T14:39:24 | C++ | UTF-8 | C++ | false | false | 3,751 | ino | /* Autor: Paulo Borges
* Data: 02 setembro de 2018
* E-mail: [email protected]
*/
// Rótulo das entradas/saídas físicas
#define VERDE 2
#define BOBINA 3
#define VERMELHO 4
#define ANALOGPILA 0
#define MONITORIA true
// Delay(milisegundos) para o julgamento de chaveamento.
#define TEMPO_ADICIONAL 1000
// Variáveis
unsigned long TEMPO_MARCADO = 0;
int entradaAnalogica;
float tensaoEntradaArduino = 0;
float tensaoSaidaBateria;
float tensaoValorAproximado;
const float tensaoAlimentacao = 4.6; /* Típica tensão de alimentação, sujeita a mudança dependente
do nível utilizado na shield. */
const float R1 = 7.5;
const float R2 = 30.0;
int aceito = 0, negado = 0;
bool resultado;
// Para definição dos limites, edite aqui c/ apenas uma casa decimal após a vírgula.
float limiteAlto = 14.0;
float limiteBaixo = 12.7;
float limiteMuitoBaixo = 1.0;
void setup() {
// Iniciamos 0 monitor serie
#if MONITORIA
Serial.begin(9600);
#endif
// Los pinos de LED en modo salida
pinMode(VERDE, OUTPUT);
pinMode(BOBINA, OUTPUT);
pinMode(VERMELHO, OUTPUT);
}
void loop() {
// Leitura do valor de entrada analógica
entradaAnalogica = analogRead(ANALOGPILA);
/*Cálculo para a obtensão de valor que provêm do divesor de tensão(0~4,71Volts).
Resultado com 2 casa decimais */
tensaoEntradaArduino = ((entradaAnalogica * tensaoAlimentacao) / 1024);
/*Cálculo matemático envolvendo o valor do divisor de tensão p/ encontrar o valor da bateria.
Resultado com 2 casa decimais */
tensaoSaidaBateria = tensaoEntradaArduino * ((R1 + R2) / R1);
/*Cálculo matemático p/ equivalência do valor medido no arduino com valor registrado no display.
Resultado com 1 casa decimal */
tensaoValorAproximado = tensaoSaidaBateria * 10;
tensaoValorAproximado = round(tensaoValorAproximado);
tensaoValorAproximado /= 10;
/*Mostrando o resultado na saída serial p/ acompanhamento em tempo real.*/
#if false
Serial.print("VOLT: ");
Serial.println(tensaoValorAproximado);
#endif
if ((millis() > (TEMPO_MARCADO + TEMPO_ADICIONAL)) || (millis() < TEMPO_MARCADO)) {
/* Julgando a condição de medição por relação de medidas acima ou abaixo do limite analógico estabelecido.*/
if (aceito > negado)
resultado = true;
else
resultado = false;
/*Mostrando na porta serial o resultado p/ acompanhamento em tempo real, sob as seguintes condições:
Positivo - Quer dizer que a leitura analógica esteve em niveis "aceitáveis" por mais tempo;
Negativo - Quer dizer que a leitura analógica esteve em niveis "inaceitáveis" por mais tempo.
*/
#if MONITORIA
Serial.print("Resultado: ");
Serial.print(((resultado == true) ? "Positivo " : "Negativo "));
Serial.print(aceito);
Serial.print("/");
Serial.print(negado);
Serial.print("\t");
Serial.print(tensaoSaidaBateria);
Serial.print("/");
Serial.print(tensaoValorAproximado);
Serial.println("Volt(s)");
#endif
/*Limpeza dos marcadores e contadores p/ uma nova leitura durante o tempo determinado.*/
TEMPO_MARCADO = millis();
aceito = 0 ; negado = 0;
}
else {
if (tensaoValorAproximado >= limiteBaixo && tensaoValorAproximado < limiteAlto) {
aceito++;
}
else {
negado++;
}
}
/*Chaveamento das saídas físicas de acordo com o valor booleano presente na variável "resultado".*/
if (resultado) {
digitalWrite(VERDE, HIGH);
digitalWrite(BOBINA, LOW);
digitalWrite(VERMELHO, LOW);
}
else {
digitalWrite(VERDE, LOW);
digitalWrite(BOBINA, HIGH);
digitalWrite(VERMELHO, HIGH);
}
}
| [
"[email protected]"
] | |
e6fbc6d27f4b1362b2ff5fa5cc673e85d6834c94 | 2f329704f0b497c5751194697a9833011ea023ff | /hostcardemulation/src/BerTLV.h | 119725414acdd3281d3bfef7d99577e58e49d868 | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | permissive | jcmurray/Cascades-Community-Samples | 7f5f9f04d46a5a94932947d507d93dc2273584af | 4749d8105d1136b960784ae451cd78fca5377b4a | refs/heads/master | 2020-04-03T16:46:29.260600 | 2016-01-25T20:03:01 | 2016-01-25T20:03:01 | 4,585,897 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,153 | h | /*
* Copyright (c) 2011-2014 BlackBerry Limited.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef BERTLV_H_
#define BERTLV_H_
#include <QObject>
#include <stdint.h>
/*
* Abstract base class
*
* References:
* https://en.wikipedia.org/wiki/Basic_Encoding_Rules#BER_encoding
*/
class BerTLV {
public:
BerTLV(const QString& tag, const QString& name);
virtual ~BerTLV() {};
virtual void appendBytes(QByteArray& buffer) = 0;
virtual void trace(uint32_t indent = 0) = 0;
protected:
void appendTag(QByteArray& buffer);
void appendLength(QByteArray& buffer, uint32_t _length, uint32_t _lengthSize);
bool lengthFitsInSimpleForm(uint32_t length);
void traceLine(uint32_t indent, const QString& line) const;
const QString _tag;
const QString _name;
};
/*
* Simple node containing values, but no sub-nodes
*/
class BerSimpleTLV : public BerTLV {
public:
BerSimpleTLV(const QString& tag, const QString& name, uint32_t lengthSize, const QByteArray& value);
virtual void appendBytes(QByteArray& buffer);
virtual void trace(uint32_t indent = 0);
private:
uint32_t _lengthSize;
QByteArray _value;
};
/*
* Node consisting of sub-nodes
*/
class BerCompositeTLV : public BerTLV {
public:
BerCompositeTLV(const QString& tag, const QString& name, uint32_t lengthSize = 0);
virtual ~BerCompositeTLV();
virtual void appendBytes(QByteArray& buffer);
virtual void trace(uint32_t indent = 0);
void addChild(BerTLV* child);
private:
void appendChilds(QByteArray& serializedChilds);
uint32_t _lengthSize;
QList<BerTLV*> _childs;
};
#endif /* BERTLV_H_ */
| [
"[email protected]"
] | |
5bbaa65e90ca79d8fcd1d9084343f36cca50715e | 366d1b9a999aaa856a325ae80268af20b995babe | /src/shogun/optimization/SMIDASMinimizer.h | 3ebdaca049467bc638e3bc2d9783bc94326b8bba | [
"BSD-3-Clause",
"DOC",
"GPL-3.0-only"
] | permissive | karlnapf/shogun | bc3fcbeef377b8157bd8a9639211c2667b535846 | eebce07a4309bb7e1d3a4f0981efd49e687533b6 | refs/heads/develop | 2020-04-05T22:46:38.369312 | 2019-07-09T08:59:14 | 2019-07-09T08:59:14 | 4,420,161 | 1 | 1 | BSD-3-Clause | 2018-09-04T10:50:41 | 2012-05-23T13:12:40 | C++ | UTF-8 | C++ | false | false | 2,824 | h | /*
* Copyright (c) The Shogun Machine Learning Toolbox
* Written (w) 2015 Wu Lin
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*
* The views and conclusions contained in the software and documentation are those
* of the authors and should not be interpreted as representing official policies,
* either expressed or implied, of the Shogun Development Team.
*
*/
#ifndef SMIDASMINIMIZER_H
#define SMIDASMINIMIZER_H
#include <shogun/optimization/SMDMinimizer.h>
namespace shogun
{
/** @brief The class implements the Stochastic MIrror Descent mAde Sparse (SMIDAS) minimizer
*
* Reference:
* Shai Shalev-Shwartz and Ambuj Tewari,
* Stochastic methods for l1 regularized loss minimization.
* Proceedings of the 26th International Conference on Machine Learning,
* pages 929-936, 2009.
*/
class SMIDASMinimizer: public SMDMinimizer
{
public:
/** Default constructor */
SMIDASMinimizer();
/** Constructor
* @param fun stochastic cost function
*/
SMIDASMinimizer(FirstOrderStochasticCostFunction *fun);
/** Destructor */
virtual ~SMIDASMinimizer();
/** Do minimization and get the optimal value
*
* @return optimal value
*/
virtual float64_t minimize();
/** returns the name of the class
*
* @return name ConstLearningRate
*/
virtual const char* get_name() const { return "SMIDASMinimizer"; }
protected:
/** init minimization */
virtual void init_minimization();
/** dual variable */
SGVector<float64_t> m_dual_variable;
private:
/* Init */
void init();
};
}
#endif /* SMIDASMINIMIZER_H */
| [
"[email protected]"
] | |
2cddab3cddc3aee5443ad80e872849423b5c587a | 51d3832a54890bcec32cdc1b0b67c7146271ae9b | /Undergrad/Year 5/Semester 2/60-340 (C++)/Assignment 5/ostoic_BinaryTrees.cpp | cad078db57e803a3ae5d9c7e3aca4ea43fc720b4 | [
"MIT"
] | permissive | war-man/School | c645f586d91d03fa7e0727a37e6e19fc29c07311 | dd78cc926ef65e4b6e04b56e948a5c9f3e15624c | refs/heads/master | 2020-04-13T08:13:46.837023 | 2018-10-03T18:06:10 | 2018-10-03T18:06:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,370 | cpp | // ostoic_BinaryTrees.cpp : Defines the entry point for the console application.
#include "binary_tree.h"
#include "employee_info.h"
#include <string>
#include <cctype>
using command = void(*)(binary_tree<employee_info>&);
void reset_cin()
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::size_t>::max(), '\n');
}
void display_menu()
{
std::cout <<
"\n******** Binary Trees MENU ********\n\n"
"1. Insert one or more items\n"
"2. Delete one or more elements\n"
"3. Display the nodes of the tree\n"
"4. Get the number of nodes in the tree\n"
"5. Get the height of the tree\n"
"6. Get the width of the tree\n"
"7. Get the number of leaves of the tree\n"
"8. Find an employee in the employee tree\n"
"9. Exit\n\n";
}
int get_menu_choice(int min_choice, int max_choice)
{
int choice = 0;
const auto bad_input_for = [min_choice, max_choice](int& choice)
{
return (!(std::cin >> choice)) || (choice < min_choice || choice > max_choice);
};
std::cout << "Your choice, please (" << min_choice << " - " << max_choice << "): ";
while (bad_input_for(choice))
{
reset_cin();
std::cout << "Enter a number from " << min_choice << " through " << max_choice << " please: ";
}
return choice;
}
void display_submenu()
{
std::cout <<
"\n******* Binary Trees Display modes Sub MENU *******\n\n"
"1. Via inorder traversal\n"
"2. Via preorder traversal\n"
"3. Via postorder traversal\n"
"4. Exit\n\n";
}
bool is_number(const std::string& text)
{
return std::find_if(text.begin(), text.end(), [](char c)
{
return !std::isdigit(c);
}) == text.end();
}
void insert_items(binary_tree<employee_info>& tree)
{
std::string input = "";
do
{
std::cout << "Inserting any number or text to the tree or 00 to exit: \n";
std::cin >> input;
// If it's a number, insert it as a key
if (is_number(input))
tree.insert({static_cast<unsigned int>(std::stoi(input)), ""});
// Otherwise insert it as text.
else
tree.insert({0, input});
} while (input != "00");
}
// This is used in the binary_tree search function to find an employee record given a key
bool equals_key_employee(int key, const employee_info& info)
{
return key == info.id();
}
// This is used in the binary_tree search function to find an employee record given a key
bool less_than_key_employee(int key, const employee_info& info)
{
return key < info.id();
}
void delete_items(binary_tree<employee_info>& tree)
{
int choice;
while (true)
{
std::cout << "Enter an employee number to delete or 0 to exit: ";
std::cin >> choice;
if (std::cin.good())
{
if (choice == 0) break;
const auto* employee = tree.find(choice, equals_key_employee, less_than_key_employee);
if (employee)
{
tree.erase(*employee);
std::cout << "Deleted employee record\n";
}
else
std::cout << "Employee not found!\n";
}
else
reset_cin();
}
}
void display_nodes(binary_tree<employee_info>& tree)
{
command commands[3] = {
// Command 1
[](binary_tree<employee_info>& tree)
{ std::cout << "Now, here are the nodes via inorder traversal:\n"; tree.display_inorder(); },
// Command 2
[](binary_tree<employee_info>& tree)
{ std::cout << "Now, here are the nodes via preorder traversal:\n"; tree.display_preorder(); },
// Command 3
[](binary_tree<employee_info>& tree)
{ std::cout << "Now, here are the nodes via postorder traversal:\n"; tree.display_postorder(); },
};
while (true)
{
display_submenu();
int choice = get_menu_choice(1, 4);
if (choice == 4) break;
commands[choice - 1](tree);
}
}
void display_size(binary_tree<employee_info>& tree)
{
std::cout << "Number of nodes: " << tree.size() << "\n\n";
}
void display_height(binary_tree<employee_info>& tree)
{
std::cout << "Height: " << tree.height() << "\n\n";
}
void display_width(binary_tree<employee_info>& tree)
{
std::cout << "Width: " << tree.width() << "\n\n";
}
void display_leaf_count(binary_tree<employee_info>& tree)
{
std::cout << "Number of leaf nodes: " << tree.leaf_count() << "\n\n";
}
void find_employee(binary_tree<employee_info>& tree)
{
int choice;
while (true)
{
std::cout << "Enter an employee number to find or 0 to exit: ";
std::cin >> choice;
if (std::cin.good())
{
if (choice == 0) break;
const auto* employee = tree.find(choice, equals_key_employee, less_than_key_employee);
if (employee)
std::cout << *employee << '\n';
else
std::cout << "Employee not found!\n";
}
else
reset_cin();
}
}
void exit_driver(binary_tree<employee_info>& tree)
{
std::exit(0);
}
int main()
{
command commands[9] = {
insert_items,
delete_items,
display_nodes,
display_size,
display_height,
display_width,
display_leaf_count,
find_employee,
exit_driver
};
binary_tree<employee_info> employee_tree;
employee_tree.insert({ 1021, "John Williams" });
employee_tree.insert({ 1057, "Bill Witherspoon" });
employee_tree.insert({ 2487, "Jennifer Twain" });
employee_tree.insert({ 3769, "Sophie Lancaster" });
employee_tree.insert({ 1017, "Debbie Reece" });
employee_tree.insert({ 1275, "Georgie McMullen" });
employee_tree.insert({ 1899, "Ashley Smith" });
employee_tree.insert({ 4218, "Josh Plemmons" });
while (true)
{
display_menu();
int choice = get_menu_choice(1, 9);
commands[choice - 1](employee_tree);
}
return 0;
}
| [
"[email protected]"
] | |
e0f4abebbad981c72287da2e3cc394c5f66ae4f5 | d687048405954a3360db43a13cca0fff25967318 | /src/algo/GameNumber.hpp | c4e21450622e54cf7c9919b8398f9ce4fcfbd410 | [] | no_license | starquell/bulls-and-cows-bot | ad54720ed1073ece911fb6aeb8bcb66dd3906f97 | 46db478341ed8b3e6df0721fe5273e87b4a10b90 | refs/heads/master | 2022-04-28T16:03:22.277540 | 2020-05-01T12:55:26 | 2020-05-01T12:55:26 | 257,039,934 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 515 | hpp | #pragma once
#include <string>
#include <optional>
namespace game::algo {
struct Number {
std::string str;
using IntegerRepr = unsigned;
using SizeType = std::uint16_t;
static auto from_int(IntegerRepr num, const SizeType length) -> std::optional<Number>;
static auto with_similar_digits(Number other, const SizeType digits) -> Number;
static auto random(const SizeType size) -> Number;
auto valid() const -> bool;
};
} // namespace game::algo
| [
"[email protected]"
] | |
7a1ac820fd199e7895b1c7f4576f118150233237 | 9e74c08ea413ae8c8b80f2581b59f0740fc4e050 | /arduino/TTL/TTL.ino | dceee8f93077d4a212e5b15a9224a7fc594c1e37 | [] | no_license | Cqxstevexw/mess_knowledge | 4010fa299d4e8c9085af89010285a0b8253508f4 | b17d9edfaacc794dfeb7d84d66f69023569a21ca | refs/heads/master | 2020-04-09T01:49:04.563959 | 2019-10-07T02:44:43 | 2019-10-07T02:44:43 | 159,918,155 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 734 | ino | #include "Syn6288.h"
Syn6288 syn;
uint8_t text1[]={0xB3,0xC9,0xB6,0xBC,0xBC,0xAB,0xC8,0xA4,0xBF,0xC6,0xBC,0xBC,0xD3,0xD0,0xCF,0xDE,0xB9,0xAB,0xCB,0xBE}; //成都极趣科技有限公司
uint8_t text2[]={0x77,0x77,0x77,0x2E,0x64,0x66,0x72,0x6F,0x62,0x6F,0x74,0x2E,0x63,0x6F,0x6D,0x2E,0x63,0x6E}; //www.dfrobot.com.cn
uint8_t text3[]={0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39}; //0,1,2,3,4,5,6,7,8,9
void setup()
{
Serial.begin(9600);
// syn.Slaveboudset(9600);//修改波特率
//Serial.begin(19200);
}
void loop()
{
syn.play(text1,sizeof(text1),1);//合成text1,背景音乐1
syn.play(text2,sizeof(text2),2);//合成text2,背景音乐2
syn.play(text3,sizeof(text3),3);//合成text3,背景音乐3
}
| [
"[email protected]"
] | |
50a62e4181b47ad472c0d83ff6272288a2676f69 | 70543ad95e8216a937fb7a56dc4ca63dd07e1ce3 | /CPPExamples/MessageUtils/YahooConstants.h | 506aaf8b440d43859488daff03f99f5de8b91c5c | [
"MIT"
] | permissive | tpayne/lang-examples | 9ebc44a7b1399c696eba17af65de4e456b3dc9cb | 966b196ae150ef87e3f803255503a8577fc054ff | refs/heads/master | 2023-08-18T21:07:20.531649 | 2023-08-11T17:20:11 | 2023-08-11T17:20:11 | 93,518,664 | 1 | 0 | MIT | 2023-09-05T10:58:39 | 2017-06-06T12:58:29 | C++ | UTF-8 | C++ | false | false | 1,948 | h | ///
/// YahooConstants.h
/// MessengerUtils
/// Created by Tim Payne on 24/09/2008.
/// Copyright 2008 __MyCompanyName__. All rights reserved.
///
/// @file
#ifndef __yahooconstants_h__
#define __yahooconstants_h__
#include <set>
#include <string>
/// Protocol headers
/// Yahoo services
namespace YahooServices {
enum Services {
ADDBUDDY = 0x83,
ADDIDENT, /* 0x10 */
ADDIGNORE,
Authent = 0x57,
AUTHRESP = 0x54,
CALENDAR,
CHATEXIT = 0x9b,
CHATGOTO,
CHATINVITE,
CHATJOIN, /* > 1 104-room 129-1600326591 62-2 */
CHATLEAVE,
CHATLOGOFF,
CHATLOGON,
CHATLOGOUT = 0xa0,
CHATMSG = 0x20,
CHATONLINE = 0x96, /* > 109(id), 1, 6(abcde) < 0,1*/
CHATPING,
COMMENT = 0xa8,
CONFADDINVITE,
CONFDECLINE,
CONFINVITE = 0x18,
CONFLOGOFF,
CONFLOGON,
CONFMSG,
FILETRANSFER = 0x46,
GAMELOGOFF,
GAMELOGON = 0x28,
GAMEMSG = 0x2a,
GOTGROUPRENAME, /* < 1, 36(old), 37(new) */
GROUPRENAME = 0x89, /* > 1, 65(new), 66(0), 67(old) */
IDACT,
IDDEACT,
IDLE, /* 5 (placemarker) */
IGNORECONTACT, /* > 1, 7, 13 < 1, 66, 13, 0*/
ISAWAY,
ISBACK,
LIST,
LOGOFF,
LOGON = 1,
MAILSTAT,
MESSAGE,
NEWCONTACT,
NEWMAIL,
NEWPERSONALMAIL,
NOTIFY,
P2PFILEXFER,
PASSTHROUGH2 = 0x16,
PEERTOPEER = 0x4F, /* Checks if P2P possible */
PICTURE = 0xbe,
PICTURE_CHECKSUM = 0xbd,
PICTURE_UPDATE = 0xc1,
PICTURE_UPLOAD = 0xc2,
PING,
REJECTCONTACT,
REMBUDDY,
STEALTH = 0xb9,
SYSMESSAGE = 0x14,
USERSTAT, /* 0xa */
VERIFY,
VOICECHAT = 0x4A,
WEBCAM
};
};
/// Yahoo status
namespace YahooStatus {
enum Status {
Available = 0,
Away,
Brb,
Custom = 99,
Disconnected = -1,
Idle = 999,
Invisible = 12,
Notify = 0x16, /* TYPING */
Occupied,
Offline = 0x5a55aa56, /* don't ask */
Onphone,
OnVacation,
OutToLunch,
WEBLOGIN = 0x5a55aa55
};
};
/// Packet header
#define PACKETHRDLEN 20
typedef std::pair<int, std::string> MessagePair;
#endif
| [
"[email protected]"
] | |
b92fe4e7d7eeae750b216003283459f24f649f3d | abd1bb0719402bfd67a72b876aa0afb0bac9e7ea | /MIDTERM1/StudentShare/linkedList2.cpp | 27983f30e4f8537272afb0f4b26a08fcdd8e8dff | [] | no_license | Chimer2017/data_structures | ac71c98f1864931806efe74a9088560e0a79f652 | 3ef9eac62d74916e9ac260acd48b49daac7f33e8 | refs/heads/master | 2021-09-13T20:25:48.817758 | 2018-05-03T22:24:49 | 2018-05-03T22:24:49 | 119,078,759 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,201 | cpp | #include <iostream>
using namespace std;
struct Node
{
string item;
Node *next;
};
int main()
{
string a[] = {"uno", "dos", "tres", "cuatro"};
// for(int i = 0; i < 4; i++)
// {
// cout << a[i] << endl;
// }
Node *head, *current, *tmp;
head = new Node;
current = new Node;
head->item = a[0];
head->next = nullptr;
// if( head->next == nullptr )
// cout << "head->next = nullptr" << endl;
current = head;
int i = 1;
while( i < 4 )
{
// create new node; use tmp to point to it
tmp = new Node;
// populate the payload of tmp with i-th array element
tmp->item = a[i];
// in case it's the last element, set current node to indicate end
tmp->next = nullptr;
// at this point "current" is still pointing to previous element
// (could be head)
// connect the previous element such that it is pointing to the newly created one (tmp)
current->next = tmp;
// move forward. Make current point to the new element
current = tmp;
i++;
}
cout << "Traverse and print the LL: " << endl;
current = head;
while( current != nullptr )
{
cout << current->item << endl;
cout << current << endl;
current = current->next;
}
return 0;
}
| [
"[email protected]"
] | |
b65c6ecba1737143019ac792ff14e1d7bf909ba7 | 63eb4de5d61c049e18366c2082977f581857ed19 | /Classes/loading.cpp | 519f6b1ea9a1ba6ca88de5927f067983b9644bbe | [] | no_license | zesr/TankWar | 660e72f8ff9824ebbc271b28e9dcce2ce99dfee7 | d123e0b3954afb7ebdf5ab3113bf9f7200074beb | refs/heads/master | 2020-03-21T17:25:51.938779 | 2018-06-27T10:13:44 | 2018-06-27T10:13:44 | 138,831,408 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,454 | cpp | #include"loading.h"
GameData in;
Loading::Loading()
{
}
Loading::~Loading()
{
}
bool Loading::init()
{
if (!Layer::init())
{
return false;
}
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
//确定需要显示的文字
String temp;
switch (in.mapType) {
case 0:
temp = "Chapter 1";
break;
case 1:
temp = "Chapter 2";
break;
case 2:
temp = "BOSS";
break;
}
//按键提示
auto myLabel = Label::createWithSystemFont("Press any key", "Arial", 32);
myLabel->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 3));
this->addChild(myLabel);
//显示当前关卡数
myLabel = Label::createWithSystemFont(temp.getCString(), "Arial", 64);
myLabel->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 2));
this->addChild(myLabel);
//键盘注册
auto key_listener = EventListenerKeyboard::create();
key_listener->onKeyPressed = CC_CALLBACK_2(Loading::onKeyPressed, this);
Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(key_listener, this);
return true;
}
void Loading::onKeyPressed(EventKeyboard::KeyCode keyCode, Event* event) {
CCDirector::sharedDirector()->replaceScene(GameClient::createScene(in));
}
Scene* Loading::createScene(GameData gameData)
{
in = gameData;
auto scene = Scene::create();
auto layer = Loading::create();
scene->addChild(layer);
return scene;
} | [
"[email protected]"
] | |
97046d2aaa72e4d01cd05c04aa9783be6176b290 | c436fc304da315ed7cfa4129faaba14d165a246e | /foundation/src/sqlite/SqliteRow.h | caaa54c48f257607eda5d00b7f343ac09436c60f | [] | no_license | wjbwstone/wstone | dae656ffff30616d85293bcc356ab7ab7cebd5ba | 25da4de6900e6cc34a96a3882f1307b7a9bbf8b0 | refs/heads/main | 2023-02-17T16:44:50.679974 | 2021-01-20T05:53:24 | 2021-01-20T05:53:24 | 330,961,566 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 590 | h | #ifndef _SQLITE_ROW_2020_01_14_17_00_46_H
#define _SQLITE_ROW_2020_01_14_17_00_46_H
#include <helper/Types.h>
#include "SqliteCell.h"
namespace ws {
namespace sqlite {
class Row {
public:
Row() {
_cells.reserve(20);
}
~Row() {
for(auto it : _cells) {
delete it;
}
}
inline u32 size() const { return _cells.size(); }
inline void push(Cell* cell) { _cells.push_back(cell); }
inline const Cell* get(u32 index) const { return _cells[index]; }
private:
std::vector<Cell*> _cells;
};
}
}
#endif //_SQLITE_ROW_2020_01_14_17_00_46_H | [
"[email protected]"
] | |
e9de68af3cb5b7097f7ebc169b1dae50b8f9da6a | 2cd2c16bf249179d64a42dcb97e0e1049e7f9cfc | /arkanoid/Ball.cpp | 64688638f276fe07fdbcb8349a635d5017542317 | [] | no_license | bratek20/PGK | 5913edc77a5fc95cc8ee690a6e4385bf77437044 | 164c2e782ccf1af4e84fce438ca1ab8d188d5990 | refs/heads/master | 2020-04-01T20:59:51.854183 | 2019-01-30T12:14:36 | 2019-01-30T12:14:36 | 153,631,729 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 587 | cpp | #include "Ball.h"
#include "Globals.h"
Ball::Ball(MeshPtr mesh) : Actor(mesh) {}
BallPtr Ball::create(float xVelocity, float yVelocity){
auto mesh = Mesh::create(Mesh::EQUILATERAL, Mesh::RED);
auto ball = BallPtr(new Ball(mesh));
ball->setVelocity({xVelocity, yVelocity});
ball->setScale(0.42f, 0.42f);
return ball;
}
void Ball::setVelocity(glm::vec2 velocity){
this->velocity = velocity;
}
glm::vec2 Ball::getVelocity() const{
return velocity;
}
void Ball::onUpdate(){
move(velocity * Globals::deltaTime);
rotate(180.0f * Globals::deltaTime);
} | [
"[email protected]"
] | |
a6698ffdded7394e532c34dfac7ace0074401822 | 8f99599d341fdda1d4553452950b4832a630e812 | /daily_coding/8/0818/1854.cpp | 6bb5d83aab26181bedbd0868efa54b4d9384e4b9 | [] | no_license | JJungwoo/algorithm | 7fc8e76a51bd81c59a06393aa158286c45190366 | faadecb499dad06cd4552e1cd8ea482206affeb5 | refs/heads/master | 2022-05-20T00:14:31.950576 | 2022-03-16T14:10:32 | 2022-03-16T14:10:32 | 222,277,844 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,468 | cpp | /*
[boj] 1854. K번째 최단경로 찾기
https://www.acmicpc.net/problem/1854
ref : https://dyndy.tistory.com/230
*/
#include <iostream>
#include <vector>
#include <queue>
#define io ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
using namespace std;
int n, m, k, a, b, c;
vector<pair<int, int> > vp[1001];
priority_queue<int> path[1001];
struct comp{
bool operator() (const pair<int, int> &a, const pair<int, int> &b) {
return a.second > b.second;
}
};
priority_queue<pair<int, int>, vector<pair<int, int> >, comp > pq;
int main()
{
io;
cin>>n>>m>>k;
for(int i=0;i<m;i++){
cin>>a>>b>>c;
vp[a-1].push_back(make_pair(b-1, c));
}
pq.push(make_pair(0, 0));
path[0].push(0);
while(!pq.empty()) {
int cur = pq.top().first;
int cost = pq.top().second;
pq.pop();
for(auto next : vp[cur]) {
if(path[next.first].size() < k) {
path[next.first].push(cost + next.second);
}
else if(path[next.first].top() > cost + next.second) {
path[next.first].pop();
path[next.first].push(cost + next.second);
}
else
continue;
pq.push(make_pair(next.first, cost + next.second));
}
}
for(int i=0;i<n;i++){
if(path[i].size() == k) cout<<path[i].top()<<"\n";
else cout<<"-1\n";
}
return 0;
}
| [
"[email protected]"
] | |
e692aa12eb878485922821b48b3d02de6020ddc6 | c8cc37acf00f2eda393e7185805cf0c622725e9a | /2020/D10_1.cpp | 22efaa99eff101f9c5bb5b267d77e0cf0fb0baac | [
"MIT"
] | permissive | kociap/AoC | 6effcb21da562ac5ae2227f3e55d2cd74705253a | 9b7e231afe18c0dd5f3f3e4d325f2f21e7b4de55 | refs/heads/master | 2023-01-30T19:10:07.369369 | 2020-12-11T11:32:22 | 2020-12-11T11:32:22 | 318,447,398 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 716 | cpp | #include <iostream>
#include <vector>
#include <algorithm>
using i64 = long long;
int main() {
std::vector<i64> adapters;
while(true) {
i64 a;
std::cin >> a;
if(!std::cin) {
break;
}
adapters.push_back(a);
}
std::sort(adapters.begin(), adapters.end());
i64 jolt_1 = 0;
i64 jolt_3 = 0;
i64 last_adapter = 0;
for(i64 adapter: adapters) {
i64 dj = adapter - last_adapter;
std::cout << adapter << ' ' << dj << '\n';
if(dj == 1) {
jolt_1 += 1;
} else {
jolt_3 += 1;
}
last_adapter = adapter;
}
std::cout << (jolt_1 * (jolt_3 + 1));
return 0;
}
| [
"[email protected]"
] | |
ef200c08c99ae237a2430dad89e345fff9e72eae | 4c1d515719425db127ba5285b5be4f03af10d5a1 | /UVa-Judge/UVa_12210.cpp | ef24a1b1304a32fb15ec4a5da2642442a1539c85 | [] | no_license | matheusmtta/Competitive-Programming | 26e51741332aed223b9231da33749940f5a1b977 | e254b80090cc75bc213aad0a7957875842e90f1a | refs/heads/master | 2023-04-28T18:08:51.417470 | 2023-04-24T21:09:00 | 2023-04-24T21:09:00 | 223,605,672 | 7 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 780 | cpp | #include <bits/stdc++.h>
using namespace std;
#define MOD 1000000007
#define INF (int)0x3f3f3f3f
#define LINF (long long)0x3f3f3f3f3f3f3f3fll
#define mp make_pair
#define pb push_back
typedef long int int32;
typedef unsigned long int uint32;
typedef long long int int64;
typedef unsigned long long int uint64;
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n, m, q = 1;
while (cin >> n >> m){
if (n == 0 && m == 0) break;
vector <int> b, s;
int mn = INF;
for (int i = 0; i < n; i++){
int x; cin >> x;
mn = min(x, mn);
}
for (int j = 0; j < m; j++){
int x; cin >> x;
}
int diff = n - m;
cout << "Case " << q << ": ";
if (diff > 0) cout << diff << " " << mn << endl;
else cout << 0 << endl;
q++;
}
return 0;
} | [
"[email protected]"
] | |
1eb1dafba386c15805085590bcdedce13d2c9ef4 | 8bc0c9319c7e927c2409675c0f20757a55e6d699 | /cbhdprocedure.cpp | 1ca803f611614715f33d0a74090955e4863ea433 | [] | no_license | dchechel/PlanowanieRuchuRobotow | 53556d58242f405c178e43fa80ee4f257d5498c7 | c9871ef207b093cac7bd18922a2a9ecdc8db3d84 | refs/heads/master | 2021-01-21T14:52:41.335976 | 2017-11-29T19:26:09 | 2017-11-29T19:26:39 | 95,348,046 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,739 | cpp | #include "cbhdprocedure.h"
#include "mobilerobot.h"
#include <iostream>
#include <QVector>
#include<functional>
using namespace std;
CBHDProcedure::CBHDProcedure(MobileRobot* mr, double t_arg, int N_arg, int s0_arg) :
robot(mr),t(t_arg),N(N_arg),s0(s0_arg)
{
defaultPosition.resize(robot->q.size());
for (int i=0;i<defaultPosition.size();i++)
defaultPosition[i]=robot->q[i];
}
Trajectory* CBHDProcedure::CBHDexecute()
{
double timeOfStep = t/N;
Trajectory* tr = new Trajectory(robot->q.size(),timeOfStep,4*N+1);
auto dqNormal = std::bind(&MobileRobot::dq,robot,std::placeholders::_1);
if (s0<N)
{
tr=robot->executeMotion(t/N,1,1,N-s0,dqNormal);
tr->addTrajectory(robot->executeMotion(t/N,2,1,N,dqNormal));
tr->addTrajectory(robot->executeMotion(t/N,1,-1,N,dqNormal));
tr->addTrajectory(robot->executeMotion(t/N,2,-1,N,dqNormal));
if (s0!=0)
tr->addTrajectory(robot->executeMotion(t/N,1,1,s0,dqNormal));
}
if (s0>=N && s0<2*N)
{
tr=robot->executeMotion(t/N,2,1,N-(s0%N),dqNormal);
tr->addTrajectory(robot->executeMotion(t/N,1,-1,N,dqNormal));
tr->addTrajectory(robot->executeMotion(t/N,2,-1,N,dqNormal));
tr->addTrajectory(robot->executeMotion(t/N,1,1,N,dqNormal));
if (s0%N!=0)
tr->addTrajectory(robot->executeMotion(t/N,2,1,s0%N,dqNormal));
}
if (s0>=2*N && s0<3*N)
{
tr=robot->executeMotion(t/N,1,-1,N-(s0%N),dqNormal);
tr->addTrajectory(robot->executeMotion(t/N,2,-1,N,dqNormal));
tr->addTrajectory(robot->executeMotion(t/N,1,1,N,dqNormal));
tr->addTrajectory(robot->executeMotion(t/N,2,1,N,dqNormal));
if(s0%N!=0)
tr->addTrajectory(robot->executeMotion(t/N,1,-1,s0%N,dqNormal));
}
if (s0>=3*N)
{
tr=robot->executeMotion(t/N,2,-1,N-(s0%N),dqNormal);
tr->addTrajectory(robot->executeMotion(t/N,1,1,N,dqNormal));
tr->addTrajectory(robot->executeMotion(t/N,2,1,N,dqNormal));
tr->addTrajectory(robot->executeMotion(t/N,1,-1,N,dqNormal));
if (s0%N!=0)
tr->addTrajectory(robot->executeMotion(t/N,2,-1,s0%N,dqNormal));
}
returnToDefaultPosition();
return tr;
}
Trajectory* CBHDProcedure::designateExpectedPosition()
{
robot->q[0]=0;
robot->q[1]=0;
robot->q[2]=0;
auto dqLie = std::bind(&MobileRobot::dqLie,robot,std::placeholders::_1);
double timeOfStep = t/N;
Trajectory* tr = new Trajectory(robot->q.size(),timeOfStep,N);
tr=robot->executeMotion(t*t/N,1,1,N,dqLie);
returnToDefaultPosition();
return tr;
}
void CBHDProcedure::returnToDefaultPosition()
{
robot->q=defaultPosition;
}
| [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.