hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
65551e3323413306bf702fb22bb9d8c2f05f776c
950
cpp
C++
minic/src/unity_build.cpp
waldnercharles/MiniC
a8a86d3174bc54acd24fc1df0bdba6e9eac0cc5d
[ "Unlicense" ]
null
null
null
minic/src/unity_build.cpp
waldnercharles/MiniC
a8a86d3174bc54acd24fc1df0bdba6e9eac0cc5d
[ "Unlicense" ]
null
null
null
minic/src/unity_build.cpp
waldnercharles/MiniC
a8a86d3174bc54acd24fc1df0bdba6e9eac0cc5d
[ "Unlicense" ]
null
null
null
#define DEBUG //#define __STDDEF_H //#define NULL nullptr #define UNICODE //#define NOMINMAX //#define WIN32_LEAN_AND_MEAN //#include <Windows.h> //#include "minic/assert.h" //#include "minic/iterator.cpp" //#include "minic/asset.cpp" #include "minic/allocator.cpp" #include "minic/array.cpp" #include "minic/fp.cpp" //#include "minic/hashtable.c" #include "minic/handle.cpp" #include "minic/io.cpp" #include "minic/math.cpp" #include "minic/memory.cpp" #include "minic/rand.cpp" #include "minic/string.cpp" #include "minic/timer.cpp" #include "minic/win32_allocator_default.cpp" #include "minic/win32_assert.cpp" #include "minic/win32_file.cpp" #include "minic/win32_io.cpp" #include "minic/win32_log.cpp" #include "minic/win32_timer.cpp" #include "minic/win32_platform.cpp" #include "minic/win32_window.cpp" extern "C" void *__stdcall memset(void *dst, int val, size_t size); extern "C" int __stdcall mainCRTStartup(); #include "main.cpp"
22.619048
67
0.746316
waldnercharles
6563063c513fae945c8ac37b92c43d6b188b9467
444
cpp
C++
timus/volume-08/deer_is_better.cpp
Rkhoiwal/Competitive-prog-Archive
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
[ "MIT" ]
null
null
null
timus/volume-08/deer_is_better.cpp
Rkhoiwal/Competitive-prog-Archive
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
[ "MIT" ]
null
null
null
timus/volume-08/deer_is_better.cpp
Rkhoiwal/Competitive-prog-Archive
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; inline void use_io_optimizations() { ios_base::sync_with_stdio(false); cin.tie(nullptr); } int main() { use_io_optimizations(); unsigned int distance; unsigned int segment; unsigned int time; cin >> distance >> segment >> time; cout << distance / segment * time << ' ' << (distance + segment - 1) / segment * time << '\n'; return 0; }
16.444444
62
0.59009
Rkhoiwal
6563e87603f7e3c4145b407a2e90c2706d9b908c
2,919
cpp
C++
src/ugawg_linear.cpp
joshia5/ayj-omega_h
8b65215013df29af066fa076261ba897d64a72c2
[ "BSD-2-Clause-FreeBSD" ]
44
2019-01-23T03:37:18.000Z
2021-08-24T02:20:29.000Z
src/ugawg_linear.cpp
joshia5/ayj-omega_h
8b65215013df29af066fa076261ba897d64a72c2
[ "BSD-2-Clause-FreeBSD" ]
67
2019-01-29T15:35:42.000Z
2021-08-17T20:42:40.000Z
src/ugawg_linear.cpp
joshia5/ayj-omega_h
8b65215013df29af066fa076261ba897d64a72c2
[ "BSD-2-Clause-FreeBSD" ]
29
2019-01-14T21:33:32.000Z
2021-08-10T11:35:24.000Z
#include <Omega_h_adapt.hpp> #include <Omega_h_file.hpp> #include <Omega_h_for.hpp> #include <Omega_h_mesh.hpp> #include <Omega_h_metric.hpp> #include <Omega_h_timer.hpp> #include <iostream> using namespace Omega_h; template <Int dim> static void set_target_metric(Mesh* mesh) { auto coords = mesh->coords(); auto target_metrics_w = Write<Real>(mesh->nverts() * symm_ncomps(dim)); auto f = OMEGA_H_LAMBDA(LO v) { auto z = coords[v * dim + (dim - 1)]; auto h = Vector<dim>(); for (Int i = 0; i < dim - 1; ++i) h[i] = 0.1; h[dim - 1] = 0.001 + 0.198 * std::abs(z - 0.5); auto m = diagonal(metric_eigenvalues_from_lengths(h)); set_symm(target_metrics_w, v, m); }; parallel_for(mesh->nverts(), f); mesh->set_tag(VERT, "target_metric", Reals(target_metrics_w)); } template <Int dim> void run_case(Mesh* mesh, char const* vtk_path) { auto world = mesh->comm(); mesh->set_parting(OMEGA_H_GHOSTED); auto implied_metrics = get_implied_metrics(mesh); mesh->add_tag(VERT, "metric", symm_ncomps(dim), implied_metrics); mesh->add_tag<Real>(VERT, "target_metric", symm_ncomps(dim)); set_target_metric<dim>(mesh); mesh->set_parting(OMEGA_H_ELEM_BASED); mesh->ask_lengths(); mesh->ask_qualities(); vtk::FullWriter writer; if (vtk_path) { writer = vtk::FullWriter(vtk_path, mesh); writer.write(); } auto opts = AdaptOpts(mesh); opts.verbosity = EXTRA_STATS; opts.length_histogram_max = 2.0; opts.max_length_allowed = opts.max_length_desired * 2.0; Now t0 = now(); while (approach_metric(mesh, opts)) { adapt(mesh, opts); if (mesh->has_tag(VERT, "target_metric")) set_target_metric<dim>(mesh); if (vtk_path) writer.write(); } Now t1 = now(); std::cout << "total time: " << (t1 - t0) << " seconds\n"; } int main(int argc, char** argv) { auto lib = Library(&argc, &argv); char const* in_path = nullptr; char const* out_path = nullptr; char const* vtk_path = nullptr; bool should_help = false; for (int i = 1; i < argc; ++i) { if (std::string("-a") == argv[i]) { if (i == argc - 1) { std::cout << "-a takes an argument\n"; should_help = true; } else { vtk_path = argv[++i]; } } else if (!in_path) { in_path = argv[i]; } else if (!out_path) { out_path = argv[i]; } else { std::cout << "unknown argument " << argv[i] << '\n'; should_help = true; } } if (!in_path || !out_path) should_help = true; if (should_help) { std::cout << "usage: " << argv[0] << " [options] input.mesh[b] output.mesh[b]\n"; std::cout << "options: -a vtk_path debug output for adaptivity\n"; return -1; } Mesh mesh(&lib); meshb::read(&mesh, in_path); if (mesh.dim() == 2) run_case<2>(&mesh, vtk_path); if (mesh.dim() == 3) run_case<3>(&mesh, vtk_path); meshb::write(&mesh, out_path, 2); return 0; }
30.40625
79
0.617335
joshia5
6564348f804bb5186886f277ee233dde963d32bb
1,353
cpp
C++
kernel/Panic.cpp
brightprogrammer/MisraOS
fe7fa81b81b42e69ec8b06c8efa55106e58f444d
[ "BSD-3-Clause" ]
10
2022-01-25T13:05:42.000Z
2022-02-08T21:26:19.000Z
kernel/Panic.cpp
brightprogrammer/MisraOS
fe7fa81b81b42e69ec8b06c8efa55106e58f444d
[ "BSD-3-Clause" ]
null
null
null
kernel/Panic.cpp
brightprogrammer/MisraOS
fe7fa81b81b42e69ec8b06c8efa55106e58f444d
[ "BSD-3-Clause" ]
null
null
null
#include "Panic.hpp" #include "Renderer/Framebuffer.hpp" #include "Renderer/Colors.hpp" #include "Renderer/FontRenderer.hpp" #include "Utils/String.hpp" #include <cstdint> #include <cstdarg> #include <cwctype> #include "Printf.hpp" uint32_t oldbgcolor = 0; uint32_t oldfgcolor = 0; void PRINTF_API(1, 2) INTERRUPT_CALLEE_API PanicPrintf(const char* fmtstr, ...){ // shorter name "r" FontRenderer& r = GetDefaultFontRenderer(); // cache colors oldbgcolor = r.backgroundColour; oldfgcolor = r.foregroundColour; // change to panic colors r.backgroundColour = PANIC_BGCOLOR; r.foregroundColour = PANIC_FGCOLOR; // print va_list vl; va_start(vl, fmtstr); Printf(fmtstr, vl); va_end(vl); // restore colors r.backgroundColour = oldbgcolor; r.foregroundColour = oldfgcolor; } // normal print without formatting void INTERRUPT_CALLEE_API PanicPuts(const char* str){ // shorter name "r" FontRenderer& r = GetDefaultFontRenderer(); // cache colors oldbgcolor = r.backgroundColour; oldfgcolor = r.foregroundColour; // change colors to panic colros r.backgroundColour = PANIC_BGCOLOR; r.foregroundColour = PANIC_FGCOLOR; // draw string DrawString(str); // restore colors r.backgroundColour = oldbgcolor; r.foregroundColour = oldfgcolor; }
23.736842
80
0.699926
brightprogrammer
6565b59898e1a7f3f2a7dd8f1fde50826b5722d1
1,399
cpp
C++
SimpleDivX/ConfigData.cpp
StefH/SimpleDivX
9740b4e2e497dbb602a907ea4328c0be59651a55
[ "MIT" ]
1
2020-08-01T18:29:50.000Z
2020-08-01T18:29:50.000Z
SimpleDivX/ConfigData.cpp
StefH/SimpleDivX
9740b4e2e497dbb602a907ea4328c0be59651a55
[ "MIT" ]
null
null
null
SimpleDivX/ConfigData.cpp
StefH/SimpleDivX
9740b4e2e497dbb602a907ea4328c0be59651a55
[ "MIT" ]
null
null
null
#include "stdafx.h" #include ".\configdata.h" #include "SimpleDivX_Defines.h" #include "SimpleDivXBatch.h" #include "EncodingInfo.h" #include "ProgramInfo.h" IMPLEMENT_SERIAL( CConfigData, CObject, 1 ) #define SIMPLEDIVXDATA "SimpleDivX.dat" CConfigData::CConfigData(void) { status = 0; } CConfigData::~CConfigData(void) { } CSimpleDivXBatch* CConfigData::GetBatchInfo() { return &Batch_Info; } void CConfigData::Serialize(CArchive& ar) { CObject::Serialize( ar ); if( ar.IsStoring() ) { TRY { Batch_Info.Serialize(ar); } CATCH(CArchiveException, pEx) { // invalid; } END_CATCH } else { TRY { //Prog_Info.Serialize(ar); Batch_Info.Serialize(ar); } CATCH(CArchiveException, pEx) { status = 1; } END_CATCH } } void CConfigData::Write_Settings(void) { CFile theFile; CFileException e; theFile.Open(SIMPLEDIVXDATA, CFile::modeCreate | CFile::modeWrite, &e); CArchive ar(&theFile, CArchive::store); Serialize(ar); ar.Close(); theFile.Close(); } void CConfigData::Read_Settings(void) { CFile theFile; BOOL fileStatus = theFile.Open(SIMPLEDIVXDATA, CFile::modeRead); if (fileStatus) { CArchive ar(&theFile, CArchive::load); TRY { Serialize(ar); } CATCH(CFileException, pEx) { // invalid; status = -1; } END_CATCH ar.Close(); theFile.Close(); } else { status = 2; } }
13.851485
72
0.659042
StefH
65676e872a2109ed5045430324f27a18bd427c15
535
hpp
C++
driver/includes.hpp
justvmexit/dumpr
35da30e9488281b22e133ef24413f61a9cbb2356
[ "MIT" ]
5
2021-12-14T19:44:21.000Z
2022-03-27T05:47:52.000Z
driver/includes.hpp
justvmexit/dumpr
35da30e9488281b22e133ef24413f61a9cbb2356
[ "MIT" ]
1
2021-12-07T02:24:14.000Z
2021-12-07T02:24:14.000Z
driver/includes.hpp
justvmexit/dumpr
35da30e9488281b22e133ef24413f61a9cbb2356
[ "MIT" ]
3
2021-12-19T09:45:35.000Z
2022-02-16T08:48:46.000Z
#pragma once #include <ntifs.h> #include <ntddk.h> #include <windef.h> #include <wdf.h> #include <stdlib.h> #include <cstdint> extern "C" { NTSTATUS NTAPI MmCopyVirtualMemory(PEPROCESS SourceProcess, PVOID SourceAddress, PEPROCESS TargetProcess, PVOID TargetAddress, SIZE_T BufferSize, KPROCESSOR_MODE PreviousMode, size_t* ReturnSize); NTKERNELAPI PVOID PsGetProcessSectionBaseAddress(PEPROCESS Process); NTKERNELAPI NTSTATUS IoCreateDriver(IN PUNICODE_STRING DriverName, OPTIONAL IN PDRIVER_INITIALIZE InitializationFunction); }
38.214286
197
0.820561
justvmexit
656b2024b7089cde8cf15499175bb80ee7973bfd
11,803
cpp
C++
tests/board/test_board_n6000.cpp
OPAE/opae-sdk
7140533d5383e144aeedda9e8cf63fe24854af33
[ "BSD-3-Clause" ]
220
2017-09-02T20:07:11.000Z
2022-03-01T03:53:35.000Z
tests/board/test_board_n6000.cpp
OPAE/opae-sdk
7140533d5383e144aeedda9e8cf63fe24854af33
[ "BSD-3-Clause" ]
1,335
2017-11-05T03:02:55.000Z
2022-03-29T23:14:06.000Z
tests/board/test_board_n6000.cpp
OPAE/opae-sdk
7140533d5383e144aeedda9e8cf63fe24854af33
[ "BSD-3-Clause" ]
80
2017-09-01T21:28:16.000Z
2022-03-09T08:04:05.000Z
// Copyright(c) 2021, Intel Corporation // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Intel Corporation nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #ifdef HAVE_CONFIG_H #include <config.h> #endif // HAVE_CONFIG_H extern "C" { #include <json-c/json.h> #include <uuid/uuid.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include "opae_int.h" } #include <opae/fpga.h> #include "intel-fpga.h" #include <linux/ioctl.h> #include <cstdlib> #include <string> #include "gtest/gtest.h" #include "mock/test_system.h" #include "libboard/board_common/board_common.h" #include "libboard/board_n6000/board_n6000.h" using namespace opae::testing; class board_n6000_c_p : public ::testing::TestWithParam<std::string> { protected: board_n6000_c_p() : tokens_{ {nullptr, nullptr} } {} fpga_result write_sysfs_file(const char *file, void *buf, size_t count); ssize_t eintr_write(int fd, void *buf, size_t count); fpga_result delete_sysfs_file(const char *file); virtual void SetUp() override { ASSERT_TRUE(test_platform::exists(GetParam())); platform_ = test_platform::get(GetParam()); system_ = test_system::instance(); system_->initialize(); system_->prepare_syfs(platform_); filter_ = nullptr; ASSERT_EQ(fpgaInitialize(NULL), FPGA_OK); ASSERT_EQ(fpgaGetProperties(nullptr, &filter_), FPGA_OK); ASSERT_EQ(fpgaPropertiesSetObjectType(filter_, FPGA_DEVICE), FPGA_OK); num_matches_ = 0; ASSERT_EQ(fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_), FPGA_OK); EXPECT_GT(num_matches_, 0); dev_ = nullptr; ASSERT_EQ(fpgaOpen(tokens_[0], &dev_, 0), FPGA_OK); } virtual void TearDown() override { EXPECT_EQ(fpgaDestroyProperties(&filter_), FPGA_OK); if (dev_) { EXPECT_EQ(fpgaClose(dev_), FPGA_OK); dev_ = nullptr; } for (auto &t : tokens_) { if (t) { EXPECT_EQ(fpgaDestroyToken(&t), FPGA_OK); t = nullptr; } } fpgaFinalize(); system_->finalize(); } std::array<fpga_token, 2> tokens_; fpga_properties filter_; fpga_handle dev_; test_platform platform_; uint32_t num_matches_; test_system *system_; }; ssize_t board_n6000_c_p::eintr_write(int fd, void *buf, size_t count) { ssize_t bytes_written = 0, total_written = 0; char *ptr = (char*)buf; if (!buf) { return -1; } while (total_written < (ssize_t)count) { bytes_written = write(fd, ptr + total_written, count - total_written); if (bytes_written < 0) { if (errno == EINTR) { continue; } return bytes_written; } total_written += bytes_written; } return total_written; } fpga_result board_n6000_c_p::write_sysfs_file(const char *file, void *buf, size_t count) { fpga_result res = FPGA_OK; char sysfspath[SYSFS_PATH_MAX]; int fd = 0; snprintf(sysfspath, sizeof(sysfspath), "%s/%s", "/sys/class/fpga_region/region*/dfl-fme*", file); glob_t pglob; int gres = glob(sysfspath, GLOB_NOSORT, NULL, &pglob); if ((gres) || (1 != pglob.gl_pathc)) { globfree(&pglob); return FPGA_NOT_FOUND; } fd = open(pglob.gl_pathv[0], O_WRONLY); globfree(&pglob); if (fd < 0) { printf("open failed \n"); return FPGA_NOT_FOUND; } ssize_t total_written = eintr_write(fd, buf, count); if (total_written == 0) { close(fd); printf("total_written failed \n"); return FPGA_INVALID_PARAM; } close(fd); return res; } fpga_result board_n6000_c_p::delete_sysfs_file(const char *file) { fpga_result res = FPGA_OK; char sysfspath[SYSFS_PATH_MAX]; int status = 0; snprintf(sysfspath, sizeof(sysfspath), "%s/%s", "/sys/class/fpga_region/region*/dfl-fme*", file); glob_t pglob; int gres = glob(sysfspath, GLOB_NOSORT, NULL, &pglob); if ((gres) || (1 != pglob.gl_pathc)) { globfree(&pglob); return FPGA_NOT_FOUND; } status = remove(pglob.gl_pathv[0]); globfree(&pglob); if (status < 0) { printf("delete failed = %d \n", status); return FPGA_NOT_FOUND; } return res; } // test DFL sysfs attributes class board_dfl_n6000_c_p : public board_n6000_c_p { }; /** * @test board_n6000_1 * @brief Tests: read_bmcfw_version * @details Validates bmc firmware version <br> */ TEST_P(board_dfl_n6000_c_p, board_n6000_1) { char bmcfw_ver[SYSFS_PATH_MAX]; EXPECT_EQ(read_bmcfw_version(tokens_[0], bmcfw_ver, SYSFS_PATH_MAX), FPGA_OK); EXPECT_EQ(read_bmcfw_version(tokens_[0], NULL, SYSFS_PATH_MAX), FPGA_INVALID_PARAM); EXPECT_EQ(read_bmcfw_version(NULL, bmcfw_ver, SYSFS_PATH_MAX), FPGA_INVALID_PARAM); } /** * @test board_n6000_2 * @brief Tests: read_max10fw_version * @details Validates max10 firmware version <br> */ TEST_P(board_dfl_n6000_c_p, board_n6000_2) { char max10fw_ver[SYSFS_PATH_MAX]; EXPECT_EQ(read_max10fw_version(tokens_[0], max10fw_ver, SYSFS_PATH_MAX), FPGA_OK); EXPECT_EQ(read_max10fw_version(tokens_[0], NULL, SYSFS_PATH_MAX), FPGA_INVALID_PARAM); EXPECT_EQ(read_max10fw_version(NULL, max10fw_ver, SYSFS_PATH_MAX), FPGA_INVALID_PARAM); } /** * @test board_n6000_3 * @brief Tests: parse_fw_ver * @details Validates parse fw version <br> */ TEST_P(board_dfl_n6000_c_p, board_n6000_3) { char buf[SYSFS_PATH_MAX]; char fw_ver[SYSFS_PATH_MAX]; EXPECT_EQ(parse_fw_ver(buf, NULL, SYSFS_PATH_MAX), FPGA_INVALID_PARAM); EXPECT_EQ(parse_fw_ver(NULL, fw_ver, SYSFS_PATH_MAX), FPGA_INVALID_PARAM); } /** * @test board_n6000_4 * @brief Tests: print_sec_info * @details Validates fpga security info <br> */ TEST_P(board_dfl_n6000_c_p, board_n6000_4) { EXPECT_EQ(print_sec_info(tokens_[0]), FPGA_OK); } /** * @test board_n6000_5 * @brief Tests: print_mac_info * @details Validates prints mac info <br> */ TEST_P(board_dfl_n6000_c_p, board_n6000_5) { EXPECT_EQ(print_mac_info(tokens_[0]), FPGA_OK); } /** * @test board_n6000_6 * @brief Tests: print_board_info * @details Validates fpga board info <br> */ TEST_P(board_dfl_n6000_c_p, board_n6000_6) { EXPECT_EQ(print_board_info(tokens_[0]), FPGA_OK); } /** * @test board_n6000_8 * @brief Tests: print_phy_info * @details Validates fpga phy group info <br> */ TEST_P(board_dfl_n6000_c_p, board_n6000_8) { EXPECT_EQ(print_phy_info(tokens_[0]), FPGA_NOT_SUPPORTED); } /** * @test board_n6000_9 * @brief Tests: read_max10fw_version * read_bmcfw_version, * @details Validates fpga invalid fpga firmware version <br> */ TEST_P(board_dfl_n6000_c_p, board_n6000_9) { char buf[10] = { 0 }; memset(&buf, 0xf, sizeof(buf)); ASSERT_EQ(write_sysfs_file((const char *)"dfl_dev*/bmcfw_version", (void*)buf, sizeof(buf)), FPGA_OK); char bmcfw_ver[SYSFS_PATH_MAX]; EXPECT_NE(read_bmcfw_version(tokens_[0], bmcfw_ver, SYSFS_PATH_MAX), FPGA_OK); ASSERT_EQ(write_sysfs_file((const char *)"dfl_dev*/bmc_version", (void*)buf, sizeof(buf)), FPGA_OK); char max10fw_ver[SYSFS_PATH_MAX]; EXPECT_NE(read_max10fw_version(tokens_[0], max10fw_ver, SYSFS_PATH_MAX), FPGA_OK); } /** * @test board_n6000_10 * @brief Tests: print_phy_info * @details invalid print phy info input <br> */ TEST_P(board_dfl_n6000_c_p, board_n6000_10) { EXPECT_NE(print_phy_info(tokens_[0]), FPGA_OK); EXPECT_NE(print_phy_info(NULL), FPGA_OK); } /** * @test board_n6000_12 * @brief Tests: print_mac_info * @details prints mac address <br> */ TEST_P(board_dfl_n6000_c_p, board_n6000_12) { char mac_buf[18] = { 0 }; strncpy(mac_buf, "ff:ff:ff:ff:ff:ff", 18); write_sysfs_file((char*)"dfl_dev*/mac_address", (void*)mac_buf, 18); char mac_count[2] = { 0 }; strncpy(mac_count, "8", 2); write_sysfs_file((char*)"dfl_dev*/mac_count", (void*)mac_count, 2); EXPECT_EQ(print_mac_info(tokens_[0]), FPGA_EXCEPTION); strncpy(mac_buf, "78:56:34:12:AB:90", 18); write_sysfs_file((char*)"dfl_dev*/mac_address", (void*)mac_buf, 18); EXPECT_EQ(print_mac_info(tokens_[0]), FPGA_OK); strncpy(mac_buf, "78:56:34:12:AB:FE", 18); write_sysfs_file((char*)"dfl_dev*/mac_address", (void*)mac_buf, 18); EXPECT_EQ(print_mac_info(tokens_[0]), FPGA_OK); strncpy(mac_buf, "78:56:34:12:FF:FF", 18); write_sysfs_file((char*)"dfl_dev*/mac_address", (void*)mac_buf, 18); EXPECT_EQ(print_mac_info(tokens_[0]), FPGA_OK); strncpy(mac_buf, "78:56:34:FE:FF:FF", 18); write_sysfs_file((char*)"dfl_dev*/mac_address", (void*)mac_buf, 18); EXPECT_EQ(print_mac_info(tokens_[0]), FPGA_OK); strncpy(mac_buf, "78:56:34:FF:FF:FF", 18); write_sysfs_file((char*)"dfl_dev*/mac_address", (void*)mac_buf, 18); EXPECT_EQ(print_mac_info(tokens_[0]), FPGA_OK); strncpy(mac_buf, "78:56:FF:FF:FF:FF", 18); write_sysfs_file((char*)"dfl_dev*/mac_address", (void*)mac_buf, 18); EXPECT_EQ(print_mac_info(tokens_[0]), FPGA_OK); strncpy(mac_buf, "78:FF:FF:FF:FF:FF", 18); write_sysfs_file((char*)"dfl_dev*/mac_address", (void*)mac_buf, 18); EXPECT_EQ(print_mac_info(tokens_[0]), FPGA_OK); strncpy(mac_buf, "FE:FF:FF:FF:FF:FF", 18); write_sysfs_file((char*)"dfl_dev*/mac_address", (void*)mac_buf, 18); EXPECT_EQ(print_mac_info(tokens_[0]), FPGA_OK); strncpy(mac_buf, "00:00:00:00:00:ff", 18); write_sysfs_file((char*)"dfl_dev*/mac_address", (void*)mac_buf, 18); EXPECT_EQ(print_mac_info(tokens_[0]), FPGA_OK); } INSTANTIATE_TEST_CASE_P(board_dfl_n6000_c, board_dfl_n6000_c_p, ::testing::ValuesIn(test_platform::mock_platforms({ "dfl-n6000" }))); // test invalid sysfs attributes class board_n6000_invalid_c_p : public board_n6000_c_p { }; /** * @test board_n6000_11 * @brief Tests: read_max10fw_version * read_bmcfw_version * read_mac_info * print_board_info * print_phy_info * print_mac_info * @details Validates function with invalid sysfs <br> */ TEST_P(board_n6000_invalid_c_p, board_n6000_11) { char bmcfw_ver[SYSFS_PATH_MAX]; EXPECT_EQ(read_bmcfw_version(tokens_[0], bmcfw_ver, SYSFS_PATH_MAX), FPGA_NOT_FOUND); char max10fw_ver[SYSFS_PATH_MAX]; EXPECT_EQ(read_max10fw_version(tokens_[0], max10fw_ver, SYSFS_PATH_MAX), FPGA_NOT_FOUND); EXPECT_EQ(print_board_info(tokens_[0]), FPGA_NOT_FOUND); EXPECT_EQ(print_mac_info(tokens_[0]), FPGA_NOT_FOUND); EXPECT_EQ(print_sec_info(tokens_[0]), FPGA_NOT_FOUND); EXPECT_NE(print_phy_info(tokens_[0]), FPGA_EXCEPTION); } INSTANTIATE_TEST_CASE_P(board_n6000_invalid_c, board_n6000_invalid_c_p, ::testing::ValuesIn(test_platform::mock_platforms({ "skx-p" })));
29
103
0.719139
OPAE
656bbb95608bc2c47e955579a486b94b43e1c833
2,909
hpp
C++
src/sched/entry/reduce_local_entry.hpp
mshiryaev/oneccl
fb4bd69b0bfa72f0ed16ac2328205e51cf12d4aa
[ "Apache-2.0" ]
null
null
null
src/sched/entry/reduce_local_entry.hpp
mshiryaev/oneccl
fb4bd69b0bfa72f0ed16ac2328205e51cf12d4aa
[ "Apache-2.0" ]
null
null
null
src/sched/entry/reduce_local_entry.hpp
mshiryaev/oneccl
fb4bd69b0bfa72f0ed16ac2328205e51cf12d4aa
[ "Apache-2.0" ]
null
null
null
/* Copyright 2016-2019 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. */ #pragma once #include "comp/comp.hpp" #include "sched/entry/entry.hpp" class reduce_local_entry : public sched_entry { public: static constexpr const char* class_name() noexcept { return "REDUCE_LOCAL"; } reduce_local_entry() = delete; reduce_local_entry(ccl_sched* sched, const ccl_buffer in_buf, size_t in_cnt, ccl_buffer inout_buf, size_t* out_cnt, ccl_datatype_internal_t dtype, ccl_reduction_t reduction_op) : sched_entry(sched), in_buf(in_buf), in_cnt(in_cnt), inout_buf(inout_buf), out_cnt(out_cnt), dtype(dtype), op(reduction_op), fn(sched->coll_attr.reduction_fn) { CCL_THROW_IF_NOT(op != ccl_reduction_custom || fn, "custom reduction requires user provided callback"); } void start() override { size_t bytes = in_cnt * ccl_datatype_get_size(dtype); size_t offset = in_buf.get_offset(); const ccl_fn_context_t context = {sched->coll_attr.match_id.c_str(), offset}; ccl_status_t comp_status = ccl_comp_reduce(in_buf.get_ptr(bytes), in_cnt, inout_buf.get_ptr(bytes), out_cnt, dtype, op, fn, &context); CCL_ASSERT(comp_status == ccl_status_success, "bad status ", comp_status); status = ccl_sched_entry_status_complete; } const char* name() const override { return class_name(); } protected: void dump_detail(std::stringstream& str) const override { ccl_logger::format(str, "dt ", ccl_datatype_get_name(dtype), ", in_buf ", in_buf, ", in_cnt ", in_cnt, ", inout_buf ", inout_buf, ", out_cnt ", out_cnt, ", op ", ccl_reduction_to_str(op), ", red_fn ", fn, "\n"); } private: ccl_buffer in_buf; size_t in_cnt; ccl_buffer inout_buf; size_t* out_cnt; ccl_datatype_internal_t dtype; ccl_reduction_t op; ccl_reduction_fn_t fn; };
33.436782
87
0.5868
mshiryaev
656e762bab26c7999315130917ac0178909947b2
2,459
cpp
C++
leetcode/biweekly/14.cpp
bvbasavaraju/competitive_programming
a82ffc1b639588a84f4273b44285d57cdc2f4b11
[ "Apache-2.0" ]
1
2020-05-05T13:06:51.000Z
2020-05-05T13:06:51.000Z
leetcode/biweekly/14.cpp
bvbasavaraju/competitive_programming
a82ffc1b639588a84f4273b44285d57cdc2f4b11
[ "Apache-2.0" ]
null
null
null
leetcode/biweekly/14.cpp
bvbasavaraju/competitive_programming
a82ffc1b639588a84f4273b44285d57cdc2f4b11
[ "Apache-2.0" ]
null
null
null
/**************************************************** Date: November 30, 2019 Successful submissions : 1 Time expiration : Not Solved : 3 Wrong Answer/ Partial result : link: https://leetcode.com/contest/biweekly-contest-14 ****************************************************/ #include <iostream> #include <vector> #include <algorithm> #include <string> #include <stack> #include <queue> #include <map> #include <unordered_map> using namespace std; /* Q: 1271. Hexspeak */ class Solution1_t { public: string toHexspeak(string numInStr) { char *end; long long int numD = strtoll(numInStr.c_str(), &end, 10); stack<int> reminders; while (numD >= 16) { int r = numD % 16; numD = numD / 16; reminders.push(r); } reminders.push(numD); string retVal = ""; while (!reminders.empty()) { int i = reminders.top(); reminders.pop(); switch (i) { case 10: retVal += "A"; break; case 11: retVal += "B"; break; case 12: retVal += "C"; break; case 13: retVal += "D"; break; case 14: retVal += "E"; break; case 15: retVal += "F"; break; case 0: retVal += "O"; break; case 1: retVal += "I"; break; default: return "ERROR"; } } return retVal; } }; /* Q: 1272. Remove Interval */ class Solution2_t { public: vector<vector<int>> removeInterval(vector<vector<int>> &intervals, vector<int> &toBeRemoved) { } }; /* Q: 1273. Delete Tree Nodes */ class Solution3_t { public: int deleteTreeNodes(int nodes, vector<int> &parent, vector<int> &value) { } }; /* Q: 1274. Number of Ships in a Rectangle */ /** * // This is Sea's API interface. * // You should not implement it, or speculate about its implementation * class Sea { * public: * bool hasShips(vector<int> topRight, vector<int> bottomLeft); * }; */ class Solution4_t { public: int countShips(Sea sea, vector<int> topRight, vector<int> bottomLeft) { } };
18.488722
96
0.46645
bvbasavaraju
656f03be2c41f33f631981698d9900f2099aa36a
533
cpp
C++
src/main.cpp
huffman/StackManagerQt
5d80db97bb814a0671a2e0c8693c5ec5cc3968f9
[ "Apache-2.0" ]
null
null
null
src/main.cpp
huffman/StackManagerQt
5d80db97bb814a0671a2e0c8693c5ec5cc3968f9
[ "Apache-2.0" ]
null
null
null
src/main.cpp
huffman/StackManagerQt
5d80db97bb814a0671a2e0c8693c5ec5cc3968f9
[ "Apache-2.0" ]
null
null
null
// // main.cpp // StackManagerQt/src // // Created by Mohammed Nafees on 06/27/14. // Copyright (c) 2014 High Fidelity. All rights reserved. // #include <QApplication> #include "AppDelegate.h" int main(int argc, char* argv[]) { QApplication app(argc, argv); QApplication::setApplicationName("Stack Manager"); QApplication::setOrganizationName("High Fidelity"); QApplication::setOrganizationDomain("io.highfidelity.StackManager"); AppDelegate appDelegate; appDelegate.show(); return app.exec(); }
22.208333
72
0.703565
huffman
656f07b57b021a7a8d40016dd8b4c051b78990dd
2,185
cpp
C++
problems/codeforces/1286/b-numbers-on-tree/code.cpp
brunodccarvalho/competitive
4177c439174fbe749293b9da3445ce7303bd23c2
[ "MIT" ]
7
2020-10-15T22:37:10.000Z
2022-02-26T17:23:49.000Z
problems/codeforces/1286/b-numbers-on-tree/code.cpp
brunodccarvalho/competitive
4177c439174fbe749293b9da3445ce7303bd23c2
[ "MIT" ]
null
null
null
problems/codeforces/1286/b-numbers-on-tree/code.cpp
brunodccarvalho/competitive
4177c439174fbe749293b9da3445ce7303bd23c2
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #ifdef LOCAL #include "code/formatting.hpp" #else #define debug(...) (void)0 #endif using namespace std; template <typename Fun> class y_combinator_result { Fun fun_; public: template <typename T> explicit y_combinator_result(T&& fun) : fun_(std::forward<T>(fun)) {} template <typename... Args> decltype(auto) operator()(Args&&... args) { return fun_(std::ref(*this), std::forward<Args>(args)...); } }; template <typename Fun> auto y_combinator(Fun&& fun) { return y_combinator_result<std::decay_t<Fun>>(std::forward<Fun>(fun)); } int main() { ios::sync_with_stdio(false), cin.tie(nullptr); int N; cin >> N; vector<int> parent(N + 1); vector<vector<int>> children(N + 1); vector<int> c(N + 1); for (int i = 1; i <= N; i++) { cin >> parent[i] >> c[i]; children[parent[i]].push_back(i); } int root = children[0][0]; vector<int> subtree(N + 1); y_combinator([&](auto self, int u) -> void { subtree[u] = 1; for (int v : children[u]) { self(v); subtree[u] += subtree[v]; } })(root); for (int i = 1; i <= N; i++) { subtree[i] -= c[i] + 1; } vector<bool> vis(N + 1); vector<int> val(N + 1); int count_visited = 0; int current_value = N; auto dfs = y_combinator([&](auto self, int u) -> int { if (subtree[u] == 0 && !vis[u]) { vis[u] = true; val[u] = current_value; return 1; } else { for (int v : children[u]) { if (self(v)) { subtree[u]--; return 1; } } return 0; } }); while (count_visited < N) { int increment = dfs(root); if (increment == 0) { break; } else { count_visited += increment; current_value--; } } if (count_visited == N) { cout << "YES\n"; for (int i = 1; i <= N; i++) { cout << val[i] << " \n"[i == N]; } } else { cout << "NO\n"; } return 0; }
22.760417
74
0.473227
brunodccarvalho
65760d71a043bc74cd989c0bb75750197972ff2f
1,587
hpp
C++
rabbit/Array.hpp
atria-soft/rabbit
685dd2bca8c3ad439e9bd84cfe08f85aa20ef81e
[ "MIT" ]
null
null
null
rabbit/Array.hpp
atria-soft/rabbit
685dd2bca8c3ad439e9bd84cfe08f85aa20ef81e
[ "MIT" ]
null
null
null
rabbit/Array.hpp
atria-soft/rabbit
685dd2bca8c3ad439e9bd84cfe08f85aa20ef81e
[ "MIT" ]
null
null
null
/** * @author Alberto DEMICHELIS * @author Edouard DUPIN * @copyright 2018, Edouard DUPIN, all right reserved * @copyright 2003-2017, Alberto DEMICHELIS, all right reserved * @license MPL-2 (see license file) */ #pragma once #include <rabbit/RefCounted.hpp> #include <rabbit/ObjectPtr.hpp> #include <etk/Vector.hpp> namespace rabbit { class SharedState; class Array : public rabbit::RefCounted { private: Array(rabbit::SharedState* _ss, int64_t _nsize); ~Array(); public: // TODO : remove this ETK_ALLOC can do it natively ... static Array* create(rabbit::SharedState* _ss, int64_t _ninitialsize); void finalize(); bool get(const int64_t _nidx, rabbit::ObjectPtr& _val) const; bool set(const int64_t _nidx,const rabbit::ObjectPtr& _val) const; int64_t next(const rabbit::ObjectPtr& _refpos, rabbit::ObjectPtr& _outkey, rabbit::ObjectPtr& _outval); Array* clone() const; int64_t size() const; void resize(int64_t _size); void resize(int64_t _size, rabbit::ObjectPtr& _fill); void reserve(int64_t _size); void append(const rabbit::Object& _o); void extend(const Array* _a); rabbit::ObjectPtr &top(); void pop(); bool insert(int64_t _idx,const rabbit::Object& _val); void shrinkIfNeeded(); bool remove(int64_t _idx); void release(); rabbit::ObjectPtr& operator[] (const size_t _pos); const rabbit::ObjectPtr& operator[] (const size_t _pos) const; private: mutable etk::Vector<rabbit::ObjectPtr> m_data; }; }
29.943396
69
0.669187
atria-soft
6576d83882ba429861ee9ffcefc5817c9711e71b
1,873
cpp
C++
libgramtools/tests/prg/test_make_data_structures.cpp
bricoletc/gramtools
1ce06178b7b26f42d72e47d3d7b8a7a606e6f256
[ "MIT" ]
null
null
null
libgramtools/tests/prg/test_make_data_structures.cpp
bricoletc/gramtools
1ce06178b7b26f42d72e47d3d7b8a7a606e6f256
[ "MIT" ]
null
null
null
libgramtools/tests/prg/test_make_data_structures.cpp
bricoletc/gramtools
1ce06178b7b26f42d72e47d3d7b8a7a606e6f256
[ "MIT" ]
null
null
null
#include "gtest/gtest.h" #include "prg/make_data_structures.hpp" #include "submod_resources.hpp" using namespace gram::submods; TEST(GetNumVarSites, NoSites) { auto prg_raw = encode_prg("c"); auto prg_info = generate_prg_info(prg_raw); auto result = prg_info.num_variant_sites; uint64_t expected = 0; EXPECT_EQ(result, expected); } TEST(GetNumVarSites, UnNestedPrgString) { auto prg_raw = encode_prg("a5g6t6cccc11g12tttt12"); auto prg_info = generate_prg_info(prg_raw); auto result = prg_info.num_variant_sites; auto expected = 2; EXPECT_EQ(result, expected); } TEST(GetNumVarSites, Nested_PrgString) { auto prg_raw = prg_string_to_ints("[[A,C,G]A,T]T[,C][GA,CT]"); auto prg_info = generate_prg_info(prg_raw); auto result = prg_info.num_variant_sites; uint64_t expected = 4; EXPECT_EQ(result, expected); } TEST(BuildChildMap, GivenParentalMap_CorrectChildMap) { // Site 5 has two sites nested in haplogroup 1, and one in haplogroup 2. // Note: parental_map / quasimap stores allele haplogroups as 1-based, // but child_map moves them to 0-based (consistent with infer). parental_map par_map{ {7, VariantLocus{5, FIRST_ALLELE}}, {9, VariantLocus{5, FIRST_ALLELE}}, {11, VariantLocus{5, FIRST_ALLELE + 1}}, {15, VariantLocus{13, FIRST_ALLELE + 2}}, }; auto result = build_child_map(par_map); // Sort the internal vectors to be independent from parental hash map element // ordering for (auto& entry : result) { for (auto& entry2 : entry.second) { std::sort(entry2.second.begin(), entry2.second.end()); } } child_map expected{{5, haplo_map{ {0, marker_vec{7, 9}}, {1, marker_vec{11}}, }}, {13, haplo_map{{2, marker_vec{15}}}}}; EXPECT_EQ(result, expected); }
31.216667
79
0.665777
bricoletc
6577a19c54a56c76d4937f07ad16369689f1900e
17,117
cpp
C++
engine/src/renderer/DefaultShader.cpp
targodan/gameProgramming
5c0b36bee271dca65636d0317324a2bb786613f0
[ "MIT" ]
1
2019-07-14T11:32:30.000Z
2019-07-14T11:32:30.000Z
engine/src/renderer/DefaultShader.cpp
targodan/gameProgramming
5c0b36bee271dca65636d0317324a2bb786613f0
[ "MIT" ]
null
null
null
engine/src/renderer/DefaultShader.cpp
targodan/gameProgramming
5c0b36bee271dca65636d0317324a2bb786613f0
[ "MIT" ]
null
null
null
#include "DefaultShader.h" #include "../WTFException.h" namespace engine { namespace renderer { string DefaultShader::createFlatVertexShader(vec3 color) { return "#version 330\n" "#extension GL_ARB_explicit_attrib_location : require\n" "#extension GL_ARB_separate_shader_objects : require\n" "" "layout (location = 0) in vec3 position\n;" "" "uniform mat4 modelMatrix = mat4(vec4(1,0,0,0), vec4(0,1,0,0), vec4(0,0,1,0), vec4(0,0,0,1));\n" "uniform mat4 viewMatrix;\n" "uniform mat4 projectionMatrix;\n" "" "out vec3 vertexColor;\n" "" "void main() {\n" " gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(position, 1.0f);\n" " vertexColor = vec3(" + to_string(color.x) + "," + to_string(color.y) + "," + to_string(color.z) + ");\n" "}"; } string DefaultShader::createFlatFragmentShader() { return "#version 330\n" "in vec3 vertexColor;\n" "" "out vec4 fragmentColor;\n" "" "void main() {\n" " fragmentColor = vec4(vertexColor, 1.0f);\n" "}"; } string DefaultShader::createSimpleTextureVertexShader() { return "#version 330\n" "#extension GL_ARB_explicit_attrib_location : require\n" "#extension GL_ARB_separate_shader_objects : require\n" "" "layout (location = 0) in vec3 position;\n" "layout (location = 2) in vec2 textureCoordinate;\n" "" "uniform mat4 modelMatrix = mat4(vec4(1,0,0,0), vec4(0,1,0,0), vec4(0,0,1,0), vec4(0,0,0,1));\n" "uniform mat4 viewMatrix;\n" "uniform mat4 projectionMatrix;\n" "" "out vec2 uv;\n" "" "void main() {\n" " gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(position, 1.0f);\n" " uv = textureCoordinate;\n" "}"; } string DefaultShader::createSimpleTextureFragmentShader() { return "#version 330\n" "" "in vec2 uv;\n" "" "out vec4 fragmentColor;\n" "" "uniform sampler2D diffuseTexture1;\n" "" "void main() {\n" " fragmentColor = vec4(texture(diffuseTexture1, uv));\n" "}"; } string DefaultShader::createFlatInstancingVertexShader(vec3 color) { return "#version 330\n" "#extension GL_ARB_explicit_attrib_location : require\n" "#extension GL_ARB_separate_shader_objects : require\n" "" "layout (location = 0) in vec3 position\n;" "layout (location = 1) in vec3 instancePosition\n;" "" "uniform mat4 modelMatrix = mat4(vec4(1,0,0,0), vec4(0,1,0,0), vec4(0,0,1,0), vec4(0,0,0,1));\n" "uniform mat4 viewMatrix;\n" "uniform mat4 projectionMatrix;\n" "" "out vec3 vertexColor;\n" "" "void main() {\n" " vec4 positionView = viewMatrix * modelMatrix * vec4(instancePosition, 1.0f)\n;" " positionView.xyz += position\n;" " gl_Position = projectionMatrix * positionView;\n" " vertexColor = vec3(" + to_string(color.x) + "," + to_string(color.y) + "," + to_string(color.z) + ");\n" "}"; } string DefaultShader::createFlatInstancingFragmentShader() { return "#version 330\n" "in vec3 vertexColor;\n" "" "out vec4 fragmentColor;\n" "" "void main() {\n" " fragmentColor = vec4(vertexColor, 1.0f);\n" "}"; } string DefaultShader::createLightingVertexShader(bool normalMapping) { /* * Important todo: get viewPos and lightPos as uniforms in VERTEX-SHADER * and transform them with the inverse TBN (= transposed TBN) into * tangent space -> way faster than doing the other way around in * fragment-shader */ string inputTangents = ""; string outputTBN = ""; string calcTBN = ""; if(normalMapping) { inputTangents = "layout (location = 3) in vec3 tangent;\n" "layout (location = 4) in vec3 bitangent;\n" "\n"; outputTBN = "out mat3 TBN;\n"; calcTBN = "vec3 T = normalize(vec3(modelViewMatrix * vec4(tangent, 0.0)));\n" "vec3 B = normalize(vec3(modelViewMatrix * vec4(bitangent, 0.0)));\n" "vec3 N = normalize(vec3(modelViewMatrix * vec4(normal, 0.0)));\n" "TBN = mat3(T, B, N);\n"; } return "#version 330\n" "#extension GL_ARB_explicit_attrib_location : require\n" "#extension GL_ARB_separate_shader_objects : require\n" "" "layout (location = 0) in vec3 position;\n" "layout (location = 1) in vec3 normal;\n" "layout (location = 2) in vec2 textureCoordinates;\n" + inputTangents + "\n" "uniform mat4 modelMatrix = mat4(vec4(1,0,0,0), vec4(0,1,0,0), vec4(0,0,1,0), vec4(0,0,0,1));\n" "uniform mat4 viewMatrix;\n" "uniform mat4 projectionMatrix;\n" "\n" "out vec3 fragPosition;\n" "out vec3 fragNormal;\n" "out vec2 uv;\n" "out mat4 oModelViewMatrix;\n" + outputTBN + "" "void main() {\n" " mat4 modelViewMatrix = viewMatrix * modelMatrix;\n" "" " fragPosition = vec3(modelViewMatrix * vec4(position, 1.0f));\n" " fragNormal = vec3(inverse(transpose(modelViewMatrix)) * vec4(normal, 0.f));\n" " uv = textureCoordinates;\n" "" " gl_Position = projectionMatrix * vec4(fragPosition, 1.0f);\n" "" " oModelViewMatrix = modelViewMatrix;\n" + calcTBN + "}\n"; } // Formulae closely oriented on Basic Techniques in Computer Graphics & www.learnopengl.com string DefaultShader::createLightingFragmentShader(unsigned int nPointLights, bool directionalLight, int textures, bool normalMapping) { if(nPointLights == 0 && !directionalLight) { throw WTFException("Cannot create lighting fragment shader for 0 light sources!"); } string inTBN = ""; string getNormal = ""; string normalInput = ""; if(normalMapping) { inTBN = "in mat3 TBN;\n"; getNormal = " vec3 unitNorm = normalize(TBN * normalize((texture(normalTexture1, uv).rgb)*2.0 - 1.0));\n"; normalInput = "uniform sampler2D normalTexture1;\n"; } else { getNormal = " vec3 unitNorm = normalize(fragNormal);\n"; normalInput = "in vec3 fragNormal;\n"; } bool useDiffuseTexture = (textures & TextureType::DIFFUSE) != 0; bool useSpecularTexture = (textures & TextureType::SPECULAR) != 0; string diffuseValue = ""; string diffuseInput = "uniform "; if(useDiffuseTexture) { diffuseInput += "sampler2D diffuseTexture1;\n"; diffuseValue = "texture(diffuseTexture1, uv).rgb"; } else { diffuseInput += "vec3 diffuseColor;\n"; diffuseValue = "diffuseColor"; } string specularValue = ""; string specularInput = "uniform "; if(useSpecularTexture) { specularInput += "sampler2D specularTexture1;\n"; specularValue = "texture(specularTexture1, uv).rgb"; } else { specularInput += "vec3 specularColor;\n"; specularValue = "specularColor"; } string pointLightInput = ""; if(nPointLights>0) { pointLightInput = "uniform PointLight pointLightSources[" + std::to_string(nPointLights) + "];\n"; } string directionalLightInput = ""; if(directionalLight) { directionalLightInput = "uniform DirectionalLight directionalLight;\n"; } string directionalLightStruct = ""; if(directionalLight) { directionalLightStruct = "struct DirectionalLight{\n" " vec3 direction;\n" "" " vec3 ambient;\n" " vec3 specular;\n" " vec3 diffuse;\n" "};\n"; } string pointLightStruct = ""; if(nPointLights > 0) { pointLightStruct = "struct PointLight{\n" " vec3 position;\n" "" " vec3 ambient;\n" " vec3 specular;\n" " vec3 diffuse;\n" "" " float linAttenuation;\n" " float quadAttenuation;\n" "};\n"; } string calculateDirectionalLight = ""; if(directionalLight) { calculateDirectionalLight= "vec3 calculateDirectionalLight(DirectionalLight light, vec3 unitNormal, vec3 unitViewDirection){\n" " vec3 unitLightDirection = normalize(-light.direction);\n" "" " vec3 ambientColor = light.ambient * " + diffuseValue + ";\n" " vec3 diffuseColor = light.diffuse * calcDiffuseTerm(unitNormal, unitLightDirection) * " + diffuseValue + ";\n" " vec3 specularColor = light.specular * calcSpecularTerm(unitNormal, unitLightDirection, unitViewDirection) * " + specularValue + ";\n" " return ambientColor + diffuseColor + specularColor;\n" "}\n"; } string calculatePointLight = ""; if(nPointLights > 0) { calculatePointLight = "vec3 calculatePointLight(PointLight light, vec3 unitNormal, vec3 unitViewDirection){\n" " vec3 unitLightDirection = normalize(vec3(oModelViewMatrix * vec4(light.position, 1.f)) - fragPosition);\n" "" " vec3 ambientColor = light.ambient * " + diffuseValue + ";\n" " vec3 diffuseColor = light.diffuse * calcDiffuseTerm(unitNormal, unitLightDirection) * " + diffuseValue + ";\n" " vec3 specularColor = light.specular * calcSpecularTerm(unitNormal, unitLightDirection, unitViewDirection) * " + specularValue + ";\n" " return ambientColor + calcAttenuationFactor(length(fragPosition - vec3(oModelViewMatrix * vec4(light.position, 1.f))), light.linAttenuation, light.quadAttenuation) * (diffuseColor + specularColor);\n" " // return unitNormal;\n" " // return " +diffuseValue+ ";\n" "}\n"; } string main = "void main() {\n" + getNormal + " vec3 unitViewingDir = normalize(-fragPosition);\n" "\n"; if(directionalLight) { main += " vec3 color = calculateDirectionalLight(directionalLight, unitNorm, unitViewingDir);\n"; } else { main += " vec3 color = vec3(0.f, 0.f, 0.f);\n"; } main += " for(int i = 0; i < " + std::to_string(nPointLights) + "; i++)\n" " color += calculatePointLight(pointLightSources[i], unitNorm, unitViewingDir);\n" "\n" " fragmentColor = vec4(color, 1.0f);\n" "}\n"; return "#version 330\n" "" + pointLightStruct + directionalLightStruct + "" "in vec3 fragPosition;\n" // in CC + normalInput + inTBN + "in vec2 uv;\n" "\n" "in mat4 oModelViewMatrix;\n" "\n" "uniform float shininess;\n" + diffuseInput + specularInput + "\n" + directionalLightInput + pointLightInput + "\n" "out vec4 fragmentColor;\n" "\n" "\n" "float calcSpecularTerm(vec3 unitNormal, vec3 unitLightDirection, vec3 unitViewDirection){\n" " vec3 halfwayDirection = normalize(unitLightDirection + unitViewDirection);\n" " return pow(max(0.0, dot(unitNormal, halfwayDirection)), shininess);\n" "}\n" "float calcDiffuseTerm(vec3 unitNormal, vec3 unitLightDirection){\n" " return max(0.0, dot(unitNormal, unitLightDirection));\n" "}\n" "float calcAttenuationFactor(float distanceLightToFrag, float linAttenuation, float quadAttenuation){\n" " return 1.0 / (1.0 + linAttenuation * distanceLightToFrag + quadAttenuation * distanceLightToFrag * distanceLightToFrag);\n" "}\n" "" + calculateDirectionalLight + calculatePointLight + main; } string DefaultShader::createTextureInstancingVertexShader() { return "#version 330\n" "#extension GL_ARB_explicit_attrib_location : require\n" "#extension GL_ARB_separate_shader_objects : require\n" "" "layout (location = 0) in vec3 position\n;" "layout (location = 1) in vec3 instancePosition\n;" "layout (location = 2) in vec2 textureCoordinate;\n" "" "uniform mat4 modelMatrix = mat4(vec4(1,0,0,0), vec4(0,1,0,0), vec4(0,0,1,0), vec4(0,0,0,1));\n" "uniform mat4 viewMatrix;\n" "uniform mat4 projectionMatrix;\n" "" "out vec2 uv;\n" "" "void main() {\n" " vec4 positionView = viewMatrix * modelMatrix * vec4(instancePosition, 1.0f)\n;" " positionView.xyz += position\n;" " gl_Position = projectionMatrix * positionView;\n" " uv = textureCoordinate;\n" "}"; } string DefaultShader::createTextureInstancingFragmentShader(float opacity) { return "#version 330\n" "in vec2 uv;\n" "" "out vec4 fragmentColor;\n" "" "uniform sampler2D diffuseTexture1;\n" "" "void main() {\n" " vec4 color = vec4(texture(diffuseTexture1, uv));\n" " color.a *= " + std::to_string(opacity) + ";" " fragmentColor = color;" "}"; } } }
48.216901
226
0.456096
targodan
657a3dbd72ca798ffa6802b2f5be1829fc1d3617
6,992
cpp
C++
src/task.cpp
tusur-coex/coex-plugin-task-skype
f5523f280ee62d67a65069a1bc2f9ad9de382dee
[ "MIT" ]
1
2016-06-17T17:58:18.000Z
2016-06-17T17:58:18.000Z
src/task.cpp
tusur-coex/coex-plugin-task-skypewin
f5523f280ee62d67a65069a1bc2f9ad9de382dee
[ "MIT" ]
5
2016-06-02T10:38:10.000Z
2016-06-18T06:16:42.000Z
src/task.cpp
forensictool/forensictool-plugin-skype
f5523f280ee62d67a65069a1bc2f9ad9de382dee
[ "MIT" ]
1
2016-06-04T05:25:46.000Z
2016-06-04T05:25:46.000Z
#include "task.h" #include "writerMessagesSkype.h" #include <QString> #include <iostream> TaskSkype::TaskSkype() { m_bDebug = false; }; QString TaskSkype::help() { return "\t--debug - viewing debug messages"; }; QString TaskSkype::name() { return "Skype"; }; QStringList TaskSkype::authors() { QStringList listAuthors; listAuthors << "Igor Polyakov"; return listAuthors; }; QString TaskSkype::description() { return "Task is search logs of Skype"; }; QString TaskSkype::license() { return "MIT License"; }; QString TaskSkype::licenseFull() { return "Look here: http://forensictool.su/#LICENSE"; }; bool TaskSkype::isSupportOS(const forensictool::ITypeOperationSystem *) { return true; }; bool TaskSkype::init(const forensictool::IConfig *pConfig){ m_pConfig = pConfig; m_bDebug = pConfig->isDebugEnabled(); return true; }; bool TaskSkype::execute() { // example usage options if (m_bDebug) { qDebug() << "===============TaskSkype================\n\n"; qDebug() << "Debug mode ON\n"; qDebug() << "InputFolder: " << m_pConfig->inputFolder() << "\n"; }; QDir dir(m_pConfig->outputFolder()); dir.mkdir("skype"); QString path = m_pConfig->inputFolder(); writerMessagesSkype skypeAccouts (m_pConfig->outputFolder() + "//skype/accounts.xml"); writerMessagesSkype skypeMessages (m_pConfig->outputFolder() + "//skype/message.xml"); writerMessagesSkype skypeContacts (m_pConfig->outputFolder() + "//skype/contacts.xml"); writerMessagesSkype skypeCalls (m_pConfig->outputFolder() + "//skype/calls.xml"); if(!skypeMessages.opened()||!skypeContacts.opened()||!skypeAccouts.opened()||!skypeCalls.opened()) { qDebug() << "Failed task :: Can't create output folder & files\n"; return false; } QRegExp skypePathLog(".*Skype.*main.db"); QDirIterator dirPath (path, QDir::Files | QDir::NoSymLinks | QDir::Hidden | QDir::System | QDir::AllEntries, QDirIterator::Subdirectories); QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", "skype_sqlite_db"); while(dirPath.hasNext()) { if (dirPath.next().contains(skypePathLog)) { QString qwerty = skypePathLog.cap(0); path = dirPath.filePath(); QFileInfo f(path); QString test = f.fileName(); if(test != "main.db") continue; if(m_bDebug) std::cout << "Found database :: " << qwerty.toStdString() << "\n"; db.setDatabaseName(path); if( !db.open() ) { if(m_bDebug) std::cout << "Not connected!";// << db.lastError() << "\n"; } if(m_bDebug) std::cout << "Connected!\n"; /*QStringList listOfTables; listOfTables << "DbMeta" << "Contacts" << "LegacyMessages" << "Calls" << "Accounts" << "Transfers" << "Voicemails" << "Chats" << "Messages" << "ContactGroups" << "Videos" << "SMSes" << "CallMembers" << "ChatMembers" << "Alerts" << "Conversations" << "Participants" << "VideoMessages";*/ QString sql = "select skypename, fullName, emails, ipcountry from Accounts;"; QSqlQuery query(db); if (query.exec(sql) != false) { while (query.next()) { QSqlRecord rec = query.record(); account = query.value(rec.indexOf("skypename")).toString(); QString fullName = query.value(rec.indexOf("fullName")).toString(); QString emails = query.value(rec.indexOf("emails")).toString(); QString ipcountry = query.value(rec.indexOf("ipcountry")).toString(); skypeAccouts.writeInfo(account,fullName,emails,ipcountry); } } else { if(m_bDebug) qDebug() << query.lastError().text(); } sql = "select skypename, fullName, birthday, gender, phone_mobile, languages, country, city from Contacts"; if (query.exec(sql) != false) { while (query.next()) { QSqlRecord rec = query.record(); QString skypename = query.value(rec.indexOf("skypename")).toString(); QString fullName = query.value(rec.indexOf("fullName")).toString(); QString birthday = query.value(rec.indexOf("birthday")).toString(); QString gender = query.value(rec.indexOf("gender")).toString(); QString phone_mobile = query.value(rec.indexOf("phone_mobile")).toString(); QString languages = query.value(rec.indexOf("languages")).toString(); QString country = query.value(rec.indexOf("country")).toString(); QString city = query.value(rec.indexOf("city")).toString(); skypeContacts.writeContacts(account, skypename,fullName,birthday,gender,phone_mobile,languages,country,city); } } else { if(m_bDebug) qDebug() << query.lastError().text(); } sql = "select author, timestamp, body_xml from Messages;"; query.exec(sql); if (query.exec(sql) != false) { while (query.next()) { QSqlRecord rec = query.record(); QString author = query.value(rec.indexOf("author")).toString(); QString timestamp = query.value(rec.indexOf("timestamp")).toString(); //QDateTime::fromTime_t(x); QString body_xml = query.value(rec.indexOf("body_xml")).toString(); skypeMessages.writeMessage(author,timestamp,body_xml); } } else { if(m_bDebug) qDebug() << query.lastError().text(); } sql = "select begin_timestamp, duration, host_identity, current_video_audience from Calls;"; query.exec(sql); if (query.exec(sql) != false) { while (query.next()) { QSqlRecord rec = query.record(); QString begin_timestamp = query.value(rec.indexOf("begin_timestamp")).toString(); QString duration = query.value(rec.indexOf("duration")).toString(); QString host_identity = query.value(rec.indexOf("host_identity")).toString(); QString current_video_audience = query.value(rec.indexOf("current_video_audience")).toString(); skypeCalls.writeCalls(begin_timestamp,duration,host_identity,current_video_audience); } } else { if(m_bDebug) qDebug() << query.lastError().text(); } } } return true; }
39.954286
143
0.555492
tusur-coex
657f62ca5883be9a309c40597cf0fb4353e7496a
2,959
cpp
C++
SchoolProject/ques-11.cpp
CodingTux/CPP_Practice
802b374546815a2d82e80949c076579ece939f92
[ "Unlicense" ]
null
null
null
SchoolProject/ques-11.cpp
CodingTux/CPP_Practice
802b374546815a2d82e80949c076579ece939f92
[ "Unlicense" ]
null
null
null
SchoolProject/ques-11.cpp
CodingTux/CPP_Practice
802b374546815a2d82e80949c076579ece939f92
[ "Unlicense" ]
null
null
null
#include <iostream> #include <stdlib.h> using namespace std; ///Please fix bugs if any DON'T THINK I'M GONNA DO IT FOR YOU GUYS... int choice; ///Global Variable...cause i'm very Lazy :p int siz; void whatToDoSelector(int arr[]); void menu(int arr[]); void binarySearch(int arr[], int num){ system("clear"); int first=0; int last=siz-1; int middle = (last + first)/2; int temp=0; while(first <= last){ if(arr[middle] < num){ first = middle-1; }else if(arr[middle] == num){ temp++; cout << "Yes this element is in this array at position: " << middle << endl; break; }else{ last = middle-1; } middle = (first + last)/2; } if(temp==0){ cout << "No element found!!!" << endl; } cout << endl << endl; cout << "Press any key to go back..."; //int tp; //cin >> tp; menu(arr); } void larEle(int arr[]){ int temp = 0; for(int i=0;i<siz;i++) { if(arr[i]>temp) temp=arr[i]; } cout << "The biggest number is: " << temp << endl; } void sortArr(int arr[]){ for(int i=0; i<siz; i++){ for(int j=0; j<siz-i; ++j){ if(arr[j] > arr[j+1]){ arr[j] ^= arr[j+1]; arr[j+1] ^= arr[j]; arr[j] ^= arr[j+1]; } } } cout << "Sorted element is: "; for(int i=0; i<siz; ++i){ cout << arr[i] << ' '; } } void sqCu(int arr[]){ } void takeInput(int arr[]){ cout << "Please Enter the size of the array: "; cin >> siz; cout << "Please enter the values in the array: " << endl; for(int i=0; i<siz; ++i){ cout << "Value of Element " << i+1 << " : "; cin >> arr[i]; } } void menu(int arr[]){ system("clear"); cout << "#####################################################################" << endl; cout << " **PLEASE SELECT ANY ONE OF THE FOLLOWING: **" << endl; cout << "--1-> FIND POSITION OF THE ELEMENT IN ARRAY." << endl; cout << "--2-> PRINT LARGEST ELEMENT OF ARRAY." << endl; cout << "--3-> SORT THE ARRAY." << endl; cout << "--4-> PRINT SQUARE OF EVEN ELEMENT AND CUBE OF ODD ELEMENT." << endl; cout << "--5-> QUIT." << endl; cout << "#####################################################################" << endl; cout << endl << endl << endl; cout << "Please enter your choice: "; cin >> choice; whatToDoSelector(arr); } void whatToDoSelector(int arr[]){ if(choice==1){ int num; cout << "Please enter the number: "; cin >> num; binarySearch(arr, num); }else if(choice==2){ larEle(arr); }else if(choice==3){ sortArr(arr); }else if(choice==4){ sqCu(arr); }else exit(0); } int main() { int arr[50]; takeInput(arr); menu(arr); }
20.406897
92
0.459277
CodingTux
6583a350b3284ec1046e0d6f46805618f2d2afc8
1,919
hpp
C++
applications-linked-lists/sorted-merge.hpp
arsharaj/data-structures-and-algorithms
c978b1038b69156b7298f8cc278cf34c08474663
[ "MIT" ]
null
null
null
applications-linked-lists/sorted-merge.hpp
arsharaj/data-structures-and-algorithms
c978b1038b69156b7298f8cc278cf34c08474663
[ "MIT" ]
1
2021-11-12T19:24:53.000Z
2021-11-12T19:24:53.000Z
applications-linked-lists/sorted-merge.hpp
arsharaj/data-structures-and-algorithms
c978b1038b69156b7298f8cc278cf34c08474663
[ "MIT" ]
null
null
null
/* MIT License Copyright (c) 2020 Arsharaj Chauhan Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: */ // Include all the required files #include"applications-linked-list.hpp" /* My today's task is to merge two linked list into one and then return the address of the new list. If both the lists are empty then our new list would also be empty. Other cases the simple. List 1 : 1 3 5 List 2 : 2 4 6 New List : 1 2 3 4 5 6 Original lists would not be affected in any way. */ // Sorted List will be generated after merging the two lists. Node* SortedListMerge(Node* list1ptr, Node* list2ptr){ // If lists are empty. if(list1ptr==NULL && list2ptr==NULL){ return NULL; } // Pointer to the new list Node* newList = NULL; while(list1ptr!=NULL && list2ptr!=NULL){ int data; // Getting the data if(list1ptr->data < list2ptr->data){ data = list1ptr->data; list1ptr = list1ptr->next; }else{ data = list2ptr->data; list2ptr=list2ptr->next; } newList = InsertEnd(newList, data); } // Check for the remaining elements in the list 1 while(list1ptr!=NULL){ int data = list1ptr->data; newList = InsertEnd(newList,data); list1ptr = list1ptr->next; } // Check for the remaining elements in the list 1 while(list2ptr!=NULL){ int data = list2ptr->data; newList = InsertEnd(newList,data); list2ptr = list2ptr->next; } return newList; }
28.220588
97
0.661803
arsharaj
6583d8b595c01ddb5428db6fb12fb602cd4996ef
2,492
cpp
C++
Source/HTTPServer/Source/StatusCode.cpp
KamilKZ/SimpleHTTPServer
fc61717e8edcc39ad42690ecd59ee81b5948279a
[ "MIT" ]
1
2016-06-01T11:40:04.000Z
2016-06-01T11:40:04.000Z
Source/HTTPServer/Source/StatusCode.cpp
KamilKZ/SimpleHTTPServer
fc61717e8edcc39ad42690ecd59ee81b5948279a
[ "MIT" ]
null
null
null
Source/HTTPServer/Source/StatusCode.cpp
KamilKZ/SimpleHTTPServer
fc61717e8edcc39ad42690ecd59ee81b5948279a
[ "MIT" ]
null
null
null
#include <HTTPServer/StatusCode.hpp> namespace HTTP { namespace StatusCode { API_EXPORT const StatusCode Continue(100, "Continue", "You should've be seeing this"); API_EXPORT const StatusCode SwitchingProtocols(101, "Switching Protocols", "You should've be seeing this"); API_EXPORT const StatusCode OK(200, "OK", "You should've be seeing this"); API_EXPORT const StatusCode Created(201, "Created", "You should've be seeing this"); API_EXPORT const StatusCode Accepted(202, "Accepted", "You should've be seeing this"); API_EXPORT const StatusCode NoContent(203, "No Content", "You should've be seeing this"); API_EXPORT const StatusCode ResetContent(204, "Reset Content", "You should've be seeing this"); API_EXPORT const StatusCode PartialContent(205, "PartialContent", "You should've be seeing this"); API_EXPORT const StatusCode MultipleChoices(300, "Multiple Choice", "Multiple choices exist"); //No shit sherlock API_EXPORT const StatusCode MovedPermanently(301, "Moved Permanantly", "The website has been moved to a new location"); API_EXPORT const StatusCode MovedTemporarily(302, "Moved Temporarily", "Moved Temporarily"); API_EXPORT const StatusCode NotModified(304, "Not Modified", "What?"); API_EXPORT const StatusCode BadRequest(400, "Bad Request", "The client request could not be understood by the server, it may be malformed"); API_EXPORT const StatusCode Unauthorized(401, "Unauthorized", "You do not have access to the requested resource"); API_EXPORT const StatusCode Forbidden(402, "Forbidden", "Access to this resource has been disallowed"); API_EXPORT const StatusCode NotFound(404, "Not Found", "The requested resource could not be located on the server"); API_EXPORT const StatusCode RangeNotSatisfiable(407, "Range Not Satisfiable", "TODO: Document this"); API_EXPORT const StatusCode InternalServerError(500, "Internal Server Error", "The server could not complete the request"); API_EXPORT const StatusCode NotImplemented(501, "Method Not Implemented", "The requested HTTP method is not available on this server"); API_EXPORT const StatusCode BadGateway(502, "Bad Gateway", "Bad Gateway"); API_EXPORT const StatusCode ServiceNotAvailable(503, "Service Not Available", "Service Not Available"); API_EXPORT const StatusCode GatewayTimeout(504, "Gateway Timeout", "The gateway has timed out"); API_EXPORT const StatusCode VersionNotSupported(505, "Version Not Supported", "The client version is not supported"); } }
71.2
142
0.774478
KamilKZ
6585b968f34f028bc1efd61dfa55d7ecdc8031c5
3,388
cpp
C++
#98_validate-binary-search-tree/validate-binary-search-tree.cpp
o-oppang/lets-solve-algorithm
9983a112736ce48bbd309a9af16d1fd68b9420da
[ "MIT" ]
null
null
null
#98_validate-binary-search-tree/validate-binary-search-tree.cpp
o-oppang/lets-solve-algorithm
9983a112736ce48bbd309a9af16d1fd68b9420da
[ "MIT" ]
null
null
null
#98_validate-binary-search-tree/validate-binary-search-tree.cpp
o-oppang/lets-solve-algorithm
9983a112736ce48bbd309a9af16d1fd68b9420da
[ "MIT" ]
null
null
null
/** * 98. Validate Binary Search Tree ( Medium ) * Given a binary tree, determine if it is a valid binary search tree (BST). * * Assume a BST is defined as follows: * * The left subtree of a node contains only nodes with keys less than the node's key. * The right subtree of a node contains only nodes with keys greater than the node's key. * Both the left and right subtrees must also be binary search trees. * ss * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: bool isValidBST(TreeNode* root) { auto info = getNodeInfo(root); return info.valid; } private: struct NodeInfo { int min = INT_MAX; int max = INT_MIN; bool valid = true; }; NodeInfo getNodeInfo( TreeNode* root ) { if( root == nullptr ) return NodeInfo(); auto left = getNodeInfo( root->left ); auto right = getNodeInfo( root->right ); if( left.valid && right.valid ) { bool valid = ((root->left != nullptr) ? (left.max < root->val) : true) && //Add null check for case [2147483647](INT_MAX) ((root->right != nullptr) ? (right.min > root->val) : true); return { min( root->val, min(left.min, right.min) ), max(root->val, max(left.max, right.max) ), valid }; } else return { 0, 0, false }; } }; // Runtime: 8 ms, faster than 99.46% of C++ online submissions for Validate Binary Search Tree. // Memory Usage: 22.3 MB, less than 90.55% of C++ online submissions for Validate Binary Search Tree. class Solution { public: bool isValidBST(TreeNode* root) { return isValidBST(root, NULL, NULL); } bool isValidBST(TreeNode* root, TreeNode* minNode, TreeNode* maxNode) { if(!root) return true; if(minNode && root->val <= minNode->val || maxNode && root->val >= maxNode->val) return false; return isValidBST(root->left, minNode, root) && isValidBST(root->right, root, maxNode); } }; // Runtime: 12 ms, faster than 95.50% of C++ online submissions for Validate Binary Search Tree. // Memory Usage: 22.1 MB, less than 90.55% of C++ online submissions for Validate Binary Search Tree. /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { private: bool validIterative(TreeNode* root) { auto threshold = LONG_MIN; stack<TreeNode*> st; while (root || !st.empty()) { while (root) { st.push(root); root = root->left; } root = st.top(); st.pop(); if (root->val <= threshold) { // threshold 왼쪽 값들 중 가장 큰 값 return false; } threshold = root->val; root = root->right; } return true; } public: bool isValidBST(TreeNode* root) { return validIterative(root); } };
31.37037
134
0.603896
o-oppang
658ef48fe3ef235b4f1e7a0c9b05775447292bac
2,116
cpp
C++
solutions/160-E-Intersection-of-Two-Linked-Lists/main.cpp
ARW2705/leet-code-solutions
fa551e5b15f5340e5be3b832db39638bcbf0dc78
[ "MIT" ]
null
null
null
solutions/160-E-Intersection-of-Two-Linked-Lists/main.cpp
ARW2705/leet-code-solutions
fa551e5b15f5340e5be3b832db39638bcbf0dc78
[ "MIT" ]
null
null
null
solutions/160-E-Intersection-of-Two-Linked-Lists/main.cpp
ARW2705/leet-code-solutions
fa551e5b15f5340e5be3b832db39638bcbf0dc78
[ "MIT" ]
null
null
null
#include <iostream> #include <stack> #include "../../utilities/singly-linked-node.hpp" #include "../../utilities/print-success.cpp" std::stack<ListNode*> getStack(ListNode* node) { std::stack<ListNode*> stack; while (node) { stack.push(node); node = node->next; } return stack; } ListNode* getIntersectionNode(ListNode* headA, ListNode* headB) { std::stack<ListNode*> stackA = getStack(headA); std::stack<ListNode*> stackB = getStack(headB); ListNode* nodeA; ListNode* nodeB; while (!stackA.empty() && !stackB.empty()) { nodeA = stackA.top(); stackA.pop(); nodeB = stackB.top(); stackB.pop(); if (nodeA != nodeB) { return nodeA->next; } } return nodeA == nodeB ? nodeA : nullptr; } int main() { ListNode* c8 = new ListNode(8); ListNode* c4 = new ListNode(4); ListNode* c5 = new ListNode(5); c8->next = c4; c4->next = c5; ListNode* a4 = new ListNode(4); ListNode* a1 = new ListNode(1); a4->next = a1; a1->next = c8; ListNode* b5 = new ListNode(5); ListNode* b6 = new ListNode(6); ListNode* b1 = new ListNode(1); b5->next = b6; b6->next = b1; b1->next = c8; ListNode* r1 = getIntersectionNode(a4, b5); printSuccess(r1 == c8); /*------------*/ ListNode* c4b = new ListNode(4); ListNode* c2b = new ListNode(2); c2b->next = c4b; ListNode* a1bb = new ListNode(1); ListNode* a9b = new ListNode(9); ListNode* a1ba = new ListNode(1); a1ba->next = a9b; a9b->next = a1bb; a1bb->next = c2b; ListNode* b3b = new ListNode(3); b3b->next = c2b; ListNode* r2 = getIntersectionNode(a1ba, b3b); printSuccess(r2 == c2b); /*------------*/ ListNode* a4c = new ListNode(4); ListNode* a6c = new ListNode(6); ListNode* a2c = new ListNode(2); a2c->next = a6c; a6c->next = a4c; ListNode* b5c = new ListNode(5); ListNode* b1c = new ListNode(1); b1c->next = b5c; ListNode* r3 = getIntersectionNode(a2c, b1c); printSuccess(r3 == nullptr); /*------------*/ ListNode* a1d = new ListNode(1); ListNode* r4 = getIntersectionNode(a1d, a1d); printSuccess(r4 == a1d); return 0; }
21.591837
65
0.609168
ARW2705
6591652da513b7286f0fee88d222e5f2d6ddc2ca
288
cpp
C++
p/5k/5733/main.cpp
josedelinux/luogu
f9ce86b8623224512aa3f9e1eecc45d3c89c74e4
[ "MIT" ]
null
null
null
p/5k/5733/main.cpp
josedelinux/luogu
f9ce86b8623224512aa3f9e1eecc45d3c89c74e4
[ "MIT" ]
null
null
null
p/5k/5733/main.cpp
josedelinux/luogu
f9ce86b8623224512aa3f9e1eecc45d3c89c74e4
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { char str[105]; scanf("%s", str); int n = strlen(str); for (int i = 0; i < n; i++) { if (isalpha(str[i])) { putchar(toupper(str[i])); } else { putchar(str[i]); } } putchar('\n'); return 0; }
16
31
0.5
josedelinux
6597fedfb754eae35e903246240d6cadb5b2117d
762
cpp
C++
Common/Packets/CGUseGem.cpp
hackerlank/SourceCode
b702c9e0a9ca5d86933f3c827abb02a18ffc9a59
[ "MIT" ]
4
2021-07-31T13:56:01.000Z
2021-11-13T02:55:10.000Z
Common/Packets/CGUseGem.cpp
shacojx/SourceCodeGameTLBB
e3cea615b06761c2098a05427a5f41c236b71bf7
[ "MIT" ]
null
null
null
Common/Packets/CGUseGem.cpp
shacojx/SourceCodeGameTLBB
e3cea615b06761c2098a05427a5f41c236b71bf7
[ "MIT" ]
7
2021-08-31T14:34:23.000Z
2022-01-19T08:25:58.000Z
#include "stdafx.h" #include "CGUseGem.h" BOOL CGUseGem::Read(SocketInputStream& iStream ) { __ENTER_FUNCTION iStream.Read((CHAR*)&m_GemBagIndex,sizeof(BYTE)); iStream.Read((CHAR*)&m_EquipBagIndex,sizeof(BYTE)); iStream.Read((CHAR*)&m_Platform,sizeof(ObjID_t)); return TRUE; __LEAVE_FUNCTION return FALSE; } BOOL CGUseGem::Write(SocketOutputStream& oStream ) const { __ENTER_FUNCTION oStream.Write((CHAR*)&m_GemBagIndex,sizeof(BYTE)); oStream.Write((CHAR*)&m_EquipBagIndex,sizeof(BYTE)); oStream.Write((CHAR*)&m_Platform,sizeof(ObjID_t)); return TRUE; __LEAVE_FUNCTION return FALSE; } UINT CGUseGem::Execute(Player* pPlayer ) { __ENTER_FUNCTION return CGUseGemHandler::Execute(this,pPlayer); __LEAVE_FUNCTION return FALSE; }
17.318182
56
0.750656
hackerlank
659a4e7ecfa46554a72bb3400b8cfce1dd3f36b9
1,636
cpp
C++
revere/source/font_catalog.cpp
TroyDL/revere
541bdc2bed9db212c1b74414b24733cf39675d08
[ "BSD-3-Clause" ]
null
null
null
revere/source/font_catalog.cpp
TroyDL/revere
541bdc2bed9db212c1b74414b24733cf39675d08
[ "BSD-3-Clause" ]
null
null
null
revere/source/font_catalog.cpp
TroyDL/revere
541bdc2bed9db212c1b74414b24733cf39675d08
[ "BSD-3-Clause" ]
null
null
null
#include "font_catalog.h" #include "roboto.c" font_catalog load_fonts(ImGuiIO& io) { font_catalog f; ImFontConfig font_cfg; font_cfg.FontDataOwnedByAtlas = false; f.roboto_black = io.Fonts->AddFontFromMemoryTTF(Roboto_Black_ttf, Roboto_Black_ttf_len, 18.0, &font_cfg); f.roboto_black_italic = io.Fonts->AddFontFromMemoryTTF(Roboto_BlackItalic_ttf, Roboto_BlackItalic_ttf_len, 18.0, &font_cfg); f.roboto_bold = io.Fonts->AddFontFromMemoryTTF(Roboto_Bold_ttf, Roboto_Bold_ttf_len, 18.0, &font_cfg); f.roboto_bold_italic = io.Fonts->AddFontFromMemoryTTF(Roboto_BoldItalic_ttf, Roboto_BoldItalic_ttf_len, 18.0, &font_cfg); f.roboto_italic = io.Fonts->AddFontFromMemoryTTF(Roboto_Italic_ttf, Roboto_Italic_ttf_len, 18.0, &font_cfg); f.roboto_light = io.Fonts->AddFontFromMemoryTTF(Roboto_Light_ttf, Roboto_Light_ttf_len, 18.0, &font_cfg); f.roboto_light_italic = io.Fonts->AddFontFromMemoryTTF(Roboto_LightItalic_ttf, Roboto_LightItalic_ttf_len, 18.0, &font_cfg); f.roboto_medium = io.Fonts->AddFontFromMemoryTTF(Roboto_Medium_ttf, Roboto_Medium_ttf_len, 18.0, &font_cfg); f.roboto_medium_italic = io.Fonts->AddFontFromMemoryTTF(Roboto_MediumItalic_ttf, Roboto_MediumItalic_ttf_len, 18.0, &font_cfg); f.roboto_regular = io.Fonts->AddFontFromMemoryTTF(Roboto_Regular_ttf, Roboto_Regular_ttf_len, 18.0, &font_cfg); f.roboto_thin = io.Fonts->AddFontFromMemoryTTF(Roboto_Thin_ttf, Roboto_Thin_ttf_len, 18.0, &font_cfg); f.roboto_thin_italic = io.Fonts->AddFontFromMemoryTTF(Roboto_ThinItalic_ttf, Roboto_ThinItalic_ttf_len, 18.0, &font_cfg); return f; }
65.44
132
0.782396
TroyDL
659b14a9f7c89f748ecb533a43e5c631cbcff65d
408
hpp
C++
src/scenes/editor/toolbox/tool/pipette.hpp
Firstbober/MPS
998436b223842b089f0c048b3e7d5676a7688c67
[ "MIT" ]
9
2018-05-15T06:03:51.000Z
2022-01-30T01:23:24.000Z
src/scenes/editor/toolbox/tool/pipette.hpp
Firstbober/MPS
998436b223842b089f0c048b3e7d5676a7688c67
[ "MIT" ]
5
2018-06-28T16:48:04.000Z
2021-06-05T21:24:32.000Z
src/scenes/editor/toolbox/tool/pipette.hpp
Firstbober/MPS
998436b223842b089f0c048b3e7d5676a7688c67
[ "MIT" ]
9
2018-05-03T19:40:54.000Z
2021-06-05T17:54:32.000Z
#pragma once #include "tool.hpp" class Pipette : public Tool{ int x, y; int mouseX,mouseY; bool isMoved; float opacity; int pixel,pixel_prev; float scaleMul; public: void init(); void eventMouseMove(int x, int y); void eventMouseDown(); void eventMouseUp(); bool pushEvent(SDL_Event * evt); void update(); void render(float alpha); void select(); };
18.545455
38
0.634804
Firstbober
659df78d72b9ba1ad35ee4b91e4ad7f17b671e98
931
hpp
C++
include/InfoBar.hpp
jhpy1024/GameOfLife
580d91c6a5de1d28baee3029493d663f51b79ce2
[ "MIT" ]
1
2018-01-16T08:44:07.000Z
2018-01-16T08:44:07.000Z
include/InfoBar.hpp
jhpy1024/GameOfLife
580d91c6a5de1d28baee3029493d663f51b79ce2
[ "MIT" ]
null
null
null
include/InfoBar.hpp
jhpy1024/GameOfLife
580d91c6a5de1d28baee3029493d663f51b79ce2
[ "MIT" ]
null
null
null
#ifndef INFO_BAR_HPP #define INFO_BAR_HPP #include <SFML/Graphics.hpp> class InfoBar : public sf::Drawable, public sf::Transformable { public: InfoBar(const sf::Vector2f& position, const sf::Vector2f& size); void draw(sf::RenderTarget& target, sf::RenderStates states) const override; void handleMousePress(const sf::Event& event); void setGenerationNumber(int generation); void setUpdateRate(const sf::Time& rate); bool increaseRateClicked(); bool decreaseRateClicked(); private: void createBackground(); void createText(); void createSprites(); private: const sf::Vector2f SIZE; sf::Font m_Font; sf::Text m_GenerationText; sf::Text m_UpdateRateText; sf::RectangleShape m_Background; sf::Texture m_UpArrowTexture; sf::Sprite m_IncUpdateRate; sf::Sprite m_DecUpdateRate; bool m_IncreaseRateClicked; bool m_DecreaseRateClicked; }; #endif
20.688889
80
0.717508
jhpy1024
4f1e0d3b7f1edeacc659229bfeb1f2fa129b491a
569
hh
C++
Mu2eUtilities/inc/PointLinePCA_XYZ.hh
resnegfk/Offline
4ba81dad54486188fa83fea8c085438d104afbbc
[ "Apache-2.0" ]
9
2020-03-28T00:21:41.000Z
2021-12-09T20:53:26.000Z
Mu2eUtilities/inc/PointLinePCA_XYZ.hh
resnegfk/Offline
4ba81dad54486188fa83fea8c085438d104afbbc
[ "Apache-2.0" ]
684
2019-08-28T23:37:43.000Z
2022-03-31T22:47:45.000Z
Mu2eUtilities/inc/PointLinePCA_XYZ.hh
resnegfk/Offline
4ba81dad54486188fa83fea8c085438d104afbbc
[ "Apache-2.0" ]
61
2019-08-16T23:28:08.000Z
2021-12-20T08:29:48.000Z
#ifndef Mu2eUtilities_PointLinePCA_XYZ_hh #define Mu2eUtilities_PointLinePCA_XYZ_hh #include "Offline/DataProducts/inc/GenVector.hh" namespace mu2e { class PointLinePCA_XYZ{ public: PointLinePCA_XYZ( XYZVectorF const& point, XYZVectorF const& start , XYZVectorF const& end); ~PointLinePCA_XYZ(); double dca() const { return _dca;}; XYZVectorF const& pca() const { return _pca;}; private: XYZVectorF _point; XYZVectorF _start; XYZVectorF _end; double _dca; XYZVectorF _pca; }; } #endif
20.321429
55
0.680141
resnegfk
4f1f69be99d1e8ac219e52436245cde23f751932
3,584
cpp
C++
src/util/simplexnoise.cpp
therocode/featherkit
8631c9acb0fef6c5039783173ef173ec9488f53b
[ "Zlib" ]
22
2015-01-13T10:49:38.000Z
2020-12-23T15:25:59.000Z
src/util/simplexnoise.cpp
therocode/featherkit
8631c9acb0fef6c5039783173ef173ec9488f53b
[ "Zlib" ]
27
2015-01-11T03:47:27.000Z
2015-12-10T17:52:17.000Z
src/util/simplexnoise.cpp
therocode/featherkit
8631c9acb0fef6c5039783173ef173ec9488f53b
[ "Zlib" ]
7
2015-09-18T15:06:45.000Z
2020-02-19T15:12:34.000Z
#include <fea/util/simplexnoise.hpp> #include <cmath> namespace fea { float raw_noise_2d(float x, float y, const uint8_t* perm) { const float F2 = 0.5f * (std::sqrt(3.0f) - 1.0f); float s = (x + y) * F2; int32_t i = fast_floor(x + s); int32_t j = fast_floor(y + s); const float G2 = (3.0f - std::sqrt(3.0f)) / 6.0f; float t = (i + j) * G2; float x0 = x - (i - t); float y0 = y - (j - t); uint8_t i1 = 0; uint8_t j1 = 1; if(x0 > y0) { i1 = 1; j1 = 0; } float x1 = x0 - i1 + G2; float y1 = y0 - j1 + G2; float x2 = x0 - 1.0f + 2.0f * G2; float y2 = y0 - 1.0f + 2.0f * G2; uint8_t ii = i & 255; uint8_t jj = j & 255; uint8_t gi0 = perm[ii + perm[jj ] ] % 12; uint8_t gi1 = perm[ii + perm[jj + j1] + i1] % 12; uint8_t gi2 = perm[ii + perm[jj + 1 ] + 1 ] % 12; float t0 = 0.5f - x0 * x0 - y0 * y0; float t1 = 0.5f - x1 * x1 - y1 * y1; float t2 = 0.5f - x2 * x2 - y2 * y2; float n0 = (t0 < 0) ? 0.0f : t0*t0*t0*t0 * dot(grad3[gi0], x0, y0); float n1 = (t1 < 0) ? 0.0f : t1*t1*t1*t1 * dot(grad3[gi1], x1, y1); float n2 = (t2 < 0) ? 0.0f : t2*t2*t2*t2 * dot(grad3[gi2], x2, y2); return 70.0f * (n0 + n1 + n2); } float raw_noise_3d(float x, float y, float z, const uint8_t* perm) { constexpr float F3 = 1.0f / 3.0f; float s = (x + y + z) * F3; float i = fast_floor(x + s); float j = fast_floor(y + s); float k = fast_floor(z + s); constexpr float G3 = 1.0f / 6.0f; float t = (i + j + k) * G3; float x0 = x - (i - t); float y0 = y - (j - t); float z0 = z - (k - t); uint8_t i1 = 0, j1 = 1, k1 = 0; uint8_t i2 = 1, j2 = 1, k2 = 0; if(x0 >= y0) { if(y0 >= z0) { i1 = 1; j1 = 0; k1 = 0; i2 = 1; j2 = 1; k2 = 0; } else if(x0 >= z0) { i1 = 1; j1 = 0; k1 = 0; i2 = 1; j2 = 0; k2 = 1; } else { i1 = 0; j1 = 0; k1 = 1; i2 = 1; j2 = 0; k2 = 1; } } else { if(y0 < z0) { i1 = 0; j1 = 0; k1 = 1; i2 = 0; j2 = 1; k2 = 1; } else if(x0 < z0) { i1 = 0; j1 = 1; k1 = 0; i2 = 0; j2 = 1; k2 = 1; } } float x1 = x0 - i1 + G3; float y1 = y0 - j1 + G3; float z1 = z0 - k1 + G3; float x2 = x0 - i2 + G3 * 2.0f; float y2 = y0 - j2 + G3 * 2.0f; float z2 = z0 - k2 + G3 * 2.0f; float x3 = x0 - 1.0f + G3 * 3.0f; float y3 = y0 - 1.0f + G3 * 3.0f; float z3 = z0 - 1.0f + G3 * 3.0f; uint8_t ii = int32_t(i); uint8_t jj = int32_t(j); uint8_t kk = int32_t(k); uint8_t gi0 = perm[ii + perm[jj + perm[kk ] ] ] % 12; uint8_t gi1 = perm[ii + perm[jj + perm[kk + k1] + j1] + i1] % 12; uint8_t gi2 = perm[ii + perm[jj + perm[kk + k2] + j2] + i2] % 12; uint8_t gi3 = perm[ii + perm[jj + perm[kk + 1 ] + 1 ] + 1 ] % 12; float t0 = 0.5f - x0 * x0 - y0 * y0 - z0 * z0; float t1 = 0.5f - x1 * x1 - y1 * y1 - z1 * z1; float t2 = 0.5f - x2 * x2 - y2 * y2 - z2 * z2; float t3 = 0.5f - x3 * x3 - y3 * y3 - z3 * z3; float n0 = (t0 < 0) ? 0.0f : t0*t0*t0*t0 * dot(grad3[gi0], x0, y0, z0); float n1 = (t1 < 0) ? 0.0f : t1*t1*t1*t1 * dot(grad3[gi1], x1, y1, z1); float n2 = (t2 < 0) ? 0.0f : t2*t2*t2*t2 * dot(grad3[gi2], x2, y2, z2); float n3 = (t3 < 0) ? 0.0f : t3*t3*t3*t3 * dot(grad3[gi3], x3, y3, z3); return 32.0f * (n0 + n1 + n2 + n3); } float dot(const int8_t* grad, float x, float y) { return grad[0] * x + grad[1] * y; } float dot(const int8_t* grad, float x, float y, float z) { return grad[0] * x + grad[1] * y + grad[2] * z; } inline int fast_floor(float x){return ((x>=0)?((int)x):((x==(int)x)?(int)x:((int)x)-1));} }
24.216216
90
0.482143
therocode
4f20ca4d28f5fbc4aa7519498cda6cfd8b34e30b
7,289
cpp
C++
src/fs.cpp
crptec/sinovate
345a81f99ec7e624e0ec244a7dbe1ebb3698c347
[ "MIT" ]
149
2021-03-21T18:04:20.000Z
2021-07-01T21:14:39.000Z
src/fs.cpp
crptec/sinovate
345a81f99ec7e624e0ec244a7dbe1ebb3698c347
[ "MIT" ]
366
2015-01-08T05:10:17.000Z
2022-03-07T02:30:03.000Z
src/fs.cpp
crptec/sinovate
345a81f99ec7e624e0ec244a7dbe1ebb3698c347
[ "MIT" ]
110
2015-01-03T17:00:15.000Z
2022-02-13T15:31:08.000Z
// Copyright (c) 2017-2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <fs.h> #ifndef WIN32 #include <cstring> #include <fcntl.h> #include <string> #include <sys/file.h> #include <sys/utsname.h> #include <unistd.h> #else #ifndef NOMINMAX #define NOMINMAX #endif #include <codecvt> #include <windows.h> #endif namespace fsbridge { FILE *fopen(const fs::path& p, const char *mode) { #ifndef WIN32 return ::fopen(p.string().c_str(), mode); #else std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>,wchar_t> utf8_cvt; return ::_wfopen(p.wstring().c_str(), utf8_cvt.from_bytes(mode).c_str()); #endif } fs::path AbsPathJoin(const fs::path& base, const fs::path& path) { assert(base.is_absolute()); return fs::absolute(path, base); } #ifndef WIN32 static std::string GetErrorReason() { return std::strerror(errno); } FileLock::FileLock(const fs::path& file) { fd = open(file.string().c_str(), O_RDWR); if (fd == -1) { reason = GetErrorReason(); } } FileLock::~FileLock() { if (fd != -1) { close(fd); } } static bool IsWSL() { struct utsname uname_data; return uname(&uname_data) == 0 && std::string(uname_data.version).find("Microsoft") != std::string::npos; } bool FileLock::TryLock() { if (fd == -1) { return false; } // Exclusive file locking is broken on WSL using fcntl (issue #18622) // This workaround can be removed once the bug on WSL is fixed static const bool is_wsl = IsWSL(); if (is_wsl) { if (flock(fd, LOCK_EX | LOCK_NB) == -1) { reason = GetErrorReason(); return false; } } else { struct flock lock; lock.l_type = F_WRLCK; lock.l_whence = SEEK_SET; lock.l_start = 0; lock.l_len = 0; if (fcntl(fd, F_SETLK, &lock) == -1) { reason = GetErrorReason(); return false; } } return true; } #else static std::string GetErrorReason() { wchar_t* err; FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), reinterpret_cast<WCHAR*>(&err), 0, nullptr); std::wstring err_str(err); LocalFree(err); return std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>>().to_bytes(err_str); } FileLock::FileLock(const fs::path& file) { hFile = CreateFileW(file.wstring().c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if (hFile == INVALID_HANDLE_VALUE) { reason = GetErrorReason(); } } FileLock::~FileLock() { if (hFile != INVALID_HANDLE_VALUE) { CloseHandle(hFile); } } bool FileLock::TryLock() { if (hFile == INVALID_HANDLE_VALUE) { return false; } _OVERLAPPED overlapped = {0}; if (!LockFileEx(hFile, LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY, 0, std::numeric_limits<DWORD>::max(), std::numeric_limits<DWORD>::max(), &overlapped)) { reason = GetErrorReason(); return false; } return true; } #endif std::string get_filesystem_error_message(const fs::filesystem_error& e) { #ifndef WIN32 return e.what(); #else // Convert from Multi Byte to utf-16 std::string mb_string(e.what()); int size = MultiByteToWideChar(CP_ACP, 0, mb_string.data(), mb_string.size(), nullptr, 0); std::wstring utf16_string(size, L'\0'); MultiByteToWideChar(CP_ACP, 0, mb_string.data(), mb_string.size(), &*utf16_string.begin(), size); // Convert from utf-16 to utf-8 return std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t>().to_bytes(utf16_string); #endif } #ifdef WIN32 #ifdef __GLIBCXX__ // reference: https://github.com/gcc-mirror/gcc/blob/gcc-7_3_0-release/libstdc%2B%2B-v3/include/std/fstream#L270 static std::string openmodeToStr(std::ios_base::openmode mode) { switch (mode & ~std::ios_base::ate) { case std::ios_base::out: case std::ios_base::out | std::ios_base::trunc: return "w"; case std::ios_base::out | std::ios_base::app: case std::ios_base::app: return "a"; case std::ios_base::in: return "r"; case std::ios_base::in | std::ios_base::out: return "r+"; case std::ios_base::in | std::ios_base::out | std::ios_base::trunc: return "w+"; case std::ios_base::in | std::ios_base::out | std::ios_base::app: case std::ios_base::in | std::ios_base::app: return "a+"; case std::ios_base::out | std::ios_base::binary: case std::ios_base::out | std::ios_base::trunc | std::ios_base::binary: return "wb"; case std::ios_base::out | std::ios_base::app | std::ios_base::binary: case std::ios_base::app | std::ios_base::binary: return "ab"; case std::ios_base::in | std::ios_base::binary: return "rb"; case std::ios_base::in | std::ios_base::out | std::ios_base::binary: return "r+b"; case std::ios_base::in | std::ios_base::out | std::ios_base::trunc | std::ios_base::binary: return "w+b"; case std::ios_base::in | std::ios_base::out | std::ios_base::app | std::ios_base::binary: case std::ios_base::in | std::ios_base::app | std::ios_base::binary: return "a+b"; default: return std::string(); } } void ifstream::open(const fs::path& p, std::ios_base::openmode mode) { close(); mode |= std::ios_base::in; m_file = fsbridge::fopen(p, openmodeToStr(mode).c_str()); if (m_file == nullptr) { return; } m_filebuf = __gnu_cxx::stdio_filebuf<char>(m_file, mode); rdbuf(&m_filebuf); if (mode & std::ios_base::ate) { seekg(0, std::ios_base::end); } } void ifstream::close() { if (m_file != nullptr) { m_filebuf.close(); fclose(m_file); } m_file = nullptr; } void ofstream::open(const fs::path& p, std::ios_base::openmode mode) { close(); mode |= std::ios_base::out; m_file = fsbridge::fopen(p, openmodeToStr(mode).c_str()); if (m_file == nullptr) { return; } m_filebuf = __gnu_cxx::stdio_filebuf<char>(m_file, mode); rdbuf(&m_filebuf); if (mode & std::ios_base::ate) { seekp(0, std::ios_base::end); } } void ofstream::close() { if (m_file != nullptr) { m_filebuf.close(); fclose(m_file); } m_file = nullptr; } #else // __GLIBCXX__ static_assert(sizeof(*fs::path().BOOST_FILESYSTEM_C_STR) == sizeof(wchar_t), "Warning: This build is using boost::filesystem ofstream and ifstream " "implementations which will fail to open paths containing multibyte " "characters. You should delete this static_assert to ignore this warning, " "or switch to a different C++ standard library like the Microsoft C++ " "Standard Library (where boost uses non-standard extensions to construct " "stream objects with wide filenames), or the GNU libstdc++ library (where " "a more complicated workaround has been implemented above)."); #endif // __GLIBCXX__ #endif // WIN32 } // fsbridge
28.251938
168
0.642475
crptec
4f2233693305aec1333e790bfa68af5d3d0cae2e
13,891
hpp
C++
saga/impl/packages/namespace/namespace_entry_cpi.hpp
saga-project/saga-cpp
7376c0de0529e7d7b80cf08b94ec484c2e56d38e
[ "BSL-1.0" ]
5
2015-09-15T16:24:14.000Z
2021-08-12T11:05:55.000Z
saga/impl/packages/namespace/namespace_entry_cpi.hpp
saga-project/saga-cpp
7376c0de0529e7d7b80cf08b94ec484c2e56d38e
[ "BSL-1.0" ]
null
null
null
saga/impl/packages/namespace/namespace_entry_cpi.hpp
saga-project/saga-cpp
7376c0de0529e7d7b80cf08b94ec484c2e56d38e
[ "BSL-1.0" ]
3
2016-11-17T04:38:38.000Z
2021-04-10T17:23:52.000Z
#ifndef SAGA_IMPL_PACKAGES_DATA_NAMESPACE_NAMESPACEENTRY_CPI_HPP #define SAGA_IMPL_PACKAGES_DATA_NAMESPACE_NAMESPACEENTRY_CPI_HPP #if defined(__WAVE__) && defined(SAGA_CREATE_PREPROCESSED_FILES) #pragma wave option(preserve: 2, line: 0, output: "preprocessed/namespace_entry_cpi.hpp") #endif // Copyright (c) 2005-2009 Hartmut Kaiser // Copyright (c) 2005-2007 Andre Merzky (andre@merzky.net) // Copyright (c) 2005 Michel Zandstra [michelzandstra@gmail.com] // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #if defined(__WAVE__) && defined(SAGA_CREATE_PREPROCESSED_FILES) #pragma wave option(output: null) #endif #include <string> #include <saga/saga/util.hpp> #include <saga/saga/types.hpp> #include <saga/saga/exception.hpp> #include <saga/saga/adaptors/instance_data.hpp> #include <saga/saga/adaptors/packages/namespace_entry_cpi_instance_data.hpp> #include <saga/saga/adaptors/permissions_cpi.hpp> #include <saga/impl/call.hpp> #include <saga/impl/config.hpp> #include <saga/impl/engine/register_members.hpp> #ifdef SAGA_DEBUG #include <saga/impl/packages/namespace/preprocessed/namespace_entry_cpi.hpp> #else #if defined(__WAVE__) && defined(SAGA_CREATE_PREPROCESSED_FILES) #pragma wave option(output: "preprocessed/namespace_entry_cpi.hpp") #endif /////////////////////////////////////////////////////////////////////////////// namespace saga { namespace impl { namespace v1_0 { /////////////////////////////////////////////////////////////////////////// class namespace_entry_cpi : public permissions_cpi { public: namespace_entry_cpi (proxy * p, cpi_info const& info, TR1::shared_ptr <saga::adaptor> adaptor, cpi::flags flags) : permissions_cpi (p, info, adaptor, flags) { } ~namespace_entry_cpi (void) { } cpi::type get_type() const { return cpi::NSEntry; } // basic properties: get url SAGA_CALL_CPI_DECL_VIRT_0(namespace_entry_cpi, saga::url, get_url) SAGA_CALL_CPI_DECL_VIRT_0(namespace_entry_cpi, saga::url, get_cwd) SAGA_CALL_CPI_DECL_VIRT_0(namespace_entry_cpi, saga::url, get_name) // navigation/query methods SAGA_CALL_CPI_DECL_VIRT_0(namespace_entry_cpi, saga::url, read_link) SAGA_CALL_CPI_DECL_VIRT_0(namespace_entry_cpi, bool, is_dir) SAGA_CALL_CPI_DECL_VIRT_0(namespace_entry_cpi, bool, is_entry) SAGA_CALL_CPI_DECL_VIRT_0(namespace_entry_cpi, bool, is_link) // entry management methods SAGA_CALL_CPI_DECL_VIRT_2(namespace_entry_cpi, saga::impl::void_t, copy, saga::url, int) SAGA_CALL_CPI_DECL_VIRT_2(namespace_entry_cpi, saga::impl::void_t, link, saga::url, int) SAGA_CALL_CPI_DECL_VIRT_2(namespace_entry_cpi, saga::impl::void_t, move, saga::url, int) SAGA_CALL_CPI_DECL_VIRT_1(namespace_entry_cpi, saga::impl::void_t, remove, int) SAGA_CALL_CPI_DECL_VIRT_1(namespace_entry_cpi, saga::impl::void_t, close, double) // permissions with flags SAGA_CALL_CPI_DECL_VIRT_3(namespace_entry_cpi, saga::impl::void_t, permissions_allow, std::string, int, int) SAGA_CALL_CPI_DECL_VIRT_3(namespace_entry_cpi, saga::impl::void_t, permissions_deny, std::string, int, int) }; // class namespace_entry_cpi /////////////////////////////////////////////////////////////////////////////// }}} // namespace saga::impl::v1_0 /////////////////////////////////////////////////////////////////////////////// namespace saga { namespace adaptors { namespace v1_0 { /////////////////////////////////////////////////////////////////////////////// // register namespace_entry CPI functions template <typename Derived> inline bool register_namespace_entry_functions( std::vector<saga::impl::v1_0::cpi_info>& infos, saga::impl::v1_0::cpi::maker_type maker, saga::impl::v1_0::preference_type const& prefs, saga::uuid const& cpi_uuid, saga::uuid const& adaptor_uuid, std::string const& cpi_name) { bool retval = false; saga::impl::v1_0::cpi_info info(adaptors::namespace_entry_cpi, cpi_name, maker, prefs, cpi_uuid, adaptor_uuid); SAGA_LOG(SAGA_VERBOSE_LEVEL_BLURB) << "begin register_namespace_entry_functions (" << cpi_name << "): " << adaptor_uuid.string() << ":"; typedef saga::impl::v1_0::namespace_entry_cpi base_cpi; SAGA_REGISTER_MEMBER(retval, info, base_cpi, Derived, get_url, prefs); SAGA_REGISTER_MEMBER(retval, info, base_cpi, Derived, get_cwd, prefs); SAGA_REGISTER_MEMBER(retval, info, base_cpi, Derived, get_name, prefs); SAGA_REGISTER_MEMBER(retval, info, base_cpi, Derived, close, prefs); // register ambiguous cpi functions typedef void (base_cpi::*base_sync_read_link_type)(saga::url&); typedef saga::task (base_cpi::*base_async_read_link_type)(); typedef void (Derived::*sync_read_link_type)(saga::url&); typedef saga::task (Derived::*async_read_link_type)(); SAGA_REGISTER_MEMBER_EX(retval, info, base_cpi, Derived, read_link, prefs, base_sync_read_link_type, base_async_read_link_type, sync_read_link_type, async_read_link_type); typedef void (base_cpi::*base_sync_is_dir_type)(bool&); typedef saga::task (base_cpi::*base_async_is_dir_type)(); typedef void (Derived::*sync_is_dir_type)(bool&); typedef saga::task (Derived::*async_is_dir_type)(); SAGA_REGISTER_MEMBER_EX(retval, info, base_cpi, Derived, is_dir, prefs, base_sync_is_dir_type, base_async_is_dir_type, sync_is_dir_type, async_is_dir_type); typedef void (base_cpi::*base_sync_is_entry_type)(bool&); typedef saga::task (base_cpi::*base_async_is_entry_type)(); typedef void (Derived::*sync_is_entry_type)(bool&); typedef saga::task (Derived::*async_is_entry_type)(); SAGA_REGISTER_MEMBER_EX(retval, info, base_cpi, Derived, is_entry, prefs, base_sync_is_entry_type, base_async_is_entry_type, sync_is_entry_type, async_is_entry_type); typedef void (base_cpi::*base_sync_is_link_type)(bool&); typedef saga::task (base_cpi::*base_async_is_link_type)(); typedef void (Derived::*sync_is_link_type)(bool&); typedef saga::task (Derived::*async_is_link_type)(); SAGA_REGISTER_MEMBER_EX(retval, info, base_cpi, Derived, is_link, prefs, base_sync_is_link_type, base_async_is_link_type, sync_is_link_type, async_is_link_type); typedef void (base_cpi::*base_sync_copy_type)(saga::impl::void_t&, saga::url, int); typedef saga::task (base_cpi::*base_async_copy_type)(saga::url, int); typedef void (Derived::*sync_copy_type)(saga::impl::void_t&, saga::url, int); typedef saga::task (Derived::*async_copy_type)(saga::url, int); SAGA_REGISTER_MEMBER_EX(retval, info, base_cpi, Derived, copy, prefs, base_sync_copy_type, base_async_copy_type, sync_copy_type, async_copy_type); typedef void (base_cpi::*base_sync_link_type)(saga::impl::void_t&, saga::url, int); typedef saga::task (base_cpi::*base_async_link_type)(saga::url, int); typedef void (Derived::*sync_link_type)(saga::impl::void_t&, saga::url, int); typedef saga::task (Derived::*async_link_type)(saga::url, int); SAGA_REGISTER_MEMBER_EX(retval, info, base_cpi, Derived, link, prefs, base_sync_link_type, base_async_link_type, sync_link_type, async_link_type); typedef void (base_cpi::*base_sync_move_type)(saga::impl::void_t&, saga::url, int); typedef saga::task (base_cpi::*base_async_move_type)(saga::url, int); typedef void (Derived::*sync_move_type)(saga::impl::void_t&, saga::url, int); typedef saga::task (Derived::*async_move_type)(saga::url, int); SAGA_REGISTER_MEMBER_EX(retval, info, base_cpi, Derived, move, prefs, base_sync_move_type, base_async_move_type, sync_move_type, async_move_type); typedef void (base_cpi::*base_sync_remove_type)(saga::impl::void_t&, int); typedef saga::task (base_cpi::*base_async_remove_type)(int); typedef void (Derived::*sync_remove_type)(saga::impl::void_t&, int); typedef saga::task (Derived::*async_remove_type)(int); SAGA_REGISTER_MEMBER_EX(retval, info, base_cpi, Derived, remove, prefs, base_sync_remove_type, base_async_remove_type, sync_remove_type, async_remove_type); typedef void (base_cpi::*base_sync_permissions_allow_type)(saga::impl::void_t&, std::string, int, int); typedef saga::task (base_cpi::*base_async_permissions_allow_type)(std::string, int, int); typedef void (Derived::*sync_permissions_allow_type)(saga::impl::void_t&, std::string, int, int); typedef saga::task (Derived::*async_permissions_allow_type)(std::string, int, int); SAGA_REGISTER_MEMBER_EX(retval, info, base_cpi, Derived, permissions_allow, prefs, base_sync_permissions_allow_type, base_async_permissions_allow_type, sync_permissions_allow_type, async_permissions_allow_type); typedef void (base_cpi::*base_sync_permissions_deny_type)(saga::impl::void_t&, std::string, int, int); typedef saga::task (base_cpi::*base_async_permissions_deny_type)(std::string, int, int); typedef void (Derived::*sync_permissions_deny_type)(saga::impl::void_t&, std::string, int, int); typedef saga::task (Derived::*async_permissions_deny_type)(std::string, int, int); SAGA_REGISTER_MEMBER_EX(retval, info, base_cpi, Derived, permissions_deny, prefs, base_sync_permissions_deny_type, base_async_permissions_deny_type, sync_permissions_deny_type, async_permissions_deny_type); infos.push_back(info); SAGA_LOG(SAGA_VERBOSE_LEVEL_BLURB) << "end register_namespace_entry_functions"; return retval; // is true if at least one function got registered } /////////////////////////////////////////////////////////////////////////// template <typename Derived, typename Mutex = boost::recursive_mutex> class namespace_entry_cpi : public saga::impl::v1_0::namespace_entry_cpi { protected: typedef saga::impl::v1_0::namespace_entry_cpi base_type; typedef saga::impl::proxy proxy; typedef saga::impl::v1_0::cpi cpi; typedef saga::impl::v1_0::cpi_info cpi_info; typedef saga::impl::v1_0::preference_type preference_type; typedef Mutex mutex_type; mutex_type mtx_; // secure access to cpi_instance_data public: namespace_entry_cpi (proxy* p, cpi_info const& info, TR1::shared_ptr <saga::adaptor> adaptor, cpi::flags flags) : saga::impl::v1_0::namespace_entry_cpi (p, info, adaptor, flags) { } ~namespace_entry_cpi (void) { } /////////////////////////////////////////////////////////////////////// // instance data // data associated with the API object instance, i.e. visible to all // CPI object instances associated with the API object instance // regardless of the shared library (adaptor) they are implemented in. typedef saga::adaptors::v1_0::namespace_entry_cpi_instance_data ns_instance_data; friend class saga::adaptors::instance_data<ns_instance_data>; typedef saga::adaptors::instance_data<ns_instance_data> instance_data; /////////////////////////////////////////////////////////////////////// // generic factory function static cpi* cpi_maker (proxy* p, cpi_info const& info, saga::ini::ini const& glob_ini, saga::ini::ini const& adap_ini, TR1::shared_ptr<saga::adaptor> adaptor) { return new Derived (p, info, glob_ini, adap_ini, adaptor); } /////////////////////////////////////////////////////////////////////// // register implemented functions static void register_cpi(std::vector<cpi_info>& infos, preference_type prefs, saga::uuid adaptor_uuid, std::string const& cpi_name = saga::adaptors::namespace_entry_cpi) { // register namespace_entry CPI functions saga::uuid cpi_uuid; register_namespace_entry_functions<Derived>(infos, &saga::adaptors::v1_0::namespace_entry_cpi<Derived>::cpi_maker, prefs, cpi_uuid, adaptor_uuid, cpi_name); // register attribute CPI functions register_attribute_functions<Derived>(infos, &saga::adaptors::v1_0::namespace_entry_cpi<Derived>::cpi_maker, prefs, cpi_uuid, adaptor_uuid, cpi_name); // register permissions CPI functions register_permissions_functions<Derived>(infos, &saga::adaptors::v1_0::permissions_cpi<Derived>::cpi_maker, prefs, cpi_uuid, adaptor_uuid, cpi_name); } /////////////////////////////////////////////////////////////////////// // generic up-cast of the impl pointer TR1::shared_ptr<Derived> shared_from_this() { return TR1::static_pointer_cast<Derived>( this->base_type::shared_from_this()); } }; /////////////////////////////////////////////////////////////////////////////// }}} // namespace saga::adaptors::v1_0 #if defined(__WAVE__) && defined(SAGA_CREATE_PREPROCESSED_FILES) #pragma wave option(output: null) #endif #endif // !defined(SAGA_DEBUG) #endif // SAGA_IMPL_PACKAGES_DATA_NAMESPACE_NAMESPACEENTRY_CPI_HPP
45.996689
114
0.648549
saga-project
4f22e5ea66fa010845908e3275ef065ff55c2f89
10,996
cpp
C++
src/pd/painter.cpp
mtribiere/Pixel-dungeon-CPP
ed930aaeefd1f08eed73ced928acae6e1fe34fa4
[ "MIT" ]
null
null
null
src/pd/painter.cpp
mtribiere/Pixel-dungeon-CPP
ed930aaeefd1f08eed73ced928acae6e1fe34fa4
[ "MIT" ]
null
null
null
src/pd/painter.cpp
mtribiere/Pixel-dungeon-CPP
ed930aaeefd1f08eed73ced928acae6e1fe34fa4
[ "MIT" ]
null
null
null
#include "painter.h" #include "level.h" #include "../engine/util.h" #include "room.h" #include "terrain.h" #include <algorithm> void Painter::set(Level* level, int cell, int value) { level->map[cell] = value; } void Painter::set(Level* level, int x, int y, int value) { set(level, x + y * Level::WIDTH, value); } void Painter::set(Level* level, Point p, int value) { set(level, p.x, p.y, value); } void Painter::fill(Level* level, int x, int y, int w, int h, int value) { int width = Level::WIDTH; int pos = y * width + x; for (int i = y; i < y + h; i++, pos += width) { Arrays<int>::fill(level->map, pos, pos + w, value); } } void Painter::fill(Level* level, Rect rect, int value) { int left = GameMath::RECTLeft(rect); int top = GameMath::RECTTop(rect); int width = GameMath::RECTWidth(rect); int height = GameMath::RECTHeight(rect); fill(level, left, top, width + 1, height + 1, value); } void Painter::fill(Level* level, Rect rect, int m, int value) { int left = GameMath::RECTLeft(rect); int top = GameMath::RECTTop(rect); int width = GameMath::RECTWidth(rect); int height = GameMath::RECTHeight(rect); fill(level, left + m, top + m, width + 1 - m * 2, height + 1 - m * 2, value); } void Painter::fill(Level* level, Rect rect, int l, int t, int r, int b, int value) { int left = GameMath::RECTLeft(rect); int top = GameMath::RECTTop(rect); int width = GameMath::RECTWidth(rect); int height = GameMath::RECTHeight(rect); fill(level, left + l, top + t, width + 1 - (l + r), height + 1 - (t + b), value); } Point Painter::drawInside(Level* level, Room* room, Point from, int n, int value) { int left = GameMath::RECTLeft(room->getBounds()); int top = GameMath::RECTTop(room->getBounds()); int right = GameMath::RECTRight(room->getBounds()); int bottom = GameMath::RECTBottom(room->getBounds()); Point step; if (from.x == left) { //step.set(+1, 0); step.x = 1; step.y = 0; } else if (from.x == right) { //step.set(-1, 0); step.x = -1; step.y = 0; } else if (from.y == top) { //step.set(0, +1); step.x = 0; step.y = 1; } else if (from.y == bottom) { //step.set(0, -1); step.x = 0; step.y = -1; } Point p = from; p.x += step.x; p.y += step.y; for (int i = 0; i < n; i++) { if (value != -1) { set(level, p, value); } //p.offset(step); p.x += step.x; p.y += step.y; } return p; } void EntrancePainter::paint(Level* level, Room* room) { fill(level, room->getBounds(), Terrain::WALL); fill(level, room->getBounds(), 1, Terrain::EMPTY); for (std::map<Room*, Room::Door*>::iterator itr = room->connected.begin(); itr != room->connected.end(); itr++) { itr->second->set(Room::Door::Type::REGULAR); } level->entrance = room->random(1); set(level, level->entrance, Terrain::ENTRANCE); } void ExitPainter::paint(Level* level, Room* room) { fill(level, room->getBounds(), Terrain::WALL); fill(level, room->getBounds(), 1, Terrain::EMPTY); for (std::map<Room*, Room::Door*>::iterator itr = room->connected.begin(); itr != room->connected.end(); itr++) { itr->second->set(Room::Door::Type::REGULAR); } level->exit = room->random(1); set(level, level->exit, Terrain::EXIT); } void BossExitPainter::paint(Level* level, Room* room) { Rect bound = room->getBounds(); int top = GameMath::RECTTop(bound); int left = GameMath::RECTLeft(bound); int right = GameMath::RECTRight(bound); fill(level, bound, Terrain::WALL); fill(level, bound, 1, Terrain::EMPTY); for (std::map<Room*, Room::Door*>::iterator itr = room->connected.begin(); itr != room->connected.end(); itr++) { Room::Door* door = itr->second; door->set(Room::Door::Type::REGULAR); } level->exit = top * Level::WIDTH + (left + right) / 2; set(level, level->exit, Terrain::LOCKED_EXIT); } void TunnelPainter::paint(Level* level, Room* room) { Rect bound = room->getBounds(); int top = GameMath::RECTTop(bound); int bottom = GameMath::RECTBottom(bound); int left = GameMath::RECTLeft(bound); int right = GameMath::RECTRight(bound); int floor = level->tunnelTile(); Point c = room->center(); if (room->width() > room->height() || (room->width() == room->height() && Random::Int(2) == 0)) { int from = right - 1; int to = left + 1; for (std::map<Room*, Room::Door*>::iterator itr = room->connected.begin(); itr != room->connected.end(); itr++) { Room::Door* door = itr->second; Point p = door->getPoint(); int dx = p.x; int dy = p.y; int step = dy < c.y ? +1 : -1; if (dx == left) { from = left + 1; for (int i = dy; i != c.y; i += step) { set(level, from, i, floor); } } else if (dx == right) { to = right - 1; for (int i = dy; i != c.y; i += step) { set(level, to, i, floor); } } else { if (dx < from) { from = dx; } if (dx > to) { to = dx; } for (int i = dy + step; i != c.y; i += step) { set(level, dx, i, floor); } } } for (int i = from; i <= to; i++) { set(level, i, c.y, floor); } } else { int from = bottom - 1; int to = top + 1; for (std::map<Room*, Room::Door*>::iterator itr = room->connected.begin(); itr != room->connected.end(); itr++) { Room::Door* door = itr->second; Point p = door->getPoint(); int dx = p.x; int dy = p.y; int step = dx < c.x ? +1 : -1; if (dy == top) { from = top + 1; for (int i = dx; i != c.x; i += step) { set(level, i, from, floor); } } else if (dy == bottom) { to = bottom - 1; for (int i = dx; i != c.x; i += step) { set(level, i, to, floor); } } else { if (dy < from) { from = dy; } if (dy > to) { to = dy; } for (int i = dx + step; i != c.x; i += step) { set(level, i, dy, floor); } } } for (int i = from; i <= to; i++) { set(level, c.x, i, floor); } } for (std::map<Room*, Room::Door*>::iterator itr = room->connected.begin(); itr != room->connected.end(); itr++) { Room::Door* door = itr->second; door->set(Room::Door::Type::TUNNEL); } } int PassagePainter::pasWidth; int PassagePainter::pasHeight; int PassagePainter::xy2p(Room* room, Point xy) { Rect bound = room->getBounds(); int top = GameMath::RECTTop(bound); int bottom = GameMath::RECTBottom(bound); int left = GameMath::RECTLeft(bound); int right = GameMath::RECTRight(bound); if (xy.y == top) { return (xy.x - left - 1); } else if (xy.x == right) { return (xy.y - top - 1) + pasWidth; } else if (xy.y == bottom) { return (right - xy.x - 1) + pasWidth + pasHeight; } else /*if (xy.x == room.left)*/ { if (xy.y == top + 1) { return 0; } else { return (bottom - xy.y - 1) + pasWidth * 2 + pasHeight; } } } Point PassagePainter::p2xy(Room* room, int p) { Rect bound = room->getBounds(); int top = GameMath::RECTTop(bound); int bottom = GameMath::RECTBottom(bound); int left = GameMath::RECTLeft(bound); int right = GameMath::RECTRight(bound); if (p < pasWidth) { return Point(left + 1 + p, top + 1); } else if (p < pasWidth + pasHeight) { return Point(right - 1, top + 1 + (p - pasWidth)); } else if (p < pasWidth * 2 + pasHeight) { return Point(right - 1 - (p - (pasWidth + pasHeight)), bottom - 1); } else { return Point(left + 1, bottom - 1 - (p - (pasWidth * 2 + pasHeight))); } } void PassagePainter::paint(Level* level, Room* room) { pasWidth = room->width() - 2; pasHeight = room->height() - 2; int floor = level->tunnelTile(); std::vector<int> joints; for (std::map<Room*, Room::Door*>::iterator itr = room->connected.begin(); itr != room->connected.end(); itr++) { Room::Door* door = itr->second; joints.push_back(xy2p(room, door->getPoint())); } std::sort(joints.begin(), joints.end()); int nJoints = joints.size(); int perimeter = pasWidth * 2 + pasHeight * 2; int start = 0; int maxD = joints[0] + perimeter - joints[nJoints - 1]; for (int i = 1; i < nJoints; i++) { int d = joints[i] - joints[i - 1]; if (d > maxD) { maxD = d; start = i; } } int end = (start + nJoints - 1) % nJoints; int p = joints[start]; do { set(level, p2xy(room, p), floor); p = (p + 1) % perimeter; } while (p != joints[end]); set(level, p2xy(room, p), floor); for (std::map<Room*, Room::Door*>::iterator itr = room->connected.begin(); itr != room->connected.end(); itr++) { Room::Door* door = itr->second; door->set(Room::Door::Type::TUNNEL); } } void BlacksmithPainter::paint(Level* level, Room* room) { //fill(level, room, Terrain.WALL); //fill(level, room, 1, Terrain.FIRE_TRAP); //fill(level, room, 2, Terrain.EMPTY_SP); // //for (int i = 0; i < 2; i++) { // int pos; // do { // pos = room.random(); // } while (level.map[pos] != Terrain.EMPTY_SP); // level.drop( // Generator.random(Random.oneOf( // Generator.Category.ARMOR, // Generator.Category.WEAPON // )), pos); //} // //for (Room.Door door : room.connected.values()) { // door.set(Room.Door.Type.UNLOCKED); // drawInside(level, room, door, 1, Terrain.EMPTY); //} // //Blacksmith npc = new Blacksmith(); //do { // npc.pos = room.random(1); //} while (level.heaps.get(npc.pos) != null); //level.mobs.add(npc); //Actor.occupyCell(npc); } void WeakFloorPainter::paint(Level* level, Room* room) { Rect bound = room->getBounds(); int top = GameMath::RECTTop(bound); int bottom = GameMath::RECTBottom(bound); int left = GameMath::RECTLeft(bound); int right = GameMath::RECTRight(bound); fill(level, bound, Terrain::WALL); fill(level, bound, 1, Terrain::CHASM); Room::Door* door = room->entrance(); door->set(Room::Door::Type::REGULAR); Point p = door->getPoint(); int dx = p.x; int dy = p.y; if (dx == left) { for (int i = top + 1; i < bottom; i++) { drawInside(level, room, Point(left, i), Random::IntRange(1, room->width() - 2), Terrain::EMPTY_SP); } } else if (dx == right) { for (int i = top + 1; i < bottom; i++) { drawInside(level, room, Point(right, i), Random::IntRange(1, room->width() - 2), Terrain::EMPTY_SP); } } else if (dy == top) { for (int i = left + 1; i < right; i++) { drawInside(level, room, Point(i, top), Random::IntRange(1, room->height() - 2), Terrain::EMPTY_SP); } } else if (dy == bottom) { for (int i = left + 1; i < right; i++) { drawInside(level, room, Point(i, bottom), Random::IntRange(1, room->height() - 2), Terrain::EMPTY_SP); } } }
22.813278
106
0.554292
mtribiere
4f2412604bc12d4180278b36476c278a54a5af02
15,816
cpp
C++
samples/snippets/cpp/VS_Snippets_IIS/IIS7/IHttpFileInfo/cpp/GetLastModifiedTime.cpp
mitchelsellers/iis-docs
376c5b4a1b88b807eb8dbe7c63ba7cd9c59f7429
[ "CC-BY-4.0", "MIT" ]
90
2017-06-13T19:56:04.000Z
2022-03-15T16:42:09.000Z
samples/snippets/cpp/VS_Snippets_IIS/IIS7/IHttpFileInfo/cpp/GetLastModifiedTime.cpp
mitchelsellers/iis-docs
376c5b4a1b88b807eb8dbe7c63ba7cd9c59f7429
[ "CC-BY-4.0", "MIT" ]
453
2017-05-22T18:00:05.000Z
2022-03-30T21:07:55.000Z
samples/snippets/cpp/VS_Snippets_IIS/IIS7/IHttpFileInfo/cpp/GetLastModifiedTime.cpp
mitchelsellers/iis-docs
376c5b4a1b88b807eb8dbe7c63ba7cd9c59f7429
[ "CC-BY-4.0", "MIT" ]
343
2017-05-26T08:57:30.000Z
2022-03-25T23:05:04.000Z
// <Snippet11> #pragma warning( disable : 4290 ) #pragma warning( disable : 4530 ) #define _WINSOCKAPI_ #include <windows.h> #include <io.h> #include <sal.h> #include <httpserv.h> #include <string> using namespace std; // The CConvert class mirrors the Convert class that is // defined in the .NET Framework. It converts primitives // and other data types to wstring types. class CConvert { public: // The ToString method converts a FILETIME pointer to a wstring. // fileTime: the FILETIME pointer to convert to a wstring. // return: the FILETIME pointer as a wstring. static wstring ToString(FILETIME* fileTime) { // If fileTime is NULL, return the empty string. if (NULL == fileTime) { return L"NULL"; } // Convert the FILETIME to a local time, and // then convert that local time to a wstring. SYSTEMTIME stUTC; SYSTEMTIME stLocal; FileTimeToSystemTime(fileTime, &stUTC); SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal); // Create a wstring to return. Note: wsprintf // can be also used. However, it is more difficult // to handle both UNICODE and non-UNICODE correctly. wstring timeString = ToString(stLocal.wMonth) + wstring(L"/") + ToString(stLocal.wDay) + wstring(L"/") + ToString(stLocal.wYear) + wstring(L" ") + ToString(stLocal.wHour) + wstring(L":") + ToString(stLocal.wMinute); // Return the FILETIME data as a wstring. return timeString; } // The ToString method converts a long to a wstring. // l: the long value to convert to a wstring. // return: the long as a wstring. static wstring ToString(long l) { WCHAR str[256]; str[0] = '\0'; _ltow_s(l, str, 256, 10); return str; } // The ToByteString converts a double-byte // character string to a single-byte string. // str: the double-byte string to convert. // return: a single-byte string copied from str. static string ToByteString(const wstring& str) { // Get the length of the // double-byte string. size_t length = str.length(); // Create a temporary char pointer. char* byteChar = new char[length+1]; byteChar[0] = '\0'; // Copy the double-byte character string // into the single-byte string. size_t charsReturned = 0; wcstombs_s(&charsReturned, byteChar, length+1, str.c_str(), length+1); // Create a string to return. string retString = byteChar; // Delete the temporary string and // set that string to NULL. delete[] byteChar; byteChar = NULL; // Return the single-byte string. return retString; } // The ToString method converts a USHORT to a wstring. // u: the USHORT value to convert to a wstring. // return: the value of u as a wstring. static wstring ToString(USHORT u) { return (ToString((long)u)); } }; // The CResponseWriter class writes // text to the response stream. class CResponseWriter { public: // Creates the CResponseWriter class. // response: the IHttpResponse // pointer to write to. // throws: a _com_error exception if // the IHttpResponse pointer is NULL. CResponseWriter(IHttpResponse* response) throw (_com_error) { // If the response is NULL, // throw an exception. if (NULL == response) { ThrowOnFail(E_INVALIDARG); } // Set the internal response. m_response = response; } // The destructor for the CResponseWriter // class. The CResponseWriter method // sets the IHttpResponse pointer to NULL. virtual ~CResponseWriter() { m_response = NULL; } // The Write method writes the // PCSTR to the response stream. // pszValue: the PCSTR to write. // throws: a _com_error if the // Write method fails. void Write ( PCSTR pszValue ) throw (_com_error) { // The string must not be // NULL, and its length must // be greater than 0. if ((NULL == pszValue) || (strlen(pszValue) < 1)) { // Throw an invalid argument // exception. ThrowOnFail(E_INVALIDARG); } // Create a data chunk structure. HTTP_DATA_CHUNK dataChunk; // Set the chunk to a chunk in memory. dataChunk.DataChunkType = HttpDataChunkFromMemory; // Set the chunk to // the pszValue parameter. dataChunk.FromMemory.pBuffer = (PVOID)pszValue; // Set the chunk size // to the pszValue length. dataChunk.FromMemory.BufferLength = (USHORT)strlen(pszValue); // Declare and initialize OUT // parameters for the WriteEntityChunks // method. DWORD pcbSent = 0; BOOL pfCompletionExpected = FALSE; // Write the entity chunks to // the response stream. HRESULT hr = m_response->WriteEntityChunks (&dataChunk, 1, FALSE, FALSE, &pcbSent, &pfCompletionExpected); // Throw an exception if the call // to WriteEntityChunks is not a // success. ThrowOnFail(hr); } // The WriteLine method writes a string // and newline characters to the response steam. // pszValue: the PCSTR string to write. // throws: a _com_error if the PCSTR // or the newline characters are not // written to the response stream. void WriteLine ( PCSTR pszValue ) throw (_com_error) { // Try to write the pszValue parameter. Write(pszValue); // Try to write the newline characters. Write("\r\n"); } // Convenience method that writes a name // and value pair to the response stream. // name: the name of the parameter. // value: the value of the parameter. // throws: a _com_error exception if // the response stream is not written. void WriteLine ( const wstring& name, const wstring& value ) throw (_com_error) { // Convert the UNICODE strings // to mutlibyte strings. string nameMulti = CConvert::ToByteString(name); string valueMulti = CConvert::ToByteString(value); // Create the string to write. string writeString = nameMulti + string(": ") + valueMulti; // Write the line to // the response stream. WriteLine(writeString.c_str()); } // Tests an HRESULT for success. // hr: the HRESULT value to inspect. // throws: a _com_error if the HRESULT // parameter is not S_OK. static void ThrowOnFail(HRESULT hr) { if (FAILED(hr)) { _com_error ce(hr); throw ce; } } private: // Specify the IHttpResponse // pointer to write to. IHttpResponse* m_response; }; // The MyHttpModule class extends the CHttpModule // class and handles response processing. This // class handles retrieving an IHttpFileInfo pointer // from the IHttpContext pointer during the overridden // OnSendResponse method, and writes the IHttpFileInfo // data to the response stream. class MyHttpModule : public CHttpModule { public: // The MyHttpModule method is the public // constructor for the MyHttpModule class. MyHttpModule() { } // The OnSendResponse method // handles respose processing. // pHttpContext: an IHttpContext pointer. // pProvider: an ISendResponseProvider pointer. // return: RQ_NOTIFICATION_FINISH_REQUEST if the // IHttpFileInfo pointer can be retrieved from the // pHttpContext parameter; otherwise, // RQ_NOTIFICATION_CONTINUE. REQUEST_NOTIFICATION_STATUS OnSendResponse ( IN IHttpContext* pHttpContext, IN OUT ISendResponseProvider* pProvider ) { // Use the UNREFERENCED_PARAMETER macro since // the pProvider parameter is never used. UNREFERENCED_PARAMETER(pProvider); if (NULL == pHttpContext) { return RQ_NOTIFICATION_CONTINUE; } // Get an IHttpFileInfo pointer // from the IHttpContext pointer. IHttpFileInfo* fileInfo = pHttpContext->GetFileInfo(); // Get the IHttpResponse pointer // from the IHttpContext pointer. IHttpResponse* response = pHttpContext->GetResponse(); // Both the IHttpFileInfo pointer // and IHttpResponse pointer are // required for processing. if ((NULL == fileInfo) || (NULL == response)) { return RQ_NOTIFICATION_CONTINUE; } // Clear the existing response stream. response->Clear(); // Set the response header to plain text. HRESULT hr = response->SetHeader(HttpHeaderContentType, "text/plain", (USHORT)strlen("text/plain"), TRUE); // If the SetHeader method fails, // call the SetStatus with an error code. if (FAILED(hr)) { response->SetStatus(500, "IHttpResponse::SetHeader", 0, hr); return RQ_NOTIFICATION_CONTINUE; } // The CResponseWriter will throw a // com_exception if it cannot be created, // or if the response stream cannot be written. // Create a new CResponseWriter, and wrap // all calls into that CResponseWriter, // with a try-catch statement. try { // Declare a writer for // the response stream. CResponseWriter writer(response); // Call the GetLastModifiedTime method // on the IHttpFileInfo pointer. FILETIME fileTime; fileInfo->GetLastModifiedTime(&fileTime); // Convert the FILETIME // structure to a wstring. wstring lastModifiedTimeString = CConvert::ToString(&fileTime); // Write the last modified time // information to the response stream. writer.WriteLine(L"Last Modified Time", lastModifiedTimeString); } catch (_com_error& ce) { // Attempt to get the // description of the error. _bstr_t description = ce.Description(); // Print the description if // it is not empty. if (0 == description.length()) { description = ce.ErrorMessage(); } // Set an error status on the // IHttpResponse pointer. response->SetStatus(500, description, 0, ce.Error()); } // Return RQ_NOTIFICATION_FINISH_REQUEST, which // will terminate any additional request processing. return RQ_NOTIFICATION_FINISH_REQUEST; } protected: // The MyHttpModule is the protected virtual // constructor for the MyHttpModule class. virtual ~MyHttpModule() { } }; // The MyHttpModuleFactory class implements the IHttpModuleFactory // interface, and creates a new MyHttpModule pointer, where this // MyHttpModule listens for RQ_SEND_RESPONSE events. class MyHttpModuleFactory : public IHttpModuleFactory { public: // The RegisterGlobalModule method creates a new // MyHttpModuleFactory pointer, assigns that pointer // as the factory on the pModuleInfo parameter, and // registers for RQ_SEND_RESPONSE events. // dwServerVersion: the current server version. // pModuleInfo: the IHttpModuleRegistrationInfo // used for requesting notifications. // pGlobalInfo: the IHttpServer pointer. static HRESULT RegisterGlobalModule ( DWORD dwServerVersion, IHttpModuleRegistrationInfo* pModuleInfo, IHttpServer* pGlobalInfo ) { // Create a new MyHttpModuleFactory pointer. MyHttpModuleFactory* factory = new MyHttpModuleFactory; // If the factory is NULL, return a // return a ERROR_NOT_ENOUGH_MEMORY // errror. if (NULL == factory) { return HRESULT_FROM_WIN32(ERROR_NOT_ENOUGH_MEMORY); } // Return the value from calling the // SetRequestNotifications method by // passing the factory for RQ_SEND_RESPONSE // events. return pModuleInfo->SetRequestNotifications( factory, RQ_SEND_RESPONSE, 0); } // The GetHttpModule method creates a new MyHttpModule // pointer and sets the ppModule with this pointer. // ppModule: the OUT parameter which // accepts a new CHttpModule subclass. // pAllocator: the IModuleAllocator pointer, // which is unused in this implementation. virtual HRESULT GetHttpModule ( OUT CHttpModule** ppModule, IN IModuleAllocator* pAllocator ) { // Call the UNREFERENCED_PARAMETER with // the IModuleAllocator pointer, because // this parameter is never used. UNREFERENCED_PARAMETER(pAllocator); // Create a new MyHttpModule pointer and assign // it to the dereferenced ppModule pointer. *ppModule = new MyHttpModule; // If the dereferenced ppModule is NULL // then heap memory is exhausted. Return // an ERROR_NOT_ENOUGH_MEMORY error. if (NULL == *ppModule) { return HRESULT_FROM_WIN32(ERROR_NOT_ENOUGH_MEMORY); } // Creating a new MyHttpModule pointer // was successful; return S_OK. return S_OK; } // The Terminate method must be implemented // by IHttpModuleFactory implementers, // and calls delete on this. virtual void Terminate() { delete this; } private: // The MyHttpModuleFactory is the // protected constructor for the // MyHttpModuleFactory class. MyHttpModuleFactory() { } // The MyHttpModuleFactory method is the // protected virtual destructor for the // MyHttpModuleFactory class. virtual ~MyHttpModuleFactory() { } }; // The RegisterModule method is the // main entry point for the DLL. // dwServerVersion: the current server version. // pModuleInfo: the current // IHttpModuleRegistrationInfo pointer. // pGlobalInfo: the current IHttpServer pointer. // return: the HRESULT value returned from // the MyHttpModuleFactory::RegisterGlobalModule // static method. HRESULT __stdcall RegisterModule ( DWORD dwServerVersion, IHttpModuleRegistrationInfo* pModuleInfo, IHttpServer* pGlobalInfo ) { // Register for global events using the MyHttpModuleFactory // class' static RegisterGlobalModule method. return MyHttpModuleFactory::RegisterGlobalModule (dwServerVersion, pModuleInfo, pGlobalInfo); } // </Snippet11>
30.125714
77
0.59111
mitchelsellers
4f25631cbce5f6a9dc8c9de229b764e5db614fb7
22,036
cc
C++
app/fpn_eval/src/main.cc
Vertical-Beach/ai-edge-contest4
4b5211a9adb383756acade42c8a8b104f6fd7363
[ "Apache-2.0" ]
3
2021-02-13T05:16:10.000Z
2022-03-08T16:00:02.000Z
app/fpn_eval/src/main.cc
Vertical-Beach/ai-edge-contest4
4b5211a9adb383756acade42c8a8b104f6fd7363
[ "Apache-2.0" ]
null
null
null
app/fpn_eval/src/main.cc
Vertical-Beach/ai-edge-contest4
4b5211a9adb383756acade42c8a8b104f6fd7363
[ "Apache-2.0" ]
null
null
null
/** * © Copyright (C) 2016-2017 Xilinx, Inc * * Licensed under the Apache License, Version 2.0 (the "License"). You may * not use this file except in compliance with the License. A copy of the * License is located 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. */ /** * Last Modified in 2020/12/26 * by lp6m, medalotte */ #include <deque> #include <assert.h> #include <dirent.h> #include <stdio.h> #include <stdlib.h> #include <atomic> #include <sys/stat.h> #include <sys/time.h> #include <cstdio> #include <iomanip> #include <unistd.h> #include <algorithm> #include <chrono> #include <cmath> #include <cstring> #include <fstream> #include <iostream> #include <functional> #include <mutex> #include <queue> #include <string> #include <thread> #include <vector> #include <opencv2/opencv.hpp> #include <dnndk/dnndk.h> #define DEBUG_MODE (0) namespace { template<typename T> class ObjWithMtx { public: T obj; ObjWithMtx() = default; ObjWithMtx(const T& _obj) : obj(_obj) {} void operator =(const ObjWithMtx& obj) = delete; ObjWithMtx(const ObjWithMtx& obj) = delete; void lock() { mtx_.lock(); } bool try_lock() { return mtx_.try_lock(); } void unlock() { mtx_.unlock(); } private: std::mutex mtx_; }; template<typename T, size_t D> class MultiThreadFIFO { public: explicit MultiThreadFIFO(const uint32_t& sleep_t_us = 100) : sleep_t_us_(sleep_t_us) { init(); } void operator =(const MultiThreadFIFO& obj) = delete; MultiThreadFIFO(const MultiThreadFIFO& obj) = delete; void init() { std::unique_lock<std::mutex> lock_w_func(w_func_guard_, std::try_to_lock); std::unique_lock<std::mutex> lock_r_func(r_func_guard_, std::try_to_lock); if (!lock_w_func.owns_lock() || !lock_r_func.owns_lock()) { throw std::runtime_error("[ERROR] Initialization of the FIFO failed."); } for (auto& state : fifo_state_) { std::lock_guard<ObjWithMtx<ElementState>> lock_state(state); state.obj = ElementState::INVALID; } r_idx_ = 0; w_idx_ = 0; } void write(ObjWithMtx<bool>& no_abnormality, const bool& is_last, std::function<void(T&)> write_func) { std::unique_lock<std::mutex> lock_w_func(w_func_guard_, std::try_to_lock); if (!lock_w_func.owns_lock()) { throw std::runtime_error("[ERROR] The write function can't be called at the same time from multiple threads."); } while (true) { { std::lock_guard<ObjWithMtx<ElementState>> lock_state(fifo_state_[w_idx_]); if (fifo_state_[w_idx_].obj == ElementState::INVALID) { break; } else { std::lock_guard<ObjWithMtx<bool>> lock(no_abnormality); if (no_abnormality.obj == false) { throw std::runtime_error("[ERROR] Terminate write process."); } } } std::this_thread::sleep_for(std::chrono::microseconds(sleep_t_us_)); } { std::lock_guard<ObjWithMtx<T>> lock_fifo(fifo_[w_idx_]); write_func(fifo_[w_idx_].obj); } { std::lock_guard<ObjWithMtx<ElementState>> lock_state(fifo_state_[w_idx_]); fifo_state_[w_idx_].obj = is_last ? ElementState::VALID_LAST : ElementState::VALID; } incrementIdx(w_idx_); } void read(ObjWithMtx<bool>& no_abnormality, std::function<void(const T&)> read_func) { std::unique_lock<std::mutex> lock_r_func(r_func_guard_, std::try_to_lock); if (!lock_r_func.owns_lock()) { throw std::runtime_error("[ERROR] The read function can't be called at the same time from multiple threads."); } while (true) { { std::lock_guard<ObjWithMtx<ElementState>> lock_state(fifo_state_[r_idx_]); if (fifo_state_[r_idx_].obj == ElementState::VALID || fifo_state_[r_idx_].obj == ElementState::VALID_LAST) { break; } else { std::lock_guard<ObjWithMtx<bool>> lock(no_abnormality); if (no_abnormality.obj == false) { throw std::runtime_error("[ERROR] Terminate read process."); } } } std::this_thread::sleep_for(std::chrono::microseconds(sleep_t_us_)); } { std::lock_guard<ObjWithMtx<T>> lock_fifo(fifo_[r_idx_]); read_func(fifo_[r_idx_].obj); } { std::lock_guard<ObjWithMtx<ElementState>> lock_state(fifo_state_[r_idx_]); if (fifo_state_[r_idx_].obj == ElementState::VALID) { fifo_state_[r_idx_].obj = ElementState::INVALID; incrementIdx(r_idx_); } else { fifo_state_[r_idx_].obj = ElementState::INVALID_LAST; } } } bool neverReadNextElement() { std::unique_lock<std::mutex> lock_r_func(r_func_guard_, std::try_to_lock); if (!lock_r_func.owns_lock()) { throw std::runtime_error("[ERROR] The read function can't be called at the same time from multiple threads."); } std::lock_guard<ObjWithMtx<ElementState>> lock_state(fifo_state_[r_idx_]); return (fifo_state_[r_idx_].obj == ElementState::INVALID_LAST); } private: enum class ElementState { VALID, VALID_LAST, INVALID, INVALID_LAST }; void incrementIdx(size_t& idx) const { idx = (idx < D - 1) ? idx + 1 : 0; } const uint32_t sleep_t_us_; std::array<ObjWithMtx<T>, D> fifo_; std::array<ObjWithMtx<ElementState>, D> fifo_state_; std::mutex r_func_guard_, w_func_guard_; size_t r_idx_{0}, w_idx_{0}; }; struct DPUInOutInfo { cv::Size in_size, out_size; size_t in_channel, out_channel; int8_t* in_addr; int8_t* out_addr; float in_mean[3]; float in_scale_fix; }; std::ostream& operator << (std::ostream& os, const DPUInOutInfo& obj) { os << "[in_size : " << obj.in_size; os << ", out_size : " << obj.out_size; os << ", in_channel : " << obj.in_channel; os << ", in_scale_fix : " << obj.in_scale_fix; os << ", in_addr : " << static_cast<void*>(obj.in_addr); os << ", out_addr : " << static_cast<void*>(obj.out_addr); os << ", mean : ["; for (size_t mi = 0; mi < 3; mi++) { os << obj.in_mean[mi] << ((mi != 2) ? ", " : "]]"); } return os; }; const std::string SEG_TEST_IMG_PATH = "../seg_test_images/"; const std::string SEG_OUT_PATH = "../seg_out/"; const std::string KERNEL_CONV = "segmentation_0"; const std::string CONV_INPUT_NODE = "conv1_7x7_s2"; const std::string CONV_OUTPUT_NODE = "toplayer_p2"; constexpr auto BATCH_SIZE = 130U; constexpr auto PREPROC_FIFO_DEPTH = 3U; constexpr auto POSTPROC_FIFO_DEPTH = 3U; constexpr auto SLEEP_T_US = 100U; constexpr auto DPU_INPUT_IMG_WIDTH = 640U; constexpr auto DPU_INPUT_IMG_HEIGHT = 320U; constexpr auto DPU_INPUT_IMG_CHANNEL = 3U; constexpr auto DPU_INPUT_IMG_SCALE = 1.0f; constexpr auto DPU_INPUT_IMG_MEAN = {104.0f, 117.0f, 123.0f}; constexpr auto DPU_OUTPUT_IMG_WIDTH = 640U; constexpr auto DPU_OUTPUT_IMG_HEIGHT = 320U; constexpr auto DPU_OUTPUT_NOF_CLASS = 5U; using PreprocFIFOElementType = std::array<int8_t, DPU_INPUT_IMG_WIDTH * DPU_INPUT_IMG_HEIGHT * DPU_INPUT_IMG_CHANNEL>; using PostprocFIFOElementType = std::array<int8_t, DPU_OUTPUT_IMG_WIDTH * DPU_OUTPUT_IMG_HEIGHT * DPU_OUTPUT_NOF_CLASS>; ObjWithMtx<bool> no_abnormality(true); MultiThreadFIFO<PreprocFIFOElementType, PREPROC_FIFO_DEPTH> preproc_fifo(SLEEP_T_US); MultiThreadFIFO<PostprocFIFOElementType, POSTPROC_FIFO_DEPTH> postproc_fifo(SLEEP_T_US); DPUKernel* kernel_conv; DPUTask* task_conv_1; DPUTensor* conv_out_tensor; DPUInOutInfo dpu_inout_info; std::vector<cv::Mat> read_buffer, write_buffer; #if DEBUG_MODE std::mutex cout_guard; #endif void do_preprocess() { cv::Mat resized_img(dpu_inout_info.in_size, CV_8UC3); auto img_src = read_buffer.begin(); auto end_flag = false; while(!end_flag) { /***** PREPROCESS FOR INFERENCE *****/ #if DEBUG_MODE const auto t0 = std::chrono::system_clock::now(); #endif cv::resize(*img_src, resized_img, resized_img.size(), 0, 0, cv::INTER_LINEAR); img_src++; #if DEBUG_MODE const auto t1 = std::chrono::system_clock::now(); #endif end_flag = static_cast<bool>(img_src == read_buffer.end()); preproc_fifo.write(no_abnormality, end_flag, [&](PreprocFIFOElementType& dst) -> void { dpuProcessNormalizion(dst.data(), resized_img.data, resized_img.rows, resized_img.cols, dpu_inout_info.in_mean, dpu_inout_info.in_scale_fix, resized_img.step1()); }); #if DEBUG_MODE const auto t2 = std::chrono::system_clock::now(); const auto elapsed_time_ms0 = std::chrono::duration_cast<std::chrono::microseconds>(t1 - t0).count() / (double)1e3; const auto elapsed_time_ms1 = std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count() / (double)1e3; { std::lock_guard<std::mutex> lock_cout(cout_guard); std::cout << "[DEBUG] (PREPROCESS) Elapsed time of cv::resize : " << elapsed_time_ms0 << " ms" << std::endl; std::cout << "[DEBUG] (PREPROCESS) Elapsed time of normalization : " << elapsed_time_ms1 << " ms" << std::endl; } #endif /***** END *****/ } } void do_inference() { constexpr auto in_byte_size = sizeof(int8_t) * DPU_INPUT_IMG_WIDTH * DPU_INPUT_IMG_HEIGHT * DPU_INPUT_IMG_CHANNEL; constexpr auto out_byte_size = sizeof(int8_t) * DPU_OUTPUT_IMG_WIDTH * DPU_OUTPUT_IMG_HEIGHT * DPU_OUTPUT_NOF_CLASS; auto end_flag = false; while (!end_flag) { /***** INFERENCE *****/ #if DEBUG_MODE const auto t0 = std::chrono::system_clock::now(); #endif preproc_fifo.read(no_abnormality, [&](const PreprocFIFOElementType& src) -> void { std::memcpy(dpu_inout_info.in_addr, src.data(), in_byte_size); }); #if DEBUG_MODE const auto t1 = std::chrono::system_clock::now(); #endif dpuRunTask(task_conv_1); #if DEBUG_MODE const auto t2 = std::chrono::system_clock::now(); #endif end_flag = preproc_fifo.neverReadNextElement(); postproc_fifo.write(no_abnormality, end_flag, [&](PostprocFIFOElementType& dst) -> void { std::memcpy(dst.data(), dpu_inout_info.out_addr, out_byte_size); }); #if DEBUG_MODE const auto t3 = std::chrono::system_clock::now(); const auto elapsed_time_ms0 = std::chrono::duration_cast<std::chrono::microseconds>(t1 - t0).count() / (double)1e3; const auto elapsed_time_ms1 = std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count() / (double)1e3; const auto elapsed_time_ms2 = std::chrono::duration_cast<std::chrono::microseconds>(t3 - t2).count() / (double)1e3; { std::lock_guard<std::mutex> lock_cout(cout_guard); std::cout << "[DEBUG] (INFERENCE) Elapsed time of memcpy from preproc FIFO : " << elapsed_time_ms0 << " ms" << std::endl; std::cout << "[DEBUG] (INFERENCE) Elapsed time of inference by DPU : " << elapsed_time_ms1 << " ms" << std::endl; std::cout << "[DEBUG] (INFERENCE) Elapsed time of memcpy to postproce FIFO : " << elapsed_time_ms2 << " ms" << std::endl; } #endif /***** END *****/ } } void do_postprocess() { cv::Mat seg(dpu_inout_info.out_size, CV_8UC1); auto img_dst = write_buffer.begin(); const auto area = seg.size().area(); while (img_dst != write_buffer.end()) { /***** POSTPROCESS OF INFERENCE *****/ #if DEBUG_MODE const auto t0 = std::chrono::system_clock::now(); #endif postproc_fifo.read(no_abnormality, [&](const PostprocFIFOElementType& src) -> void { auto offset = src.data(); for (int seg_i = 0; seg_i < area; seg_i++) { seg.data[seg_i] = static_cast<uint8_t>(std::distance(offset, std::max_element(offset, offset + DPU_OUTPUT_NOF_CLASS))); offset += DPU_OUTPUT_NOF_CLASS; } }); #if DEBUG_MODE const auto t1 = std::chrono::system_clock::now(); #endif cv::resize(seg, *img_dst, (*img_dst).size(), 0, 0, cv::INTER_NEAREST); img_dst++; #if DEBUG_MODE const auto t2 = std::chrono::system_clock::now(); const auto elapsed_time_ms0 = std::chrono::duration_cast<std::chrono::microseconds>(t1 - t0).count() / (double)1e3; const auto elapsed_time_ms1 = std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count() / (double)1e3; { std::lock_guard<std::mutex> lock_cout(cout_guard); std::cout << "[DEBUG] (POSTPROCESS) Elapsed time of softmax : " << elapsed_time_ms0 << " ms" << std::endl; std::cout << "[DEBUG] (POSTPROCESS) Elapsed time of cv::resize : " << elapsed_time_ms1 << " ms" << std::endl; } #endif /***** END *****/ } if (!postproc_fifo.neverReadNextElement()) { throw std::runtime_error("[ERROR] The data is still in the postproc FIFO."); } } std::vector<std::string> load_img_names(const std::string& path) { const std::set<std::string> img_file_ext = { "JPEG", "jpeg", "JPG", "jpg", "PNG", "png" }; struct stat s; lstat(path.c_str(), &s); if (!S_ISDIR(s.st_mode)) { throw std::runtime_error("[ERROR] " + path + " is not a valid directory!"); } DIR *dir = opendir(path.c_str()); if (dir == nullptr) { throw std::runtime_error("[ERROR] Open " + path + " path failed."); } struct dirent *entry; std::vector<std::string> img_names; while ((entry = readdir(dir)) != nullptr) { if (entry->d_type == DT_REG || entry->d_type == DT_UNKNOWN) { const std::string name = entry->d_name; const std::string ext = name.substr(name.find_last_of(".") + 1); if (img_file_ext.find(ext) != img_file_ext.end()) { img_names.push_back(name); } } } std::sort(img_names.begin(), img_names.end()); closedir(dir); return img_names; } } int main() { try { std::exception_ptr ep; const auto gen_func = [&](const auto do_worker) -> auto { return [&]() -> void { try { do_worker(); } catch(...) { std::lock_guard<ObjWithMtx<bool>> lock(no_abnormality); if (no_abnormality.obj) { no_abnormality.obj = false; ep = std::current_exception(); } } }; }; // Attach to DPU driver and prepare for running dpuOpen(); // Create DPU Kernels and Tasks for CONV Nodes kernel_conv = dpuLoadKernel(KERNEL_CONV.c_str()); task_conv_1 = dpuCreateTask(kernel_conv, 0); conv_out_tensor = dpuGetOutputTensor(task_conv_1, CONV_OUTPUT_NODE.c_str()); dpu_inout_info.in_size.height = dpuGetInputTensorHeight(task_conv_1, CONV_INPUT_NODE.c_str(), 0); dpu_inout_info.in_size.width = dpuGetInputTensorWidth(task_conv_1, CONV_INPUT_NODE.c_str(), 0); dpu_inout_info.in_channel = dpuGetInputTensorChannel(task_conv_1, CONV_INPUT_NODE.c_str(), 0); dpu_inout_info.out_size.height = dpuGetTensorHeight(conv_out_tensor); dpu_inout_info.out_size.width = dpuGetTensorWidth(conv_out_tensor); const auto validate_dpu_inout = [](const bool& cond, const std::string& e_str) -> void { if (!cond) { throw std::logic_error("[ERROR] DPU in/out parameter is invalid : " + e_str); } }; validate_dpu_inout(dpu_inout_info.in_size.width == DPU_INPUT_IMG_WIDTH, "input width"); validate_dpu_inout(dpu_inout_info.in_size.height == DPU_INPUT_IMG_HEIGHT, "input height"); validate_dpu_inout(dpu_inout_info.in_channel == DPU_INPUT_IMG_CHANNEL, "input channel"); validate_dpu_inout(dpu_inout_info.out_size.width == DPU_OUTPUT_IMG_WIDTH, "output width"); validate_dpu_inout(dpu_inout_info.out_size.height == DPU_OUTPUT_IMG_HEIGHT, "output height"); dpu_inout_info.in_addr = dpuGetInputTensorAddress(task_conv_1, CONV_INPUT_NODE.c_str(), 0); dpu_inout_info.in_scale_fix = dpuGetInputTensorScale(task_conv_1, CONV_INPUT_NODE.c_str(), 0) * DPU_INPUT_IMG_SCALE; std::copy(DPU_INPUT_IMG_MEAN.begin(), DPU_INPUT_IMG_MEAN.end(), dpu_inout_info.in_mean); dpu_inout_info.out_addr = dpuGetTensorAddress(conv_out_tensor); dpu_inout_info.out_channel = DPU_OUTPUT_NOF_CLASS; std::cout << "[INFO] DPU information : " << dpu_inout_info << std::endl; const auto img_names = load_img_names(SEG_TEST_IMG_PATH); auto elapsed_time_ms = 0.0; for (size_t bi = 0; bi < std::ceil(img_names.size() / (double)BATCH_SIZE); bi++) { const auto idx_offset = bi * BATCH_SIZE; const auto buffer_size = std::min((uint32_t)(img_names.size() - idx_offset), BATCH_SIZE); // Initialize buffers read_buffer.clear(); write_buffer.clear(); preproc_fifo.init(); postproc_fifo.init(); // Load images read_buffer.reserve(buffer_size); write_buffer.reserve(buffer_size); for (size_t im_i = 0; im_i < buffer_size; im_i++) { const std::string filepath = SEG_TEST_IMG_PATH + img_names[idx_offset + im_i]; read_buffer.push_back(cv::imread(filepath)); write_buffer.emplace_back(read_buffer.back().size(), CV_8UC1); std::cout << "[INFO] Load : " << filepath << std::endl; } std::cout << "[INFO] Perform inference for the " << idx_offset + 1 << "th to " << idx_offset + buffer_size << "th images." << std::endl; /***** START OF INFERENCE INCLUDING PRE/POST PROCESSES *****/ const auto start_time = std::chrono::system_clock::now(); auto preprocess = std::thread(gen_func([&]() -> void { do_preprocess(); })); auto inference = std::thread(gen_func([&]() -> void { do_inference(); })); auto postprocess = std::thread(gen_func([&]() -> void { do_postprocess(); })); preprocess.join(); inference.join(); postprocess.join(); const auto end_time = std::chrono::system_clock::now(); /***** END *****/ if (ep) { std::rethrow_exception(ep); } for (size_t im_i = 0; im_i < buffer_size; im_i++) { std::string out_filepath = SEG_OUT_PATH + img_names[idx_offset + im_i]; out_filepath = out_filepath.substr(0, out_filepath.find_last_of(".")); out_filepath += ".png"; cv::imwrite(out_filepath, write_buffer[im_i]); std::cout << "[INFO] Store : " << out_filepath << std::endl; } if constexpr (!DEBUG_MODE) { elapsed_time_ms += std::chrono::duration_cast<std::chrono::microseconds>(end_time - start_time).count() / (double)1e3; std::cout << "[INFO] Average elapsed time of inference for the 1th to " << idx_offset + buffer_size << "th : " << elapsed_time_ms / (idx_offset + buffer_size) << " ms" << std::endl; std::this_thread::sleep_for(std::chrono::seconds(1)); } } std::cout << "[INFO] Done." << std::endl; // Destroy DPU Tasks and Kernels and free resources dpuDestroyTask(task_conv_1); dpuDestroyKernel(kernel_conv); // Detach from DPU driver and release resources dpuClose(); } catch (const std::exception& e) { std::cout << e.what() << std::endl; } catch (...) { std::cout << "An unexpected exception has occurred." << std::endl; } return 0; }
40.883117
139
0.574741
Vertical-Beach
4f27bba831e202a4893eef9b49bc7fc1d3ddde4f
54,658
cpp
C++
dali-toolkit/internal/controls/table-view/table-view-impl.cpp
zyndor/dali-toolkit
9e3fd659c4d25706ab65345bc7c562ac27248325
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
dali-toolkit/internal/controls/table-view/table-view-impl.cpp
zyndor/dali-toolkit
9e3fd659c4d25706ab65345bc7c562ac27248325
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
dali-toolkit/internal/controls/table-view/table-view-impl.cpp
zyndor/dali-toolkit
9e3fd659c4d25706ab65345bc7c562ac27248325
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2017 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ // CLASS HEADER #include <dali-toolkit/internal/controls/table-view/table-view-impl.h> // EXTERNAL INCLUDES #include <sstream> #include <dali/public-api/object/ref-object.h> #include <dali/public-api/object/type-registry.h> #include <dali/public-api/object/type-registry-helper.h> #include <dali/devel-api/actors/actor-devel.h> #include <dali/devel-api/scripting/scripting.h> #include <dali/public-api/size-negotiation/relayout-container.h> #include <dali/integration-api/debug.h> // INTERNAL INCLUDES #include <dali-toolkit/internal/controls/control/control-data-impl.h> using namespace Dali; namespace { /** * @brief Should the tableview fit around the given actor * * @param[in] actor The child actor to test against * @param[dimension] The dimension to test against */ bool FitToChild( Actor actor, Dimension::Type dimension ) { return actor.GetResizePolicy( dimension ) != ResizePolicy::FILL_TO_PARENT && actor.GetRelayoutSize( dimension ) > 0.0f; } #if defined(DEBUG_ENABLED) // debugging support, very useful when new features are added or bugs are hunted down // currently not called from code so compiler will optimize these away, kept here for future debugging #define TABLEVIEW_TAG "DALI Toolkit::TableView " #define TV_LOG(fmt, args,...) Debug::LogMessage(Debug::DebugInfo, TABLEVIEW_TAG fmt, ## args) //#define TABLEVIEW_DEBUG 1 #if defined(TABLEVIEW_DEBUG) void PrintArray( Array2d<Dali::Toolkit::Internal::TableView::CellData>& array ) { TV_LOG( "Array2d<CellData> size [%d,%d] \n", array.GetRows(), array.GetColumns() ); // print values for( unsigned int i = 0; i < array.GetRows(); ++i ) { for( unsigned int j = 0; j < array.GetColumns(); ++j ) { Dali::Toolkit::Internal::TableView::CellData data = array[i][j]; char actor = ' '; std::string actorName; if( data.actor ) { actor = 'A'; actorName = data.actor.GetProperty< std::string >( Dali::Actor::Property::NAME ); } TV_LOG("Array[%d,%d]=%c %s %d,%d,%d,%d ", i, j, actor, actorName.c_str(), data.position.rowIndex, data.position.columnIndex, data.position.rowSpan, data.position.columnSpan ); } TV_LOG( "\n" ); } } // debugging support, very useful when new features are added or bugs are hunted down // currently not called from code so compiler will optimize these away, kept here for future debugging void PrintArray( Array2d<Size>& array ) { TV_LOG( "Array2d<Size> size [%d,%d] \n", array.GetRows(), array.GetColumns() ); // print values for( unsigned int i = 0; i < array.GetRows(); ++i ) { for( unsigned int j = 0; j < array.GetColumns(); ++j ) { TV_LOG( "Array[%d,%d]=%.2f,%.2f ", i, j, array[i][j].width, array[i][j].height ); } TV_LOG( "\n" ); } } // debugging support, very useful when new features are added or bugs are hunted down // currently not called from code so compiler will optimize these away, kept here for future debugging void PrintVector( std::vector<float>& array ) { TV_LOG( "vector, size [%d]\n", array.size() ); // print values for( unsigned int i = 0; i < array.size(); ++i ) { TV_LOG( "vector[%d]=%.2f ", i, array[i] ); } TV_LOG( "\n" ); } #endif // defined(TABLEVIEW_DEBUG) #endif // defined(DEBUG_ENABLED) } // namespace namespace Dali { namespace Toolkit { namespace Internal { namespace { // Type registration BaseHandle Create() { return Toolkit::TableView::New( 0, 0 ); } // Setup properties, signals and actions using the type-registry. DALI_TYPE_REGISTRATION_BEGIN( Toolkit::TableView, Toolkit::Control, Create ); DALI_PROPERTY_REGISTRATION( Toolkit, TableView, "rows", INTEGER, ROWS ) DALI_PROPERTY_REGISTRATION( Toolkit, TableView, "columns", INTEGER, COLUMNS ) DALI_PROPERTY_REGISTRATION( Toolkit, TableView, "cellPadding", VECTOR2, CELL_PADDING ) DALI_PROPERTY_REGISTRATION( Toolkit, TableView, "layoutRows", MAP, LAYOUT_ROWS ) DALI_PROPERTY_REGISTRATION( Toolkit, TableView, "layoutColumns", MAP, LAYOUT_COLUMNS ) DALI_CHILD_PROPERTY_REGISTRATION( Toolkit, TableView, "cellIndex", VECTOR2, CELL_INDEX ) DALI_CHILD_PROPERTY_REGISTRATION( Toolkit, TableView, "rowSpan", INTEGER, ROW_SPAN ) DALI_CHILD_PROPERTY_REGISTRATION( Toolkit, TableView, "columnSpan", INTEGER, COLUMN_SPAN ) DALI_CHILD_PROPERTY_REGISTRATION( Toolkit, TableView, "cellHorizontalAlignment", STRING, CELL_HORIZONTAL_ALIGNMENT ) DALI_CHILD_PROPERTY_REGISTRATION( Toolkit, TableView, "cellVerticalAlignment", STRING, CELL_VERTICAL_ALIGNMENT ) DALI_TYPE_REGISTRATION_END() const Scripting::StringEnum LAYOUT_POLICY_STRING_TABLE[] = { { "fixed", Toolkit::TableView::FIXED }, { "relative", Toolkit::TableView::RELATIVE }, { "fill", Toolkit::TableView::FILL }, { "fit", Toolkit::TableView::FIT } }; const unsigned int LAYOUT_POLICY_STRING_TABLE_COUNT = sizeof(LAYOUT_POLICY_STRING_TABLE) / sizeof( LAYOUT_POLICY_STRING_TABLE[0] ); const Scripting::StringEnum HORIZONTAL_ALIGNMENT_STRING_TABLE[] = { {"left", HorizontalAlignment::LEFT}, {"center", HorizontalAlignment::CENTER}, {"right", HorizontalAlignment::RIGHT} }; const unsigned int HORIZONTAL_ALIGNMENT_STRING_TABLE_COUNT = sizeof(HORIZONTAL_ALIGNMENT_STRING_TABLE) / sizeof( HORIZONTAL_ALIGNMENT_STRING_TABLE[0] ); const Scripting::StringEnum VERTICAL_ALIGNMENT_STRING_TABLE[] = { {"top", VerticalAlignment::TOP}, {"center", VerticalAlignment::CENTER}, {"bottom", VerticalAlignment::BOTTOM} }; const unsigned int VERTICAL_ALIGNMENT_STRING_TABLE_COUNT = sizeof(VERTICAL_ALIGNMENT_STRING_TABLE) / sizeof( VERTICAL_ALIGNMENT_STRING_TABLE[0] ); } // Unnamed namespace Toolkit::TableView TableView::New( unsigned int initialRows, unsigned int initialColumns ) { // Create the implementation, temporarily owned by this handle on stack IntrusivePtr< TableView > impl = new TableView( initialRows, initialColumns ); // Pass ownership to CustomActor handle Toolkit::TableView handle( *impl ); // Second-phase init of the implementation // This can only be done after the CustomActor connection has been made... impl->Initialize(); return handle; } bool TableView::AddChild( Actor& child, const Toolkit::TableView::CellPosition& position ) { // check that the child is valid DALI_ASSERT_ALWAYS( child ); // if child is already parented, we adopt it child.Unparent(); // check if we need to expand our data array if( position.rowIndex >= mCellData.GetRows() ) { // only adding new rows ResizeContainers( position.rowIndex + 1, mCellData.GetColumns() ); } if( position.columnIndex >= mCellData.GetColumns() ) { // only adding new columns ResizeContainers( mCellData.GetRows(), position.columnIndex + 1 ); } // check if there already is something in this cell if( mCellData[ position.rowIndex ][ position.columnIndex ].actor ) { return false; // cannot share a cell, it would complicate all logic and not bring much benefit } RelayoutingLock lock( *this ); // adopt the child Self().Add( child ); // if child spans multiple rows of columns if( ( position.rowSpan > 1 ) && ( position.rowIndex + position.rowSpan > mCellData.GetRows() ) ) { // increase table size for the full span, only increasing rows ResizeContainers( position.rowIndex + position.rowSpan, mCellData.GetColumns() ); } if( ( position.columnSpan > 1 ) && ( position.columnIndex + position.columnSpan > mCellData.GetColumns() ) ) { // increase table size for the full span, only increasing columns ResizeContainers( mCellData.GetRows(), position.columnIndex + position.columnSpan ); } // Fill in all cells that need the data CellData data; data.actor = child; data.position = position; for( unsigned int row = position.rowIndex; row < ( position.rowIndex + position.rowSpan ); ++row ) { // store same information to all cells, this way we can identify // if a cell is the prime location of an actor or a spanned one for( unsigned int column = position.columnIndex; column < ( position.columnIndex + position.columnSpan ); ++column ) { // store same information to all cells, this way we can identify // if a cell is the prime location of an actor or a spanned one mCellData[ row ][ column ] = data; } } // Relayout the whole table if( mRowData[position.rowIndex].sizePolicy == Toolkit::TableView::FIT && position.rowSpan == 1 ) { mRowDirty = true; } if( mColumnData[position.columnIndex].sizePolicy == Toolkit::TableView::FIT && position.columnSpan == 1 ) { mColumnDirty = true; } RelayoutRequest(); return true; // Addition successful } Actor TableView::GetChildAt( const Toolkit::TableView::CellPosition& position ) { if( ( position.rowIndex < mCellData.GetRows() ) && ( position.columnIndex < mCellData.GetColumns() ) ) { return mCellData[ position.rowIndex ][ position.columnIndex ].actor; } // Return an empty handle return Actor(); } Actor TableView::RemoveChildAt( const Toolkit::TableView::CellPosition& position ) { // get the child handle Actor child = GetChildAt( position ); // if no real actor there, nothing else to be done if( child ) { RelayoutingLock lock( *this ); // Remove the child, this will trigger a call to OnChildRemove Self().Remove( child ); // relayout the table only if instances were found if( RemoveAllInstances( child ) ) { if( mRowData[position.rowIndex].sizePolicy == Toolkit::TableView::FIT ) { mRowDirty = true; } if( mColumnData[position.columnIndex].sizePolicy == Toolkit::TableView::FIT ) { mColumnDirty = true; } RelayoutRequest(); } } // return the child back to caller return child; } bool TableView::FindChildPosition( const Actor& child, Toolkit::TableView::CellPosition& positionOut ) { // Only find valid child actors if( child ) { // Walk through the layout data const unsigned int rowCount = mCellData.GetRows(); const unsigned int columnCount = mCellData.GetColumns(); for( unsigned int row = 0; row < rowCount; ++row ) { for( unsigned int column = 0; column < columnCount; ++column ) { if( mCellData[ row ][ column ].actor == child ) { positionOut = mCellData[ row ][ column ].position; return true; } } } } return false; } void TableView::InsertRow( unsigned int rowIndex ) { RelayoutingLock lock( *this ); mCellData.InsertRow( rowIndex ); // Need to update the cell infos for the items that moved const unsigned int rowCount = mCellData.GetRows(); const unsigned int columnCount = mCellData.GetColumns(); for( unsigned int row = 0; row < rowCount; ++row ) { for( unsigned int column = 0; column < columnCount; ++column ) { Toolkit::TableView::CellPosition& position = mCellData[ row ][ column ].position; // If cell is spanning and above and spans to inserted row if( ( position.rowSpan > 1 ) && ( position.rowIndex <= rowIndex ) && ( position.rowIndex + position.rowSpan > rowIndex ) ) { // Increment span position.rowSpan++; // Copy cell to occupy the new column mCellData[ rowIndex ][ column ] = mCellData[ row ][ column ]; } else if( row > rowIndex ) // If below of inserted row, increase row index { // Increment index position.rowIndex++; } } } // Expand row data array mRowData.Insert( mRowData.Begin() + rowIndex, RowColumnData() ); // Sizes may have changed, so relayout mRowDirty = true; RelayoutRequest(); } void TableView::DeleteRow( unsigned int rowIndex ) { std::vector< Actor > ignored; DeleteRow( rowIndex, ignored ); } void TableView::DeleteRow( unsigned int rowIndex, std::vector<Actor>& removed ) { RelayoutingLock lock( *this ); // Delete the row std::vector< CellData > lost; mCellData.DeleteRow( rowIndex, lost ); // Need to update the cell infos for the items that moved const unsigned int rowCount = mCellData.GetRows(); const unsigned int columnCount = mCellData.GetColumns(); for( unsigned int row = 0; row < rowCount; ++row ) { for( unsigned int column = 0; column < columnCount; ++column ) { Toolkit::TableView::CellPosition& position = mCellData[ row ][ column ].position; // If cell is spanning and above and spans to deleted row if( ( position.rowSpan > 1 ) && ( position.rowIndex <= rowIndex ) && ( position.rowIndex + position.rowSpan > rowIndex ) ) { // Decrement span if( position.rowSpan > 1 ) { position.rowSpan--; } } else if( row >= rowIndex ) // If below of or at the inserted row, decrease row index { // Decrement index if( position.rowIndex > 0 ) { position.rowIndex--; } } } } // 1 row removed, 0 columns RemoveAndGetLostActors( lost, removed, 1u, 0u ); // Contract row data array mRowData.Erase( mRowData.Begin() + rowIndex ); // Sizes may have changed, so relayout mRowDirty = true; // it is possible that the deletion of row leads to remove of child which might further lead to the change of FIT column mColumnDirty = true; RelayoutRequest(); } void TableView::InsertColumn( unsigned int columnIndex ) { RelayoutingLock lock( *this ); // Insert the new column mCellData.InsertColumn( columnIndex ); // Need to update the cell infos for the items that moved const unsigned int rowCount = mCellData.GetRows(); const unsigned int columnCount = mCellData.GetColumns(); for( unsigned int row = 0; row < rowCount; ++row ) { for( unsigned int column = 0; column < columnCount; ++column ) { Toolkit::TableView::CellPosition& position = mCellData[ row ][ column ].position; // If cell is spanning and left side and spans to inserted column if( ( position.columnSpan > 1 ) && ( position.columnIndex <= columnIndex ) && ( position.columnIndex + position.columnSpan > columnIndex ) ) { // Increment span position.columnSpan++; // Copy cell to occupy the new column mCellData[ row ][ columnIndex ] = mCellData[ row ][ column ]; } else if( column > columnIndex ) // If on the right side of inserted column, increase column index { // Increment index position.columnIndex++; } } } // Expand column data array mColumnData.Insert( mColumnData.Begin() + columnIndex, RowColumnData() ); // Sizes may have changed so relayout mColumnDirty = true; RelayoutRequest(); } void TableView::DeleteColumn( unsigned int columnIndex ) { std::vector< Actor > ignored; DeleteColumn( columnIndex, ignored ); } void TableView::DeleteColumn( unsigned int columnIndex, std::vector<Actor>& removed ) { RelayoutingLock lock( *this ); // Remove the column std::vector< CellData > lost; mCellData.DeleteColumn( columnIndex, lost ); // Need to update the cell infos for the items that moved const unsigned int rowCount = mCellData.GetRows(); const unsigned int columnCount = mCellData.GetColumns(); for( unsigned int row = 0; row < rowCount; ++row ) { for( unsigned int column = 0; column < columnCount; ++column ) { Toolkit::TableView::CellPosition& position = mCellData[ row ][ column ].position; // If cell is spanning and left side and spans to inserted column if( ( position.columnSpan > 1 ) && ( position.columnIndex <= columnIndex ) && ( position.columnIndex + position.columnSpan > columnIndex ) ) { // Decrement span if( position.columnSpan > 1 ) { position.columnSpan--; } } else if( column >= columnIndex ) // If on the right side of or at the inserted column, decrease column index { // Decrement index if( position.columnIndex > 0 ) { position.columnIndex--; } } } } // 0 rows, 1 column removed RemoveAndGetLostActors( lost, removed, 0u, 1u ); // Contract column data array mColumnData.Erase( mColumnData.Begin() + columnIndex ); // Size may have changed so relayout mColumnDirty = true; // it is possible that the deletion of column leads to remove of child which might further lead to the change of FIT row mRowDirty = true; RelayoutRequest(); } void TableView::Resize( unsigned int rows, unsigned int columns ) { std::vector< Actor > ignored; Resize( rows, columns, ignored ); } void TableView::Resize( unsigned int rows, unsigned int columns, std::vector<Actor>& removed ) { RelayoutingLock lock( *this ); unsigned int oldRows = GetRows(); unsigned int oldColumns = GetColumns(); // Resize data array std::vector< CellData > lost; ResizeContainers( rows, columns, lost ); // Calculate if we lost rows unsigned int rowsRemoved = 0; unsigned int newRows = GetRows(); if( oldRows < newRows ) { rowsRemoved = newRows - oldRows; } // Calculate if we lost columns unsigned int columnsRemoved = 0; unsigned int newColumns = GetColumns(); if( oldColumns < newColumns ) { rowsRemoved = newColumns - oldColumns; } RemoveAndGetLostActors( lost, removed, rowsRemoved, columnsRemoved ); // Sizes may have changed so request a relayout mRowDirty = true; mColumnDirty = true; RelayoutRequest(); } void TableView::SetCellPadding( Size padding ) { // If padding really changed if( padding != mPadding ) { mPadding = padding; RelayoutRequest(); } } Size TableView::GetCellPadding() { return mPadding; } void TableView::SetFitHeight( unsigned int rowIndex ) { DALI_ASSERT_ALWAYS( rowIndex < mRowData.Size() ); if( mRowData[ rowIndex ].sizePolicy != Toolkit::TableView::FIT ) { mRowData[ rowIndex ].sizePolicy = Toolkit::TableView::FIT; mRowDirty = true; RelayoutRequest(); } } bool TableView::IsFitHeight( unsigned int rowIndex ) const { DALI_ASSERT_ALWAYS( rowIndex < mRowData.Size() ); return mRowData[ rowIndex ].sizePolicy == Toolkit::TableView::FIT; } void TableView::SetFitWidth( unsigned int columnIndex ) { DALI_ASSERT_ALWAYS( columnIndex < mColumnData.Size() ); if( mColumnData[ columnIndex ].sizePolicy != Toolkit::TableView::FIT ) { mColumnData[ columnIndex ].sizePolicy = Toolkit::TableView::FIT; mColumnDirty = true; RelayoutRequest(); } } bool TableView::IsFitWidth( unsigned int columnIndex ) const { DALI_ASSERT_ALWAYS( columnIndex < mColumnData.Size() ); return mColumnData[ columnIndex ].sizePolicy == Toolkit::TableView::FIT; } void TableView::SetFixedHeight( unsigned int rowIndex, float height ) { DALI_ASSERT_ALWAYS( rowIndex < mRowData.Size() ); RowColumnData& data = mRowData[ rowIndex ]; data.size = height; data.sizePolicy = Toolkit::TableView::FIXED; mRowDirty = true; RelayoutRequest(); } float TableView::GetFixedHeight( unsigned int rowIndex ) const { DALI_ASSERT_ALWAYS( rowIndex < mRowData.Size() ); return mRowData[ rowIndex ].size; } void TableView::SetFixedWidth( unsigned int columnIndex, float width ) { DALI_ASSERT_ALWAYS( columnIndex < mColumnData.Size() ); RowColumnData& data = mColumnData[ columnIndex ]; data.size = width; data.sizePolicy = Toolkit::TableView::FIXED; mColumnDirty = true; RelayoutRequest(); } float TableView::GetFixedWidth( unsigned int columnIndex ) const { DALI_ASSERT_ALWAYS( columnIndex < mColumnData.Size() ); return mColumnData[ columnIndex ].size; } void TableView::SetRelativeHeight( unsigned int rowIndex, float heightPercentage ) { DALI_ASSERT_ALWAYS( rowIndex < mRowData.Size() ); RowColumnData& data = mRowData[ rowIndex ]; data.fillRatio = heightPercentage; data.sizePolicy = Toolkit::TableView::RELATIVE; mRowDirty = true; RelayoutRequest(); } float TableView::GetRelativeHeight( unsigned int rowIndex ) const { DALI_ASSERT_ALWAYS( rowIndex < mRowData.Size() ); return mRowData[ rowIndex ].fillRatio; } void TableView::SetRelativeWidth( unsigned int columnIndex, float widthPercentage ) { DALI_ASSERT_ALWAYS( columnIndex < mColumnData.Size() ); RowColumnData& data = mColumnData[ columnIndex ]; data.fillRatio = widthPercentage; data.sizePolicy = Toolkit::TableView::RELATIVE; mColumnDirty = true; RelayoutRequest(); } float TableView::GetRelativeWidth( unsigned int columnIndex ) const { DALI_ASSERT_ALWAYS( columnIndex < mColumnData.Size() ); return mColumnData[ columnIndex ].fillRatio; } void TableView::OnCalculateRelayoutSize( Dimension::Type dimension ) { if( (dimension & Dimension::WIDTH) && mColumnDirty ) { /* * FIXED and FIT have size in pixel * Nothing to do with FIXED, as its value is assigned by user and will not get changed * * Need to update the size for FIT column here */ CalculateFitSizes( mColumnData, Dimension::WIDTH ); /* RELATIVE and FILL have size in ratio * Their size in pixel is not available until we get the negotiated size for the whole table * Nothing to do with RELATIVE, as its ratio is assigned by user and will not get changed * * Need to update the ratio for FILL column here */ CalculateFillSizes( mColumnData ); mFixedTotals.width = CalculateTotalFixedSize( mColumnData ); } if( (dimension & Dimension::HEIGHT) && mRowDirty ) { // refer to the comment above CalculateFitSizes( mRowData, Dimension::HEIGHT ); // refer to the comment above CalculateFillSizes( mRowData ); mFixedTotals.height = CalculateTotalFixedSize( mRowData ); } } void TableView::OnLayoutNegotiated( float size, Dimension::Type dimension ) { // Update the column sizes if( (dimension & Dimension::WIDTH) && mColumnDirty ) { float remainingSize = size - mFixedTotals.width; if( remainingSize < 0.0f ) { remainingSize = 0.0f; } // update every column position in ColumnData array float cumulatedWidth = 0.0f; for( auto&& element : mColumnData ) { if( element.sizePolicy == Toolkit::TableView::FILL || element.sizePolicy == Toolkit::TableView::RELATIVE ) { element.size = element.fillRatio * remainingSize; } cumulatedWidth += element.size; element.position = cumulatedWidth; } mColumnDirty = false; } // Update the row sizes if( (dimension & Dimension::HEIGHT) && mRowDirty ) { float remainingSize = size - mFixedTotals.height; if( remainingSize < 0.0f ) { remainingSize = 0.0f; } // update every row position in RowData array float cumulatedHeight = 0.0f; for( unsigned int row = 0, rowCount = mCellData.GetRows(); row < rowCount; ++row ) { if( mRowData[ row ].sizePolicy == Toolkit::TableView::FILL || mRowData[ row ].sizePolicy == Toolkit::TableView::RELATIVE) { mRowData[ row ].size = mRowData[ row ].fillRatio * remainingSize; } cumulatedHeight += mRowData[ row ].size; mRowData[row].position = cumulatedHeight; } mRowDirty = false; } } void TableView::OnSizeSet( const Vector3& size ) { // If this table view is size negotiated by another actor or control, then the // rows and columns must be recalculated or the new size will not take effect. mRowDirty = mColumnDirty = true; RelayoutRequest(); Control::OnSizeSet( size ); } void TableView::OnRelayout( const Vector2& size, RelayoutContainer& container ) { // Go through the layout data float totalWidth = 0.0; Dali::LayoutDirection::Type layoutDirection = static_cast<Dali::LayoutDirection::Type>( Self().GetProperty(Dali::Actor::Property::LAYOUT_DIRECTION).Get<int>() ); if( Dali::LayoutDirection::RIGHT_TO_LEFT == layoutDirection ) { for (auto&& element : mColumnData) { totalWidth += element.size; } } for( unsigned int row = 0, rowCount = mCellData.GetRows(); row < rowCount; ++row ) { for( unsigned int column = 0, columnCount = mCellData.GetColumns(); column < columnCount; ++column ) { CellData& cellData= mCellData[ row ][ column ]; Actor& actor = cellData.actor; const Toolkit::TableView::CellPosition position = cellData.position; // If there is an actor and this is the main cell of the actor. // An actor can be in multiple cells if its row or column span is more than 1. // We however must lay out each actor only once. if( actor && position.rowIndex == row && position.columnIndex == column ) { // Anchor actor to top left of the cell if( actor.GetProperty( Actor::Property::POSITION_USES_ANCHOR_POINT ).Get< bool >() ) { actor.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT ); } actor.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT ); Padding padding = actor.GetProperty<Vector4>( Actor::Property::PADDING ); float left = (column > 0) ? mColumnData[column - 1].position : 0.f; float right; if( Dali::LayoutDirection::RIGHT_TO_LEFT == layoutDirection ) { right = totalWidth - left; left = right - mColumnData[column].size; } else { right = left + mColumnData[column].size; } float top = row > 0 ? mRowData[row-1].position : 0.f; float bottom = mRowData[row+position.rowSpan-1].position; if( cellData.horizontalAlignment == HorizontalAlignment::LEFT ) { actor.SetProperty( Actor::Property::POSITION_X, left + mPadding.width + padding.left ); } else if( cellData.horizontalAlignment == HorizontalAlignment::RIGHT ) { actor.SetProperty( Actor::Property::POSITION_X, right - mPadding.width - padding.right - actor.GetRelayoutSize( Dimension::WIDTH ) ); } else //if( cellData.horizontalAlignment == HorizontalAlignment::CENTER ) { actor.SetProperty( Actor::Property::POSITION_X, (left + right + padding.left - padding.right - actor.GetRelayoutSize( Dimension::WIDTH )) * 0.5f ); } if( cellData.verticalAlignment == VerticalAlignment::TOP ) { actor.SetProperty( Actor::Property::POSITION_Y, top + mPadding.height + padding.top ); } else if( cellData.verticalAlignment == VerticalAlignment::BOTTOM ) { actor.SetProperty( Actor::Property::POSITION_Y, bottom - mPadding.height - padding.bottom - actor.GetRelayoutSize( Dimension::HEIGHT ) ); } else //if( cellData.verticalAlignment = VerticalAlignment::CENTER ) { actor.SetProperty( Actor::Property::POSITION_Y, (top + bottom + padding.top - padding.bottom - actor.GetRelayoutSize( Dimension::HEIGHT )) * 0.5f ); } } } } } unsigned int TableView::GetRows() { return mCellData.GetRows(); } unsigned int TableView::GetColumns() { return mCellData.GetColumns(); } void TableView::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value ) { Toolkit::TableView tableView = Toolkit::TableView::DownCast( Dali::BaseHandle( object ) ); if( tableView ) { TableView& tableViewImpl( GetImpl( tableView ) ); switch( index ) { case Toolkit::TableView::Property::ROWS: { int rows = 0; if( value.Get( rows ) && rows >= 0 ) { if( static_cast<unsigned int>(rows) != tableViewImpl.GetRows() ) { tableViewImpl.Resize( rows, tableViewImpl.GetColumns() ); } } break; } case Toolkit::TableView::Property::COLUMNS: { int columns = 0; if( value.Get( columns ) && columns >= 0 ) { if( static_cast<unsigned int>( columns ) != tableViewImpl.GetColumns() ) { tableViewImpl.Resize( tableViewImpl.GetRows(), value.Get<int>() ); } } break; } case Toolkit::TableView::Property::CELL_PADDING: { tableViewImpl.SetCellPadding( value.Get<Vector2>() ); break; } case Toolkit::TableView::Property::LAYOUT_ROWS: { SetHeightOrWidthProperty( tableViewImpl, &TableView::SetFixedHeight, &TableView::SetRelativeHeight, &TableView::SetFitHeight, value ); break; } case Toolkit::TableView::Property::LAYOUT_COLUMNS: { SetHeightOrWidthProperty( tableViewImpl, &TableView::SetFixedWidth, &TableView::SetRelativeWidth, &TableView::SetFitWidth, value ); break; } } } } Property::Value TableView::GetProperty( BaseObject* object, Property::Index index ) { Property::Value value; Toolkit::TableView tableView = Toolkit::TableView::DownCast( Dali::BaseHandle( object ) ); if( tableView ) { TableView& tableViewImpl( GetImpl( tableView ) ); switch( index ) { case Toolkit::TableView::Property::ROWS: { value = static_cast<int>( tableViewImpl.GetRows() ); break; } case Toolkit::TableView::Property::COLUMNS: { value = static_cast<int>( tableViewImpl.GetColumns() ); break; } case Toolkit::TableView::Property::CELL_PADDING: { value = tableViewImpl.GetCellPadding(); break; } case Toolkit::TableView::Property::LAYOUT_ROWS: { value = tableViewImpl.GetRowHeightsPropertyValue(); break; } case Toolkit::TableView::Property::LAYOUT_COLUMNS: { value = tableViewImpl.GetColumnWidthsPropertyValue(); break; } } } return value; } void TableView::OnChildAdd( Actor& child ) { if( ! mLayoutingChild ) { // Ensure we're not in the middle of laying out children // Check child properties on actor to decide its position inside the table HorizontalAlignment::Type horizontalAlignment = HorizontalAlignment::LEFT; VerticalAlignment::Type verticalAlignment = VerticalAlignment::TOP; if( child.GetPropertyType( Toolkit::TableView::ChildProperty::CELL_HORIZONTAL_ALIGNMENT ) != Property::NONE ) { std::string value = child.GetProperty( Toolkit::TableView::ChildProperty::CELL_HORIZONTAL_ALIGNMENT ).Get<std::string >(); Scripting::GetEnumeration< HorizontalAlignment::Type >( value.c_str(), HORIZONTAL_ALIGNMENT_STRING_TABLE, HORIZONTAL_ALIGNMENT_STRING_TABLE_COUNT, horizontalAlignment ); } if( child.GetPropertyType( Toolkit::TableView::ChildProperty::CELL_VERTICAL_ALIGNMENT ) != Property::NONE ) { std::string value = child.GetProperty( Toolkit::TableView::ChildProperty::CELL_VERTICAL_ALIGNMENT ).Get<std::string >(); Scripting::GetEnumeration< VerticalAlignment::Type >( value.c_str(), VERTICAL_ALIGNMENT_STRING_TABLE, VERTICAL_ALIGNMENT_STRING_TABLE_COUNT, verticalAlignment ); } Toolkit::TableView::CellPosition cellPosition; if( child.GetPropertyType( Toolkit::TableView::ChildProperty::ROW_SPAN ) != Property::NONE ) { cellPosition.rowSpan = child.GetProperty( Toolkit::TableView::ChildProperty::ROW_SPAN ).Get< int >(); } if( child.GetPropertyType( Toolkit::TableView::ChildProperty::COLUMN_SPAN ) != Property::NONE ) { cellPosition.columnSpan = child.GetProperty( Toolkit::TableView::ChildProperty::COLUMN_SPAN ).Get< int >(); } if( child.GetPropertyType( Toolkit::TableView::ChildProperty::CELL_INDEX ) != Property::NONE ) { Vector2 indices = child.GetProperty( Toolkit::TableView::ChildProperty::CELL_INDEX ).Get<Vector2 >(); cellPosition.rowIndex = static_cast<unsigned int>( indices.x ); cellPosition.columnIndex = static_cast<unsigned int>( indices.y ); AddChild( child, cellPosition ); SetCellAlignment(cellPosition, horizontalAlignment, verticalAlignment); } else { bool availableCellFound = false; // Find the first available cell to store the actor in const unsigned int rowCount = mCellData.GetRows(); const unsigned int columnCount = mCellData.GetColumns(); for( unsigned int row = 0; row < rowCount && !availableCellFound; ++row ) { for( unsigned int column = 0; column < columnCount && !availableCellFound; ++column ) { if( !(mCellData[ row ][ column ].actor) ) { // Put the actor in the cell CellData data; data.actor = child; data.position.columnIndex = column; data.position.rowIndex = row; data.horizontalAlignment = horizontalAlignment; data.verticalAlignment = verticalAlignment; mCellData[ row ][ column ] = data; availableCellFound = true; break; } } } if( ! availableCellFound ) { // No empty cells, so increase size of the table unsigned int newColumnCount = ( columnCount > 0 ) ? columnCount : 1; ResizeContainers( rowCount + 1, newColumnCount ); // Put the actor in the first cell of the new row CellData data; data.actor = child; data.position.rowIndex = rowCount; data.position.columnIndex = 0; data.horizontalAlignment = horizontalAlignment; data.verticalAlignment = verticalAlignment; mCellData[ rowCount ][ 0 ] = data; } RelayoutRequest(); } } Control::OnChildAdd( child ); } void TableView::OnChildRemove( Actor& child ) { // dont process if we're in the middle of bigger operation like delete row, column or resize if( !mLayoutingChild ) { // relayout the table only if instances were found if( RemoveAllInstances( child ) ) { RelayoutRequest(); } } Control::OnChildRemove( child ); } TableView::TableView( unsigned int initialRows, unsigned int initialColumns ) : Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ), mCellData( initialRows, initialColumns ), mPreviousFocusedActor(), mLayoutingChild( false ), mRowDirty( true ), // Force recalculation first time mColumnDirty( true ) { SetKeyboardNavigationSupport( true ); ResizeContainers( initialRows, initialColumns ); } void TableView::OnInitialize() { // Make self as keyboard focusable and focus group Actor self = Self(); self.SetProperty( Actor::Property::KEYBOARD_FOCUSABLE,true); SetAsKeyboardFocusGroup(true); DevelControl::SetAccessibilityConstructor( self, []( Dali::Actor actor ) { return std::unique_ptr< Dali::Accessibility::Accessible >( new Control::Impl::AccessibleImpl( actor, Dali::Accessibility::Role::TABLE ) ); } ); } void TableView::ResizeContainers( unsigned int rows, unsigned int columns ) { std::vector<CellData> ignored; ResizeContainers( rows, columns, ignored ); } void TableView::ResizeContainers( unsigned int rows, unsigned int columns, std::vector<CellData>& removed ) { // Resize cell data mCellData.Resize( rows, columns, removed ); // We don't care if these go smaller, data will be regenerated or is not needed anymore mRowData.Resize( rows ); mColumnData.Resize( columns ); } void TableView::RemoveAndGetLostActors( const std::vector<CellData>& lost, std::vector<Actor>& removed, unsigned int rowsRemoved, unsigned int columnsRemoved ) { // iterate through all lost cells std::vector< CellData >::const_iterator iter = lost.begin(); for( ; iter != lost.end(); ++iter ) { // if it is a valid actor if( (*iter).actor ) { // is this actor still somewhere else in the table Toolkit::TableView::CellPosition position; if( FindChildPosition( (*iter).actor, position ) ) { // it must be spanning multiple cells, position contains the top left most one // check if position is left of the removed location if( position.columnIndex < (*iter).position.columnIndex ) { // if column span is greater than 1 if( mCellData[ position.rowIndex ][ position.columnIndex ].position.columnSpan > 1 ) { // decrease column span mCellData[ position.rowIndex ][ position.columnIndex ].position.columnSpan -= columnsRemoved; } } // check if position is left of the removed location if( position.rowIndex < (*iter).position.rowIndex ) { // if row span is greater than 1 if( mCellData[ position.rowIndex ][ position.columnIndex ].position.rowSpan > 1 ) { // decrease row span mCellData[ position.rowIndex ][ position.columnIndex ].position.rowSpan -= rowsRemoved; } } } else { // this actor is gone for good // add actor to removed container removed.push_back( (*iter).actor ); // we dont want the child actor anymore Self().Remove( (*iter).actor ); } } } } bool TableView::RemoveAllInstances( const Actor& child ) { bool found = false; // walk through the layout data const unsigned int rowCount = mCellData.GetRows(); const unsigned int columnCount = mCellData.GetColumns(); for( unsigned int row = 0; row < rowCount; ++row ) { for( unsigned int column = 0; column < columnCount; ++column ) { if( mCellData[ row ][ column ].actor == child ) { // clear the cell, NOTE that the cell might be spanning multiple cells mCellData[ row ][ column ] = CellData(); found = true; } } } return found; } void TableView::SetHeightOrWidthProperty(TableView& tableViewImpl, void(TableView::*funcFixed)(unsigned int, float), void(TableView::*funcRelative)(unsigned int, float), void(TableView::*funcFit)(unsigned int), const Property::Value& value ) { const Property::Map* map = value.GetMap(); if( map ) { unsigned int index(0); for ( unsigned int i = 0, count = map->Count(); i < count; ++i ) { Property::Value& item = map->GetValue(i); Property::Map* childMap = item.GetMap(); std::istringstream( map->GetKey(i) ) >> index; if( childMap ) { Property::Value* policy = childMap->Find( "policy" ); Property::Value* childMapValue = childMap->Find( "value" ); if( policy && childMapValue ) { std::string policyValue; policy->Get( policyValue ); Toolkit::TableView::LayoutPolicy policy; if( Scripting::GetEnumeration< Toolkit::TableView::LayoutPolicy >( policyValue.c_str(), LAYOUT_POLICY_STRING_TABLE, LAYOUT_POLICY_STRING_TABLE_COUNT, policy ) ) { if( policy == Toolkit::TableView::FIXED ) { (tableViewImpl.*funcFixed)( index, childMapValue->Get<float>() ); } else if( policy == Toolkit::TableView::RELATIVE ) { (tableViewImpl.*funcRelative)( index, childMapValue->Get<float>() ); } else if( policy == Toolkit::TableView::FIT ) { (tableViewImpl.*funcFit)( index ); } // do nothing for FILL policy } } } } } } Property::Value TableView::GetRowHeightsPropertyValue() { Property::Map map; GetMapPropertyValue( mRowData, map); return Property::Value(map); } Property::Value TableView::GetColumnWidthsPropertyValue() { Property::Map map; GetMapPropertyValue( mColumnData, map); return Property::Value(map); } void TableView::GetMapPropertyValue( const RowColumnArray& data, Property::Map& map ) { const char* fixedPolicy = Scripting::GetEnumerationName< Toolkit::TableView::LayoutPolicy >( Toolkit::TableView::FIXED, LAYOUT_POLICY_STRING_TABLE, LAYOUT_POLICY_STRING_TABLE_COUNT ); const char* relativePolicy = Scripting::GetEnumerationName< Toolkit::TableView::LayoutPolicy >( Toolkit::TableView::RELATIVE, LAYOUT_POLICY_STRING_TABLE, LAYOUT_POLICY_STRING_TABLE_COUNT ); const char* fillPolicy = Scripting::GetEnumerationName< Toolkit::TableView::LayoutPolicy >( Toolkit::TableView::FILL, LAYOUT_POLICY_STRING_TABLE, LAYOUT_POLICY_STRING_TABLE_COUNT ); const char* fitPolicy = Scripting::GetEnumerationName< Toolkit::TableView::LayoutPolicy >( Toolkit::TableView::FIT, LAYOUT_POLICY_STRING_TABLE, LAYOUT_POLICY_STRING_TABLE_COUNT ); const RowColumnArray::SizeType count = data.Size(); for( RowColumnArray::SizeType i = 0; i < count; i++ ) { const RowColumnData& dataInstance = data[ i ]; Property::Map item; switch( dataInstance.sizePolicy ) { case Toolkit::TableView::FIXED: { item[ "policy" ] = fixedPolicy; item[ "value" ] = dataInstance.size; break; } case Toolkit::TableView::RELATIVE: { item[ "policy" ] = relativePolicy; item[ "value" ] = dataInstance.fillRatio; break; } case Toolkit::TableView::FIT: { item[ "policy" ] = fitPolicy; item[ "value" ] = 0.f; break; } case Toolkit::TableView::FILL: default: { item[ "policy" ] = fillPolicy; item[ "value" ] = 0.f; break; } } std::ostringstream ss; ss << i; map[ ss.str() ] = item; } } TableView::~TableView() { // nothing to do } Actor TableView::GetNextKeyboardFocusableActor(Actor currentFocusedActor, Toolkit::Control::KeyboardFocus::Direction direction, bool loopEnabled) { Actor nextFocusableActor; if ( !currentFocusedActor ) { // Nothing is currently focused, so the child in the first cell should be focused. nextFocusableActor = GetChildAt(Toolkit::TableView::CellPosition(0, 0)); } else { Toolkit::TableView::CellPosition position; if( FindChildPosition( currentFocusedActor, position ) ) { // The current focused actor is a child of TableView bool focusLost = false; int currentRow = position.rowIndex; int currentColumn = position.columnIndex; int numberOfColumns = GetColumns(); int numberOfRows = GetRows(); bool lastCell = false; Actor nextValidActor; switch ( direction ) { case Toolkit::Control::KeyboardFocus::LEFT: { do { if(--currentColumn < 0) { currentColumn = numberOfColumns - 1; if(--currentRow < 0) { lastCell = true; currentRow = loopEnabled ? numberOfRows - 1 : 0; focusLost = (currentRow == 0); } } nextValidActor = GetChildAt(Toolkit::TableView::CellPosition(currentRow, currentColumn)); } while ( !nextValidActor && !lastCell ); break; } case Toolkit::Control::KeyboardFocus::RIGHT: { do { if(++currentColumn > numberOfColumns - 1) { currentColumn = 0; if(++currentRow > numberOfRows - 1) { lastCell = true; currentRow = loopEnabled ? 0 : numberOfRows - 1; focusLost = (currentRow == numberOfRows - 1); } } nextValidActor = GetChildAt(Toolkit::TableView::CellPosition(currentRow, currentColumn)); } while ( !nextValidActor && !lastCell ); break; } case Toolkit::Control::KeyboardFocus::UP: { do { if(--currentRow < 0) { lastCell = true; currentRow = loopEnabled ? numberOfRows - 1 : 0; focusLost = (currentRow == 0); } nextValidActor = GetChildAt(Toolkit::TableView::CellPosition(currentRow, currentColumn)); } while ( !nextValidActor && !lastCell ); break; } case Toolkit::Control::KeyboardFocus::DOWN: { do { if(++currentRow > numberOfRows - 1) { lastCell = true; currentRow = loopEnabled ? 0 : numberOfRows - 1; focusLost = (currentRow == numberOfRows - 1); } nextValidActor = GetChildAt(Toolkit::TableView::CellPosition(currentRow, currentColumn)); } while ( !nextValidActor && !lastCell ); break; } default: { break; } } // Move the focus if we haven't lost it. if(!focusLost) { nextFocusableActor = GetChildAt(Toolkit::TableView::CellPosition(currentRow, currentColumn)); // Save the focused actor in the TableView. mPreviousFocusedActor = nextFocusableActor; } } else { // The current focused actor is not within this TableView. unsigned int numberOfColumns = GetColumns(); unsigned int numberOfRows = GetRows(); // Check whether the previous focused actor is a focus group (i.e. a layout container) bool wasFocusedOnLayoutContainer = false; Actor previousFocusedActor = mPreviousFocusedActor.GetHandle(); if( previousFocusedActor ) { Toolkit::Control control = Toolkit::Control::DownCast( previousFocusedActor ); if( control ) { Internal::Control& controlImpl = static_cast<Internal::Control&>(control.GetImplementation()); wasFocusedOnLayoutContainer = controlImpl.IsKeyboardFocusGroup(); } } // Check whether the previous focused actor is a layout container and also a child of this TableView Toolkit::TableView::CellPosition position; if( wasFocusedOnLayoutContainer && FindChildPosition( previousFocusedActor, position ) ) { nextFocusableActor = GetNextKeyboardFocusableActor(previousFocusedActor, direction, loopEnabled); } else { // Otherwise, move the focus to either the first or the last cell according to the given direction. if(direction == Toolkit::Control::KeyboardFocus::LEFT || direction == Toolkit::Control::KeyboardFocus::UP) { nextFocusableActor = GetChildAt(Toolkit::TableView::CellPosition(numberOfRows - 1, numberOfColumns - 1)); } else { nextFocusableActor = GetChildAt(Toolkit::TableView::CellPosition(0, 0)); } } } } return nextFocusableActor; } Vector3 TableView::GetNaturalSize() { // Natural size is the size of all fixed cell widths or heights. This ignores cells with relative heights. return Vector3( mFixedTotals.width, mFixedTotals.height, 1.0f ); } float TableView::CalculateChildSize( const Actor& child, Dimension::Type dimension ) { Toolkit::TableView::CellPosition position; if( FindChildPosition( child, position) ) { switch( dimension ) { case Dimension::WIDTH: { float cellSize = 0.0f; cellSize = mColumnData[position.columnIndex+position.columnSpan-1].position - (position.columnIndex > 0 ? mColumnData[position.columnIndex-1].position : 0.f) - mPadding.width * 2.0f; if( cellSize < 0.0f ) { cellSize = 0.0f; } return cellSize; } case Dimension::HEIGHT: { float cellSize = 0.0f; cellSize = mRowData[position.rowIndex+position.rowSpan-1].position - (position.rowIndex > 0 ? mRowData[position.rowIndex-1].position : 0.f) - mPadding.height * 2.0f; if( cellSize < 0.0f ) { cellSize = 0.0f; } return cellSize; } default: { return 0.0f; } } } return 0.0f; // Child not found } bool TableView::RelayoutDependentOnChildren( Dimension::Type dimension ) { if ( Control::RelayoutDependentOnChildren( dimension ) ) { return true; } return FindFit( mRowData ) || FindFit( mColumnData ); } void TableView::SetCellAlignment( Toolkit::TableView::CellPosition position, HorizontalAlignment::Type horizontal, VerticalAlignment::Type vertical ) { // Check if we need to expand our data array if( position.rowIndex >= mCellData.GetRows() ) { // Only adding new rows ResizeContainers( position.rowIndex + 1, mCellData.GetColumns() ); } if( position.columnIndex >= mCellData.GetColumns() ) { // Only adding new columns ResizeContainers( mCellData.GetRows(), position.columnIndex + 1 ); } // Set the alignment of the cell CellData& data = mCellData[ position.rowIndex ][ position.columnIndex ]; data.horizontalAlignment = horizontal; data.verticalAlignment = vertical; } void TableView::CalculateFillSizes( RowColumnArray& data ) { // First pass: Count number of fill entries and calculate used relative space Dali::Vector< RowColumnData* > fillData; float relativeTotal = 0.0f; const unsigned int dataCount = data.Size(); for( unsigned int i = 0; i < dataCount; ++i ) { RowColumnData& dataInstance = data[ i ]; if( dataInstance.sizePolicy == Toolkit::TableView::RELATIVE ) { relativeTotal += dataInstance.fillRatio; } else if(dataInstance.sizePolicy == Toolkit::TableView::FILL) { fillData.PushBack( &dataInstance ); } } // Second pass: Distribute remaining relative space const unsigned int fillCount = fillData.Size(); if( fillCount > 0 ) { if( relativeTotal > 1.0f ) { relativeTotal = 1.0f; } const float evenFillRatio = (1.0f - relativeTotal ) / fillCount; for( unsigned int i = 0; i < fillCount; ++i ) { fillData[ i ]->fillRatio = evenFillRatio; } } } float TableView::CalculateTotalFixedSize( const RowColumnArray& data ) { float totalSize = 0.0f; const unsigned int dataCount = data.Size(); for( unsigned int i = 0; i < dataCount; ++i ) { const RowColumnData& dataInstance = data[ i ]; switch( dataInstance.sizePolicy ) { // we have absolute size to FIXED and FIT column/row and relative size for RELATIVE and FILL column/row case Toolkit::TableView::FIXED: case Toolkit::TableView::FIT: { totalSize += dataInstance.size; break; } default: { break; } } } return totalSize; } Vector2 TableView::GetCellPadding( Dimension::Type dimension ) { switch( dimension ) { case Dimension::WIDTH: { return Vector2( mPadding.x, mPadding.x ); } case Dimension::HEIGHT: { return Vector2( mPadding.y, mPadding.y ); } default: { break; } } return Vector2(); } void TableView::CalculateFitSizes( RowColumnArray& data, Dimension::Type dimension ) { Vector2 cellPadding = GetCellPadding( dimension ); const unsigned int dataCount = data.Size(); for( unsigned int i = 0; i < dataCount; ++i ) { RowColumnData& dataInstance = data[ i ]; if( dataInstance.sizePolicy == Toolkit::TableView::FIT ) { // Find the size of the biggest actor in the row or column float maxActorHeight = 0.0f; unsigned int fitCount = ( dimension == Dimension::WIDTH ) ? mCellData.GetRows() : mCellData.GetColumns(); for( unsigned int j = 0; j < fitCount; ++j ) { unsigned int row = ( dimension == Dimension::WIDTH ) ? j : i; unsigned int column = ( dimension == Dimension::WIDTH ) ? i : j; DALI_ASSERT_DEBUG( row < mCellData.GetRows() ); DALI_ASSERT_DEBUG( column < mCellData.GetColumns() ); const CellData& cellData = mCellData[ row ][ column ]; const Actor& actor = cellData.actor; if( actor ) { if( FitToChild( actor, dimension ) && ( dimension == Dimension::WIDTH ) ? ( cellData.position.columnSpan == 1 ) : ( cellData.position.rowSpan == 1 ) ) { maxActorHeight = std::max( maxActorHeight, actor.GetRelayoutSize( dimension ) + cellPadding.x + cellPadding.y ); } } } dataInstance.size = maxActorHeight; } } } bool TableView::FindFit( const RowColumnArray& data ) { for( unsigned int i = 0, count = data.Size(); i < count; ++i ) { if( data[ i ].sizePolicy == Toolkit::TableView::FIT ) { return true; } } return false; } } // namespace Internal } // namespace Toolkit } // namespace Dali
31.704176
163
0.632552
zyndor
4f281778434e31bcb916752075846cc817a668a9
2,996
cpp
C++
TMuffin/Engine/ExportFunction.cpp
thirty30/Muffin
06db87761be740408457728a40d95cdc8ec05108
[ "MIT" ]
5
2019-10-06T02:41:59.000Z
2020-10-10T13:07:26.000Z
TMuffin/Engine/ExportFunction.cpp
thirty30/Muffin
06db87761be740408457728a40d95cdc8ec05108
[ "MIT" ]
null
null
null
TMuffin/Engine/ExportFunction.cpp
thirty30/Muffin
06db87761be740408457728a40d95cdc8ec05108
[ "MIT" ]
null
null
null
#include "ExportFunction.h" #include "Engine.h" #include "Camera/CCamera.h" #include "Camera/CCameraManager.h" #include "Graphics/SkyBox/CSkyBox.h" #include "Graphics/CGraphicsWorld.h" #include "Audio/CAudioManager.h" tbool TMuffin_Initialize(n32 a_nWinWidth, n32 a_nWinHigh, const tcchar* a_strWinName) { return MuffinInit(a_nWinWidth, a_nWinHigh, a_strWinName); } void TMuffin_Loop() { MuffinMainLoop(); } void TMuffin_Clear() { MuffinClear(); } #define TMUFFIN_REGISTER_CALLBACK(FUNC_NAME, FUNC_TYPE, FUNC_VARIABLE) FUNC_TYPE FUNC_VARIABLE = NULL; \ void FUNC_NAME(FUNC_TYPE a_func) { FUNC_VARIABLE = a_func; } TMUFFIN_REGISTER_CALLBACK(TMuffin_RegisterKeyCallback, MuffinKeyCallBack, pExternalKeyCallBack) TMUFFIN_REGISTER_CALLBACK(TMuffin_RegisterMouseCallback, MuffinMouseCallBack, pExternalMouseCallBack) TMUFFIN_REGISTER_CALLBACK(TMuffin_RegisterCursorCallback, MuffinCursorCallBack, pExternalCursorCallBack) TMUFFIN_REGISTER_CALLBACK(TMuffin_RegisterScrollCallback, MuffinScrollCallBack, pExternalScrollCallBack) TMUFFIN_REGISTER_CALLBACK(TMuffin_RegisterPhysicsCallBack, MuffinPhysicsCallBack, pExternalGameLogicCallBack) TMUFFIN_REGISTER_CALLBACK(TMuffin_RegisterGameLogicCallBack, MuffinGameLogicCallBack, pExternalPhysicsCallBack) #undef TMUFFIN_REGISTER_CALLBACK T_DLL_EXPORT f64 TMuffin_GetAppTime() { return glfwGetTime(); } f64 TMuffin_GetNowFrameTime() { return MUFFIN.GetNowFrameTime(); } f32 TMuffin_GetDeltaFrameTime() { return MUFFIN.GetDeltaFrameTime(); } void TMuffin_SetSkyBox(const tcchar* a_strMeshFile, const tcchar* a_strVertexShader, const tcchar* a_strFragmentShader, const tcchar* a_strXTexture, const tcchar* a_strNegXTexture, const tcchar* a_strYTexture, const tcchar* a_strNegYTexture, const tcchar* a_strZTexture, const tcchar* a_strNegZTexture) { CSkyBox* pSkyBox = new CSkyBox(); pSkyBox->Init(a_strMeshFile, a_strVertexShader, a_strFragmentShader, a_strXTexture, a_strNegXTexture, a_strYTexture, a_strNegYTexture, a_strZTexture, a_strNegZTexture ); MUFFIN.GetGraphicsWorld()->SetSkyBox(pSkyBox); } MuffinCreateComponent pExternalCreateComponent = NULL; void TMuffin_RegisterComponent(MuffinCreateComponent a_fuc) { pExternalCreateComponent = a_fuc; } T_DLL_EXPORT void TMuffin_LoadAudio(tstring a_strName, const tcchar* a_strFilePath) { MUFFIN.GetAudioMgr()->LoadAudio(a_strName, a_strFilePath); } T_DLL_EXPORT void TMuffin_LoadAudioASync(tstring a_strName, const tcchar* a_strFilePath) { MUFFIN.GetAudioMgr()->LoadAudio(a_strName, a_strFilePath); } T_DLL_EXPORT void TMuffin_PlayAudio(tstring a_strName, tbool a_bIsLoop, f32 a_fVolume) { MUFFIN.GetAudioMgr()->Play(a_strName, a_bIsLoop, a_fVolume); } T_DLL_EXPORT void TMuffin_StopAudio(tstring a_strName) { MUFFIN.GetAudioMgr()->Stop(a_strName); } T_DLL_EXPORT void TMuffin_DrawLine(glm::vec3 a_vStartPoint, glm::vec3 a_vEndPoint, glm::vec3 a_vColor, f32 a_fLineWidth) { MUFFIN.GetGraphicsWorld()->DrawLine(a_vStartPoint, a_vEndPoint, a_vColor, a_fLineWidth); }
31.536842
120
0.829105
thirty30
4f2953e4cca8da8ff74b1b78672a5fad7262224e
3,828
cpp
C++
divi/src/walletBackupCreator.cpp
domob1812/Divi
dc7fd7bf9028ed9e256d6ac5ba5d529c21f566dd
[ "MIT" ]
1
2021-08-14T10:13:46.000Z
2021-08-14T10:13:46.000Z
divi/src/walletBackupCreator.cpp
domob1812/Divi
dc7fd7bf9028ed9e256d6ac5ba5d529c21f566dd
[ "MIT" ]
null
null
null
divi/src/walletBackupCreator.cpp
domob1812/Divi
dc7fd7bf9028ed9e256d6ac5ba5d529c21f566dd
[ "MIT" ]
1
2021-12-28T15:53:49.000Z
2021-12-28T15:53:49.000Z
#include "walletBackupCreator.h" #include <utiltime.h> #include <util.h> #include <boost/foreach.hpp> #include <db.h> #include <iostream> #include <ui_interface.h> WalletBackupCreator::WalletBackupCreator ( int numberOfBackups, I_FileSystem& fileSystem, std::string dataDirectory, std::string walletFilename, std::string backupSubfolderDirectory ): nWalletBackups(numberOfBackups) , fileSystem_(fileSystem) , dataDirectory_(dataDirectory) , walletFilename_(walletFilename) , backupSubfolderDirectory_(backupSubfolderDirectory) { nWalletBackups = std::max(0, nWalletBackups); } bool Error (std::string msg) { LogPrintf("%s", msg); return false; } bool Warning (std::string msg) { LogPrintf("%s", msg); return true; } std::string make_preferred(std::string path) { boost::filesystem::path boostPath = path; boostPath.make_preferred(); return boostPath.string(); } bool WalletBackupCreator::BackupFile(PathType& sourceFile, PathType& backupFile) { try { fileSystem_.copy_file(sourceFile, backupFile); LogPrintf("Creating backup of %s -> %s\n", sourceFile.c_str(), backupFile.c_str()); return true; } catch (...) { LogPrintf("Failed to create backup\n"); return false; } return false; } bool WalletBackupCreator::BackupWalletFile(std::string strWalletFile, PathType backupDir) { // Create backup of the wallet std::string dateTimeStr = DateTimeStrFormat(".%Y-%m-%d-%H-%M", GetTime()); std::string backupPathStr = backupDir; backupPathStr += "/" + strWalletFile; std::string sourcePathStr = dataDirectory_; sourcePathStr += "/" + strWalletFile; PathType sourceFile = sourcePathStr; PathType backupFile = backupPathStr + dateTimeStr; sourceFile = make_preferred(sourceFile); backupFile = make_preferred(backupFile); if (fileSystem_.exists(sourceFile)) { return BackupFile(sourceFile,backupFile); } return false; } void WalletBackupCreator::PruneOldBackups(std::string strWalletFile, PathType backupDir) { // Loop backward through backup files and keep the N newest ones (1 <= N <= 10) TimeStampedFolderContents folderContents = fileSystem_.get_timestamped_folder_contents(backupDir); if(folderContents.empty()){ return; } typedef TimeStampedFolderContents::value_type TimeStampedPath; std::sort(folderContents.begin(), folderContents.end(), [](const TimeStampedPath& a, const TimeStampedPath& b) { return a.first < b.first; }); int counter = 0; BOOST_REVERSE_FOREACH (TimeStampedFolderContents::value_type file, folderContents) { counter++; if (counter > nWalletBackups) { // More than nWalletBackups backups: delete oldest one(s) try { fileSystem_.remove(file.second); LogPrintf("Old backup deleted: %s\n", file.second.c_str()); } catch (...) { LogPrintf("Failed to delete backup\n"); } } } } bool WalletBackupCreator::BackupWallet() { bool backupWalletStatus = false; PathType backupDir = dataDirectory_ + backupSubfolderDirectory_; if (!fileSystem_.exists(backupDir)) { // Always create backup folder to not confuse the operating system's file browser fileSystem_.create_directories(backupDir); } if (nWalletBackups > 0) { if (fileSystem_.exists(backupDir)) { backupWalletStatus = BackupWalletFile(walletFilename_,backupDir); PruneOldBackups(walletFilename_,backupDir); } } return backupWalletStatus; } std::string WalletBackupCreator::GetBackupSubfolderDirectory() const { return dataDirectory_ + backupSubfolderDirectory_; }
30.141732
102
0.676855
domob1812
4f2994bfc744616ba8181f8edd2ffe0a28458aa1
1,595
hpp
C++
ReactNativeFrontend/ios/Pods/boost/boost/mpi/detail/ignore_oprimitive.hpp
Harshitha91/Tmdb-react-native-node
e06e3f25a7ee6946ef07a1f524fdf62e48424293
[ "Apache-2.0" ]
12,278
2015-01-29T17:11:33.000Z
2022-03-31T21:12:00.000Z
ios/Pods/boost-for-react-native/boost/mpi/detail/ignore_oprimitive.hpp
c7yrus/alyson-v3
5ad95a8f782f5f5d2fd543d44ca6a8b093395965
[ "Apache-2.0" ]
9,469
2015-01-30T05:33:07.000Z
2022-03-31T16:17:21.000Z
ios/Pods/boost-for-react-native/boost/mpi/detail/ignore_oprimitive.hpp
c7yrus/alyson-v3
5ad95a8f782f5f5d2fd543d44ca6a8b093395965
[ "Apache-2.0" ]
1,343
2017-12-08T19:47:19.000Z
2022-03-26T11:31:36.000Z
// (C) Copyright 2005 Matthias Troyer // Use, modification and distribution is subject to the Boost Software // License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // Authors: Matthias Troyer #ifndef BOOST_MPI_DETAIL_IGNORE_OPRIMITIVE_HPP #define BOOST_MPI_DETAIL_IGNORE_OPRIMITIVE_HPP #include <boost/config.hpp> #include <boost/mpi/datatype.hpp> #include <boost/serialization/array.hpp> namespace boost { namespace mpi { namespace detail { /// @brief a minimal output archive, which ignores any save /// /// This class implements a minimal output archive, probably an output archive /// archetype, doing nothing at any save. It's use, besides acting as an /// archetype is as a base class to implement special archives that ignore /// saving of most types class ignore_oprimitive { public: /// a trivial default constructor ignore_oprimitive() {} /// don't do anything when saving binary data void save_binary(const void *, std::size_t ) { } /// don't do anything when saving arrays template<class T> void save_array(serialization::array_wrapper<T> const&, unsigned int ) { } typedef is_mpi_datatype<mpl::_1> use_array_optimization; #ifndef BOOST_NO_MEMBER_TEMPLATE_FRIENDS friend class archive::save_access; protected: #else public: #endif /// don't do anything when saving primitive types template<class T> void save(const T &) { } }; } } } // end namespace boost::mpi::detail #endif // BOOST_MPI_DETAIL_IGNORE_OPRIMITIVE_HPP
25.31746
78
0.722257
Harshitha91
4f2bb81099a2086e74ada2212cd835f289ae4cf4
6,850
cxx
C++
vtkm/exec/arg/testing/UnitTestFetchArrayNeighborhoodIn.cxx
rushah05/VTKm_FP16
487819a1dbdd8dc3f95cca2942e3f2706a2514b5
[ "BSD-3-Clause" ]
14
2019-10-25T03:25:47.000Z
2022-01-19T02:14:53.000Z
vtkm/exec/arg/testing/UnitTestFetchArrayNeighborhoodIn.cxx
rushah05/VTKm_FP16
487819a1dbdd8dc3f95cca2942e3f2706a2514b5
[ "BSD-3-Clause" ]
2
2020-11-18T16:50:34.000Z
2022-01-21T13:31:47.000Z
vtkm/exec/arg/testing/UnitTestFetchArrayNeighborhoodIn.cxx
rushah05/VTKm_FP16
487819a1dbdd8dc3f95cca2942e3f2706a2514b5
[ "BSD-3-Clause" ]
5
2020-10-02T10:14:35.000Z
2022-03-10T07:50:22.000Z
//============================================================================ // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.txt for details. // // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notice for more information. //============================================================================ #include <vtkm/exec/arg/FetchTagArrayNeighborhoodIn.h> #include <vtkm/exec/arg/ThreadIndicesPointNeighborhood.h> #include <vtkm/testing/Testing.h> namespace { static const vtkm::Id3 POINT_DIMS = { 10, 4, 16 }; template <typename T> struct TestPortal { using ValueType = T; VTKM_EXEC_CONT vtkm::Id GetNumberOfValues() const { return POINT_DIMS[0] * POINT_DIMS[1] * POINT_DIMS[2]; } VTKM_EXEC_CONT ValueType Get(vtkm::Id index) const { VTKM_TEST_ASSERT(index >= 0, "Bad portal index."); VTKM_TEST_ASSERT(index < this->GetNumberOfValues(), "Bad portal index."); return TestValue(index, ValueType()); } }; template <typename NeighborhoodType, typename T> void verify_neighbors(NeighborhoodType neighbors, vtkm::Id index, vtkm::Id3 index3d, T) { T expected; auto* boundary = neighbors.Boundary; //Verify the boundary flags first VTKM_TEST_ASSERT(((index3d[0] != 0) && (index3d[0] != (POINT_DIMS[0] - 1))) == boundary->IsRadiusInXBoundary(1), "Got invalid X radius boundary"); VTKM_TEST_ASSERT(((index3d[1] != 0) && (index3d[1] != (POINT_DIMS[1] - 1))) == boundary->IsRadiusInYBoundary(1), "Got invalid Y radius boundary"); VTKM_TEST_ASSERT(((index3d[2] != 0) && (index3d[2] != (POINT_DIMS[2] - 1))) == boundary->IsRadiusInZBoundary(1), "Got invalid Z radius boundary"); VTKM_TEST_ASSERT((index3d[0] != 0) == boundary->IsNeighborInXBoundary(-1), "Got invalid X negative neighbor boundary"); VTKM_TEST_ASSERT((index3d[1] != 0) == boundary->IsNeighborInYBoundary(-1), "Got invalid Y negative neighbor boundary"); VTKM_TEST_ASSERT((index3d[2] != 0) == boundary->IsNeighborInZBoundary(-1), "Got invalid Z negative neighbor boundary"); VTKM_TEST_ASSERT((index3d[0] != (POINT_DIMS[0] - 1)) == boundary->IsNeighborInXBoundary(1), "Got invalid X positive neighbor boundary"); VTKM_TEST_ASSERT((index3d[1] != (POINT_DIMS[1] - 1)) == boundary->IsNeighborInYBoundary(1), "Got invalid Y positive neighbor boundary"); VTKM_TEST_ASSERT((index3d[2] != (POINT_DIMS[2] - 1)) == boundary->IsNeighborInZBoundary(1), "Got invalid Z positive neighbor boundary"); VTKM_TEST_ASSERT(((boundary->MinNeighborIndices(1)[0] == -1) && (boundary->MaxNeighborIndices(1)[0] == 1)) == boundary->IsRadiusInXBoundary(1), "Got invalid min/max X indices"); VTKM_TEST_ASSERT(((boundary->MinNeighborIndices(1)[1] == -1) && (boundary->MaxNeighborIndices(1)[1] == 1)) == boundary->IsRadiusInYBoundary(1), "Got invalid min/max Y indices"); VTKM_TEST_ASSERT(((boundary->MinNeighborIndices(1)[2] == -1) && (boundary->MaxNeighborIndices(1)[2] == 1)) == boundary->IsRadiusInZBoundary(1), "Got invalid min/max Z indices"); T forwardX = neighbors.Get(1, 0, 0); expected = (index3d[0] == POINT_DIMS[0] - 1) ? TestValue(index, T()) : TestValue(index + 1, T()); VTKM_TEST_ASSERT(test_equal(forwardX, expected), "Got invalid value from Load."); T backwardsX = neighbors.Get(-1, 0, 0); expected = (index3d[0] == 0) ? TestValue(index, T()) : TestValue(index - 1, T()); VTKM_TEST_ASSERT(test_equal(backwardsX, expected), "Got invalid value from Load."); } template <typename T> struct FetchArrayNeighborhoodInTests { void operator()() { TestPortal<T> execObject; using FetchType = vtkm::exec::arg::Fetch<vtkm::exec::arg::FetchTagArrayNeighborhoodIn, vtkm::exec::arg::AspectTagDefault, TestPortal<T>>; FetchType fetch; vtkm::internal::ConnectivityStructuredInternals<3> connectivityInternals; connectivityInternals.SetPointDimensions(POINT_DIMS); vtkm::exec:: ConnectivityStructured<vtkm::TopologyElementTagPoint, vtkm::TopologyElementTagCell, 3> connectivity(connectivityInternals); // Verify that 3D scheduling works with neighborhoods { vtkm::Id3 index3d; vtkm::Id index = 0; for (vtkm::Id k = 0; k < POINT_DIMS[2]; k++) { index3d[2] = k; for (vtkm::Id j = 0; j < POINT_DIMS[1]; j++) { index3d[1] = j; for (vtkm::Id i = 0; i < POINT_DIMS[0]; i++, index++) { index3d[0] = i; vtkm::exec::arg::ThreadIndicesPointNeighborhood indices(index3d, index, connectivity); auto neighbors = fetch.Load(indices, execObject); T value = neighbors.Get(0, 0, 0); VTKM_TEST_ASSERT(test_equal(value, TestValue(index, T())), "Got invalid value from Load."); //We now need to check the neighbors. verify_neighbors(neighbors, index, index3d, value); // This should be a no-op, but we should be able to call it. fetch.Store(indices, execObject, neighbors); } } } } //Verify that 1D scheduling works with neighborhoods for (vtkm::Id index = 0; index < (POINT_DIMS[0] * POINT_DIMS[1] * POINT_DIMS[2]); index++) { vtkm::exec::arg::ThreadIndicesPointNeighborhood indices(index, index, 0, index, connectivity); auto neighbors = fetch.Load(indices, execObject); T value = neighbors.Get(0, 0, 0); //center value VTKM_TEST_ASSERT(test_equal(value, TestValue(index, T())), "Got invalid value from Load."); const vtkm::Id indexij = index % (POINT_DIMS[0] * POINT_DIMS[1]); vtkm::Id3 index3d( indexij % POINT_DIMS[0], indexij / POINT_DIMS[0], index / (POINT_DIMS[0] * POINT_DIMS[1])); //We now need to check the neighbors. verify_neighbors(neighbors, index, index3d, value); // This should be a no-op, but we should be able to call it. fetch.Store(indices, execObject, neighbors); } } }; struct TryType { template <typename T> void operator()(T) const { FetchArrayNeighborhoodInTests<T>()(); } }; void TestExecNeighborhoodFetch() { vtkm::testing::Testing::TryTypes(TryType()); } } // anonymous namespace int UnitTestFetchArrayNeighborhoodIn(int argc, char* argv[]) { return vtkm::testing::Testing::Run(TestExecNeighborhoodFetch, argc, argv); }
36.827957
100
0.613723
rushah05
4f2cae4effb4e0781b0c6286c1c50bfd54dd43d0
57,621
cpp
C++
src/pal/src/sync/cs.cpp
CyberSys/coreclr-mono
83b2cb83b32faa45b4f790237b5c5e259692294a
[ "MIT" ]
1
2015-05-22T14:11:51.000Z
2015-05-22T14:11:51.000Z
src/pal/src/sync/cs.cpp
CyberSys/coreclr-mono
83b2cb83b32faa45b4f790237b5c5e259692294a
[ "MIT" ]
null
null
null
src/pal/src/sync/cs.cpp
CyberSys/coreclr-mono
83b2cb83b32faa45b4f790237b5c5e259692294a
[ "MIT" ]
null
null
null
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // /////////////////////////////////////////////////////////////////////////////// // // File: // cs.cpp // // Purpose: // Implementation of critical sections // /////////////////////////////////////////////////////////////////////////////// #include "pal/thread.hpp" #include "pal/cs.hpp" #include "pal/malloc.hpp" #include "pal/list.h" #include "pal/dbgmsg.h" #include "pal/init.h" #include "pal/process.h" #include <sched.h> #include <pthread.h> using namespace CorUnix; // // Uncomment the following line to turn CS behavior from // unfair to fair lock // // #define PALCS_TRANSFER_OWNERSHIP_ON_RELEASE // // Uncomment the following line to enable simple mutex based CSs // Note: when MUTEX_BASED_CSS is defined, PALCS_TRANSFER_OWNERSHIP_ON_RELEASE // has no effect // // #define MUTEX_BASED_CSS // // Important notes on critical sections layout/semantics on Unix // // 1) The PAL_CRITICAL_SECTION structure below must match the size of the // CRITICAL_SECTION defined in pal.h. Besides the "windows part" // of both the structures must be identical. // 2) Both PAL_CRITICAL_SECTION and CRITICAL_SECTION currently do not match // the size of the Windows' CRITICAL_SECTION. // - From unmanaged code point of view, one should never make assumptions // on the size and layout of the CRITICAL_SECTION structure, and anyway // on Unix PAL's CRITICAL_SECTION extends the Windows one, so that some // assumptions may still work. // - From managed code point of view, one could try to interop directly // to unmanaged critical sections APIs (though that would be quite // meaningless). In order to do that, she would need to define a copy // of the CRITICAL_SECTION structure in his/her code, and that may lead // to access random data beyond the structure limit, if that managed // code is compiled on Unix. // In case such scenario should be supported, the current implementation // will have to be modified in a way to go back to the original Windows // CRITICAL_SECTION layout. That would require to dynamically allocate // the native data and use LockSemaphore as a pointer to it. The current // solution intentionally avoids that since an effort has been made to // make CSs objects completely independent from any other PAL subsystem, // so that they can be used during initialization and shutdown. // In case the "dynamically allocate native data" solution should be // implemented, CSs would acquire a dependency on memory allocation and // thread suspension subsystems, since the first contention on a specific // CS would trigger the native data allocation. // 3) The semantics of the LockCount field has not been kept compatible with // the Windows implementation. // Both on Windows and Unix the lower bit of LockCount indicates // whether or not the CS is locked (for both fair and unfair lock // solution), the second bit indicates whether or not currently there is a // waiter that has been awakened and that is trying to acquire the CS // (only unfair lock solution, unused in the fair one); starting from the // third bit, LockCount represents the number of waiter threads currently // waiting on the CS. // Windows, anyway, implements this semantics in negative logic, so that // an unlocked CS is represented by a LockCount == -1 (i.e. 0xFFFFFFFF, // all the bits set), while on Unix an unlocked CS has LockCount == 0. // Windows needs to use negative logic to support legacy code bad enough // to directly access CS's fields making the assumption that // LockCount == -1 means CS unlocked. Unix will not support that, and // it uses positive logic. // 4) The CRITICAL_SECTION_DEBUG_INFO layout on Unix is intentionally not // compatible with the Windows layout. // 5) For legacy code dependencies issues similar to those just described for // the LockCount field, Windows CS code maintains a per-process list of // debug info for all the CSs, both on debug and free/retail builds. On // Unix such a list is maintained only on debug builds, and no debug // info structure is allocated on free/retail builds // SET_DEFAULT_DEBUG_CHANNEL(CRITSEC); #ifdef TRACE_CS_LOGIC #define CS_TRACE TRACE #else #ifdef __GNUC__ #define CS_TRACE(args...) #else #define CS_TRACE(...) #endif #endif // TRACE_CS_LOGIC // // Note: PALCS_LOCK_WAITER_INC must be 2 * PALCS_LOCK_AWAKENED_WAITER // #define PALCS_LOCK_INIT 0 #define PALCS_LOCK_BIT 1 #define PALCS_LOCK_AWAKENED_WAITER 2 #define PALCS_LOCK_WAITER_INC 4 #define PALCS_GETLBIT(val) ((int)(0!=(PALCS_LOCK_BIT&val))) #define PALCS_GETAWBIT(val) ((int)(0!=(PALCS_LOCK_AWAKENED_WAITER&val))) #define PALCS_GETWCOUNT(val) (val/PALCS_LOCK_WAITER_INC) enum PalCsInitState { PalCsNotInitialized, // Critical section not initialized (InitializedCriticalSection // has not yet been called, or DeleteCriticalsection has been // called). PalCsUserInitialized, // Critical section initialized from the user point of view, // i.e. InitializedCriticalSection has been called. PalCsFullyInitializing, // A thread found the CS locked, this is the first contention on // this CS, and the thread is initializing the CS's native data. PalCsFullyInitialized // Internal CS's native data has been fully initialized. }; enum PalCsWaiterReturnState { PalCsReturnWaiterAwakened, PalCsWaiterDidntWait }; struct _PAL_CRITICAL_SECTION; // fwd declaration typedef struct _CRITICAL_SECTION_DEBUG_INFO { LIST_ENTRY Link; struct _PAL_CRITICAL_SECTION * pOwnerCS; Volatile<ULONG> lAcquireCount; Volatile<ULONG> lEnterCount; Volatile<LONG> lContentionCount; } CRITICAL_SECTION_DEBUG_INFO, *PCRITICAL_SECTION_DEBUG_INFO; typedef struct _PAL_CRITICAL_SECTION_NATIVE_DATA { pthread_mutex_t mutex; pthread_cond_t condition; int iPredicate; } PAL_CRITICAL_SECTION_NATIVE_DATA, *PPAL_CRITICAL_SECTION_NATIVE_DATA; typedef struct _PAL_CRITICAL_SECTION { // Windows part PCRITICAL_SECTION_DEBUG_INFO DebugInfo; Volatile<LONG> LockCount; LONG RecursionCount; SIZE_T OwningThread; HANDLE LockSemaphore; ULONG_PTR SpinCount; // Private Unix part BOOL fInternal; Volatile<PalCsInitState> cisInitState; PAL_CRITICAL_SECTION_NATIVE_DATA csndNativeData; } PAL_CRITICAL_SECTION, *PPAL_CRITICAL_SECTION, *LPPAL_CRITICAL_SECTION; #ifdef _DEBUG namespace CorUnix { PAL_CRITICAL_SECTION g_csPALCSsListLock; LIST_ENTRY g_PALCSList = { &g_PALCSList, &g_PALCSList}; } #endif // _DEBUG #define ObtainCurrentThreadId(thread) ObtainCurrentThreadIdImpl(thread, __func__) static SIZE_T ObtainCurrentThreadIdImpl(CPalThread *pCurrentThread, const char *callingFuncName) { SIZE_T threadId; if(pCurrentThread) { threadId = pCurrentThread->GetThreadId(); _ASSERTE(threadId == THREADSilentGetCurrentThreadId()); } else { threadId = THREADSilentGetCurrentThreadId(); CS_TRACE("Early %s, no pthread data, getting TID internally\n", callingFuncName); } _ASSERTE(0 != threadId); return threadId; } /*++ Function: InitializeCriticalSection See MSDN doc. --*/ void InitializeCriticalSection(LPCRITICAL_SECTION lpCriticalSection) { PERF_ENTRY(InitializeCriticalSection); ENTRY("InitializeCriticalSection(lpCriticalSection=%p)\n", lpCriticalSection); InternalInitializeCriticalSectionAndSpinCount(lpCriticalSection, 0, false); LOGEXIT("InitializeCriticalSection returns void\n"); PERF_EXIT(InitializeCriticalSection); } /*++ Function: InitializeCriticalSectionEx - Flags is ignored. See MSDN doc. --*/ BOOL InitializeCriticalSectionEx(LPCRITICAL_SECTION lpCriticalSection, DWORD dwSpinCount, DWORD Flags) { PERF_ENTRY(InitializeCriticalSection); ENTRY("InitializeCriticalSectionEx(lpCriticalSection=%p, dwSpinCount=%d, Flags=%d)\n", lpCriticalSection, dwSpinCount, Flags); InternalInitializeCriticalSectionAndSpinCount(lpCriticalSection, dwSpinCount, false); LOGEXIT("InitializeCriticalSectionEx returns TRUE\n"); PERF_EXIT(InitializeCriticalSection); return true; } /*++ Function: InitializeCriticalSectionAndSpinCount See MSDN doc. --*/ BOOL InitializeCriticalSectionAndSpinCount(LPCRITICAL_SECTION lpCriticalSection, DWORD dwSpinCount) { BOOL bRet = TRUE; PERF_ENTRY(InitializeCriticalSectionAndSpinCount); ENTRY("InitializeCriticalSectionAndSpinCount(lpCriticalSection=%p, " "dwSpinCount=%u)\n", lpCriticalSection, dwSpinCount); InternalInitializeCriticalSectionAndSpinCount(lpCriticalSection, dwSpinCount, false); LOGEXIT("InitializeCriticalSectionAndSpinCount returns BOOL %d\n", bRet); PERF_EXIT(InitializeCriticalSectionAndSpinCount); return bRet; } /*++ Function: DeleteCriticalSection See MSDN doc. --*/ void DeleteCriticalSection(LPCRITICAL_SECTION lpCriticalSection) { PERF_ENTRY(DeleteCriticalSection); ENTRY("DeleteCriticalSection(lpCriticalSection=%p)\n", lpCriticalSection); InternalDeleteCriticalSection(lpCriticalSection); LOGEXIT("DeleteCriticalSection returns void\n"); PERF_EXIT(DeleteCriticalSection); } /*++ Function: EnterCriticalSection See MSDN doc. --*/ void EnterCriticalSection(LPCRITICAL_SECTION lpCriticalSection) { PERF_ENTRY(EnterCriticalSection); ENTRY("EnterCriticalSection(lpCriticalSection=%p)\n", lpCriticalSection); CPalThread * pThread = InternalGetCurrentThread(); InternalEnterCriticalSection(pThread, lpCriticalSection); LOGEXIT("EnterCriticalSection returns void\n"); PERF_EXIT(EnterCriticalSection); } /*++ Function: TryEnterCriticalSection See MSDN doc. --*/ BOOL TryEnterCriticalSection(LPCRITICAL_SECTION lpCriticalSection) { PERF_ENTRY(TryEnterCriticalSection); ENTRY("TryEnterCriticalSection(lpCriticalSection=%p)\n", lpCriticalSection); CPalThread * pThread = InternalGetCurrentThread(); bool fRet = InternalTryEnterCriticalSection(pThread, lpCriticalSection); LOGEXIT("TryEnterCriticalSection returns bool %d\n", (int)fRet); PERF_EXIT(TryEnterCriticalSection); return (BOOL)fRet; } /*++ Function: LeaveCriticalSection See MSDN doc. --*/ VOID LeaveCriticalSection(LPCRITICAL_SECTION lpCriticalSection) { PERF_ENTRY(LeaveCriticalSection); ENTRY("LeaveCriticalSection(lpCriticalSection=%p)\n", lpCriticalSection); CPalThread * pThread = InternalGetCurrentThread(); InternalLeaveCriticalSection(pThread, lpCriticalSection); LOGEXIT("LeaveCriticalSection returns void\n"); PERF_EXIT(LeaveCriticalSection); } /*++ Function: InternalInitializeCriticalSection Initializes a critical section. It assumes the CS is an internal one, i.e. thread entering it will be marked unsafe for suspension --*/ VOID InternalInitializeCriticalSection(CRITICAL_SECTION *pcs) { InternalInitializeCriticalSectionAndSpinCount(pcs, 0, true); } /*++ Function: InternalDeleteCriticalSection Deletes a critical section --*/ VOID InternalDeleteCriticalSection( PCRITICAL_SECTION pCriticalSection) { PAL_CRITICAL_SECTION * pPalCriticalSection = reinterpret_cast<PAL_CRITICAL_SECTION*>(pCriticalSection); _ASSERT_MSG(PalCsUserInitialized == pPalCriticalSection->cisInitState || PalCsFullyInitialized == pPalCriticalSection->cisInitState, "CS %p is not initialized", pPalCriticalSection); #ifdef _DEBUG CPalThread * pThread = (PALIsThreadDataInitialized() ? GetCurrentPalThread() : NULL); if (0 != pPalCriticalSection->LockCount) { SIZE_T tid; tid = ObtainCurrentThreadId(pThread); int iWaiterCount = (int)PALCS_GETWCOUNT(pPalCriticalSection->LockCount); if (0 != (PALCS_LOCK_BIT & pPalCriticalSection->LockCount)) { // CS is locked if (tid != pPalCriticalSection->OwningThread) { // not owner ASSERT("Thread tid=%u deleting a CS owned by thread tid=%u\n", tid, pPalCriticalSection->OwningThread); } else { // owner if (0 != iWaiterCount) { ERROR("Thread tid=%u is deleting a CS with %d threads waiting on it\n", tid, iWaiterCount); } else { WARN("Thread tid=%u is deleting a critical section it still owns\n", tid); } } } else { // CS is not locked if (0 != iWaiterCount) { ERROR("Deleting a CS with %d threads waiting on it\n", iWaiterCount); } else { ERROR("Thread tid=%u is deleting a critical section currently not " "owned, but with one waiter awakened\n", tid); } } } if (NULL != pPalCriticalSection->DebugInfo) { if (pPalCriticalSection != &CorUnix::g_csPALCSsListLock) { InternalEnterCriticalSection(pThread, reinterpret_cast<CRITICAL_SECTION*>(&g_csPALCSsListLock)); RemoveEntryList(&pPalCriticalSection->DebugInfo->Link); InternalLeaveCriticalSection(pThread, reinterpret_cast<CRITICAL_SECTION*>(&g_csPALCSsListLock)); } else { RemoveEntryList(&pPalCriticalSection->DebugInfo->Link); } #ifdef PAL_TRACK_CRITICAL_SECTIONS_DATA LONG lVal, lNewVal; Volatile<LONG> * plDest; // Update delete count InterlockedIncrement(pPalCriticalSection->fInternal ? &g_lPALCSInternalDeleteCount : &g_lPALCSDeleteCount); // Update acquire count plDest = pPalCriticalSection->fInternal ? &g_lPALCSInternalAcquireCount : &g_lPALCSAcquireCount; do { lVal = *plDest; lNewVal = lVal + pPalCriticalSection->DebugInfo->lAcquireCount; lNewVal = InterlockedCompareExchange(plDest, lNewVal, lVal); } while (lVal != lNewVal); // Update enter count plDest = pPalCriticalSection->fInternal ? &g_lPALCSInternalEnterCount : &g_lPALCSEnterCount; do { lVal = *plDest; lNewVal = lVal + pPalCriticalSection->DebugInfo->lEnterCount; lNewVal = InterlockedCompareExchange(plDest, lNewVal, lVal); } while (lVal != lNewVal); // Update contention count plDest = pPalCriticalSection->fInternal ? &g_lPALCSInternalContentionCount : &g_lPALCSContentionCount; do { lVal = *plDest; lNewVal = lVal + pPalCriticalSection->DebugInfo->lContentionCount; lNewVal = InterlockedCompareExchange(plDest, lNewVal, lVal); } while (lVal != lNewVal); #endif // PAL_TRACK_CRITICAL_SECTIONS_DATA InternalDelete(pThread, pPalCriticalSection->DebugInfo); pPalCriticalSection->DebugInfo = NULL; } #endif // _DEBUG if (PalCsFullyInitialized == pPalCriticalSection->cisInitState) { int iRet; // destroy condition iRet = pthread_cond_destroy(&pPalCriticalSection->csndNativeData.condition); _ASSERT_MSG(0 == iRet, "Failed destroying condition in CS @ %p " "[err=%d]\n", pPalCriticalSection, iRet); // destroy mutex iRet = pthread_mutex_destroy(&pPalCriticalSection->csndNativeData.mutex); _ASSERT_MSG(0 == iRet, "Failed destroying mutex in CS @ %p " "[err=%d]\n", pPalCriticalSection, iRet); } // Reset critical section state pPalCriticalSection->cisInitState = PalCsNotInitialized; } // The following PALCEnterCriticalSection and PALCLeaveCriticalSection // functions are intended to provide CorUnix's InternalEnterCriticalSection // and InternalLeaveCriticalSection functionalities to legacy C code, // which has no knowledge of CPalThread, classes and namespaces. /*++ Function: PALCEnterCriticalSection Provides CorUnix's InternalEnterCriticalSection functionality to legacy C code, which has no knowledge of CPalThread, classes and namespaces. --*/ VOID PALCEnterCriticalSection(CRITICAL_SECTION * pcs) { CPalThread * pThread = (PALIsThreadDataInitialized() ? GetCurrentPalThread() : NULL); CorUnix::InternalEnterCriticalSection(pThread, pcs); } /*++ Function: PALCLeaveCriticalSection Provides CorUnix's InternalLeaveCriticalSection functionality to legacy C code, which has no knowledge of CPalThread, classes and namespaces. --*/ VOID PALCLeaveCriticalSection(CRITICAL_SECTION * pcs) { CPalThread * pThread = (PALIsThreadDataInitialized() ? GetCurrentPalThread() : NULL); CorUnix::InternalLeaveCriticalSection(pThread, pcs); } namespace CorUnix { static PalCsWaiterReturnState PALCS_WaitOnCS( PAL_CRITICAL_SECTION * pPalCriticalSection, LONG lInc); static PAL_ERROR PALCS_DoActualWait(PAL_CRITICAL_SECTION * pPalCriticalSection); static PAL_ERROR PALCS_WakeUpWaiter(PAL_CRITICAL_SECTION * pPalCriticalSection); static bool PALCS_FullyInitialize(PAL_CRITICAL_SECTION * pPalCriticalSection); #ifdef _DEBUG enum CSSubSysInitState { CSSubSysNotInitialzed, CSSubSysInitializing, CSSubSysInitialized }; static Volatile<CSSubSysInitState> csssInitState = CSSubSysNotInitialzed; #ifdef PAL_TRACK_CRITICAL_SECTIONS_DATA static Volatile<LONG> g_lPALCSInitializeCount = 0; static Volatile<LONG> g_lPALCSDeleteCount = 0; static Volatile<LONG> g_lPALCSAcquireCount = 0; static Volatile<LONG> g_lPALCSEnterCount = 0; static Volatile<LONG> g_lPALCSContentionCount = 0; static Volatile<LONG> g_lPALCSInternalInitializeCount = 0; static Volatile<LONG> g_lPALCSInternalDeleteCount = 0; static Volatile<LONG> g_lPALCSInternalAcquireCount = 0; static Volatile<LONG> g_lPALCSInternalEnterCount = 0; static Volatile<LONG> g_lPALCSInternalContentionCount = 0; #endif // PAL_TRACK_CRITICAL_SECTIONS_DATA #endif // _DEBUG /*++ Function: CorUnix::CriticalSectionSubSysInitialize Initializes CS subsystem --*/ void CriticalSectionSubSysInitialize() { static_assert(sizeof(CRITICAL_SECTION) >= sizeof(PAL_CRITICAL_SECTION), "PAL fatal internal error: sizeof(CRITICAL_SECTION) is " "smaller than sizeof(PAL_CRITICAL_SECTION)"); #ifdef _DEBUG LONG lRet = InterlockedCompareExchange((LONG *)&csssInitState, (LONG)CSSubSysInitializing, (LONG)CSSubSysNotInitialzed); if ((LONG)CSSubSysNotInitialzed == lRet) { InitializeListHead(&g_PALCSList); InternalInitializeCriticalSectionAndSpinCount( reinterpret_cast<CRITICAL_SECTION*>(&g_csPALCSsListLock), 0, true); InterlockedExchange((LONG *)&csssInitState, (LONG)CSSubSysInitialized); } else { while (csssInitState != CSSubSysInitialized) { sched_yield(); } } #endif // _DEBUG } /*++ Function: CorUnix::InternalInitializeCriticalSectionAndSpinCount Initializes a CS with the given spin count. If 'fInternal' is true the CS will be treatead as an internal one for its whole lifetime, i.e. any thread that will enter it will be marked as unsafe for suspension as long as it holds the CS --*/ void InternalInitializeCriticalSectionAndSpinCount( PCRITICAL_SECTION pCriticalSection, DWORD dwSpinCount, bool fInternal) { PAL_CRITICAL_SECTION * pPalCriticalSection = reinterpret_cast<PAL_CRITICAL_SECTION*>(pCriticalSection); #ifndef PALCS_TRANSFER_OWNERSHIP_ON_RELEASE // Make sure bits are defined in a usable way _ASSERTE(PALCS_LOCK_AWAKENED_WAITER * 2 == PALCS_LOCK_WAITER_INC); #endif // !PALCS_TRANSFER_OWNERSHIP_ON_RELEASE // Make sure structure sizes are compatible _ASSERTE(sizeof(CRITICAL_SECTION) >= sizeof(PAL_CRITICAL_SECTION)); #ifdef _DEBUG if (sizeof(CRITICAL_SECTION) > sizeof(PAL_CRITICAL_SECTION)) { WARN("PAL_CS_NATIVE_DATA_SIZE appears to be defined to a value (%d) " "larger than needed on this platform (%d).\n", sizeof(CRITICAL_SECTION), sizeof(PAL_CRITICAL_SECTION)); } #endif // _DEBUG // Init CS data pPalCriticalSection->DebugInfo = NULL; pPalCriticalSection->LockCount = 0; pPalCriticalSection->RecursionCount = 0; pPalCriticalSection->SpinCount = dwSpinCount; pPalCriticalSection->OwningThread = NULL; pPalCriticalSection->LockSemaphore = NULL; pPalCriticalSection->fInternal = fInternal; #ifdef _DEBUG CPalThread * pThread = (PALIsThreadDataInitialized() ? GetCurrentPalThread() : NULL); pPalCriticalSection->DebugInfo = InternalNew<CRITICAL_SECTION_DEBUG_INFO>(pThread); _ASSERT_MSG(NULL != pPalCriticalSection->DebugInfo, "Failed to allocate debug info for new CS\n"); // Init debug info data pPalCriticalSection->DebugInfo->lAcquireCount = 0; pPalCriticalSection->DebugInfo->lEnterCount = 0; pPalCriticalSection->DebugInfo->lContentionCount = 0; pPalCriticalSection->DebugInfo->pOwnerCS = pPalCriticalSection; // Insert debug info struct in global list if (pPalCriticalSection != &g_csPALCSsListLock) { InternalEnterCriticalSection(pThread, reinterpret_cast<CRITICAL_SECTION*>(&g_csPALCSsListLock)); InsertTailList(&g_PALCSList, &pPalCriticalSection->DebugInfo->Link); InternalLeaveCriticalSection(pThread, reinterpret_cast<CRITICAL_SECTION*>(&g_csPALCSsListLock)); } else { InsertTailList(&g_PALCSList, &pPalCriticalSection->DebugInfo->Link); } #ifdef PAL_TRACK_CRITICAL_SECTIONS_DATA InterlockedIncrement(fInternal ? &g_lPALCSInternalInitializeCount : &g_lPALCSInitializeCount); #endif // PAL_TRACK_CRITICAL_SECTIONS_DATA #endif // _DEBUG // Set initializazion state pPalCriticalSection->cisInitState = PalCsUserInitialized; #ifdef MUTEX_BASED_CSS bool fInit; do { fInit = PALCS_FullyInitialize(pPalCriticalSection); _ASSERTE(fInit); } while (!fInit && 0 == sched_yield()); if (fInit) { // Set initializazion state pPalCriticalSection->cisInitState = PalCsFullyInitialized; } #endif // MUTEX_BASED_CSS } #ifndef MUTEX_BASED_CSS /*++ Function: CorUnix::InternalEnterCriticalSection Enters a CS, causing the thread to block if the CS is owned by another thread --*/ void InternalEnterCriticalSection( CPalThread * pThread, PCRITICAL_SECTION pCriticalSection) { PAL_CRITICAL_SECTION * pPalCriticalSection = reinterpret_cast<PAL_CRITICAL_SECTION*>(pCriticalSection); LONG lSpinCount; LONG lVal, lNewVal; LONG lBitsToChange, lWaitInc; PalCsWaiterReturnState cwrs; SIZE_T threadId; _ASSERTE(PalCsNotInitialized != pPalCriticalSection->cisInitState); threadId = ObtainCurrentThreadId(pThread); // Check if the current thread already owns the CS // // Note: there is no need for this double check to be atomic. In fact // if the first check fails, the second doesn't count (and it's not // even executed). If the first one succeeds and the second one // doesn't, it doesn't matter if LockCount has already changed by the // time OwningThread is tested. Instead, if the first one succeeded, // and the second also succeeds, LockCount cannot have changed in the // meanwhile, since this is the owning thread and only the owning // thread can change the lock bit when the CS is owned. if ((pPalCriticalSection->LockCount & PALCS_LOCK_BIT) && (pPalCriticalSection->OwningThread == threadId)) { pPalCriticalSection->RecursionCount += 1; #ifdef _DEBUG if (NULL != pPalCriticalSection->DebugInfo) { pPalCriticalSection->DebugInfo->lEnterCount += 1; } #endif // _DEBUG goto IECS_exit; } // Set bits to change and waiter increment for an incoming thread lBitsToChange = PALCS_LOCK_BIT; lWaitInc = PALCS_LOCK_WAITER_INC; lSpinCount = pPalCriticalSection->SpinCount; while (TRUE) { // Either this is an incoming thread, and therefore lBitsToChange // is just PALCS_LOCK_BIT, or this is an awakened waiter _ASSERTE(PALCS_LOCK_BIT == lBitsToChange || (PALCS_LOCK_BIT | PALCS_LOCK_AWAKENED_WAITER) == lBitsToChange); // Make sure the waiter increment is in a valid range _ASSERTE(PALCS_LOCK_WAITER_INC == lWaitInc || PALCS_LOCK_AWAKENED_WAITER == lWaitInc); do { lVal = pPalCriticalSection->LockCount; while (0 == (lVal & PALCS_LOCK_BIT)) { // CS is not locked: try lo lock it // Make sure that whether we are an incoming thread // or the PALCS_LOCK_AWAKENED_WAITER bit is set _ASSERTE((PALCS_LOCK_BIT == lBitsToChange) || (PALCS_LOCK_AWAKENED_WAITER & lVal)); lNewVal = lVal ^ lBitsToChange; // Make sure we are actually trying to lock _ASSERTE(lNewVal & PALCS_LOCK_BIT); CS_TRACE("[ECS %p] Switching from {%d, %d, %d} to " "{%d, %d, %d} ==>\n", pPalCriticalSection, PALCS_GETWCOUNT(lVal), PALCS_GETAWBIT(lVal), PALCS_GETLBIT(lVal), PALCS_GETWCOUNT(lNewVal), PALCS_GETAWBIT(lNewVal), PALCS_GETLBIT(lNewVal)); // Try to switch the value lNewVal = InterlockedCompareExchange (&pPalCriticalSection->LockCount, lNewVal, lVal); CS_TRACE("[ECS %p] ==> %s LockCount={%d, %d, %d} " "lVal={%d, %d, %d}\n", pPalCriticalSection, (lNewVal == lVal) ? "OK" : "NO", PALCS_GETWCOUNT(pPalCriticalSection->LockCount), PALCS_GETAWBIT(pPalCriticalSection->LockCount), PALCS_GETLBIT(pPalCriticalSection->LockCount), PALCS_GETWCOUNT(lVal), PALCS_GETAWBIT(lVal), PALCS_GETLBIT(lVal)); if (lNewVal == lVal) { // CS successfully acquired goto IECS_set_ownership; } // Acquisition failed, some thread raced with us; // update value for next loop lVal = lNewVal; } if (0 < lSpinCount) { sched_yield(); } } while (0 <= --lSpinCount); cwrs = PALCS_WaitOnCS(pPalCriticalSection, lWaitInc); if (PalCsReturnWaiterAwakened == cwrs) { #ifdef PALCS_TRANSFER_OWNERSHIP_ON_RELEASE // // Fair Critical Sections // // In the fair lock case, when a waiter wakes up the CS // must be locked (i.e. ownership passed on to the waiter) _ASSERTE(0 != (PALCS_LOCK_BIT & pPalCriticalSection->LockCount)); // CS successfully acquired goto IECS_set_ownership; #else // PALCS_TRANSFER_OWNERSHIP_ON_RELEASE // // Unfair Critical Sections // _ASSERTE(PALCS_LOCK_AWAKENED_WAITER & pPalCriticalSection->LockCount); lBitsToChange = PALCS_LOCK_BIT | PALCS_LOCK_AWAKENED_WAITER; lWaitInc = PALCS_LOCK_AWAKENED_WAITER; #endif // PALCS_TRANSFER_OWNERSHIP_ON_RELEASE } } IECS_set_ownership: // Critical section acquired: set ownership data pPalCriticalSection->OwningThread = threadId; pPalCriticalSection->RecursionCount = 1; #ifdef _DEBUG if (NULL != pPalCriticalSection->DebugInfo) { pPalCriticalSection->DebugInfo->lAcquireCount += 1; pPalCriticalSection->DebugInfo->lEnterCount += 1; } #endif // _DEBUG IECS_exit: return; } /*++ Function: CorUnix::InternalLeaveCriticalSection Leaves a currently owned CS --*/ void InternalLeaveCriticalSection(CPalThread * pThread, PCRITICAL_SECTION pCriticalSection) { PAL_CRITICAL_SECTION * pPalCriticalSection = reinterpret_cast<PAL_CRITICAL_SECTION*>(pCriticalSection); LONG lVal, lNewVal; #ifdef _DEBUG SIZE_T threadId; _ASSERTE(PalCsNotInitialized != pPalCriticalSection->cisInitState); threadId = ObtainCurrentThreadId(pThread); _ASSERTE(threadId == pPalCriticalSection->OwningThread); #endif // _DEBUG _ASSERT_MSG(PALCS_LOCK_BIT & pPalCriticalSection->LockCount, "Trying to release an unlocked CS\n"); _ASSERT_MSG(0 < pPalCriticalSection->RecursionCount, "Trying to release an unlocked CS\n"); if (--pPalCriticalSection->RecursionCount > 0) { // Recursion was > 1, still owning the CS goto ILCS_cs_exit; } // Reset CS ownership pPalCriticalSection->OwningThread = NULL; // Load the current LockCount value lVal = pPalCriticalSection->LockCount; while (true) { _ASSERT_MSG(0 != (PALCS_LOCK_BIT & lVal), "Trying to release an unlocked CS\n"); // NB: In the fair lock case (PALCS_TRANSFER_OWNERSHIP_ON_RELEASE) the // PALCS_LOCK_AWAKENED_WAITER bit is not used if ( (PALCS_LOCK_BIT == lVal) #ifndef PALCS_TRANSFER_OWNERSHIP_ON_RELEASE || (PALCS_LOCK_AWAKENED_WAITER & lVal) #endif // !PALCS_TRANSFER_OWNERSHIP_ON_RELEASE ) { // Whether there are no waiters (PALCS_LOCK_BIT == lVal) // or a waiter has already been awakened, therefore we // just need to reset the lock bit and return lNewVal = lVal & ~PALCS_LOCK_BIT; CS_TRACE("[LCS-UN %p] Switching from {%d, %d, %d} to " "{%d, %d, %d} ==>\n", pPalCriticalSection, PALCS_GETWCOUNT(lVal), PALCS_GETAWBIT(lVal), PALCS_GETLBIT(lVal), PALCS_GETWCOUNT(lNewVal), PALCS_GETAWBIT(lNewVal), PALCS_GETLBIT(lNewVal)); lNewVal = InterlockedCompareExchange(&pPalCriticalSection->LockCount, lNewVal, lVal); CS_TRACE("[LCS-UN %p] ==> %s\n", pPalCriticalSection, (lNewVal == lVal) ? "OK" : "NO"); if (lNewVal == lVal) { goto ILCS_cs_exit; } } else { // There is at least one waiter, we need to wake it up #ifdef PALCS_TRANSFER_OWNERSHIP_ON_RELEASE // Fair lock case: passing ownership on to the first waiter. // Here we need only to decrement the waiters count. CS will // remain locked and ownership will be passed to the waiter, // which will take care of setting ownership data as soon as // it wakes up lNewVal = lVal - PALCS_LOCK_WAITER_INC; #else // PALCS_TRANSFER_OWNERSHIP_ON_RELEASE // Unfair lock case: we need to atomically decrement the waiters // count (we are about ot wake up one of them), set the // "waiter awakened" bit and to reset the "CS locked" bit. // Note that, since we know that at this time PALCS_LOCK_BIT // is set and PALCS_LOCK_AWAKENED_WAITER is not set, none of // the addenda will affect bits other than its target bit(s), // i.e. PALCS_LOCK_BIT will not affect PALCS_LOCK_AWAKENED_WAITER, // PALCS_LOCK_AWAKENED_WAITER will not affect the actual // count of waiters, and the latter will not change the two // former ones lNewVal = lVal - PALCS_LOCK_WAITER_INC + PALCS_LOCK_AWAKENED_WAITER - PALCS_LOCK_BIT; #endif // PALCS_TRANSFER_OWNERSHIP_ON_RELEASE CS_TRACE("[LCS-CN %p] Switching from {%d, %d, %d} to {%d, %d, %d} ==>\n", pPalCriticalSection, PALCS_GETWCOUNT(lVal), PALCS_GETAWBIT(lVal), PALCS_GETLBIT(lVal), PALCS_GETWCOUNT(lNewVal), PALCS_GETAWBIT(lNewVal), PALCS_GETLBIT(lNewVal)); lNewVal = InterlockedCompareExchange(&pPalCriticalSection->LockCount, lNewVal, lVal); CS_TRACE("[LCS-CN %p] ==> %s\n", pPalCriticalSection, (lNewVal == lVal) ? "OK" : "NO"); if (lNewVal == lVal) { // Wake up the waiter PALCS_WakeUpWaiter (pPalCriticalSection); #ifdef PALCS_TRANSFER_OWNERSHIP_ON_RELEASE // In the fair lock case, we need to yield here to defeat // the inherently unfair nature of the condition/predicate // construct sched_yield(); #endif // PALCS_TRANSFER_OWNERSHIP_ON_RELEASE goto ILCS_cs_exit; } } // CS unlock failed due to race with another thread trying to // register as waiter on it. We need to keep on looping. We // intentionally do not yield here in order to reserve higher // priority for the releasing thread. // // At this point lNewVal contains the latest LockCount value // retrieved by one of the two InterlockedCompareExchange above; // we can use this value as expected LockCount for the next loop, // without the need to fetch it again. lVal = lNewVal; } ILCS_cs_exit: return; } /*++ Function: CorUnix::InternalTryEnterCriticalSection Tries to acquire a CS. It returns true on success, false if the CS is locked by another thread --*/ bool InternalTryEnterCriticalSection( CPalThread * pThread, PCRITICAL_SECTION pCriticalSection) { PAL_CRITICAL_SECTION * pPalCriticalSection = reinterpret_cast<PAL_CRITICAL_SECTION*>(pCriticalSection); LONG lNewVal; SIZE_T threadId; bool fRet = true; _ASSERTE(PalCsNotInitialized != pPalCriticalSection->cisInitState); threadId = ObtainCurrentThreadId(pThread); lNewVal = InterlockedCompareExchange (&pPalCriticalSection->LockCount, (LONG)PALCS_LOCK_BIT, (LONG)PALCS_LOCK_INIT); if (lNewVal == PALCS_LOCK_INIT) { // CS successfully acquired: setting ownership data pPalCriticalSection->OwningThread = threadId; pPalCriticalSection->RecursionCount = 1; #ifdef _DEBUG if (NULL != pPalCriticalSection->DebugInfo) { pPalCriticalSection->DebugInfo->lAcquireCount += 1; pPalCriticalSection->DebugInfo->lEnterCount += 1; } #endif // _DEBUG goto ITECS_exit; } // check if the current thread already owns the criticalSection if ((lNewVal & PALCS_LOCK_BIT) && (pPalCriticalSection->OwningThread == threadId)) { pPalCriticalSection->RecursionCount += 1; #ifdef _DEBUG if (NULL != pPalCriticalSection->DebugInfo) { pPalCriticalSection->DebugInfo->lEnterCount += 1; } #endif // _DEBUG goto ITECS_exit; } // Failed to acquire the CS fRet = false; ITECS_exit: return fRet; } #endif // MUTEX_BASED_CSS /*++ Function: CorUnix::PALCS_FullyInitialize Fully initializes a CS previously initialied true InitializeCriticalSection. This method is called at the first contention on the target CS --*/ bool PALCS_FullyInitialize(PAL_CRITICAL_SECTION * pPalCriticalSection) { LONG lVal, lNewVal; bool fRet = true; lVal = pPalCriticalSection->cisInitState; if (PalCsFullyInitialized == lVal) { goto PCDI_exit; } if (PalCsUserInitialized == lVal) { int iRet; lNewVal = (LONG)PalCsFullyInitializing; lNewVal = InterlockedCompareExchange( (LONG *)&pPalCriticalSection->cisInitState, lNewVal, lVal); if (lNewVal != lVal) { if (PalCsFullyInitialized == lNewVal) { // Another thread did initialize this CS: we can // safely return 'true' goto PCDI_exit; } // Another thread is still initializing this CS: yield and // spin by returning 'false' sched_yield(); fRet = false; goto PCDI_exit; } // // Actual native initialization // // Mutex iRet = pthread_mutex_init(&pPalCriticalSection->csndNativeData.mutex, NULL); if (0 != iRet) { ASSERT("Failed initializing mutex in CS @ %p [err=%d]\n", pPalCriticalSection, iRet); pPalCriticalSection->cisInitState = PalCsUserInitialized; fRet = false; goto PCDI_exit; } #ifndef MUTEX_BASED_CSS // Condition iRet = pthread_cond_init(&pPalCriticalSection->csndNativeData.condition, NULL); if (0 != iRet) { ASSERT("Failed initializing condition in CS @ %p [err=%d]\n", pPalCriticalSection, iRet); pthread_mutex_destroy(&pPalCriticalSection->csndNativeData.mutex); pPalCriticalSection->cisInitState = PalCsUserInitialized; fRet = false; goto PCDI_exit; } // Predicate pPalCriticalSection->csndNativeData.iPredicate = 0; #endif pPalCriticalSection->cisInitState = PalCsFullyInitialized; } else if (PalCsFullyInitializing == lVal) { // Another thread is still initializing this CS: yield and // spin by returning 'false' sched_yield(); fRet = false; goto PCDI_exit; } else { ASSERT("CS %p is not initialized", pPalCriticalSection); fRet = false; goto PCDI_exit; } PCDI_exit: return fRet; } /*++ Function: CorUnix::PALCS_WaitOnCS Waits on a CS owned by anothr thread. It returns PalCsReturnWaiterAwakened if the thread actually waited on the CS and it has been awakened on CS release. It returns PalCsWaiterDidntWait if another thread is currently fully-initializing the CS and therefore the current thread couldn't wait on it --*/ PalCsWaiterReturnState PALCS_WaitOnCS(PAL_CRITICAL_SECTION * pPalCriticalSection, LONG lInc) { DWORD lVal, lNewVal; PAL_ERROR palErr = NO_ERROR; if (PalCsFullyInitialized != pPalCriticalSection->cisInitState) { // First contention, the CS native wait support need to be // initialized at this time if (!PALCS_FullyInitialize(pPalCriticalSection)) { // The current thread failed the full initialization of the CS, // whether because another thread is race-initializing it, or // there are no enough memory/resources at this time, or // InitializeCriticalSection has never been called. By // returning we will cause the thread to spin on CS trying // again until the CS is initialized return PalCsWaiterDidntWait; } } // Make sure we have a valid waiter increment _ASSERTE(PALCS_LOCK_WAITER_INC == lInc || PALCS_LOCK_AWAKENED_WAITER == lInc); do { lVal = pPalCriticalSection->LockCount; // Make sure the waiter increment is compatible with the // awakened waiter bit value _ASSERTE(PALCS_LOCK_WAITER_INC == lInc || PALCS_LOCK_AWAKENED_WAITER & lVal); if (0 == (lVal & PALCS_LOCK_BIT)) { // the CS is no longer locked, let's bail out return PalCsWaiterDidntWait; } lNewVal = lVal + lInc; // Make sure that this thread was whether an incoming one or it // was an awakened waiter and, in this case, we are now going to // turn off the awakened waiter bit _ASSERT_MSG(PALCS_LOCK_WAITER_INC == lInc || 0 == (PALCS_LOCK_AWAKENED_WAITER & lNewVal)); CS_TRACE("[WCS %p] Switching from {%d, %d, %d} to " "{%d, %d, %d} ==> ", pPalCriticalSection, PALCS_GETWCOUNT(lVal), PALCS_GETAWBIT(lVal), PALCS_GETLBIT(lVal), PALCS_GETWCOUNT(lNewVal), PALCS_GETAWBIT(lNewVal), PALCS_GETLBIT(lNewVal)); lNewVal = InterlockedCompareExchange (&pPalCriticalSection->LockCount, lNewVal, lVal); CS_TRACE("[WCS %p] ==> %s\n", pPalCriticalSection, (lNewVal == lVal) ? "OK" : "NO"); } while (lNewVal != lVal); #ifdef _DEBUG if (NULL != pPalCriticalSection->DebugInfo) { pPalCriticalSection->DebugInfo->lContentionCount += 1; } #endif // _DEBUG // Do the actual native wait palErr = PALCS_DoActualWait(pPalCriticalSection); _ASSERT_MSG(NO_ERROR == palErr, "Native CS wait failed\n"); return PalCsReturnWaiterAwakened; } /*++ Function: CorUnix::PALCS_DoActualWait Performs the actual native wait on the CS --*/ PAL_ERROR PALCS_DoActualWait(PAL_CRITICAL_SECTION * pPalCriticalSection) { int iRet; PAL_ERROR palErr = NO_ERROR; CS_TRACE("Trying to go to sleep [CS=%p]\n", pPalCriticalSection); // Lock the mutex iRet = pthread_mutex_lock(&pPalCriticalSection->csndNativeData.mutex); if (0 != iRet) { palErr = ERROR_INTERNAL_ERROR; goto PCDAW_exit; } CS_TRACE("Actually Going to sleep [CS=%p]\n", pPalCriticalSection); while (0 == pPalCriticalSection->csndNativeData.iPredicate) { // Wait on the condition iRet = pthread_cond_wait(&pPalCriticalSection->csndNativeData.condition, &pPalCriticalSection->csndNativeData.mutex); CS_TRACE("Got a signal on condition [pred=%d]!\n", pPalCriticalSection->csndNativeData.iPredicate); if (0 != iRet) { // Failed: unlock the mutex and bail out ASSERT("Failed waiting on condition in CS %p [err=%d]\n", pPalCriticalSection, iRet); pthread_mutex_unlock(&pPalCriticalSection->csndNativeData.mutex); palErr = ERROR_INTERNAL_ERROR; goto PCDAW_exit; } } // Reset the predicate pPalCriticalSection->csndNativeData.iPredicate = 0; // Unlock the mutex iRet = pthread_mutex_unlock(&pPalCriticalSection->csndNativeData.mutex); if (0 != iRet) { palErr = ERROR_INTERNAL_ERROR; goto PCDAW_exit; } PCDAW_exit: CS_TRACE("Just woken up [CS=%p]\n", pPalCriticalSection); return palErr; } /*++ Function: CorUnix::PALCS_WakeUpWaiter Wakes up the first thread waiting on the CS --*/ PAL_ERROR PALCS_WakeUpWaiter(PAL_CRITICAL_SECTION * pPalCriticalSection) { int iRet; PAL_ERROR palErr = NO_ERROR; _ASSERT_MSG(PalCsFullyInitialized == pPalCriticalSection->cisInitState, "Trying to wake up a waiter on CS not fully initialized\n"); // Lock the mutex iRet = pthread_mutex_lock(&pPalCriticalSection->csndNativeData.mutex); if (0 != iRet) { palErr = ERROR_INTERNAL_ERROR; goto PCWUW_exit; } // Set the predicate pPalCriticalSection->csndNativeData.iPredicate = 1; CS_TRACE("Signaling condition/predicate [pred=%d]!\n", pPalCriticalSection->csndNativeData.iPredicate); // Signal the condition iRet = pthread_cond_signal(&pPalCriticalSection->csndNativeData.condition); if (0 != iRet) { // Failed: set palErr, but continue in order to unlock // the mutex anyway ASSERT("Failed setting condition in CS %p [ret=%d]\n", pPalCriticalSection, iRet); palErr = ERROR_INTERNAL_ERROR; } // Unlock the mutex iRet = pthread_mutex_unlock(&pPalCriticalSection->csndNativeData.mutex); if (0 != iRet) { palErr = ERROR_INTERNAL_ERROR; goto PCWUW_exit; } PCWUW_exit: return palErr; } #ifdef _DEBUG /*++ Function: CorUnix::PALCS_ReportStatisticalData Report creation/acquisition/contention statistical data for the all the CSs so far existed and no longer existing in the current process --*/ void PALCS_ReportStatisticalData() { #ifdef PAL_TRACK_CRITICAL_SECTIONS_DATA CPalThread * pThread = InternalGetCurrentThread(); if (NULL == pThread) DebugBreak(); // Take the lock for the global list of CS debug infos InternalEnterCriticalSection(pThread, (CRITICAL_SECTION*)&g_csPALCSsListLock); LONG lPALCSInitializeCount = g_lPALCSInitializeCount; LONG lPALCSDeleteCount = g_lPALCSDeleteCount; LONG lPALCSAcquireCount = g_lPALCSAcquireCount; LONG lPALCSEnterCount = g_lPALCSEnterCount; LONG lPALCSContentionCount = g_lPALCSContentionCount; LONG lPALCSInternalInitializeCount = g_lPALCSInternalInitializeCount; LONG lPALCSInternalDeleteCount = g_lPALCSInternalDeleteCount; LONG lPALCSInternalAcquireCount = g_lPALCSInternalAcquireCount; LONG lPALCSInternalEnterCount = g_lPALCSInternalEnterCount; LONG lPALCSInternalContentionCount = g_lPALCSInternalContentionCount; PLIST_ENTRY pItem = g_PALCSList.Flink; while (&g_PALCSList != pItem) { PCRITICAL_SECTION_DEBUG_INFO pDebugInfo = (PCRITICAL_SECTION_DEBUG_INFO)pItem; if (pDebugInfo->pOwnerCS->fInternal) { lPALCSInternalAcquireCount += pDebugInfo->lAcquireCount; lPALCSInternalEnterCount += pDebugInfo->lEnterCount; lPALCSInternalContentionCount += pDebugInfo->lContentionCount; } else { lPALCSAcquireCount += pDebugInfo->lAcquireCount; lPALCSEnterCount += pDebugInfo->lEnterCount; lPALCSContentionCount += pDebugInfo->lContentionCount; } pItem = pItem->Flink; } // Release the lock for the global list of CS debug infos InternalLeaveCriticalSection(pThread, (CRITICAL_SECTION*)&g_csPALCSsListLock); TRACE("Critical Sections Statistical Data:\n"); TRACE("{\n"); TRACE(" Client code CSs:\n"); TRACE(" {\n"); TRACE(" Initialize Count: %d\n", lPALCSInitializeCount); TRACE(" Delete Count: %d\n", lPALCSDeleteCount); TRACE(" Acquire Count: %d\n", lPALCSAcquireCount); TRACE(" Enter Count: %d\n", lPALCSEnterCount); TRACE(" Contention Count: %d\n", lPALCSContentionCount); TRACE(" }\n"); TRACE(" Internal PAL CSs:\n"); TRACE(" {\n"); TRACE(" Initialize Count: %d\n", lPALCSInternalInitializeCount); TRACE(" Delete Count: %d\n", lPALCSInternalDeleteCount); TRACE(" Acquire Count: %d\n", lPALCSInternalAcquireCount); TRACE(" Enter Count: %d\n", lPALCSInternalEnterCount); TRACE(" Contention Count: %d\n", lPALCSInternalContentionCount); TRACE(" }\n"); TRACE("}\n"); #endif // PAL_TRACK_CRITICAL_SECTIONS_DATA } /*++ Function: CorUnix::PALCS_DumpCSList Dumps the list of all the CS currently existing in this process. --*/ void PALCS_DumpCSList() { CPalThread * pThread = InternalGetCurrentThread(); // Take the lock for the global list of CS debug infos InternalEnterCriticalSection(pThread, (CRITICAL_SECTION*)&g_csPALCSsListLock); PLIST_ENTRY pItem = g_PALCSList.Flink; while (&g_PALCSList != pItem) { PCRITICAL_SECTION_DEBUG_INFO pDebugInfo = (PCRITICAL_SECTION_DEBUG_INFO)pItem; PPAL_CRITICAL_SECTION pCS = pDebugInfo->pOwnerCS; printf("CS @ %p \n" "{\tDebugInfo = %p -> \n", pCS, pDebugInfo); printf("\t{\n\t\t[Link]\n\t\tpOwnerCS = %p\n" "\t\tAcquireCount \t= %d\n" "\t\tEnterCount \t= %d\n" "\t\tContentionCount = %d\n", pDebugInfo->pOwnerCS, pDebugInfo->lAcquireCount.Load(), pDebugInfo->lEnterCount.Load(), pDebugInfo->lContentionCount.Load()); printf("\t}\n"); printf("\tLockCount \t= %#x\n" "\tRecursionCount \t= %d\n" "\tOwningThread \t= %p\n" "\tLockSemaphore \t= %p\n" "\tSpinCount \t= %u\n" "\tfInternal \t= %d\n" "\teInitState \t= %u\n" "\tpNativeData \t= %p ->\n", pCS->LockCount.Load(), pCS->RecursionCount, (void *)pCS->OwningThread, pCS->LockSemaphore, (unsigned)pCS->SpinCount, (int)pCS->fInternal, pCS->cisInitState.Load(), &pCS->csndNativeData); printf("\t{\n\t\t[mutex]\n\t\t[condition]\n" "\t\tPredicate \t= %d\n" "\t}\n}\n",pCS->csndNativeData.iPredicate); printf("}\n"); pItem = pItem->Flink; } // Release the lock for the global list of CS debug infos InternalLeaveCriticalSection(pThread, (CRITICAL_SECTION*)&g_csPALCSsListLock); } #endif // _DEBUG #if defined(MUTEX_BASED_CSS) || defined(_DEBUG) /*++ Function: CorUnix::InternalEnterCriticalSection Enters a CS, causing the thread to block if the CS is owned by another thread --*/ #ifdef MUTEX_BASED_CSS void InternalEnterCriticalSection( CPalThread * pThread, PCRITICAL_SECTION pCriticalSection) #else // MUTEX_BASED_CSS void MTX_InternalEnterCriticalSection( CPalThread * pThread, PCRITICAL_SECTION pCriticalSection) #endif // MUTEX_BASED_CSS { PAL_CRITICAL_SECTION * pPalCriticalSection = reinterpret_cast<PAL_CRITICAL_SECTION*>(pCriticalSection); int iRet; SIZE_T threadId; _ASSERTE(PalCsNotInitialized != pPalCriticalSection->cisInitState); threadId = ObtainCurrentThreadId(pThread); /* check if the current thread already owns the criticalSection */ if (pPalCriticalSection->OwningThread == threadId) { _ASSERTE(0 < pPalCriticalSection->RecursionCount); pPalCriticalSection->RecursionCount += 1; return; } iRet = pthread_mutex_lock(&pPalCriticalSection->csndNativeData.mutex); _ASSERTE(0 == iRet); pPalCriticalSection->OwningThread = threadId; pPalCriticalSection->RecursionCount = 1; } /*++ Function: CorUnix::InternalLeaveCriticalSection Leaves a currently owned CS --*/ #ifdef MUTEX_BASED_CSS void InternalLeaveCriticalSection( CPalThread * pThread, PCRITICAL_SECTION pCriticalSection) #else // MUTEX_BASED_CSS void MTX_InternalLeaveCriticalSection( CPalThread * pThread, PCRITICAL_SECTION pCriticalSection) #endif // MUTEX_BASED_CSS { PAL_CRITICAL_SECTION * pPalCriticalSection = reinterpret_cast<PAL_CRITICAL_SECTION*>(pCriticalSection); int iRet; #ifdef _DEBUG SIZE_T threadId; _ASSERTE(PalCsNotInitialized != pPalCriticalSection->cisInitState); threadId = ObtainCurrentThreadId(pThread); _ASSERTE(threadId == pPalCriticalSection->OwningThread); if (0 >= pPalCriticalSection->RecursionCount) DebugBreak(); _ASSERTE(0 < pPalCriticalSection->RecursionCount); #endif // _DEBUG if (0 < --pPalCriticalSection->RecursionCount) return; pPalCriticalSection->OwningThread = 0; iRet = pthread_mutex_unlock(&pPalCriticalSection->csndNativeData.mutex); _ASSERTE(0 == iRet); } /*++ Function: CorUnix::InternalTryEnterCriticalSection Tries to acquire a CS. It returns true on success, false if the CS is locked by another thread --*/ #ifdef MUTEX_BASED_CSS bool InternalTryEnterCriticalSection( CPalThread * pThread, PCRITICAL_SECTION pCriticalSection) #else // MUTEX_BASED_CSS bool MTX_InternalTryEnterCriticalSection( CPalThread * pThread, PCRITICAL_SECTION pCriticalSection) #endif // MUTEX_BASED_CSS { PAL_CRITICAL_SECTION * pPalCriticalSection = reinterpret_cast<PAL_CRITICAL_SECTION*>(pCriticalSection); bool fRet; SIZE_T threadId; _ASSERTE(PalCsNotInitialized != pPalCriticalSection->cisInitState); threadId = ObtainCurrentThreadId(pThread); /* check if the current thread already owns the criticalSection */ if (pPalCriticalSection->OwningThread == threadId) { pPalCriticalSection->RecursionCount += 1; fRet = true; goto ITECS_exit; } fRet = (0 == pthread_mutex_trylock(&pPalCriticalSection->csndNativeData.mutex)); if (fRet) { pPalCriticalSection->OwningThread = threadId; pPalCriticalSection->RecursionCount = 1; } ITECS_exit: return fRet; } #endif // MUTEX_BASED_CSS || _DEBUG }
35.900935
102
0.612155
CyberSys
4f2cb27bb8f497c5abebacc5166c3337eaff3307
843
cpp
C++
aws-cpp-sdk-mobile/source/model/UpdateProjectRequest.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-mobile/source/model/UpdateProjectRequest.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-mobile/source/model/UpdateProjectRequest.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/mobile/model/UpdateProjectRequest.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/http/URI.h> #include <aws/core/utils/HashingUtils.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <utility> using namespace Aws::Mobile::Model; using namespace Aws::Utils::Stream; using namespace Aws::Utils; using namespace Aws::Http; using namespace Aws; UpdateProjectRequest::UpdateProjectRequest() : m_projectIdHasBeenSet(false) { } void UpdateProjectRequest::AddQueryStringParameters(URI& uri) const { Aws::StringStream ss; if(m_projectIdHasBeenSet) { ss << m_projectId; uri.AddQueryStringParameter("projectId", ss.str()); ss.str(""); } }
22.184211
69
0.725979
perfectrecall
4f2de5fbcab4d8c9ebe97043e6bdd58abe41c99c
4,303
cpp
C++
modules/etc/texture_loader_pkm.cpp
dsrw/godot
61ea011e05dd182351eef1e59ab14cd26bbd73a1
[ "MIT", "Apache-2.0", "CC-BY-4.0", "Unlicense" ]
222
2018-09-10T17:52:03.000Z
2022-03-24T04:55:19.000Z
modules/etc/texture_loader_pkm.cpp
dsrw/godot
61ea011e05dd182351eef1e59ab14cd26bbd73a1
[ "MIT", "Apache-2.0", "CC-BY-4.0", "Unlicense" ]
27
2022-01-11T06:12:37.000Z
2022-03-29T01:07:53.000Z
modules/etc/texture_loader_pkm.cpp
dsrw/godot
61ea011e05dd182351eef1e59ab14cd26bbd73a1
[ "MIT", "Apache-2.0", "CC-BY-4.0", "Unlicense" ]
26
2019-04-12T11:21:26.000Z
2022-03-11T00:20:53.000Z
/*************************************************************************/ /* texture_loader_pkm.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "texture_loader_pkm.h" #include "core/os/file_access.h" #include <string.h> struct ETC1Header { char tag[6]; // "PKM 10" uint16_t format; // Format == number of mips (== zero) uint16_t texWidth; // Texture dimensions, multiple of 4 (big-endian) uint16_t texHeight; uint16_t origWidth; // Original dimensions (big-endian) uint16_t origHeight; }; RES ResourceFormatPKM::load(const String &p_path, const String &p_original_path, Error *r_error) { if (r_error) *r_error = ERR_CANT_OPEN; Error err; FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err); if (!f) return RES(); FileAccessRef fref(f); if (r_error) *r_error = ERR_FILE_CORRUPT; ERR_FAIL_COND_V_MSG(err != OK, RES(), "Unable to open PKM texture file '" + p_path + "'."); // big endian f->set_endian_swap(true); ETC1Header h; f->get_buffer((uint8_t *)&h.tag, sizeof(h.tag)); ERR_FAIL_COND_V_MSG(strncmp(h.tag, "PKM 10", sizeof(h.tag)), RES(), "Invalid or unsupported PKM texture file '" + p_path + "'."); h.format = f->get_16(); h.texWidth = f->get_16(); h.texHeight = f->get_16(); h.origWidth = f->get_16(); h.origHeight = f->get_16(); PoolVector<uint8_t> src_data; uint32_t size = h.texWidth * h.texHeight / 2; src_data.resize(size); PoolVector<uint8_t>::Write wb = src_data.write(); f->get_buffer(wb.ptr(), size); wb.release(); int mipmaps = h.format; int width = h.origWidth; int height = h.origHeight; Ref<Image> img = memnew(Image(width, height, mipmaps, Image::FORMAT_ETC, src_data)); Ref<ImageTexture> texture = memnew(ImageTexture); texture->create_from_image(img); if (r_error) *r_error = OK; f->close(); memdelete(f); return texture; } void ResourceFormatPKM::get_recognized_extensions(List<String> *p_extensions) const { p_extensions->push_back("pkm"); } bool ResourceFormatPKM::handles_type(const String &p_type) const { return ClassDB::is_parent_class(p_type, "Texture"); } String ResourceFormatPKM::get_resource_type(const String &p_path) const { if (p_path.get_extension().to_lower() == "pkm") return "ImageTexture"; return ""; }
37.417391
130
0.571694
dsrw
4f2f798b00bd27c5bce82676977ae7149df73e71
24,566
cpp
C++
src/Gaffer/PlugAlgo.cpp
fbhradec/gaffer
eda6eaf44a5506af781488e914e9c6f6318c081c
[ "BSD-3-Clause" ]
null
null
null
src/Gaffer/PlugAlgo.cpp
fbhradec/gaffer
eda6eaf44a5506af781488e914e9c6f6318c081c
[ "BSD-3-Clause" ]
null
null
null
src/Gaffer/PlugAlgo.cpp
fbhradec/gaffer
eda6eaf44a5506af781488e914e9c6f6318c081c
[ "BSD-3-Clause" ]
null
null
null
////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2012, John Haddon. All rights reserved. // Copyright (c) 2014, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above // copyright notice, this list of conditions and the following // disclaimer. // // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided with // the distribution. // // * Neither the name of John Haddon nor the names of // any other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "Gaffer/PlugAlgo.h" #include "Gaffer/Box.h" #include "Gaffer/CompoundNumericPlug.h" #include "Gaffer/MetadataAlgo.h" #include "Gaffer/Node.h" #include "Gaffer/NumericPlug.h" #include "Gaffer/StringPlug.h" #include "Gaffer/SplinePlug.h" #include "Gaffer/TransformPlug.h" #include "Gaffer/TypedObjectPlug.h" #include "Gaffer/ValuePlug.h" #include "IECore/SplineData.h" #include "boost/algorithm/string/predicate.hpp" #include "boost/algorithm/string/replace.hpp" #include "boost/format.hpp" using namespace std; using namespace IECore; using namespace Gaffer; ////////////////////////////////////////////////////////////////////////// // Replace ////////////////////////////////////////////////////////////////////////// namespace { struct Connections { Plug *plug; PlugPtr input; vector<PlugPtr> outputs; }; typedef vector<Connections> ConnectionsVector; void replacePlugWalk( Plug *existingPlug, Plug *plug, ConnectionsVector &connections ) { // Record output connections. Connections c; c.plug = plug; c.outputs.insert( c.outputs.begin(), existingPlug->outputs().begin(), existingPlug->outputs().end() ); if( plug->children().size() ) { // Recurse for( PlugIterator it( plug ); !it.done(); ++it ) { if( Plug *existingChildPlug = existingPlug->getChild<Plug>( (*it)->getName() ) ) { replacePlugWalk( existingChildPlug, it->get(), connections ); } } } else { // At a leaf - record input connection and transfer values if // necessary. We only store inputs for leaves because automatic // connection tracking will take care of connecting the parent // levels when all children are connected. c.input = existingPlug->getInput(); if( !c.input && plug->direction() == Plug::In ) { ValuePlug *existingValuePlug = runTimeCast<ValuePlug>( existingPlug ); ValuePlug *valuePlug = runTimeCast<ValuePlug>( plug ); if( existingValuePlug && valuePlug ) { valuePlug->setFrom( existingValuePlug ); } } } connections.push_back( c ); } } // namespace namespace Gaffer { namespace PlugAlgo { void replacePlug( Gaffer::GraphComponent *parent, PlugPtr plug ) { Plug *existingPlug = parent->getChild<Plug>( plug->getName() ); if( !existingPlug ) { parent->addChild( plug ); return; } // Transfer values where necessary, and store connections // to transfer after reparenting. ConnectionsVector connections; replacePlugWalk( existingPlug, plug.get(), connections ); // Replace old plug by parenting in new one. parent->setChild( plug->getName(), plug ); // Transfer old connections. We do this after // parenting because downstream acceptsInput() methods // might care what sort of node the connection is coming // from. for( ConnectionsVector::const_iterator it = connections.begin(), eIt = connections.end(); it != eIt; ++it ) { if( it->input ) { it->plug->setInput( it->input.get() ); } for( vector<PlugPtr>::const_iterator oIt = it->outputs.begin(), oeIt = it->outputs.end(); oIt != oeIt; ++oIt ) { (*oIt)->setInput( it->plug ); } } } } // namespace PlugAlgo } // namespace Gaffer ////////////////////////////////////////////////////////////////////////// // Convert to/from Data ////////////////////////////////////////////////////////////////////////// namespace { template<typename T> ValuePlugPtr boxValuePlug( const std::string &name, Plug::Direction direction, unsigned flags, const T *value ) { return new BoxPlug<typename T::ValueType>( name, direction, value->readable(), flags ); } template<typename T> ValuePlugPtr compoundNumericValuePlug( const std::string &name, Plug::Direction direction, unsigned flags, const T *value ) { typedef typename T::ValueType ValueType; typedef typename ValueType::BaseType BaseType; typedef CompoundNumericPlug<ValueType> PlugType; typename PlugType::Ptr result = new PlugType( name, direction, value->readable(), ValueType( Imath::limits<BaseType>::min() ), ValueType( Imath::limits<BaseType>::max() ), flags ); return result; } template<typename T> ValuePlugPtr geometricCompoundNumericValuePlug( const std::string &name, Plug::Direction direction, unsigned flags, const T *value ) { typedef typename T::ValueType ValueType; typedef typename ValueType::BaseType BaseType; typedef CompoundNumericPlug<ValueType> PlugType; typename PlugType::Ptr result = new PlugType( name, direction, value->readable(), ValueType( Imath::limits<BaseType>::min() ), ValueType( Imath::limits<BaseType>::max() ), flags, value->getInterpretation() ); return result; } template<typename T> ValuePlugPtr typedObjectValuePlug( const std::string &name, Plug::Direction direction, unsigned flags, const T *value ) { typename TypedObjectPlug<T>::Ptr result = new TypedObjectPlug<T>( name, direction, value, flags ); return result; } } namespace Gaffer { namespace PlugAlgo { ValuePlugPtr createPlugFromData( const std::string &name, Plug::Direction direction, unsigned flags, const IECore::Data *value ) { switch( value->typeId() ) { case FloatDataTypeId : { FloatPlugPtr valuePlug = new FloatPlug( name, direction, static_cast<const FloatData *>( value )->readable(), Imath::limits<float>::min(), Imath::limits<float>::max(), flags ); return valuePlug; } case IntDataTypeId : { IntPlugPtr valuePlug = new IntPlug( name, direction, static_cast<const IntData *>( value )->readable(), Imath::limits<int>::min(), Imath::limits<int>::max(), flags ); return valuePlug; } case StringDataTypeId : { StringPlugPtr valuePlug = new StringPlug( name, direction, static_cast<const StringData *>( value )->readable(), flags ); return valuePlug; } case BoolDataTypeId : { BoolPlugPtr valuePlug = new BoolPlug( name, direction, static_cast<const BoolData *>( value )->readable(), flags ); return valuePlug; } case V2iDataTypeId : { return geometricCompoundNumericValuePlug( name, direction, flags, static_cast<const V2iData *>( value ) ); } case V3iDataTypeId : { return geometricCompoundNumericValuePlug( name, direction, flags, static_cast<const V3iData *>( value ) ); } case V2fDataTypeId : { return geometricCompoundNumericValuePlug( name, direction, flags, static_cast<const V2fData *>( value ) ); } case V3fDataTypeId : { return geometricCompoundNumericValuePlug( name, direction, flags, static_cast<const V3fData *>( value ) ); } case Color3fDataTypeId : { return compoundNumericValuePlug( name, direction, flags, static_cast<const Color3fData *>( value ) ); } case Color4fDataTypeId : { return compoundNumericValuePlug( name, direction, flags, static_cast<const Color4fData *>( value ) ); } case Box2fDataTypeId : { return boxValuePlug( name, direction, flags, static_cast<const Box2fData *>( value ) ); } case Box2iDataTypeId : { return boxValuePlug( name, direction, flags, static_cast<const Box2iData *>( value ) ); } case Box3fDataTypeId : { return boxValuePlug( name, direction, flags, static_cast<const Box3fData *>( value ) ); } case Box3iDataTypeId : { return boxValuePlug( name, direction, flags, static_cast<const Box3iData *>( value ) ); } case M44fDataTypeId : { M44fPlugPtr valuePlug = new M44fPlug( name, direction, static_cast<const M44fData *>( value )->readable(), flags ); return valuePlug; } case FloatVectorDataTypeId : { return typedObjectValuePlug( name, direction, flags, static_cast<const FloatVectorData *>( value ) ); } case IntVectorDataTypeId : { return typedObjectValuePlug( name, direction, flags, static_cast<const IntVectorData *>( value ) ); } case StringVectorDataTypeId : { return typedObjectValuePlug( name, direction, flags, static_cast<const StringVectorData *>( value ) ); } case InternedStringVectorDataTypeId : { return typedObjectValuePlug( name, direction, flags, static_cast<const InternedStringVectorData *>( value ) ); } case BoolVectorDataTypeId : { return typedObjectValuePlug( name, direction, flags, static_cast<const BoolVectorData *>( value ) ); } case V2iVectorDataTypeId : { return typedObjectValuePlug( name, direction, flags, static_cast<const V2iVectorData *>( value ) ); } case V3fVectorDataTypeId : { return typedObjectValuePlug( name, direction, flags, static_cast<const V3fVectorData *>( value ) ); } case Color3fVectorDataTypeId : { return typedObjectValuePlug( name, direction, flags, static_cast<const Color3fVectorData *>( value ) ); } case M44fVectorDataTypeId : { return typedObjectValuePlug( name, direction, flags, static_cast<const M44fVectorData *>( value ) ); } case M33fVectorDataTypeId : { return typedObjectValuePlug( name, direction, flags, static_cast<const M33fVectorData *>( value ) ); } default : throw IECore::Exception( boost::str( boost::format( "Data for \"%s\" has unsupported value data type \"%s\"" ) % name % value->typeName() ) ); } } IECore::DataPtr extractDataFromPlug( const ValuePlug *plug ) { switch( static_cast<Gaffer::TypeId>(plug->typeId()) ) { case FloatPlugTypeId : return new FloatData( static_cast<const FloatPlug *>( plug )->getValue() ); case IntPlugTypeId : return new IntData( static_cast<const IntPlug *>( plug )->getValue() ); case StringPlugTypeId : return new StringData( static_cast<const StringPlug *>( plug )->getValue() ); case BoolPlugTypeId : return new BoolData( static_cast<const BoolPlug *>( plug )->getValue() ); case V2iPlugTypeId : { const V2iPlug *v2iPlug = static_cast<const V2iPlug *>( plug ); V2iDataPtr data = new V2iData( v2iPlug->getValue() ); data->setInterpretation( v2iPlug->interpretation() ); return data; } case V3iPlugTypeId : { const V3iPlug *v3iPlug = static_cast<const V3iPlug *>( plug ); V3iDataPtr data = new V3iData( v3iPlug->getValue() ); data->setInterpretation( v3iPlug->interpretation() ); return data; } case V2fPlugTypeId : { const V2fPlug *v2fPlug = static_cast<const V2fPlug *>( plug ); V2fDataPtr data = new V2fData( v2fPlug->getValue() ); data->setInterpretation( v2fPlug->interpretation() ); return data; } case V3fPlugTypeId : { const V3fPlug *v3fPlug = static_cast<const V3fPlug *>( plug ); V3fDataPtr data = new V3fData( v3fPlug->getValue() ); data->setInterpretation( v3fPlug->interpretation() ); return data; } case Color3fPlugTypeId : return new Color3fData( static_cast<const Color3fPlug *>( plug )->getValue() ); case Color4fPlugTypeId : return new Color4fData( static_cast<const Color4fPlug *>( plug )->getValue() ); case Box2fPlugTypeId : return new Box2fData( static_cast<const Box2fPlug *>( plug )->getValue() ); case Box2iPlugTypeId : return new Box2iData( static_cast<const Box2iPlug *>( plug )->getValue() ); case Box3fPlugTypeId : return new Box3fData( static_cast<const Box3fPlug *>( plug )->getValue() ); case Box3iPlugTypeId : return new Box3iData( static_cast<const Box3iPlug *>( plug )->getValue() ); case FloatVectorDataPlugTypeId : return static_cast<const FloatVectorDataPlug *>( plug )->getValue()->copy(); case IntVectorDataPlugTypeId : return static_cast<const IntVectorDataPlug *>( plug )->getValue()->copy(); case StringVectorDataPlugTypeId : return static_cast<const StringVectorDataPlug *>( plug )->getValue()->copy(); case InternedStringVectorDataPlugTypeId : return static_cast<const InternedStringVectorDataPlug *>( plug )->getValue()->copy(); case BoolVectorDataPlugTypeId : return static_cast<const BoolVectorDataPlug *>( plug )->getValue()->copy(); case V2iVectorDataPlugTypeId : return static_cast<const V2iVectorDataPlug *>( plug )->getValue()->copy(); case V3fVectorDataPlugTypeId : return static_cast<const V3fVectorDataPlug *>( plug )->getValue()->copy(); case Color3fVectorDataPlugTypeId : return static_cast<const Color3fVectorDataPlug *>( plug )->getValue()->copy(); case M44fVectorDataPlugTypeId : return static_cast<const M44fVectorDataPlug *>( plug )->getValue()->copy(); case M33fVectorDataPlugTypeId : return static_cast<const M33fVectorDataPlug *>( plug )->getValue()->copy(); case SplineffPlugTypeId : return new SplineffData( static_cast<const SplineffPlug *>( plug )->getValue().spline() ); case SplinefColor3fPlugTypeId : return new SplinefColor3fData( static_cast<const SplinefColor3fPlug *>( plug )->getValue().spline() ); case TransformPlugTypeId : return new M44fData( static_cast<const TransformPlug *>( plug )->matrix() ); case M44fPlugTypeId : return new M44fData( static_cast<const M44fPlug *>( plug )->getValue() ); case M33fPlugTypeId : return new M33fData( static_cast<const M33fPlug *>( plug )->getValue() ); default : throw IECore::Exception( boost::str( boost::format( "Plug \"%s\" has unsupported type \"%s\"" ) % plug->getName().string() % plug->typeName() ) ); } } } // namespace PlugAlgo } // namespace Gaffer ////////////////////////////////////////////////////////////////////////// // Promotion ////////////////////////////////////////////////////////////////////////// namespace { Node *externalNode( Plug *plug ) { Node *node = plug->node(); return node ? node->parent<Node>() : nullptr; } const Node *externalNode( const Plug *plug ) { const Node *node = plug->node(); return node ? node->parent<Node>() : nullptr; } bool validatePromotability( const Plug *plug, const Plug *parent, bool throwExceptions, bool childPlug = false ) { if( !plug ) { if( !throwExceptions ) { return false; } else { throw IECore::Exception( "Cannot promote null plug" ); } } if( PlugAlgo::isPromoted( plug ) ) { if( !throwExceptions ) { return false; } else { throw IECore::Exception( boost::str( boost::format( "Cannot promote plug \"%s\" as it is already promoted." ) % plug->fullName() ) ); } } if( plug->direction() == Plug::In ) { // The plug must be serialisable, as we need its input to be saved, // but we only need to check this for the topmost plug and not for // children, because a setInput() call for a parent plug will also // restore child inputs. if( !childPlug && !plug->getFlags( Plug::Serialisable ) ) { if( !throwExceptions ) { return false; } else { throw IECore::Exception( boost::str( boost::format( "Cannot promote plug \"%s\" as it is not serialisable." ) % plug->fullName() ) ); } } if( !plug->getFlags( Plug::AcceptsInputs ) ) { if( !throwExceptions ) { return false; } else { throw IECore::Exception( boost::str( boost::format( "Cannot promote plug \"%s\" as it does not accept inputs." ) % plug->fullName() ) ); } } if( plug->getInput() ) { if( !throwExceptions ) { return false; } else { throw IECore::Exception( boost::str( boost::format( "Cannot promote plug \"%s\" as it already has an input." ) % plug->fullName() ) ); } } } if( !childPlug ) { const Node *node = externalNode( plug ); if( !node ) { if( !throwExceptions ) { return false; } else { throw IECore::Exception( boost::str( boost::format( "Cannot promote plug \"%s\" as there is no external node." ) % plug->fullName() ) ); } } if( parent && parent->node() != node ) { if( !throwExceptions ) { return false; } else { throw IECore::Exception( boost::str( boost::format( "Cannot promote plug \"%s\" because parent \"%s\" is not a descendant of \"%s\"." ) % plug->fullName() % parent % node ) ); } } } // Check all the children of this plug too for( RecursivePlugIterator it( plug ); !it.done(); ++it ) { if( !validatePromotability( it->get(), parent, throwExceptions, /* childPlug = */ true ) ) { return false; } } return true; } std::string promotedName( const Plug *plug ) { std::string result = plug->relativeName( plug->node() ); boost::replace_all( result, ".", "_" ); return result; } void applyDynamicFlag( Plug *plug ) { plug->setFlags( Plug::Dynamic, true ); // Flags are not automatically propagated to the children of compound plugs, // so we need to do that ourselves. We don't want to propagate them to the // children of plug types which create the children themselves during // construction though, hence the typeId checks for the base classes // which add no children during construction. I'm not sure this approach is // necessarily the best - the alternative would be to set everything dynamic // unconditionally and then implement Serialiser::childNeedsConstruction() // for types like CompoundNumericPlug that create children in their constructors. // Or, even better, abolish the Dynamic flag entirely and deal with everything // via serialisers. const Gaffer::TypeId compoundTypes[] = { PlugTypeId, ValuePlugTypeId, ArrayPlugTypeId }; const Gaffer::TypeId *compoundTypesEnd = compoundTypes + 3; if( find( compoundTypes, compoundTypesEnd, (Gaffer::TypeId)plug->typeId() ) != compoundTypesEnd ) { for( RecursivePlugIterator it( plug ); !it.done(); ++it ) { (*it)->setFlags( Plug::Dynamic, true ); if( find( compoundTypes, compoundTypesEnd, (Gaffer::TypeId)(*it)->typeId() ) == compoundTypesEnd ) { it.prune(); } } } } void setFrom( Plug *dst, const Plug *src ) { assert( dst->typeId() == src->typeId() ); if( ValuePlug *dstValuePlug = IECore::runTimeCast<ValuePlug>( dst ) ) { dstValuePlug->setFrom( static_cast<const ValuePlug *>( src ) ); } else { for( PlugIterator it( dst ); !it.done(); ++it ) { Plug *dstChild = it->get(); const Plug *srcChild = src->getChild<Plug>( dstChild->getName() ); assert( srcChild ); setFrom( dstChild, srcChild ); } } } } // namespace namespace Gaffer { namespace PlugAlgo { bool canPromote( const Plug *plug, const Plug *parent ) { return validatePromotability( plug, parent, /* throwExceptions = */ false ); } Plug *promote( Plug *plug, Plug *parent, const StringAlgo::MatchPattern &excludeMetadata ) { return promoteWithName( plug, promotedName( plug ), parent, excludeMetadata ); } Plug *promoteWithName( Plug *plug, const InternedString &name, Plug *parent, const StringAlgo::MatchPattern &excludeMetadata ) { validatePromotability( plug, parent, /* throwExceptions = */ true ); PlugPtr externalPlug = plug->createCounterpart( name, plug->direction() ); if( externalPlug->direction() == Plug::In ) { setFrom( externalPlug.get(), plug ); } Node *externalNode = ::externalNode( plug ); const bool dynamic = runTimeCast<Box>( externalNode ) || parent == externalNode->userPlug(); MetadataAlgo::copyIf( plug, externalPlug.get(), [&excludeMetadata]( const GraphComponent *from, const GraphComponent *to, InternedString name ) { if( StringAlgo::matchMultiple( name.string(), excludeMetadata ) ) { /// \todo Remove `excludeMetadata` and rely on registered exclusions only. An obstacle /// to doing this is making it easy to exclude `layout:*` without lots and lots of /// individual exclusions. return false; } if( boost::ends_with( name.string(), ":promotable" ) ) { // No need to promote "<name>:promotable". If it's true, that's the default // which will apply to the promoted plug anyway. And if it's false, then we're not // promoting. return false; } if( auto promotable = Metadata::value<BoolData>( from, name.string() + ":promotable" ) ) { if( !promotable->readable() ) { return false; } } return true; }, // We use `persistent = dynamic` so that `promoteWithName()` can be used in // constructors for custom nodes, to promote a plug from an internal // network. In this case, we don't want the metadata to be serialised with // the node, as it will be recreated upon construction anyway. /* persistent = */ dynamic ); if( dynamic ) { applyDynamicFlag( externalPlug.get() ); externalPlug->setFlags( Plug::Serialisable, true ); } if( parent ) { parent->addChild( externalPlug ); } else { externalNode->addChild( externalPlug ); } if( externalPlug->direction() == Plug::In ) { plug->setInput( externalPlug ); } else { externalPlug->setInput( plug ); } return externalPlug.get(); } bool isPromoted( const Plug *plug ) { if( !plug ) { return false; } const Node *node = plug->node(); if( !node ) { return false; } const Node *enclosingNode = node->parent<Node>(); if( !enclosingNode ) { return false; } if( plug->direction() == Plug::In ) { const Plug *input = plug->getInput(); return input && input->node() == enclosingNode; } else { for( Plug::OutputContainer::const_iterator it = plug->outputs().begin(), eIt = plug->outputs().end(); it != eIt; ++it ) { if( (*it)->node() == enclosingNode ) { return true; } } return false; } } void unpromote( Plug *plug ) { if( !isPromoted( plug ) ) { if( plug ) { throw IECore::Exception( boost::str( boost::format( "Cannot unpromote plug \"%s\" as it has not been promoted." ) % plug->fullName() ) ); } else { throw IECore::Exception( "Cannot unpromote null plug" ); } } Node *externalNode = ::externalNode( plug ); Plug *externalPlug = nullptr; if( plug->direction() == Plug::In ) { externalPlug = plug->getInput(); plug->setInput( nullptr ); } else { for( Plug::OutputContainer::const_iterator it = plug->outputs().begin(), eIt = plug->outputs().end(); it != eIt; ++it ) { if( (*it)->node() == externalNode ) { externalPlug = *it; break; } } assert( externalPlug ); // should be true because we checked isPromoted() externalPlug->setInput( nullptr ); } // Remove the top level external plug , but only if // all the children are unused too in the case of a compound plug. bool remove = true; Plug *plugToRemove = externalPlug; while( plugToRemove->parent<Plug>() && plugToRemove->parent<Plug>() != externalNode->userPlug() ) { plugToRemove = plugToRemove->parent<Plug>(); for( PlugIterator it( plugToRemove ); !it.done(); ++it ) { if( ( (*it)->direction() == Plug::In && (*it)->outputs().size() ) || ( (*it)->direction() == Plug::Out && (*it)->getInput() ) ) { remove = false; break; } } } if( remove ) { plugToRemove->parent()->removeChild( plugToRemove ); } } } // namespace PlugAlgo } // namespace Gaffer
27.758192
132
0.662013
fbhradec
4f2fbc013c92468ce006df901b3dc1e143ad673c
1,875
hpp
C++
doc/quickbook/oglplus/quickref/dsa/vertex_attrib.hpp
highfidelity/oglplus
c5fb7cc21869cb9555cfa2a7e28ea6bc6491d11e
[ "BSL-1.0" ]
2
2017-06-09T00:28:35.000Z
2017-06-09T00:28:43.000Z
doc/quickbook/oglplus/quickref/dsa/vertex_attrib.hpp
highfidelity/oglplus
c5fb7cc21869cb9555cfa2a7e28ea6bc6491d11e
[ "BSL-1.0" ]
null
null
null
doc/quickbook/oglplus/quickref/dsa/vertex_attrib.hpp
highfidelity/oglplus
c5fb7cc21869cb9555cfa2a7e28ea6bc6491d11e
[ "BSL-1.0" ]
8
2017-01-30T22:06:41.000Z
2020-01-14T17:24:36.000Z
/* * Copyright 2014-2015 Matus Chochlik. Distributed under the Boost * Software License, Version 1.0. (See accompanying file * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ //[oglplus_dsa_vertex_array_attrib namespace oglplus { #if GL_VERSION_4_5 || GL_ARB_direct_state_access class DSAVertexArrayAttrib : public __ProgVarCommonOps_VertexAttrib<__tag_VertexAttrib> { public: DSAVertexArrayAttrib( __VertexArrayName vao, __VertexAttribSlot location ); /*< See [glfunc GetAttribLocation]. >*/ DSAVertexArrayAttrib( __VertexArrayName vao, __ProgramName program, __StrCRef identifier ); /*< See [glfunc GetAttribLocation]. >*/ DSAVertexArrayAttrib& Enable(void); /*< Enables [^this] vertex array attribute. See [glfunc EnableVertexArrayAttrib]. >*/ DSAVertexArrayAttrib& Disable(void); /*< Disables [^this] specified vertex array attribute See [glfunc DisableVertexArrayAttrib]. >*/ DSAVertexArrayAttrib& VertexBuffer( __BufferName buffer, GLintptr offset, GLsizei stride ); /*< Sets the vertex buffer for [^this] vertex array attribute. See [glfunc VertexArrayVertexBuffer]. >*/ DSAVertexArrayAttrib& Format( GLint values_per_vertex, __DataType data_type, __Boolean normalized, GLuint relative_offset ); /*< Sets up the properties of [^this] vertex array attribute. See [glfunc VertexArrayAttribFormat]. >*/ DSAVertexArrayAttrib& IFormat( GLint values_per_vertex, __DataType data_type, GLuint relative_offset ); /*< Sets up the properties of [^this] vertex array attribute. See [glfunc VertexArrayAttribIFormat]. >*/ DSAVertexArrayAttrib& LFormat( GLint values_per_vertex, __DataType data_type, GLuint relative_offset ); /*< Sets up the properties of [^this] vertex array attribute. See [glfunc VertexArrayAttribLFormat]. >*/ }; #endif } // namespace oglplus //]
22.321429
68
0.753067
highfidelity
4f316722ea38d3b2b8d049d7f32aa018644c78f9
162
hpp
C++
GpLog.hpp
ITBear/GpLog
207b3fa77240af28ff82f174629816018468dcad
[ "Apache-2.0" ]
null
null
null
GpLog.hpp
ITBear/GpLog
207b3fa77240af28ff82f174629816018468dcad
[ "Apache-2.0" ]
null
null
null
GpLog.hpp
ITBear/GpLog
207b3fa77240af28ff82f174629816018468dcad
[ "Apache-2.0" ]
null
null
null
#pragma once #include "Consumers/GpLogConsumers.hpp" #include "Formatters/GpLogFormatters.hpp" #include "Utils/GpLogUtils.hpp" #include "GpLogBuilder.hpp"
23.142857
42
0.771605
ITBear
4f31de15de5566e66722bda4ef0ca0e3c8adddf6
4,749
hh
C++
src/mmutil_select.hh
causalpathlab/mmutilR
292a70f89336c7563b2fa9f1f62e59d219739e24
[ "MIT" ]
1
2021-07-23T07:49:10.000Z
2021-07-23T07:49:10.000Z
src/mmutil_select.hh
YPARK/mmutilR
ede9948fe9a0124b9f417d010b7a376dff64ebb9
[ "MIT" ]
2
2022-01-18T22:07:44.000Z
2022-03-10T16:58:34.000Z
src/mmutil_select.hh
YPARK/mmutilR
ede9948fe9a0124b9f417d010b7a376dff64ebb9
[ "MIT" ]
null
null
null
#include "mmutil.hh" #include "mmutil_stat.hh" #include "mmutil_bgzf_util.hh" #include "mmutil_util.hh" #include "mmutil_index.hh" #include "mmutil_io.hh" #include <algorithm> #include <functional> #include <string> #include <unordered_set> #ifndef MMUTIL_SELECT_HH_ #define MMUTIL_SELECT_HH_ /** @param mtx_file @param full_row_file @param _selected @param output */ template <typename STRVEC> int copy_selected_rows(const std::string mtx_file, const std::string full_row_file, const STRVEC &_selected, const std::string output) { using namespace mmutil::io; using Str = std::string; using copier_t = triplet_copier_remapped_rows_t<obgzf_stream, Index, Scalar>; using index_map_t = copier_t::index_map_t; std::vector<Str> features(0); CHK_RET_(read_vector_file(full_row_file, features), "Failed to read features"); std::unordered_set<Str> selected(_selected.begin(), _selected.end()); row_stat_collector_t collector; visit_matrix_market_file(mtx_file, collector); std::vector<Index> Nvec; std_vector(collector.Row_N, Nvec); const Index max_row = collector.max_row; const Index max_col = collector.max_col; std::vector<Index> rows(max_row); std::iota(std::begin(rows), std::end(rows), 0); std::vector<Index> valid_rows; auto _found = [&](const Index j) { return selected.count(features[j]) > 0; }; std::copy_if(rows.begin(), rows.end(), std::back_inserter(valid_rows), _found); index_map_t remap; Index i = 0; Index NNZ = 0; std::vector<Str> out_features; for (Index old_index : valid_rows) { remap[old_index] = i; Index j = valid_rows[i]; out_features.emplace_back(features[j]); NNZ += Nvec[old_index]; ++i; } Str output_feature_file = output + ".rows.gz"; write_vector_file(output_feature_file, out_features); TLOG("Created valid row names"); Str output_mtx_file = output + ".mtx.gz"; copier_t copier(output_mtx_file, remap, NNZ); visit_matrix_market_file(mtx_file, copier); TLOG("Finished copying submatrix data"); // std::string idx_file = output_mtx_file + ".index"; // CHK_RET_(mmutil::index::build_mmutil_index(output_mtx_file, idx_file), // "Failed to construct an index file: " << idx_file); TLOG("Done"); return EXIT_SUCCESS; } /** @param mtx_file @param full_column_file @param selected_column_file @param output */ template <typename STRVEC> int copy_selected_columns(const std::string mtx_file, const std::string full_column_file, const STRVEC &_selected, const std::string output) { using namespace mmutil::io; using Str = std::string; using copier_t = triplet_copier_remapped_cols_t<obgzf_stream, Index, Scalar>; std::unordered_set<Str> selected(_selected.begin(), _selected.end()); std::vector<Str> full_column_names(0); CHK_RET_(read_vector_file(full_column_file, full_column_names), "Failed to read column names"); col_stat_collector_t collector; visit_matrix_market_file(mtx_file, collector); const IntVec &nnz_col = collector.Col_N; const Index max_row = collector.max_row, max_col = collector.max_col; ASSERT_RET(full_column_names.size() >= max_col, "Insufficient number of columns"); std::vector<Index> cols(max_col); std::iota(std::begin(cols), std::end(cols), 0); std::vector<Index> valid_cols; auto _found = [&](const Index j) { return selected.count(full_column_names.at(j)) > 0; }; std::copy_if(cols.begin(), cols.end(), std::back_inserter(valid_cols), _found); TLOG("Found " << valid_cols.size() << " columns"); copier_t::index_map_t remap; std::vector<Str> out_column_names; std::vector<Index> index_out(valid_cols.size()); std::vector<Scalar> out_scores; Index i = 0; Index NNZ = 0; for (Index old_index : valid_cols) { remap[old_index] = i; out_column_names.push_back(full_column_names.at(old_index)); NNZ += nnz_col(old_index); ++i; } TLOG("Created valid column names"); const Str output_column_file = output + ".cols.gz"; const Str output_mtx_file = output + ".mtx.gz"; write_vector_file(output_column_file, out_column_names); copier_t copier(output_mtx_file, remap, NNZ); visit_matrix_market_file(mtx_file, copier); TLOG("Finished copying submatrix data"); return EXIT_SUCCESS; } #endif
27.77193
77
0.64961
causalpathlab
4f39ab25f33aab4ed0bdd19b57e1d44869ba9bad
6,123
cpp
C++
test/sources/tools/match/test-group.cpp
Kartonagnick/tools-match
ec27ca94a031e04f072f8366bde2d567c29134c8
[ "MIT" ]
null
null
null
test/sources/tools/match/test-group.cpp
Kartonagnick/tools-match
ec27ca94a031e04f072f8366bde2d567c29134c8
[ "MIT" ]
7
2021-02-05T20:45:04.000Z
2021-03-09T15:12:14.000Z
test/sources/tools/match/test-group.cpp
Kartonagnick/tools-match
ec27ca94a031e04f072f8366bde2d567c29134c8
[ "MIT" ]
null
null
null
 // [2021y-02m-05d] Idrisov Denis R. #include <mygtest/test-list.hpp> #ifdef TEST_TOOLS_MATCH_GROUP #include <tools/match/group.hpp> #define TEST_CASE_NAME tools #define TEST_NUMBER(n) match_group_##n namespace me = ::TEST_CASE_NAME; //============================================================================== namespace {} // namespace //============================================================================== #ifndef NDEBUG // --- match_group(nullptr, mask) TEST_COMPONENT(000) { bool re = false; ASSERT_DEATH_DEBUG( char* mask = NULL; re = me::match_group("USOUSD", mask); ); ASSERT_DEATH_DEBUG( wchar_t* mask = NULL; re = me::match_group(L"USOUSD", mask); ); (void) re; } // --- match_group(mask, nullptr) TEST_COMPONENT(001) { bool re = false; ASSERT_DEATH_DEBUG( const char* const mask = NULL; re = me::match_group("USOUSD", mask) ); ASSERT_DEATH_DEBUG( const wchar_t* const mask = NULL; re = me::match_group(L"USOUSD", mask) ); (void) re; } // --- match_group(nullptr, nullptr) TEST_COMPONENT(002) { bool re = false; ASSERT_DEATH_DEBUG( const char* const text = NULL; const char* const mask = NULL; re = me::match_group(text, mask) ); ASSERT_DEATH_DEBUG( const wchar_t* const text = NULL; const wchar_t* const mask = NULL; re = me::match_group(text, mask) ); (void) re; } #endif //!!NDEBUG TEST_COMPONENT(003) { const char* group = "NASUSD,UKOUSD,USOUSD,Z30CHF,!*"; ASSERT_TRUE(!me::match_group("USOUSD", group)); } TEST_COMPONENT(004) { const char* group = "NASUSD, UKOUSD,USOUSD,Z30CHF,!* "; ASSERT_TRUE(!me::match_group("USOUSD", group)); } TEST_COMPONENT(005) { const char* group = " , NASUSD, UKOUSD,USOUSD,Z30CHF,!* , "; ASSERT_TRUE(!me::match_group("USOUSD", group)); } TEST_COMPONENT(006) { const char* group = " , ,NASUSD, UKOUSD,USOUSD,Z30CHF,!* ,,"; ASSERT_TRUE(!me::match_group("USOUSD", group)); } TEST_COMPONENT(007) { const char* group = "NASUSD,UKOUSD,USOUSD,Z30CHF,*"; ASSERT_TRUE(me::match_group("ASOUSD", group)); } TEST_COMPONENT(008) { const char* group = "EUR*,!EURHHH"; ASSERT_TRUE( me::match_group("EURUSD", group)); ASSERT_TRUE( me::match_group("EURASD", group)); ASSERT_TRUE(!me::match_group("EURHHH", group)); } TEST_COMPONENT(009) { const char* group = ",!EURHHH, EUR*"; ASSERT_TRUE( me::match_group("EURUSD", group)); ASSERT_TRUE( me::match_group("EURASD", group)); ASSERT_TRUE(!me::match_group("EURHHH", group)); } TEST_COMPONENT(010) { const char* group = "EUR*,!EUR*NH"; ASSERT_TRUE( me::match_group("EURUSD", group)); ASSERT_TRUE( me::match_group("EURASD", group)); ASSERT_TRUE( me::match_group("EURHHH", group)); ASSERT_TRUE(!me::match_group("EURNNH", group)); ASSERT_TRUE(!me::match_group("EURNH" , group)); } TEST_COMPONENT(011) { //"*,!BTC*,!USD*,!EUR*,!AUD*,!GBP*,!NZD*,!CHF*,!CAD*,!SGD*,!XAU*,!XAG*", const char* group = "*,!EUR*"; ASSERT_TRUE(!me::match_group("EURUSD", group)); ASSERT_TRUE( me::match_group("RURUSD", group)); } TEST_COMPONENT(012) { const char* group = "!EUR*,*"; ASSERT_TRUE(!me::match_group("EURUSD", group)); ASSERT_TRUE( me::match_group("RURUSD", group)); } TEST_COMPONENT(013) { const char* group = "*,!BTC*,!USD*,!EUR*,!AUD*,!GBP*,!NZD*,!CHF*,!CAD*,!SGD*,!XAU*,!XAG*"; ASSERT_TRUE(!me::match_group("USD", group)); ASSERT_TRUE( me::match_group("MMM", group)); } TEST_COMPONENT(014) { const char* group = "EURUSD,*,GBDUSD"; ASSERT_TRUE(me::match_group("MMM", group)); } TEST_COMPONENT(015) { const char* group = ",!demo*, * ,"; ASSERT_TRUE(me::match_group("dd-01", group)); } TEST_COMPONENT(016) { const char* group = ",!demo*, 111 222 ,"; ASSERT_TRUE(me::match_group("111 222", group)); } TEST_COMPONENT(017) { const char value[] = "FL"; const char group[] = ",FL,"; ASSERT_TRUE(me::match_group(value, group)); } TEST_COMPONENT(018) { ASSERT_TRUE(me::match_group("FL", "*")); ASSERT_TRUE(me::match_group("CFD", "*")); } TEST_COMPONENT(019) { ASSERT_TRUE(me::match_group("FL", ",*,")); ASSERT_TRUE(me::match_group("CFD", ",*,")); } TEST_COMPONENT(020) { ASSERT_TRUE(!me::match_group("work" , "* work")); ASSERT_TRUE( me::match_group("w work", "* work")); ASSERT_TRUE(!me::match_group("w work", " work" )); } TEST_COMPONENT(021) { ASSERT_TRUE( me::match_group("work group" , "work group")); ASSERT_TRUE(!me::match_group("work qroup" , "work group")); } TEST_COMPONENT(022) { ASSERT_TRUE(me::match_group("work" , " work")); } TEST_COMPONENT(023) { ASSERT_TRUE(me::match_group("Forex" , ",Forex*,CFD*,")); ASSERT_TRUE(me::match_group("ForexExt" , ",Forex*,CFD*,")); ASSERT_TRUE(me::match_group("CFD on Metals" , ",Forex*,CFD*,")); ASSERT_TRUE(me::match_group("CFD US Stocks" , ",Forex*,CFD*,")); ASSERT_TRUE(me::match_group("Forex" , "Forex*, CFD*")); ASSERT_TRUE(me::match_group("ForexExt" , "Forex*, CFD*")); ASSERT_TRUE(me::match_group("CFD on Metals" , "Forex*, CFD*")); ASSERT_TRUE(me::match_group("CFD US Stocks" , "Forex*, CFD*")); } #ifndef NDEBUG // --- invalid symbol TEST_COMPONENT(024) { bool re = false; // символ не имеет права начинаться с пробелов ASSERT_DEATH_DEBUG(re = me::match_group(" work", " work")); // символ не имеет права завершаться пробелами ASSERT_DEATH_DEBUG(re = me::match_group("work ", " work")); (void) re; } #endif // mask is empty TEST_COMPONENT(025) { ASSERT_TRUE(!me::match_group("Forex", "")); ASSERT_TRUE(me::match_group("", "")); } // group is empty TEST_COMPONENT(026) { ASSERT_TRUE(!me::match_group("", "Forex")); } TEST_COMPONENT(027) { const bool ok = me::match_group("cy-a", "sv-*, *-a-*, *-a, a-*"); ASSERT_TRUE(ok); } #endif // !TEST_TOOLS_MATCH_GROUP
24.991837
80
0.594317
Kartonagnick
4f3b4abe74977c98ba0884406eb41f62c0371972
744
cpp
C++
solutions/187.repeated-dna-sequences.253515083.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
78
2020-10-22T11:31:53.000Z
2022-02-22T13:27:49.000Z
solutions/187.repeated-dna-sequences.253515083.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
null
null
null
solutions/187.repeated-dna-sequences.253515083.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
26
2020-10-23T15:10:44.000Z
2021-11-07T16:13:50.000Z
class Solution { public: vector<string> findRepeatedDnaSequences(string s) { vector<string> ans; if (s.size() < 10) return ans; unordered_map<long long int, int> map; unordered_map<char, int> encode = {{'A', 1}, {'C', 2}, {'G', 3}, {'T', 4}}; long long int h = 1; long long int p = 1e9 + 7; long long int hash = 0; for (int i = 0; i < 10; i++) { hash = (hash * 5 + encode[s[i]]) % p; if (i) h = (h * 5) % p; } map[hash] = 1; for (int i = 10; i < s.size(); i++) { hash = (hash - h * (encode[s[i - 10]]) + p) % p; hash = (hash * 5 + encode[s[i]]) % p; if (map[hash]++ == 1) ans.push_back(s.substr(i - 10 + 1, 10)); } return ans; } };
24
79
0.467742
satu0king
4f3d8678d82dc91e80240b48fa851dfd6fd7b0ff
6,037
hpp
C++
src/backend/opencl/kernel/morph.hpp
ckeitz/arrayfire
a1a1bbbc8487a032eb27a6c894b1b3dfb19d123b
[ "BSD-3-Clause" ]
4
2015-12-16T09:41:32.000Z
2018-10-29T10:38:53.000Z
src/backend/opencl/kernel/morph.hpp
ckeitz/arrayfire
a1a1bbbc8487a032eb27a6c894b1b3dfb19d123b
[ "BSD-3-Clause" ]
3
2015-11-15T18:43:47.000Z
2015-12-16T09:43:14.000Z
src/backend/opencl/kernel/morph.hpp
pavanky/arrayfire
f983a79c7d402450bd2a704bbc1015b89f0cd504
[ "BSD-3-Clause" ]
null
null
null
/******************************************************* * Copyright (c) 2014, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #pragma once #include <kernel_headers/morph.hpp> #include <program.hpp> #include <traits.hpp> #include <string> #include <mutex> #include <map> #include <dispatch.hpp> #include <Param.hpp> #include <debug_opencl.hpp> #include <memory.hpp> using cl::Buffer; using cl::Program; using cl::Kernel; using cl::make_kernel; using cl::EnqueueArgs; using cl::LocalSpaceArg; using cl::NDRange; using std::string; namespace opencl { namespace kernel { static const dim_type THREADS_X = 16; static const dim_type THREADS_Y = 16; static const dim_type CUBE_X = 8; static const dim_type CUBE_Y = 8; static const dim_type CUBE_Z = 4; template<typename T, bool isDilation, dim_type windLen> void morph(Param out, const Param in, const Param mask) { try { static std::once_flag compileFlags[DeviceManager::MAX_DEVICES]; static std::map<int, Program*> morProgs; static std::map<int, Kernel*> morKernels; int device = getActiveDeviceId(); std::call_once( compileFlags[device], [device] () { std::ostringstream options; options << " -D T=" << dtype_traits<T>::getName() << " -D isDilation="<< isDilation << " -D windLen=" << windLen; if (std::is_same<T, double>::value || std::is_same<T, cdouble>::value) { options << " -D USE_DOUBLE"; } Program prog; buildProgram(prog, morph_cl, morph_cl_len, options.str()); morProgs[device] = new Program(prog); morKernels[device] = new Kernel(*morProgs[device], "morph"); }); auto morphOp = make_kernel<Buffer, KParam, Buffer, KParam, Buffer, cl::LocalSpaceArg, dim_type >(*morKernels[device]); NDRange local(THREADS_X, THREADS_Y); dim_type blk_x = divup(in.info.dims[0], THREADS_X); dim_type blk_y = divup(in.info.dims[1], THREADS_Y); // launch batch * blk_x blocks along x dimension NDRange global(blk_x * THREADS_X * in.info.dims[2], blk_y * THREADS_Y); // copy mask/filter to constant memory cl_int se_size = sizeof(T)*windLen*windLen; cl::Buffer *mBuff = bufferAlloc(se_size); getQueue().enqueueCopyBuffer(*mask.data, *mBuff, 0, 0, se_size); // calculate shared memory size const int halo = windLen/2; const int padding = 2*halo; const int locLen = THREADS_X + padding + 1; const int locSize = locLen * (THREADS_Y+padding); morphOp(EnqueueArgs(getQueue(), global, local), *out.data, out.info, *in.data, in.info, *mBuff, cl::Local(locSize*sizeof(T)), blk_x); bufferFree(mBuff); CL_DEBUG_FINISH(getQueue()); } catch (cl::Error err) { CL_TO_AF_ERROR(err); throw; } } template<typename T, bool isDilation, dim_type windLen> void morph3d(Param out, const Param in, const Param mask) { try { static std::once_flag compileFlags[DeviceManager::MAX_DEVICES]; static std::map<int, Program*> morProgs; static std::map<int, Kernel*> morKernels; int device = getActiveDeviceId(); std::call_once( compileFlags[device], [device] () { std::ostringstream options; options << " -D T=" << dtype_traits<T>::getName() << " -D isDilation="<< isDilation << " -D windLen=" << windLen; if (std::is_same<T, double>::value || std::is_same<T, cdouble>::value) { options << " -D USE_DOUBLE"; } Program prog; buildProgram(prog, morph_cl, morph_cl_len, options.str()); morProgs[device] = new Program(prog); morKernels[device] = new Kernel(*morProgs[device], "morph3d"); }); auto morphOp = make_kernel<Buffer, KParam, Buffer, KParam, Buffer, cl::LocalSpaceArg >(*morKernels[device]); NDRange local(CUBE_X, CUBE_Y, CUBE_Z); dim_type blk_x = divup(in.info.dims[0], CUBE_X); dim_type blk_y = divup(in.info.dims[1], CUBE_Y); dim_type blk_z = divup(in.info.dims[2], CUBE_Z); // launch batch * blk_x blocks along x dimension NDRange global(blk_x * CUBE_X, blk_y * CUBE_Y, blk_z * CUBE_Z); // copy mask/filter to constant memory cl_int se_size = sizeof(T)*windLen*windLen*windLen; cl::Buffer *mBuff = bufferAlloc(se_size); getQueue().enqueueCopyBuffer(*mask.data, *mBuff, 0, 0, se_size); // calculate shared memory size const int halo = windLen/2; const int padding = 2*halo; const int locLen = CUBE_X+padding+1; const int locArea = locLen *(CUBE_Y+padding); const int locSize = locArea*(CUBE_Z+padding); morphOp(EnqueueArgs(getQueue(), global, local), *out.data, out.info, *in.data, in.info, *mBuff, cl::Local(locSize*sizeof(T))); bufferFree(mBuff); CL_DEBUG_FINISH(getQueue()); } catch (cl::Error err) { CL_TO_AF_ERROR(err); throw; } } } }
33.91573
82
0.536856
ckeitz
4f3e81372f09ba59e55576ccd22b0aadaeef3962
2,470
cpp
C++
Trabalho1_CG/engine/src/camera.cpp
47Balboa/CG
1398ae37fe8d52248efd2534848f51fe15a19f96
[ "MIT" ]
1
2020-11-14T20:10:52.000Z
2020-11-14T20:10:52.000Z
Trabalho1_CG/engine/src/camera.cpp
47Balboa/CG
1398ae37fe8d52248efd2534848f51fe15a19f96
[ "MIT" ]
null
null
null
Trabalho1_CG/engine/src/camera.cpp
47Balboa/CG
1398ae37fe8d52248efd2534848f51fe15a19f96
[ "MIT" ]
1
2021-05-30T16:55:35.000Z
2021-05-30T16:55:35.000Z
#include "headers/camera.h" float deslA = float(2 * (M_PI) / 16.0); float deslB = float((M_PI) / 10.0); // responsavel por inicializar a camera. Camera::Camera() { camPosition = new Point(5.0, 5.0, 5.0); lookPoint = new Point(0.0, 0.0, 0.0); titl = new Point(0.0f, 1.0f, 0.0f); alfa = beta = 0.0; dist = 8.6f; } // Atualiza a camera conforme os valores de alfa, beta e dist. void Camera::atualizaCamPosition() { float x = dist * cos(beta)*sin(alfa); // calcula o novo valor de x para a posicao da camera. float y = dist * sin(beta); // calcula o novo valor de y para a posicao da camera. float z = dist * cos(beta)*cos(alfa); // calcula o novo valor de z para a posicao da camera. setCamPosition(x, y, z); // atualiza a posicao da camera. } //responsavel pela rotacao da posicao da camara para a esquerda. void Camera::camUp() { beta += deslB; if (beta >= M_PI / 2) beta = float(M_PI / 2 - 0.001); // beta < pi/2 atualizaCamPosition(); } //responsavel pela rotacao da posicao da camara para baixo. void Camera::camDown() { beta -= deslB; if (beta <= -M_PI / 2) beta = float(-M_PI / 2 + 0.001); // beta > -pi/2 atualizaCamPosition(); } //responsavel pela rotacao da posicao da camara para a esquerda. void Camera::camLeft() { alfa -= deslA; atualizaCamPosition(); } //responsavel pela rotacao da posicao da camara para a direita. void Camera::camRight() { alfa += deslA; atualizaCamPosition(); } //aproxima a camera do ponto a que esta a olhar. void Camera::maisZoom() { dist -= 0.2f; atualizaCamPosition(); } //afasta a camara do ponto a que esta a olhar. void Camera::menosZoom() { dist += 0.2f; atualizaCamPosition(); } // Devolve a posicao da camera. Point* Camera::getCamPosition() { return camPosition; } // Devolve o ponto para o qual a camera esta a olhar. Point* Camera::getLookPoint() { return lookPoint; } //Devolve o ponto do titl. Point* Camera::getTitl() { return titl; } // Dadas as coordenadas, coloca a camera nessa posicao. void Camera::setCamPosition(float x, float y, float z) { camPosition->setX(x); camPosition->setY(y); camPosition->setZ(z); } // Dadas as coordenadas, coloca a camera olhar para essas mesmas coordendas. void Camera::setLookPoint(float x, float y, float z) { lookPoint->setX(x); lookPoint->setY(y); lookPoint->setZ(z); } // Dadas as coordenadas, atualiza o titl. void Camera::setTitl(float x, float y, float z) { titl->setX(x); titl->setY(y); titl->setZ(z); }
23.52381
94
0.675709
47Balboa
4f3f31a4c59c671068bb6f4fc395f2682f353719
253,253
cpp
C++
src/core/Frontend.cpp
gameblabla/reeee3
1b6d0f742b1b6fb681756de702ed618e90361139
[ "Unlicense" ]
2
2021-03-24T22:11:27.000Z
2021-05-07T06:51:04.000Z
src/core/Frontend.cpp
gameblabla/reeee3
1b6d0f742b1b6fb681756de702ed618e90361139
[ "Unlicense" ]
null
null
null
src/core/Frontend.cpp
gameblabla/reeee3
1b6d0f742b1b6fb681756de702ed618e90361139
[ "Unlicense" ]
null
null
null
#define FORCE_PC_SCALING #define WITHWINDOWS #define WITHDINPUT #include "common.h" #ifndef PS2_MENU #include "crossplatform.h" #include "platform.h" #include "Frontend.h" #include "Font.h" #include "Pad.h" #include "Text.h" #include "main.h" #include "RwHelper.h" #include "Timer.h" #include "Game.h" #include "DMAudio.h" #include "FileMgr.h" #include "Streaming.h" #include "TxdStore.h" #include "General.h" #include "GenericGameStorage.h" #include "Script.h" #include "Camera.h" #include "ControllerConfig.h" #include "Vehicle.h" #include "MBlur.h" #include "PlayerSkin.h" #include "PlayerInfo.h" #include "World.h" #include "Renderer.h" #include "CdStream.h" #include "Radar.h" #include "Stats.h" #include "Messages.h" #include "FileLoader.h" #include "frontendoption.h" // Game has colors inlined in code. // For easier modification we collect them here: const CRGBA LABEL_COLOR(235, 170, 50, 255); const CRGBA SELECTION_HIGHLIGHTBG_COLOR(100, 200, 50, 50); const CRGBA MENUOPTION_COLOR = LABEL_COLOR; const CRGBA SELECTEDMENUOPTION_COLOR(255, 217, 106, 255); const CRGBA HEADER_COLOR(0, 0, 0, 255); const CRGBA DARKMENUOPTION_COLOR(155, 117, 6, 255); const CRGBA SLIDERON_COLOR = SELECTEDMENUOPTION_COLOR; const CRGBA SLIDEROFF_COLOR(185, 120, 0, 255); const CRGBA LIST_BACKGROUND_COLOR(200, 200, 50, 50); const CRGBA LIST_OPTION_COLOR(155, 155, 155, 255); const CRGBA INACTIVE_RADIO_COLOR(225, 0, 0, 170); const CRGBA SCROLLBAR_COLOR = LABEL_COLOR; const CRGBA CONTSETUP_HIGHLIGHTBG_COLOR(SELECTEDMENUOPTION_COLOR.r, SELECTEDMENUOPTION_COLOR.g, SELECTEDMENUOPTION_COLOR.b, 210); const CRGBA CONTSETUP_DISABLED_HIGHLIGHTBG_COLOR(MENUOPTION_COLOR.r, MENUOPTION_COLOR.g, MENUOPTION_COLOR.b, 150); // This is PS2 menu leftover, and variable name is original. They forgot it here and used in PrintBriefs once (but didn't use the output) #if defined(FIX_BUGS) && !defined(PS2_LIKE_MENU) const CRGBA TEXT_COLOR = LABEL_COLOR; #else const CRGBA TEXT_COLOR = CRGBA(150, 110, 30, 255); // PS2 option color #endif #define TIDY_UP_PBP // ProcessButtonPresses #define MAX_VISIBLE_LIST_ROW 30 #define SCROLLBAR_MAX_HEIGHT 263.0f // not in end result #define SCROLLABLE_PAGES #define RED_DELETE_BACKGROUND #ifdef SCROLLABLE_STATS_PAGE #define isPlainTextScreen(screen) (screen == MENUPAGE_BRIEFS) #else #define isPlainTextScreen(screen) (screen == MENUPAGE_BRIEFS || screen == MENUPAGE_STATS) #endif #define hasNativeList(screen) (screen == MENUPAGE_MULTIPLAYER_FIND_GAME || screen == MENUPAGE_SKIN_SELECT \ || screen == MENUPAGE_KEYBOARD_CONTROLS) #ifdef SCROLLABLE_PAGES #define MAX_VISIBLE_OPTION 12 #define MAX_VISIBLE_OPTION_ON_SCREEN (hasNativeList(m_nCurrScreen) ? MAX_VISIBLE_LIST_ROW : MAX_VISIBLE_OPTION) #define SCREEN_HAS_AUTO_SCROLLBAR (m_nTotalListRow > MAX_VISIBLE_OPTION && !hasNativeList(m_nCurrScreen)) int GetOptionCount(int screen) { int i = 0; for (; i < NUM_MENUROWS && aScreens[screen].m_aEntries[i].m_Action != MENUACTION_NOTHING; i++); return i; } #define SETUP_SCROLLING(screen) \ if (!hasNativeList(screen)) { \ m_nTotalListRow = GetOptionCount(screen); \ if (m_nTotalListRow > MAX_VISIBLE_OPTION) { \ m_nSelectedListRow = 0; \ m_nFirstVisibleRowOnList = 0; \ m_nScrollbarTopMargin = 0; \ } \ } #else #define MAX_VISIBLE_OPTION_ON_SCREEN MAX_VISIBLE_LIST_ROW #define SETUP_SCROLLING(screen) #endif #ifdef TRIANGLE_BACK_BUTTON #define GetBackJustUp GetTriangleJustUp #define GetBackJustDown GetTriangleJustDown #elif defined(CIRCLE_BACK_BUTTON) #define GetBackJustUp GetCircleJustUp #define GetBackJustDown GetCircleJustDown #else #define GetBackJustUp GetSquareJustUp #define GetBackJustDown GetSquareJustDown #endif #ifdef MENU_MAP bool CMenuManager::bMenuMapActive = false; float CMenuManager::fMapSize; float CMenuManager::fMapCenterY; float CMenuManager::fMapCenterX; #endif #ifdef PS2_LIKE_MENU BottomBarOption bbNames[8]; int bbTabCount = 0; bool bottomBarActive = false; int pendingScreen = -1; int pendingOption = -1; int curBottomBarOption = -1; int hoveredBottomBarOption = -1; #endif #ifdef CUTSCENE_BORDERS_SWITCH bool CMenuManager::m_PrefsCutsceneBorders = true; #endif #ifdef MULTISAMPLING int8 CMenuManager::m_nPrefsMSAALevel = 0; int8 CMenuManager::m_nDisplayMSAALevel = 0; #endif #ifdef NO_ISLAND_LOADING int8 CMenuManager::m_PrefsIslandLoading = ISLAND_LOADING_LOW; #endif #ifdef GAMEPAD_MENU int8 CMenuManager::m_PrefsControllerType = CONTROLLER_XBOXONE; #endif int32 CMenuManager::OS_Language = LANG_ENGLISH; int8 CMenuManager::m_PrefsUseVibration; int8 CMenuManager::m_DisplayControllerOnFoot; int8 CMenuManager::m_PrefsVsync = 1; int8 CMenuManager::m_PrefsVsyncDisp = 1; int8 CMenuManager::m_PrefsFrameLimiter = 1; int8 CMenuManager::m_PrefsShowSubtitles = 1; int8 CMenuManager::m_PrefsSpeakers; int32 CMenuManager::m_ControlMethod; int8 CMenuManager::m_PrefsDMA = 1; int32 CMenuManager::m_PrefsLanguage; uint8 CMenuManager::m_PrefsStereoMono; // unused except restore settings bool CMenuManager::m_PrefsAllowNastyGame = true; bool CMenuManager::m_bStartUpFrontEndRequested; bool CMenuManager::m_bShutDownFrontEndRequested; #ifdef ASPECT_RATIO_SCALE int8 CMenuManager::m_PrefsUseWideScreen = AR_AUTO; #else int8 CMenuManager::m_PrefsUseWideScreen; #endif int8 CMenuManager::m_PrefsRadioStation; int32 CMenuManager::m_PrefsBrightness = 256; float CMenuManager::m_PrefsLOD = CRenderer::ms_lodDistScale; int8 CMenuManager::m_bFrontEnd_ReloadObrTxtGxt; int32 CMenuManager::m_PrefsMusicVolume = 102; int32 CMenuManager::m_PrefsSfxVolume = 102; char CMenuManager::m_PrefsSkinFile[256] = DEFAULT_SKIN_NAME; int32 CMenuManager::m_KeyPressedCode = -1; float MENU_TEXT_SIZE_X = SMALLTEXT_X_SCALE; float MENU_TEXT_SIZE_Y = SMALLTEXT_Y_SCALE; bool holdingScrollBar; // *(bool*)0x628D59; // not original name int32 CMenuManager::m_SelectedMap; int32 CMenuManager::m_SelectedGameType; // Used in a hidden menu uint8 CMenuManager::m_PrefsPlayerRed = 255; uint8 CMenuManager::m_PrefsPlayerGreen = 128; uint8 CMenuManager::m_PrefsPlayerBlue; // why?? CMenuManager FrontEndMenuManager; uint32 TimeToStopPadShaking; char *pEditString; int32 *pControlEdit; bool DisplayComboButtonErrMsg; int32 MouseButtonJustClicked; int32 JoyButtonJustClicked; //int32 *pControlTemp = 0; #ifndef MASTER bool CMenuManager::m_PrefsMarketing = false; bool CMenuManager::m_PrefsDisableTutorials = false; #endif // !MASTER const char* FrontendFilenames[][2] = { {"fe2_mainpanel_ul", "" }, {"fe2_mainpanel_ur", "" }, {"fe2_mainpanel_dl", "" }, {"fe2_mainpanel_dr", "" }, {"fe2_mainpanel_dr2", "" }, {"fe2_tabactive", "" }, {"fe_iconbrief", "" }, {"fe_iconstats", "" }, {"fe_iconcontrols", "" }, {"fe_iconsave", "" }, {"fe_iconaudio", "" }, {"fe_icondisplay", "" }, {"fe_iconlanguage", "" }, {"fe_controller", "" }, {"fe_controllersh", "" }, {"fe_arrows1", "" }, {"fe_arrows2", "" }, {"fe_arrows3", "" }, {"fe_arrows4", "" }, {"fe_radio1", "" }, {"fe_radio2", "" }, {"fe_radio3", "" }, {"fe_radio4", "" }, {"fe_radio5", "" }, {"fe_radio6", "" }, {"fe_radio7", "" }, {"fe_radio8", "" }, {"fe_radio9", "" }, }; #ifdef MENU_MAP const char* MapFilenames[][2] = { {"mapMid01", "mapMid01A"}, {"mapMid02", "mapMid02A"}, {"mapMid03", "mapMid03A"}, {"mapBot01", "mapBot01A"}, {"mapBot02", "mapBot02A"}, {"mapBot03", "mapBot03A"}, {"mapTop01", "mapTop01A"}, {"mapTop02", "mapTop02A"}, {"mapTop03", "mapTop03A"}, }; CSprite2d CMenuManager::m_aMapSprites[NUM_MAP_SPRITES]; #endif // 0x5F3344 const char* MenuFilenames[][2] = { {"connection24", ""}, {"findgame24", ""}, {"hostgame24", ""}, {"mainmenu24", ""}, {"Playersetup24", ""}, {"singleplayer24", ""}, {"multiplayer24", ""}, {"dmalogo128", "dmalogo128m"}, {"gtaLogo128", "gtaLogo128"}, {"rockstarLogo128", "rockstarlogo128m"}, {"gamespy256", "gamespy256a"}, {"mouse", "mousetimera"}, {"mousetimer", "mousetimera"}, {"mp3logo", "mp3logoA"}, {"downOFF", "buttonA"}, {"downON", "buttonA"}, {"upOff", "buttonA"}, {"upON", "buttonA"}, {"gta3logo256", "gta3logo256m"}, { nil, nil } }; #define MENU_X_RIGHT_ALIGNED(x) SCALE_AND_CENTER_X(DEFAULT_SCREEN_WIDTH - (x)) #ifdef ASPECT_RATIO_SCALE // All of the defines below replace the StretchX function. Otherwise use SCREEN_SCALE_X. #define MENU_X_LEFT_ALIGNED(x) SCALE_AND_CENTER_X(x) #define MENU_X(x) SCREEN_SCALE_X(x) #define MENU_Y(y) SCREEN_SCALE_Y(y) #else #define MENU_X_LEFT_ALIGNED(x) StretchX(x) #define MENU_X(x) StretchX(x) #define MENU_Y(y) StretchY(y) #endif #ifdef PS2_LIKE_MENU #define PAGE_NAME_X MENU_X_RIGHT_ALIGNED #else #define PAGE_NAME_X SCREEN_SCALE_FROM_RIGHT #endif // Seperate func. in VC #define ChangeScreen(screen, option, updateDelay, clearAlpha) \ do { \ m_nPrevScreen = m_nCurrScreen; \ int newOpt = option; \ SETUP_SCROLLING(screen) \ m_nCurrScreen = screen; \ m_nCurrOption = newOpt; \ if(updateDelay) \ m_nScreenChangeDelayTimer = CTimer::GetTimeInMillisecondsPauseMode(); \ if(clearAlpha) \ m_nMenuFadeAlpha = 0; \ } while(0) #define SET_FONT_FOR_MENU_HEADER \ CFont::SetColor(CRGBA(HEADER_COLOR.r, HEADER_COLOR.g, HEADER_COLOR.b, FadeIn(255))); \ CFont::SetRightJustifyOn(); \ CFont::SetScale(MENU_X(MENUHEADER_WIDTH), MENU_Y(MENUHEADER_HEIGHT)); \ CFont::SetFontStyle(FONT_LOCALE(FONT_HEADING)); #define RESET_FONT_FOR_NEW_PAGE \ CFont::SetBackgroundOff(); \ CFont::SetScale(MENU_X(MENUACTION_SCALE_MULT), MENU_Y(MENUACTION_SCALE_MULT)); \ CFont::SetPropOn(); \ CFont::SetCentreOff(); \ CFont::SetJustifyOn(); \ CFont::SetRightJustifyOff(); \ CFont::SetBackGroundOnlyTextOn(); \ CFont::SetWrapx(MENU_X_RIGHT_ALIGNED(MENU_X_MARGIN)); \ CFont::SetRightJustifyWrap(MENU_X_LEFT_ALIGNED(MENU_X_MARGIN - 2.0f)); #define SET_FONT_FOR_HELPER_TEXT \ CFont::SetCentreOn(); \ CFont::SetScale(MENU_X(SMALLESTTEXT_X_SCALE), MENU_Y(SMALLESTTEXT_Y_SCALE)); \ CFont::SetFontStyle(FONT_LOCALE(FONT_HEADING)); #define SET_FONT_FOR_LIST_ITEM \ CFont::SetRightJustifyOff(); \ CFont::SetScale(MENU_X(SMALLESTTEXT_X_SCALE), MENU_Y(SMALLESTTEXT_Y_SCALE)); \ CFont::SetFontStyle(FONT_LOCALE(FONT_BANK)); #define ProcessSlider(value, increaseAction, decreaseAction, hoverStartX, hoverEndX) \ do { \ lastActiveBarX = DisplaySlider(MENU_X_RIGHT_ALIGNED(MENUSLIDER_X + columnWidth), MENU_Y(bitAboveNextItemY), MENU_Y(smallestSliderBar), MENU_Y(usableLineHeight), MENU_X(MENUSLIDER_UNK), value); \ if (i != m_nCurrOption || !itemsAreSelectable) \ break; \ \ if (CheckHover(hoverStartX, lastActiveBarX - MENU_X(10.0f), MENU_Y(nextYToUse), MENU_Y(28.0f + nextYToUse))) \ m_nHoverOption = decreaseAction; \ \ if (!CheckHover(MENU_X(10.0f) + lastActiveBarX, hoverEndX, MENU_Y(nextYToUse), MENU_Y(28.0f + nextYToUse))) \ break; \ \ m_nHoverOption = increaseAction; \ if (m_nMousePosX < MENU_X_RIGHT_ALIGNED(MENUSLIDER_X + columnWidth)) \ m_nHoverOption = HOVEROPTION_NOT_HOVERING; \ } while(0) #define ProcessRadioIcon(sprite, x, y, radioId, hoverOpt) \ do { \ sprite.Draw(x, y, MENU_X(MENURADIO_ICON_SCALE), MENU_Y(MENURADIO_ICON_SCALE), radioId == m_PrefsRadioStation ? CRGBA(255, 255, 255, 255) : \ CRGBA(INACTIVE_RADIO_COLOR.r, INACTIVE_RADIO_COLOR.g, INACTIVE_RADIO_COLOR.b, INACTIVE_RADIO_COLOR.a)); \ if (CheckHover(x, x + MENU_X(MENURADIO_ICON_SCALE), y, y + MENU_Y(MENURADIO_ICON_SCALE))) \ m_nHoverOption = hoverOpt; \ } while (0) // --- Functions not in the game/inlined starts void CMenuManager::ScrollUpListByOne() { if (m_nSelectedListRow == m_nFirstVisibleRowOnList) { if (m_nFirstVisibleRowOnList > 0) { m_nSelectedListRow--; m_nFirstVisibleRowOnList--; m_nScrollbarTopMargin -= SCROLLBAR_MAX_HEIGHT / m_nTotalListRow; } } else { m_nSelectedListRow--; } } void CMenuManager::ScrollDownListByOne() { if (m_nSelectedListRow == m_nFirstVisibleRowOnList + MAX_VISIBLE_OPTION_ON_SCREEN - 1) { if (m_nFirstVisibleRowOnList < m_nTotalListRow - MAX_VISIBLE_OPTION_ON_SCREEN) { m_nSelectedListRow++; m_nFirstVisibleRowOnList++; m_nScrollbarTopMargin += SCROLLBAR_MAX_HEIGHT / m_nTotalListRow; } } else { if (m_nSelectedListRow < m_nTotalListRow - 1) { m_nSelectedListRow++; } } } void CMenuManager::PageUpList(bool playSoundOnSuccess) { if (m_nTotalListRow > MAX_VISIBLE_OPTION_ON_SCREEN) { if (m_nFirstVisibleRowOnList > 0) { if(playSoundOnSuccess) DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_NAVIGATION, 0); m_nFirstVisibleRowOnList = Max(0, m_nFirstVisibleRowOnList - MAX_VISIBLE_OPTION_ON_SCREEN); m_nSelectedListRow = Min(m_nSelectedListRow, m_nFirstVisibleRowOnList + MAX_VISIBLE_OPTION_ON_SCREEN - 1); } else { m_nFirstVisibleRowOnList = 0; m_nSelectedListRow = 0; } m_nScrollbarTopMargin = (SCROLLBAR_MAX_HEIGHT / m_nTotalListRow) * m_nFirstVisibleRowOnList; } } void CMenuManager::PageDownList(bool playSoundOnSuccess) { if (m_nTotalListRow > MAX_VISIBLE_OPTION_ON_SCREEN) { if (m_nFirstVisibleRowOnList < m_nTotalListRow - MAX_VISIBLE_OPTION_ON_SCREEN) { if(playSoundOnSuccess) DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_NAVIGATION, 0); m_nFirstVisibleRowOnList = Min(m_nFirstVisibleRowOnList + MAX_VISIBLE_OPTION_ON_SCREEN, m_nTotalListRow - MAX_VISIBLE_OPTION_ON_SCREEN); m_nSelectedListRow = Max(m_nSelectedListRow, m_nFirstVisibleRowOnList); } else { m_nFirstVisibleRowOnList = m_nTotalListRow - MAX_VISIBLE_OPTION_ON_SCREEN; m_nSelectedListRow = m_nTotalListRow - 1; } m_nScrollbarTopMargin = (SCROLLBAR_MAX_HEIGHT / m_nTotalListRow) * m_nFirstVisibleRowOnList; } } #ifdef CUSTOM_FRONTEND_OPTIONS bool ScreenHasOption(int screen, const char* gxtKey) { for (int i = 0; i < NUM_MENUROWS; i++) { if (strcmp(gxtKey, aScreens[screen].m_aEntries[i].m_EntryName) == 0) return true; } return false; } #endif void CMenuManager::ThingsToDoBeforeGoingBack() { if ((m_nCurrScreen == MENUPAGE_SKIN_SELECT) && strcmp(m_aSkinName, m_PrefsSkinFile) != 0) { CWorld::Players[0].SetPlayerSkin(m_PrefsSkinFile); #ifdef CUSTOM_FRONTEND_OPTIONS } else if (ScreenHasOption(m_nCurrScreen, "FEA_3DH")) { #else } else if (m_nCurrScreen == MENUPAGE_SOUND_SETTINGS) { #endif if (m_nPrefsAudio3DProviderIndex != -1) m_nPrefsAudio3DProviderIndex = DMAudio.GetCurrent3DProviderIndex(); #ifdef TIDY_UP_PBP DMAudio.StopFrontEndTrack(); OutputDebugString("FRONTEND AUDIO TRACK STOPPED"); #endif #ifdef CUSTOM_FRONTEND_OPTIONS } else if (ScreenHasOption(m_nCurrScreen, "FED_RES")) { #else } else if (m_nCurrScreen == MENUPAGE_DISPLAY_SETTINGS) { #endif m_nDisplayVideoMode = m_nPrefsVideoMode; } if (m_nCurrScreen == MENUPAGE_SKIN_SELECT) { CPlayerSkin::EndFrontendSkinEdit(); } if ((m_nCurrScreen == MENUPAGE_SKIN_SELECT) || (m_nCurrScreen == MENUPAGE_KEYBOARD_CONTROLS)) { m_nTotalListRow = 0; } #ifdef SCROLLABLE_PAGES if (SCREEN_HAS_AUTO_SCROLLBAR) { m_nSelectedListRow = 0; m_nFirstVisibleRowOnList = 0; m_nScrollbarTopMargin = 0; } #endif #ifdef CUSTOM_FRONTEND_OPTIONS CMenuScreenCustom::CMenuEntry &option = aScreens[m_nCurrScreen].m_aEntries[m_nCurrOption]; if (option.m_Action == MENUACTION_CFO_DYNAMIC) if(option.m_CFODynamic->buttonPressFunc) option.m_CFODynamic->buttonPressFunc(FEOPTION_ACTION_FOCUSLOSS); if (option.m_Action == MENUACTION_CFO_SELECT && option.m_CFOSelect->onlyApplyOnEnter && option.m_CFOSelect->lastSavedValue != option.m_CFOSelect->displayedValue) option.m_CFOSelect->displayedValue = *option.m_CFO->value = option.m_CFOSelect->lastSavedValue; if (aScreens[m_nCurrScreen].returnPrevPageFunc) { aScreens[m_nCurrScreen].returnPrevPageFunc(); } #endif } int8 CMenuManager::GetPreviousPageOption() { #ifndef CUSTOM_FRONTEND_OPTIONS return !m_bGameNotLoaded ? aScreens[m_nCurrScreen].m_ParentEntry[1] : aScreens[m_nCurrScreen].m_ParentEntry[0]; #else int8 prevPage = !m_bGameNotLoaded ? aScreens[m_nCurrScreen].m_PreviousPage[1] : aScreens[m_nCurrScreen].m_PreviousPage[0]; if (prevPage == -1) // Game also does same return 0; prevPage = prevPage == MENUPAGE_NONE ? (!m_bGameNotLoaded ? MENUPAGE_PAUSE_MENU : MENUPAGE_START_MENU) : prevPage; for (int i = 0; i < NUM_MENUROWS; i++) { if (aScreens[prevPage].m_aEntries[i].m_Action >= MENUACTION_NOTHING) { // CFO check if (aScreens[prevPage].m_aEntries[i].m_TargetMenu == m_nCurrScreen) { return i; } } } // This shouldn't happen return 0; #endif } void CMenuManager::ProcessList(bool &goBack, bool &optionSelected) { if (m_nCurrScreen == MENUPAGE_SKIN_SELECT) { m_nTotalListRow = m_nSkinsTotal; } if (m_nCurrScreen == MENUPAGE_KEYBOARD_CONTROLS) { // GetNumOptionsCntrlConfigScreens would have been a better choice m_nTotalListRow = m_ControlMethod == CONTROL_CLASSIC ? 30 : 25; if (m_nSelectedListRow > m_nTotalListRow) m_nSelectedListRow = m_nTotalListRow - 1; } #ifndef TIDY_UP_PBP if (CPad::GetPad(0)->GetEnterJustDown() || CPad::GetPad(0)->GetCrossJustDown()) { m_bShowMouse = 0; optionSelected = true; } #endif if (CPad::GetPad(0)->GetBackspaceJustDown() && m_nCurrScreen == MENUPAGE_KEYBOARD_CONTROLS && !field_535) { if (m_nCurrExLayer == HOVEROPTION_LIST) { m_nHoverOption = HOVEROPTION_NOT_HOVERING; m_bWaitingForNewKeyBind = true; m_bStartWaitingForKeyBind = true; m_bKeyChangeNotProcessed = true; pControlEdit = &m_KeyPressedCode; } } else { field_535 = false; } static uint32 lastTimeClickedScrollButton = 0; if (CTimer::GetTimeInMillisecondsPauseMode() - lastTimeClickedScrollButton >= 200) { m_bPressedPgUpOnList = false; m_bPressedPgDnOnList = false; m_bPressedUpOnList = false; m_bPressedDownOnList = false; m_bPressedScrollButton = false; lastTimeClickedScrollButton = CTimer::GetTimeInMillisecondsPauseMode(); } if (CPad::GetPad(0)->GetTabJustDown()) { DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_NAVIGATION, 0); m_bShowMouse = false; switch (m_nCurrExLayer) { case HOVEROPTION_BACK: default: m_nCurrExLayer = HOVEROPTION_LIST; break; case HOVEROPTION_LIST: m_nCurrExLayer = HOVEROPTION_USESKIN; break; case HOVEROPTION_USESKIN: m_nCurrExLayer = HOVEROPTION_BACK; } if (((m_nCurrScreen == MENUPAGE_SKIN_SELECT) && (m_nCurrExLayer == HOVEROPTION_USESKIN)) && strcmp(m_aSkinName, m_PrefsSkinFile) == 0) { m_nCurrExLayer = HOVEROPTION_BACK; } if ((m_nCurrScreen == MENUPAGE_KEYBOARD_CONTROLS) && (m_nCurrExLayer == HOVEROPTION_USESKIN)) { m_nCurrExLayer = HOVEROPTION_BACK; } } bool pressed = false; if (CPad::GetPad(0)->GetUp() || CPad::GetPad(0)->GetAnaloguePadUp() || CPad::GetPad(0)->GetDPadUpJustDown()) { m_bShowMouse = false; pressed = true; } else if (CPad::GetPad(0)->GetMouseWheelUpJustUp()) { m_bShowMouse = true; pressed = true; } // Up if (pressed) { m_nCurrExLayer = HOVEROPTION_LIST; if (!m_bPressedUpOnList) { m_bPressedUpOnList = true; lastTimeClickedScrollButton = CTimer::GetTimeInMillisecondsPauseMode(); DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_NAVIGATION, 0); ScrollUpListByOne(); } } else { m_bPressedUpOnList = false; } pressed = false; if (CPad::GetPad(0)->GetDown() || CPad::GetPad(0)->GetAnaloguePadDown() || CPad::GetPad(0)->GetDPadDownJustDown()) { m_bShowMouse = false; pressed = true; } else if (CPad::GetPad(0)->GetMouseWheelDownJustDown()) { m_bShowMouse = true; pressed = true; } // Down if (pressed) { m_nCurrExLayer = HOVEROPTION_LIST; if (!m_bPressedDownOnList) { m_bPressedDownOnList = true; lastTimeClickedScrollButton = CTimer::GetTimeInMillisecondsPauseMode(); DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_NAVIGATION, 0); ScrollDownListByOne(); } } else { m_bPressedDownOnList = false; } if (m_nCurrScreen != MENUPAGE_KEYBOARD_CONTROLS) { if (!CPad::GetPad(0)->GetPageUp()) { m_bPressedPgUpOnList = false; } else { m_nCurrExLayer = HOVEROPTION_LIST; if (!m_bPressedPgUpOnList) { m_bPressedPgUpOnList = true; lastTimeClickedScrollButton = CTimer::GetTimeInMillisecondsPauseMode(); m_bShowMouse = false; DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_NAVIGATION, 0); PageUpList(false); } } if (!CPad::GetPad(0)->GetPageDown()) { m_bPressedPgDnOnList = false; } else { m_nCurrExLayer = HOVEROPTION_LIST; if (!m_bPressedPgDnOnList) { m_bPressedPgDnOnList = true; lastTimeClickedScrollButton = CTimer::GetTimeInMillisecondsPauseMode(); m_bShowMouse = false; DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_NAVIGATION, 0); PageDownList(false); } } if (CPad::GetPad(0)->GetHome()) { m_nCurrExLayer = HOVEROPTION_LIST; m_bShowMouse = false; DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_NAVIGATION, 0); if (m_nTotalListRow >= MAX_VISIBLE_OPTION_ON_SCREEN) { m_nFirstVisibleRowOnList = 0; } m_nSelectedListRow = 0; m_nScrollbarTopMargin = (SCROLLBAR_MAX_HEIGHT / m_nTotalListRow) * m_nFirstVisibleRowOnList; } if (CPad::GetPad(0)->GetEnd()) { m_nCurrExLayer = HOVEROPTION_LIST; m_bShowMouse = false; DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_NAVIGATION, 0); if (m_nTotalListRow >= MAX_VISIBLE_OPTION_ON_SCREEN) { m_nFirstVisibleRowOnList = m_nTotalListRow - MAX_VISIBLE_OPTION_ON_SCREEN; } m_nSelectedListRow = m_nTotalListRow - 1; m_nScrollbarTopMargin = (SCROLLBAR_MAX_HEIGHT / m_nTotalListRow) * m_nFirstVisibleRowOnList; } } #ifndef TIDY_UP_PBP if (CPad::GetPad(0)->GetEscapeJustDown() || CPad::GetPad(0)->GetBackJustDown()) { m_bShowMouse = false; goBack = true; } #endif if (CPad::GetPad(0)->GetLeftMouseJustDown()) { switch (m_nHoverOption) { case HOVEROPTION_BACK: goBack = true; break; case HOVEROPTION_PAGEUP: PageUpList(true); break; case HOVEROPTION_PAGEDOWN: PageDownList(true); break; case HOVEROPTION_USESKIN: if (m_nSkinsTotal > 0) { DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_SETTING_CHANGE, 0); m_pSelectedSkin = m_pSkinListHead.nextSkin; strcpy(m_PrefsSkinFile, m_aSkinName); CWorld::Players[0].SetPlayerSkin(m_PrefsSkinFile); SaveSettings(); } } } if (CPad::GetPad(0)->GetLeftMouseJustDown()) { switch (m_nHoverOption) { case HOVEROPTION_OVER_SCROLL_UP: m_nHoverOption = HOVEROPTION_CLICKED_SCROLL_UP; break; case HOVEROPTION_OVER_SCROLL_DOWN: m_nHoverOption = HOVEROPTION_CLICKED_SCROLL_DOWN; break; case HOVEROPTION_LIST: m_nHoverOption = HOVEROPTION_SKIN; } } else if ((CPad::GetPad(0)->GetLeftMouseJustUp()) && ((m_nHoverOption == HOVEROPTION_CLICKED_SCROLL_UP || (m_nHoverOption == HOVEROPTION_CLICKED_SCROLL_DOWN)))) { m_nHoverOption = HOVEROPTION_NOT_HOVERING; } if (!CPad::GetPad(0)->GetLeftMouse()) { holdingScrollBar = false; } else { if ((m_nHoverOption == HOVEROPTION_HOLDING_SCROLLBAR) || holdingScrollBar) { holdingScrollBar = true; // TODO: This part is a bit hard to reverse. Not much code tho assert(0 && "Holding scrollbar isn't done yet"); } else { switch (m_nHoverOption) { case HOVEROPTION_OVER_SCROLL_UP: case HOVEROPTION_CLICKED_SCROLL_UP: if (!m_bPressedScrollButton) { m_bPressedScrollButton = true; lastTimeClickedScrollButton = CTimer::GetTimeInMillisecondsPauseMode(); ScrollUpListByOne(); } break; case HOVEROPTION_OVER_SCROLL_DOWN: case HOVEROPTION_CLICKED_SCROLL_DOWN: if (!m_bPressedScrollButton) { m_bPressedScrollButton = true; lastTimeClickedScrollButton = CTimer::GetTimeInMillisecondsPauseMode(); ScrollDownListByOne(); } break; default: m_bPressedScrollButton = false; } } } } // ------ Functions not in the game/inlined ends void CMenuManager::BuildStatLine(Const char *text, void *stat, bool itsFloat, void *stat2) { if (!text) return; #ifdef MORE_LANGUAGES if (CFont::IsJapanese() && stat2) if (itsFloat) sprintf(gString2, " %.2f/%.2f", *(float*)stat, *(float*)stat2); else sprintf(gString2, " %d/%d", *(int*)stat, *(int*)stat2); else #endif if (stat2) { if (itsFloat) sprintf(gString2, " %.2f %s %.2f", *(float*)stat, UnicodeToAscii(TheText.Get("FEST_OO")), *(float*)stat2); else sprintf(gString2, " %d %s %d", *(int*)stat, UnicodeToAscii(TheText.Get("FEST_OO")), *(int*)stat2); } else if (stat) { if (itsFloat) sprintf(gString2, " %.2f", *(float*)stat); else sprintf(gString2, " %d", *(int*)stat); } else gString2[0] = '\0'; UnicodeStrcpy(gUString, TheText.Get(text)); AsciiToUnicode(gString2, gUString2); } void CMenuManager::CentreMousePointer() { if (SCREEN_WIDTH * 0.5f != 0.0f && 0.0f != SCREEN_HEIGHT * 0.5f) { #if defined RW_D3D9 || defined RWLIBS tagPOINT Point; Point.x = SCREEN_WIDTH / 2; Point.y = SCREEN_HEIGHT / 2; ClientToScreen(PSGLOBAL(window), &Point); SetCursorPos(Point.x, Point.y); #elif defined RW_GL3 glfwSetCursorPos(PSGLOBAL(window), SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2); #endif PSGLOBAL(lastMousePos.x) = SCREEN_WIDTH / 2; PSGLOBAL(lastMousePos.y) = SCREEN_HEIGHT / 2; } } void CMenuManager::CheckCodesForControls(int typeOfControl) { DisplayComboButtonErrMsg = false; bool invalidKey = false; bool escPressed = false; eControllerType typeToSave; // GetStartOptionsCntrlConfigScreens(); e_ControllerAction action = (e_ControllerAction) m_CurrCntrlAction; if (typeOfControl == KEYBOARD) { if (*pControlEdit == rsESC) { escPressed = true; } else if (*pControlEdit != rsF1 && *pControlEdit != rsF2 && *pControlEdit != rsF3 && *pControlEdit != rsF9 && *pControlEdit != rsLWIN && *pControlEdit != rsRWIN && *pControlEdit != rsRALT) { typeToSave = KEYBOARD; if (ControlsManager.GetControllerKeyAssociatedWithAction(action, KEYBOARD) != rsNULL && *pControlEdit != ControlsManager.GetControllerKeyAssociatedWithAction(action, KEYBOARD)) { typeToSave = OPTIONAL_EXTRA; } } else { invalidKey = true; } } else if (typeOfControl == MOUSE) { typeToSave = MOUSE; } else if (typeOfControl == JOYSTICK) { typeToSave = JOYSTICK; if (ControlsManager.GetIsActionAButtonCombo(action)) DisplayComboButtonErrMsg = true; } #ifdef FIX_BUGS if(!escPressed && !invalidKey) #endif ControlsManager.ClearSettingsAssociatedWithAction(action, typeToSave); if (!DisplayComboButtonErrMsg && !escPressed && !invalidKey) { if (typeOfControl == KEYBOARD) { ControlsManager.DeleteMatchingActionInitiators(action, *pControlEdit, KEYBOARD); ControlsManager.DeleteMatchingActionInitiators(action, *pControlEdit, OPTIONAL_EXTRA); } else { if (typeOfControl == MOUSE) { ControlsManager.DeleteMatchingActionInitiators(action, MouseButtonJustClicked, MOUSE); } else if (typeOfControl == JOYSTICK) { ControlsManager.DeleteMatchingActionInitiators(action, JoyButtonJustClicked, JOYSTICK); } } if (typeOfControl == KEYBOARD) { ControlsManager.SetControllerKeyAssociatedWithAction(action, *pControlEdit, typeToSave); } else if (typeOfControl == MOUSE) { ControlsManager.SetControllerKeyAssociatedWithAction(action, MouseButtonJustClicked, typeToSave); } else { if (typeOfControl == JOYSTICK) { ControlsManager.SetControllerKeyAssociatedWithAction(action, JoyButtonJustClicked, typeToSave); } } pControlEdit = nil; m_bWaitingForNewKeyBind = false; m_KeyPressedCode = -1; m_bStartWaitingForKeyBind = false; #ifdef LOAD_INI_SETTINGS SaveINIControllerSettings(); #else SaveSettings(); #endif } if (escPressed) { pControlEdit = nil; m_bWaitingForNewKeyBind = false; m_KeyPressedCode = -1; m_bStartWaitingForKeyBind = false; #ifdef LOAD_INI_SETTINGS SaveINIControllerSettings(); #else SaveSettings(); #endif } } bool CMenuManager::CheckHover(int x1, int x2, int y1, int y2) { return m_nMousePosX > x1 && m_nMousePosX < x2 && m_nMousePosY > y1 && m_nMousePosY < y2; } void CMenuManager::CheckSliderMovement(int value) { switch (aScreens[m_nCurrScreen].m_aEntries[m_nCurrOption].m_Action) { case MENUACTION_BRIGHTNESS: m_PrefsBrightness += value * (512/16); m_PrefsBrightness = clamp(m_PrefsBrightness, 0, 511); break; case MENUACTION_DRAWDIST: if(value > 0) m_PrefsLOD += ((1.8f - 0.8f) / 16.0f); else m_PrefsLOD -= ((1.8f - 0.8f) / 16.0f); m_PrefsLOD = clamp(m_PrefsLOD, 0.8f, 1.8f); CRenderer::ms_lodDistScale = m_PrefsLOD; break; case MENUACTION_MUSICVOLUME: m_PrefsMusicVolume += value * (128/16); m_PrefsMusicVolume = clamp(m_PrefsMusicVolume, 0, 127); DMAudio.SetMusicMasterVolume(m_PrefsMusicVolume); break; case MENUACTION_SFXVOLUME: m_PrefsSfxVolume += value * (128/16); m_PrefsSfxVolume = clamp(m_PrefsSfxVolume, 0, 127); DMAudio.SetEffectsMasterVolume(m_PrefsSfxVolume); break; case MENUACTION_MOUSESENS: TheCamera.m_fMouseAccelHorzntl += value * 1.0f/200.0f/15.0f; // ??? TheCamera.m_fMouseAccelHorzntl = clamp(TheCamera.m_fMouseAccelHorzntl, 1.0f/3200.0f, 1.0f/200.0f); #ifdef FIX_BUGS TheCamera.m_fMouseAccelVertical = TheCamera.m_fMouseAccelHorzntl + 0.0005f; #else TheCamera.m_fMouseAccelVertical = TheCamera.m_fMouseAccelHorzntl; #endif break; default: return; } SaveSettings(); } void CMenuManager::DisplayHelperText() { // there was a unused static bool static uint32 LastFlash = 0; int32 alpha; if (m_nHelperTextMsgId != 0 && m_nHelperTextMsgId != 1) { // FIX: High fps bug #ifndef FIX_BUGS if (CTimer::GetTimeInMillisecondsPauseMode() - LastFlash > 10) { LastFlash = CTimer::GetTimeInMillisecondsPauseMode(); m_nHelperTextAlpha -= 2; } #else static float fadeAlpha = 0.0f; // To keep it precisely if (m_nHelperTextAlpha >= 255 && fadeAlpha < 250) fadeAlpha = m_nHelperTextAlpha; // -2 per every 33 ms (1000.f/30.f - original frame limiter fps) fadeAlpha -= (frameTime / 33.0f) * 2.0f; m_nHelperTextAlpha = fadeAlpha; #endif if (m_nHelperTextAlpha < 1) ResetHelperText(); alpha = m_nHelperTextAlpha > 255 ? 255 : m_nHelperTextAlpha; } SET_FONT_FOR_HELPER_TEXT // TODO: name this cases? switch (m_nHelperTextMsgId) { case 0: { int action = aScreens[m_nCurrScreen].m_aEntries[m_nCurrOption].m_Action; if (action != MENUACTION_CHANGEMENU && action != MENUACTION_KEYBOARDCTRLS && action != MENUACTION_RESTOREDEF) { CFont::SetColor(CRGBA(255, 255, 255, 255)); CFont::PrintString(MENU_X_LEFT_ALIGNED(HELPER_TEXT_LEFT_MARGIN), SCREEN_SCALE_FROM_BOTTOM(HELPER_TEXT_BOTTOM_MARGIN), TheText.Get("FET_MIG")); } break; } case 1: CFont::SetColor(CRGBA(255, 255, 255, 255)); CFont::PrintString(MENU_X_LEFT_ALIGNED(HELPER_TEXT_LEFT_MARGIN), SCREEN_SCALE_FROM_BOTTOM(HELPER_TEXT_BOTTOM_MARGIN), TheText.Get("FET_APP")); break; case 2: CFont::SetColor(CRGBA(255, 255, 255, alpha)); CFont::PrintString(MENU_X_LEFT_ALIGNED(HELPER_TEXT_LEFT_MARGIN), SCREEN_SCALE_FROM_BOTTOM(HELPER_TEXT_BOTTOM_MARGIN), TheText.Get("FET_HRD")); break; case 3: CFont::SetColor(CRGBA(255, 255, 255, alpha)); CFont::PrintString(MENU_X_LEFT_ALIGNED(HELPER_TEXT_LEFT_MARGIN), SCREEN_SCALE_FROM_BOTTOM(HELPER_TEXT_BOTTOM_MARGIN), TheText.Get("FET_RSO")); break; case 4: CFont::SetColor(CRGBA(255, 255, 255, alpha)); CFont::PrintString(MENU_X_LEFT_ALIGNED(HELPER_TEXT_LEFT_MARGIN), SCREEN_SCALE_FROM_BOTTOM(HELPER_TEXT_BOTTOM_MARGIN), TheText.Get("FET_RSC")); break; default: break; } CFont::SetRightJustifyOff(); } int CMenuManager::DisplaySlider(float x, float y, float mostLeftBarSize, float mostRightBarSize, float rectSize, float progress) { CRGBA color; float maxBarHeight; int lastActiveBarX = 0; float curBarX = 0.0f; float spacing = SCREEN_SCALE_X(10.0f); for (int i = 0; i < 16; i++) { curBarX = i * rectSize/16.0f + x; if (i / 16.0f + 1 / 32.0f < progress) { color = CRGBA(SLIDERON_COLOR.r, SLIDERON_COLOR.g, SLIDERON_COLOR.b, FadeIn(255)); lastActiveBarX = curBarX; } else color = CRGBA(SLIDEROFF_COLOR.r, SLIDEROFF_COLOR.g, SLIDEROFF_COLOR.b, FadeIn(255)); maxBarHeight = Max(mostLeftBarSize, mostRightBarSize); float curBarFreeSpace = ((16 - i) * mostLeftBarSize + i * mostRightBarSize) / 16.0f; float left = curBarX; float top = y + maxBarHeight - curBarFreeSpace; float right = spacing + curBarX; float bottom = y + maxBarHeight; float shadowOffset = SCREEN_SCALE_X(2.0f); CSprite2d::DrawRect(CRect(left + shadowOffset, top + shadowOffset, right + shadowOffset, bottom + shadowOffset), CRGBA(0, 0, 0, FadeIn(200))); // Shadow CSprite2d::DrawRect(CRect(left, top, right, bottom), color); } return lastActiveBarX; } void CMenuManager::DoSettingsBeforeStartingAGame() { #ifdef PC_PLAYER_CONTROLS CCamera::m_bUseMouse3rdPerson = m_ControlMethod == CONTROL_STANDARD; #endif if (m_PrefsVsyncDisp != m_PrefsVsync) m_PrefsVsync = m_PrefsVsyncDisp; DMAudio.Service(); m_bWantToRestart = true; ShutdownJustMenu(); UnloadTextures(); DMAudio.SetEffectsFadeVol(0); DMAudio.SetMusicFadeVol(0); DMAudio.ResetTimers(CTimer::GetTimeInMilliseconds()); } void CMenuManager::Draw() { CFont::SetBackgroundOff(); CFont::SetPropOn(); CFont::SetCentreOff(); CFont::SetJustifyOn(); CFont::SetBackGroundOnlyTextOn(); #if GTA_VERSION >= GTA3_PC_11 && defined(DRAW_MENU_VERSION_TEXT) CFont::SetColor(CRGBA(LABEL_COLOR.r, LABEL_COLOR.g, LABEL_COLOR.b, FadeIn(255))); CFont::SetRightJustifyOn(); CFont::SetFontStyle(FONT_HEADING); CFont::SetScale(MENU_X(0.7f), MENU_Y(0.5f)); CFont::SetWrapx(SCREEN_WIDTH); CFont::SetRightJustifyWrap(0.0f); strcpy(gString, "V1.1"); AsciiToUnicode(gString, gUString); CFont::PrintString(SCREEN_WIDTH / 10, SCREEN_HEIGHT / 45, gUString); #endif CFont::SetWrapx(MENU_X_RIGHT_ALIGNED(MENU_X_MARGIN)); CFont::SetRightJustifyWrap(MENU_X_LEFT_ALIGNED(MENU_X_MARGIN - 2.0f)); switch (m_nCurrScreen) { case MENUPAGE_STATS: PrintStats(); break; case MENUPAGE_BRIEFS: PrintBriefs(); break; #ifdef MENU_MAP case MENUPAGE_MAP: PrintMap(); break; #endif } // Header height isn't accounted, we will add that later. float nextYToUse = 40.0f; // Page name #ifdef PS2_SAVE_DIALOG if(!m_bRenderGameInMenu) #endif if (aScreens[m_nCurrScreen].m_ScreenName[0] != '\0') { SET_FONT_FOR_MENU_HEADER CFont::PrintString(PAGE_NAME_X(MENUHEADER_POS_X), SCREEN_SCALE_FROM_BOTTOM(MENUHEADER_POS_Y), TheText.Get(aScreens[m_nCurrScreen].m_ScreenName)); // Weird place to put that. nextYToUse += 24.0f + 10.0f; } CFont::SetFontStyle(FONT_LOCALE(FONT_BANK)); CFont::SetScale(MENU_X(MENUACTION_SCALE_MULT * MENU_TEXT_SIZE_X), MENU_Y(MENUACTION_SCALE_MULT * MENU_TEXT_SIZE_Y)); CFont::SetRightJustifyOff(); CFont::SetColor(CRGBA(LABEL_COLOR.r, LABEL_COLOR.g, LABEL_COLOR.b, FadeIn(255))); // Label wchar *str; if (aScreens[m_nCurrScreen].m_aEntries[0].m_Action == MENUACTION_LABEL) { switch (m_nCurrScreen) { case MENUPAGE_LOAD_SLOT_CONFIRM: if (m_bGameNotLoaded) str = TheText.Get("FES_LCG"); else str = TheText.Get(aScreens[m_nCurrScreen].m_aEntries[0].m_EntryName); break; case MENUPAGE_SAVE_OVERWRITE_CONFIRM: if (Slots[m_nCurrSaveSlot + 1] == SLOT_EMPTY) str = TheText.Get("FESZ_QZ"); else str = TheText.Get(aScreens[m_nCurrScreen].m_aEntries[0].m_EntryName); break; case MENUPAGE_EXIT: if (m_bGameNotLoaded) str = TheText.Get("FEQ_SRW"); else str = TheText.Get(aScreens[m_nCurrScreen].m_aEntries[0].m_EntryName); break; default: str = TheText.Get(aScreens[m_nCurrScreen].m_aEntries[0].m_EntryName); break; } #ifdef FIX_BUGS // Label is wrapped from right by StretchX(40)px, but wrapped from left by 40px. And this is only place R* didn't use StretchX in here. CFont::PrintString(MENU_X_LEFT_ALIGNED(MENU_X_MARGIN), MENU_Y(MENUACTION_POS_Y), str); #else CFont::PrintString(MENU_X_MARGIN, MENUACTION_POS_Y, str); #endif } // Not a bug, we just want HFoV+ on menu #ifdef ASPECT_RATIO_SCALE CFont::SetCentreSize(SCREEN_SCALE_X(DEFAULT_SCREEN_WIDTH)); #else CFont::SetCentreSize(SCREEN_WIDTH); #endif #ifdef PS2_LIKE_MENU bool itemsAreSelectable = !bottomBarActive; #else bool itemsAreSelectable = true; #endif int lineHeight; int headerHeight; int columnWidth; switch (m_nCurrScreen) { case MENUPAGE_STATS: case MENUPAGE_BRIEFS: columnWidth = 320; headerHeight = 240; lineHeight = 24; CFont::SetFontStyle(FONT_LOCALE(FONT_HEADING)); CFont::SetScale(MENU_X(MENU_TEXT_SIZE_X = BIGTEXT_X_SCALE), MENU_Y(MENU_TEXT_SIZE_Y = BIGTEXT_Y_SCALE)); CFont::SetCentreOn(); break; #ifdef FIX_BUGS case MENUPAGE_CONTROLLER_SETTINGS: columnWidth = 50; headerHeight = -50; lineHeight = 20; CFont::SetFontStyle(FONT_LOCALE(FONT_HEADING)); CFont::SetScale(MENU_X(MENU_TEXT_SIZE_X = MEDIUMTEXT_X_SCALE), MENU_Y(MENU_TEXT_SIZE_Y = MEDIUMTEXT_Y_SCALE)); CFont::SetRightJustifyOff(); break; #endif case MENUPAGE_SOUND_SETTINGS: case MENUPAGE_DISPLAY_SETTINGS: case MENUPAGE_MULTIPLAYER_CREATE: case MENUPAGE_SKIN_SELECT_OLD: case MENUPAGE_CONTROLLER_PC_OLD1: case MENUPAGE_CONTROLLER_PC_OLD2: case MENUPAGE_CONTROLLER_PC_OLD3: case MENUPAGE_CONTROLLER_PC_OLD4: case MENUPAGE_CONTROLLER_DEBUG: case MENUPAGE_MOUSE_CONTROLS: columnWidth = 50; headerHeight = 0; lineHeight = 20; CFont::SetFontStyle(FONT_LOCALE(FONT_HEADING)); CFont::SetScale(MENU_X(MENU_TEXT_SIZE_X = MEDIUMTEXT_X_SCALE), MENU_Y(MENU_TEXT_SIZE_Y = MEDIUMTEXT_Y_SCALE)); CFont::SetRightJustifyOff(); break; case MENUPAGE_CHOOSE_LOAD_SLOT: case MENUPAGE_CHOOSE_DELETE_SLOT: case MENUPAGE_CHOOSE_SAVE_SLOT: columnWidth = 120; headerHeight = 38; lineHeight = 20; CFont::SetFontStyle(FONT_LOCALE(FONT_BANK)); CFont::SetScale(MENU_X(MENU_TEXT_SIZE_X = SMALLTEXT_X_SCALE), MENU_Y(MENU_TEXT_SIZE_Y = SMALLTEXT_Y_SCALE)); CFont::SetRightJustifyOff(); break; case MENUPAGE_NEW_GAME_RELOAD: case MENUPAGE_LOAD_SLOT_CONFIRM: case MENUPAGE_DELETE_SLOT_CONFIRM: case MENUPAGE_SAVE_OVERWRITE_CONFIRM: case MENUPAGE_EXIT: columnWidth = 320; headerHeight = 60; lineHeight = 24; CFont::SetFontStyle(FONT_LOCALE(FONT_HEADING)); CFont::SetScale(MENU_X(MENU_TEXT_SIZE_X = BIGTEXT_X_SCALE), MENU_Y(MENU_TEXT_SIZE_Y = BIGTEXT_Y_SCALE)); CFont::SetCentreOn(); break; case MENUPAGE_START_MENU: columnWidth = 320; headerHeight = 140; lineHeight = 24; CFont::SetFontStyle(FONT_LOCALE(FONT_HEADING)); CFont::SetScale(MENU_X(MENU_TEXT_SIZE_X = BIGTEXT_X_SCALE), MENU_Y(MENU_TEXT_SIZE_Y = BIGTEXT_Y_SCALE)); CFont::SetCentreOn(); break; case MENUPAGE_PAUSE_MENU: columnWidth = 320; headerHeight = 117; lineHeight = 24; CFont::SetFontStyle(FONT_LOCALE(FONT_HEADING)); CFont::SetScale(MENU_X(MENU_TEXT_SIZE_X = BIGTEXT_X_SCALE), MENU_Y(MENU_TEXT_SIZE_Y = BIGTEXT_Y_SCALE)); CFont::SetCentreOn(); break; #ifdef PS2_SAVE_DIALOG case MENUPAGE_SAVE: columnWidth = 180; headerHeight = 60; lineHeight = 24; CFont::SetFontStyle(FONT_LOCALE(FONT_BANK)); CFont::SetScale(MENU_X(MENU_TEXT_SIZE_X = BIGTEXT_X_SCALE), MENU_Y(MENU_TEXT_SIZE_Y = BIGTEXT_Y_SCALE)); break; #endif default: #ifdef CUSTOM_FRONTEND_OPTIONS CCustomScreenLayout *custom = aScreens[m_nCurrScreen].layout; if (custom) { columnWidth = custom->columnWidth; headerHeight = custom->headerHeight; lineHeight = custom->lineHeight; CFont::SetFontStyle(FONT_LOCALE(custom->font)); CFont::SetScale(MENU_X(MENU_TEXT_SIZE_X = custom->fontScaleX), MENU_Y(MENU_TEXT_SIZE_Y = custom->fontScaleY)); if (custom->alignment == FESCREEN_LEFT_ALIGN) { CFont::SetCentreOff(); CFont::SetRightJustifyOff(); } else if (custom->alignment == FESCREEN_RIGHT_ALIGN) { CFont::SetCentreOff(); CFont::SetRightJustifyOn(); } else { CFont::SetRightJustifyOff(); CFont::SetCentreOn(); } } if (!custom) #endif { columnWidth = 320; headerHeight = 40; lineHeight = 24; CFont::SetFontStyle(FONT_LOCALE(FONT_HEADING)); CFont::SetScale(MENU_X(MENU_TEXT_SIZE_X = BIGTEXT_X_SCALE), MENU_Y(MENU_TEXT_SIZE_Y = BIGTEXT_Y_SCALE)); CFont::SetCentreOn(); } break; } #ifdef PS2_LIKE_MENU CFont::SetFontStyle(FONT_LOCALE(FONT_BANK)); #endif switch (m_nCurrScreen) { case MENUPAGE_CONTROLLER_PC_OLD1: case MENUPAGE_CONTROLLER_PC_OLD2: case MENUPAGE_CONTROLLER_PC_OLD3: case MENUPAGE_CONTROLLER_PC_OLD4: case MENUPAGE_CONTROLLER_DEBUG: if (m_bWaitingForNewKeyBind) itemsAreSelectable = false; DrawControllerScreenExtraText(nextYToUse - 8.0f, MENU_X_LEFT_ALIGNED(350), lineHeight); break; default: break; } float usableLineHeight = lineHeight * 0.9f; // also height of biggest bar in slider float smallestSliderBar = lineHeight * 0.1f; bool foundTheHoveringItem = false; wchar unicodeTemp[64]; #ifdef ASPECT_RATIO_SCALE char asciiTemp[32]; #endif #ifdef MENU_MAP if (m_nCurrScreen == MENUPAGE_MAP) { // Back button wchar *backTx = TheText.Get("FEDS_TB"); CFont::SetDropShadowPosition(1); CFont::SetDropColor(CRGBA(0, 0, 0, FadeIn(255))); CFont::PrintString(MENU_X(60.0f), SCREEN_SCALE_FROM_BOTTOM(120.0f), backTx); CFont::SetDropShadowPosition(0); if (!CheckHover(MENU_X(30.0f), MENU_X(30.0f) + CFont::GetStringWidth(backTx), SCREEN_SCALE_FROM_BOTTOM(125.0f), SCREEN_SCALE_FROM_BOTTOM(105.0f))) { m_nHoverOption = HOVEROPTION_NOT_HOVERING; m_nCurrOption = m_nOptionMouseHovering = 0; } else { m_nHoverOption = HOVEROPTION_RANDOM_ITEM; m_nCurrOption = m_nOptionMouseHovering = 1; } return; } #endif #ifdef CUSTOM_FRONTEND_OPTIONS // Thanks R*, for checking mouse hovering in Draw(). static int lastSelectedOpt = m_nCurrOption; #endif #ifdef SCROLLABLE_PAGES int firstOption = SCREEN_HAS_AUTO_SCROLLBAR ? m_nFirstVisibleRowOnList : 0; for (int i = firstOption; i < firstOption + MAX_VISIBLE_OPTION && i < NUM_MENUROWS; ++i) { #else for (int i = 0; i < NUM_MENUROWS; ++i) { #endif #ifdef CUSTOM_FRONTEND_OPTIONS bool isOptionDisabled = false; #endif // Hide back button #ifdef PS2_LIKE_MENU if ((i == NUM_MENUROWS - 1 || aScreens[m_nCurrScreen].m_aEntries[i+1].m_EntryName[0] == '\0') && strcmp(aScreens[m_nCurrScreen].m_aEntries[i].m_EntryName, "FEDS_TB") == 0) break; #endif if (aScreens[m_nCurrScreen].m_aEntries[i].m_Action != MENUACTION_LABEL && aScreens[m_nCurrScreen].m_aEntries[i].m_EntryName[0] != '\0') { wchar *rightText = nil; wchar *leftText; if (aScreens[m_nCurrScreen].m_aEntries[i].m_SaveSlot >= SAVESLOT_1 && aScreens[m_nCurrScreen].m_aEntries[i].m_SaveSlot <= SAVESLOT_8) { CFont::SetRightJustifyOff(); leftText = GetNameOfSavedGame(i - 1); if (Slots[i] != SLOT_EMPTY) rightText = GetSavedGameDateAndTime(i - 1); if (leftText[0] == '\0') { sprintf(gString, "FEM_SL%d", i); leftText = TheText.Get(gString); } } else { leftText = TheText.Get(aScreens[m_nCurrScreen].m_aEntries[i].m_EntryName); } switch (aScreens[m_nCurrScreen].m_aEntries[i].m_Action) { case MENUACTION_CHANGEMENU: { switch (aScreens[m_nCurrScreen].m_aEntries[i].m_TargetMenu) { case MENUPAGE_MULTIPLAYER_MAP: switch (m_SelectedMap) { case 0: rightText = TheText.Get("FEM_MA0"); break; case 1: rightText = TheText.Get("FEM_MA1"); break; case 2: rightText = TheText.Get("FEM_MA2"); break; case 3: rightText = TheText.Get("FEM_MA3"); break; case 4: rightText = TheText.Get("FEM_MA4"); break; case 5: rightText = TheText.Get("FEM_MA5"); break; case 6: rightText = TheText.Get("FEM_MA6"); break; case 7: rightText = TheText.Get("FEM_MA7"); break; default: break; } break; case MENUPAGE_MULTIPLAYER_MODE: switch (m_SelectedGameType) { case 0: rightText = TheText.Get("FEN_TY0"); break; case 1: rightText = TheText.Get("FEN_TY1"); break; case 2: rightText = TheText.Get("FEN_TY2"); break; case 3: rightText = TheText.Get("FEN_TY3"); break; case 4: rightText = TheText.Get("FEN_TY4"); break; case 5: rightText = TheText.Get("FEN_TY5"); break; case 6: rightText = TheText.Get("FEN_TY6"); break; case 7: rightText = TheText.Get("FEN_TY7"); break; default: break; } break; default: break; } break; } case MENUACTION_CTRLVIBRATION: if (m_PrefsUseVibration) rightText = TheText.Get("FEM_ON"); else rightText = TheText.Get("FEM_OFF"); break; case MENUACTION_CTRLCONFIG: switch (CPad::GetPad(0)->Mode) { case 0: rightText = TheText.Get("FEC_CF1"); break; case 1: rightText = TheText.Get("FEC_CF2"); break; case 2: rightText = TheText.Get("FEC_CF3"); break; case 3: rightText = TheText.Get("FEC_CF4"); break; } break; case MENUACTION_CTRLDISPLAY: if (m_DisplayControllerOnFoot) rightText = TheText.Get("FEC_ONF"); else rightText = TheText.Get("FEC_INC"); break; case MENUACTION_FRAMESYNC: rightText = TheText.Get(m_PrefsVsyncDisp ? "FEM_ON" : "FEM_OFF"); break; case MENUACTION_FRAMELIMIT: rightText = TheText.Get(m_PrefsFrameLimiter ? "FEM_ON" : "FEM_OFF"); break; case MENUACTION_TRAILS: rightText = TheText.Get(CMBlur::BlurOn ? "FEM_ON" : "FEM_OFF"); break; case MENUACTION_SUBTITLES: rightText = TheText.Get(m_PrefsShowSubtitles ? "FEM_ON" : "FEM_OFF"); break; case MENUACTION_WIDESCREEN: #ifndef ASPECT_RATIO_SCALE rightText = TheText.Get(m_PrefsUseWideScreen ? "FEM_ON" : "FEM_OFF"); #else switch (m_PrefsUseWideScreen) { case AR_AUTO: rightText = TheText.Get("FEM_AUT"); break; case AR_4_3: sprintf(asciiTemp, "4:3"); AsciiToUnicode(asciiTemp, unicodeTemp); rightText = unicodeTemp; break; case AR_5_4: sprintf(asciiTemp, "5:4"); AsciiToUnicode(asciiTemp, unicodeTemp); rightText = unicodeTemp; break; case AR_16_10: sprintf(asciiTemp, "16:10"); AsciiToUnicode(asciiTemp, unicodeTemp); rightText = unicodeTemp; break; case AR_16_9: sprintf(asciiTemp, "16:9"); AsciiToUnicode(asciiTemp, unicodeTemp); rightText = unicodeTemp; break; case AR_21_9: sprintf(asciiTemp, "21:9"); AsciiToUnicode(asciiTemp, unicodeTemp); rightText = unicodeTemp; break; } #endif break; case MENUACTION_RADIO: if (m_PrefsRadioStation > USERTRACK) break; sprintf(gString, "FEA_FM%d", m_PrefsRadioStation); rightText = TheText.Get(gString); break; case MENUACTION_SETDBGFLAG: rightText = TheText.Get(CTheScripts::IsDebugOn() ? "FEM_ON" : "FEM_OFF"); break; case MENUACTION_SWITCHBIGWHITEDEBUGLIGHT: rightText = TheText.Get(gbBigWhiteDebugLightSwitchedOn ? "FEM_ON" : "FEM_OFF"); break; case MENUACTION_PEDROADGROUPS: rightText = TheText.Get(gbShowPedRoadGroups ? "FEM_ON" : "FEM_OFF"); break; case MENUACTION_CARROADGROUPS: rightText = TheText.Get(gbShowCarRoadGroups ? "FEM_ON" : "FEM_OFF"); break; case MENUACTION_COLLISIONPOLYS: rightText = TheText.Get(gbShowCollisionPolys ? "FEM_ON" : "FEM_OFF"); break; case MENUACTION_SHOWCULL: rightText = TheText.Get(gbShowCullZoneDebugStuff ? "FEM_ON" : "FEM_OFF"); break; case MENUACTION_SHOWHEADBOB: rightText = TheText.Get(TheCamera.m_bHeadBob ? "FEM_ON" : "FEM_OFF"); break; case MENUACTION_INVVERT: rightText = TheText.Get(MousePointerStateHelper.bInvertVertically ? "FEM_OFF" : "FEM_ON"); break; case MENUACTION_SCREENRES: AsciiToUnicode(_psGetVideoModeList()[m_nDisplayVideoMode], unicodeTemp); rightText = unicodeTemp; break; case MENUACTION_AUDIOHW: if (m_nPrefsAudio3DProviderIndex == -1) rightText = TheText.Get("FEA_NAH"); else { char *provider = DMAudio.Get3DProviderName(m_nPrefsAudio3DProviderIndex); if (!strcmp(strupr(provider), "DIRECTSOUND3D HARDWARE SUPPORT")) { strcpy(provider, "DSOUND3D HARDWARE SUPPORT"); } else if (!strcmp(strupr(provider), "DIRECTSOUND3D SOFTWARE EMULATION")) { strcpy(provider, "DSOUND3D SOFTWARE EMULATION"); } AsciiToUnicode(provider, unicodeTemp); rightText = unicodeTemp; } break; case MENUACTION_SPEAKERCONF: { if (m_nPrefsAudio3DProviderIndex == -1) rightText = TheText.Get("FEA_NAH"); else { switch (m_PrefsSpeakers) { case 0: rightText = TheText.Get("FEA_2SP"); break; case 1: rightText = TheText.Get("FEA_EAR"); break; case 2: rightText = TheText.Get("FEA_4SP"); break; } } break; } case MENUACTION_CTRLMETHOD: { switch (m_ControlMethod) { case 0: leftText = TheText.Get("FET_SCN"); break; case 1: leftText = TheText.Get("FET_CCN"); break; } break; } case MENUACTION_DYNAMICACOUSTIC: rightText = TheText.Get(m_PrefsDMA ? "FEM_ON" : "FEM_OFF"); break; case MENUACTION_MOUSESTEER: rightText = TheText.Get(CVehicle::m_bDisableMouseSteering ? "FEM_OFF" : "FEM_ON"); break; #ifdef CUSTOM_FRONTEND_OPTIONS case MENUACTION_CFO_DYNAMIC: case MENUACTION_CFO_SELECT: CMenuScreenCustom::CMenuEntry &option = aScreens[m_nCurrScreen].m_aEntries[i]; if (option.m_Action == MENUACTION_CFO_SELECT) { isOptionDisabled = option.m_CFOSelect->disableIfGameLoaded && !m_bGameNotLoaded; if (option.m_CFOSelect->onlyApplyOnEnter){ if (m_nCurrOption != i) { if (option.m_CFOSelect->displayedValue != option.m_CFOSelect->lastSavedValue) SetHelperText(3); // Restored original value // If that was previously selected option, restore it to default value. // if (m_nCurrOption != lastSelectedOpt && lastSelectedOpt == i) option.m_CFOSelect->displayedValue = option.m_CFOSelect->lastSavedValue = *option.m_CFO->value; } else { if (option.m_CFOSelect->displayedValue != *option.m_CFO->value) SetHelperText(1); // Enter to apply else if (m_nHelperTextMsgId == 1) ResetHelperText(); // Applied } } // To whom manipulate option.m_CFO->value of select options externally (like RestoreDef functions) if (*option.m_CFO->value != option.m_CFOSelect->lastSavedValue) option.m_CFOSelect->displayedValue = option.m_CFOSelect->lastSavedValue = *option.m_CFO->value; if (option.m_CFOSelect->displayedValue >= option.m_CFOSelect->numRightTexts || option.m_CFOSelect->displayedValue < 0) option.m_CFOSelect->displayedValue = 0; rightText = TheText.Get(option.m_CFOSelect->rightTexts[option.m_CFOSelect->displayedValue]); } else if (option.m_Action == MENUACTION_CFO_DYNAMIC) { if (m_nCurrOption != lastSelectedOpt && lastSelectedOpt == i) { if(option.m_CFODynamic->buttonPressFunc) option.m_CFODynamic->buttonPressFunc(FEOPTION_ACTION_FOCUSLOSS); } if (option.m_CFODynamic->drawFunc) { rightText = option.m_CFODynamic->drawFunc(&isOptionDisabled, m_nCurrOption == i); } } break; #endif } float nextItemY = headerHeight + nextYToUse; float bitAboveNextItemY = nextItemY - 2.0f; int nextYToCheck = bitAboveNextItemY; if (!foundTheHoveringItem) { #ifdef SCROLLABLE_PAGES for (int rowToCheck = firstOption + (aScreens[m_nCurrScreen].m_aEntries[firstOption].m_Action == MENUACTION_LABEL); rowToCheck < firstOption + MAX_VISIBLE_OPTION && rowToCheck < NUM_MENUROWS; ++rowToCheck) { #else for (int rowToCheck = aScreens[m_nCurrScreen].m_aEntries[0].m_Action == MENUACTION_LABEL; rowToCheck < NUM_MENUROWS; ++rowToCheck) { #endif if(aScreens[m_nCurrScreen].m_aEntries[rowToCheck].m_Action == MENUACTION_NOTHING) break; // Hide back button #ifdef PS2_LIKE_MENU if ((rowToCheck == NUM_MENUROWS - 1 || aScreens[m_nCurrScreen].m_aEntries[rowToCheck+1].m_EntryName[0] == '\0') && strcmp(aScreens[m_nCurrScreen].m_aEntries[rowToCheck].m_EntryName, "FEDS_TB") == 0) break; #endif int extraOffset = 0; if (aScreens[m_nCurrScreen].m_aEntries[rowToCheck].m_Action == MENUACTION_RADIO) extraOffset = MENURADIO_ICON_SCALE; // There were many unused codes in here to calculate how much space will texts gonna take. // FIX: nextYToCheck already starts with Y - 2, let's sync it with green bar bounds. #ifdef FIX_BUGS if (m_nMousePosY > MENU_Y(nextYToCheck) && #else if (m_nMousePosY > MENU_Y(nextYToCheck - 2) && #endif m_nMousePosY < MENU_Y((nextYToCheck + 2) + usableLineHeight)) { static int oldOption = -99; static int oldScreen = m_nCurrScreen; m_nOptionMouseHovering = rowToCheck; if (m_nMouseOldPosX != m_nMousePosX || m_nMouseOldPosY != m_nMousePosY) { m_nCurrOption = rowToCheck; m_bShowMouse = true; } if (oldOption != m_nCurrOption) { if (oldScreen == m_nCurrScreen && m_bShowMouse) DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_NAVIGATION, 0); oldOption = m_nCurrOption; oldScreen = m_nCurrScreen; } if (oldScreen == m_nPrevScreen) oldScreen = m_nCurrScreen; m_nHoverOption = HOVEROPTION_RANDOM_ITEM; foundTheHoveringItem = true; break; } m_nHoverOption = HOVEROPTION_NOT_HOVERING; nextYToCheck += extraOffset + lineHeight; } } // Green bar behind selected option #ifdef PS2_SAVE_DIALOG if (!m_bRenderGameInMenu) #endif if (i == m_nCurrOption && itemsAreSelectable) { #ifdef PS2_LIKE_MENU CSprite2d::DrawRect(CRect(MENU_X_LEFT_ALIGNED(29.0f), MENU_Y(bitAboveNextItemY), MENU_X_RIGHT_ALIGNED(29.0f), MENU_Y(usableLineHeight + nextItemY)), CRGBA(SELECTION_HIGHLIGHTBG_COLOR.r, SELECTION_HIGHLIGHTBG_COLOR.g, SELECTION_HIGHLIGHTBG_COLOR.b, FadeIn(SELECTION_HIGHLIGHTBG_COLOR.a))); #else // We keep stretching, because we also stretch background image and we want that bar to be aligned with borders of background CSprite2d::DrawRect(CRect(StretchX(10.0f), MENU_Y(bitAboveNextItemY), SCREEN_STRETCH_FROM_RIGHT(11.0f), MENU_Y(usableLineHeight + nextItemY)), CRGBA(SELECTION_HIGHLIGHTBG_COLOR.r, SELECTION_HIGHLIGHTBG_COLOR.g, SELECTION_HIGHLIGHTBG_COLOR.b, FadeIn(SELECTION_HIGHLIGHTBG_COLOR.a))); #endif } CFont::SetColor(CRGBA(0, 0, 0, FadeIn(90))); // Button and it's shadow for(int textLayer = 0; textLayer < 2; textLayer++) { if (!CFont::Details.centre) CFont::SetRightJustifyOff(); float itemY = MENU_Y(textLayer + nextItemY); float itemX = MENU_X_LEFT_ALIGNED(textLayer + columnWidth); CFont::PrintString(itemX, itemY, leftText); if (rightText) { if (!CFont::Details.centre) CFont::SetRightJustifyOn(); if(textLayer == 1) if (!strcmp(aScreens[m_nCurrScreen].m_aEntries[i].m_EntryName, "FED_RES") && !m_bGameNotLoaded #ifdef CUSTOM_FRONTEND_OPTIONS || isOptionDisabled #endif ) CFont::SetColor(CRGBA(DARKMENUOPTION_COLOR.r, DARKMENUOPTION_COLOR.g, DARKMENUOPTION_COLOR.b, FadeIn(255))); CFont::PrintString(MENU_X_RIGHT_ALIGNED(columnWidth - textLayer), itemY, rightText); } if (i == m_nCurrOption && itemsAreSelectable){ CFont::SetColor(CRGBA(SELECTEDMENUOPTION_COLOR.r, SELECTEDMENUOPTION_COLOR.g, SELECTEDMENUOPTION_COLOR.b, FadeIn(255))); } else { CFont::SetColor(CRGBA(MENUOPTION_COLOR.r, MENUOPTION_COLOR.g, MENUOPTION_COLOR.b, FadeIn(255))); } } if (m_nPrefsAudio3DProviderIndex == DMAudio.GetCurrent3DProviderIndex()) { if(!strcmp(aScreens[m_nCurrScreen].m_aEntries[m_nCurrOption].m_EntryName, "FEA_3DH") && m_nHelperTextMsgId == 1) ResetHelperText(); } if (m_nDisplayVideoMode == m_nPrefsVideoMode) { if (!strcmp(aScreens[m_nCurrScreen].m_aEntries[m_nCurrOption].m_EntryName, "FED_RES") && m_nHelperTextMsgId == 1) ResetHelperText(); } if (m_nPrefsAudio3DProviderIndex != DMAudio.GetCurrent3DProviderIndex()) { if (!strcmp(aScreens[m_nCurrScreen].m_aEntries[m_nCurrOption].m_EntryName, "FEA_3DH")) SetHelperText(1); } if (m_nDisplayVideoMode != m_nPrefsVideoMode) { if (!strcmp(aScreens[m_nCurrScreen].m_aEntries[m_nCurrOption].m_EntryName, "FED_RES")) SetHelperText(1); } if (m_nPrefsAudio3DProviderIndex != DMAudio.GetCurrent3DProviderIndex()) { if (strcmp(aScreens[m_nCurrScreen].m_aEntries[m_nCurrOption].m_EntryName, "FEA_3DH") != 0 // To make assigning built-in actions to new custom options possible. #ifdef CUSTOM_FRONTEND_OPTIONS && ScreenHasOption(m_nCurrScreen, "FEA_3DH") #else && m_nCurrScreen == MENUPAGE_SOUND_SETTINGS #endif && m_nPrefsAudio3DProviderIndex != -1) { m_nPrefsAudio3DProviderIndex = DMAudio.GetCurrent3DProviderIndex(); SetHelperText(3); } } if (m_nDisplayVideoMode != m_nPrefsVideoMode) { if (strcmp(aScreens[m_nCurrScreen].m_aEntries[m_nCurrOption].m_EntryName, "FED_RES") != 0 // To make assigning built-in actions to new custom options possible. #ifdef CUSTOM_FRONTEND_OPTIONS && ScreenHasOption(m_nCurrScreen, "FED_RES") #else && m_nCurrScreen == MENUPAGE_DISPLAY_SETTINGS #endif ){ m_nDisplayVideoMode = m_nPrefsVideoMode; SetHelperText(3); } } // Sliders int lastActiveBarX; switch (aScreens[m_nCurrScreen].m_aEntries[i].m_Action) { case MENUACTION_BRIGHTNESS: ProcessSlider(m_PrefsBrightness / 512.0f, HOVEROPTION_INCREASE_BRIGHTNESS, HOVEROPTION_DECREASE_BRIGHTNESS, MENU_X_LEFT_ALIGNED(170.0f), SCREEN_WIDTH); break; case MENUACTION_DRAWDIST: ProcessSlider((m_PrefsLOD - 0.8f) * 1.0f, HOVEROPTION_INCREASE_DRAWDIST, HOVEROPTION_DECREASE_DRAWDIST, MENU_X_LEFT_ALIGNED(170.0f), SCREEN_WIDTH); break; case MENUACTION_MUSICVOLUME: ProcessSlider(m_PrefsMusicVolume / 128.0f, HOVEROPTION_INCREASE_MUSICVOLUME, HOVEROPTION_DECREASE_MUSICVOLUME, MENU_X_LEFT_ALIGNED(170.0f), SCREEN_WIDTH); break; case MENUACTION_SFXVOLUME: ProcessSlider(m_PrefsSfxVolume / 128.0f, HOVEROPTION_INCREASE_SFXVOLUME, HOVEROPTION_DECREASE_SFXVOLUME, MENU_X_LEFT_ALIGNED(170.0f), SCREEN_WIDTH); break; case MENUACTION_MOUSESENS: ProcessSlider(TheCamera.m_fMouseAccelHorzntl * 200.0f, HOVEROPTION_INCREASE_MOUSESENS, HOVEROPTION_DECREASE_MOUSESENS, MENU_X_LEFT_ALIGNED(200.0f), SCREEN_WIDTH); break; } // Needed after the bug fix in Font.cpp #ifdef FIX_BUGS if (!CFont::Details.centre) CFont::SetRightJustifyOff(); #endif // 60.0 is silly nextYToUse += lineHeight * CFont::GetNumberLines(MENU_X_LEFT_ALIGNED(60.0f), MENU_Y(nextYToUse), leftText); // Radio icons if (aScreens[m_nCurrScreen].m_aEntries[i].m_Action == MENUACTION_RADIO) { ProcessRadioIcon(m_aFrontEndSprites[FE_RADIO1], MENU_X_LEFT_ALIGNED(30.0f), MENU_Y(nextYToUse), 0, HOVEROPTION_RADIO_0); ProcessRadioIcon(m_aFrontEndSprites[FE_RADIO2], MENU_X_LEFT_ALIGNED(90.0f), MENU_Y(nextYToUse), 1, HOVEROPTION_RADIO_1); ProcessRadioIcon(m_aFrontEndSprites[FE_RADIO5], MENU_X_LEFT_ALIGNED(150.0f), MENU_Y(nextYToUse), 2, HOVEROPTION_RADIO_2); ProcessRadioIcon(m_aFrontEndSprites[FE_RADIO7], MENU_X_LEFT_ALIGNED(210.0f), MENU_Y(nextYToUse), 3, HOVEROPTION_RADIO_3); ProcessRadioIcon(m_aFrontEndSprites[FE_RADIO8], MENU_X_LEFT_ALIGNED(270.0f), MENU_Y(nextYToUse), 4, HOVEROPTION_RADIO_4); ProcessRadioIcon(m_aFrontEndSprites[FE_RADIO3], MENU_X_LEFT_ALIGNED(320.0f), MENU_Y(nextYToUse), 5, HOVEROPTION_RADIO_5); ProcessRadioIcon(m_aFrontEndSprites[FE_RADIO4], MENU_X_LEFT_ALIGNED(360.0f), MENU_Y(nextYToUse), 6, HOVEROPTION_RADIO_6); ProcessRadioIcon(m_aFrontEndSprites[FE_RADIO6], MENU_X_LEFT_ALIGNED(420.0f), MENU_Y(nextYToUse), 7, HOVEROPTION_RADIO_7); ProcessRadioIcon(m_aFrontEndSprites[FE_RADIO9], MENU_X_LEFT_ALIGNED(480.0f), MENU_Y(nextYToUse), 8, HOVEROPTION_RADIO_8); if (DMAudio.IsMP3RadioChannelAvailable()) ProcessRadioIcon(m_aMenuSprites[MENUSPRITE_MP3LOGO], MENU_X_LEFT_ALIGNED(540.0f), MENU_Y(nextYToUse), 9, HOVEROPTION_RADIO_9); nextYToUse += 70.0f; } } } #ifdef CUSTOM_FRONTEND_OPTIONS lastSelectedOpt = m_nCurrOption; #endif #ifdef SCROLLABLE_PAGES #define SCROLLBAR_BOTTOM_Y 125.0f // only for background, scrollbar's itself is calculated #define SCROLLBAR_RIGHT_X 36.0f #define SCROLLBAR_WIDTH 9.5f #define SCROLLBAR_TOP_Y 64 if (SCREEN_HAS_AUTO_SCROLLBAR) { // Scrollbar background CSprite2d::DrawRect(CRect(MENU_X_RIGHT_ALIGNED(SCROLLBAR_RIGHT_X - 2), MENU_Y(SCROLLBAR_TOP_Y), MENU_X_RIGHT_ALIGNED(SCROLLBAR_RIGHT_X - 2 - SCROLLBAR_WIDTH), SCREEN_SCALE_FROM_BOTTOM(SCROLLBAR_BOTTOM_Y)), CRGBA(100, 100, 66, FadeIn(205))); float scrollbarHeight = SCROLLBAR_MAX_HEIGHT / (m_nTotalListRow / (float) MAX_VISIBLE_OPTION); float scrollbarBottom, scrollbarTop; scrollbarBottom = MENU_Y(SCROLLBAR_TOP_Y - 8 + m_nScrollbarTopMargin + scrollbarHeight); scrollbarTop = MENU_Y(SCROLLBAR_TOP_Y + m_nScrollbarTopMargin); // Scrollbar shadow CSprite2d::DrawRect(CRect(MENU_X_RIGHT_ALIGNED(SCROLLBAR_RIGHT_X - 4), scrollbarTop, MENU_X_RIGHT_ALIGNED(SCROLLBAR_RIGHT_X - 1 - SCROLLBAR_WIDTH), scrollbarBottom + MENU_Y(1.0f)), CRGBA(50, 50, 50, FadeIn(255))); // Scrollbar CSprite2d::DrawRect(CRect(MENU_X_RIGHT_ALIGNED(SCROLLBAR_RIGHT_X - 4), scrollbarTop, MENU_X_RIGHT_ALIGNED(SCROLLBAR_RIGHT_X - SCROLLBAR_WIDTH), scrollbarBottom), CRGBA(SCROLLBAR_COLOR.r, SCROLLBAR_COLOR.g, SCROLLBAR_COLOR.b, FadeIn(255))); } #endif switch (m_nCurrScreen) { case MENUPAGE_CONTROLLER_SETTINGS: case MENUPAGE_SOUND_SETTINGS: case MENUPAGE_DISPLAY_SETTINGS: case MENUPAGE_SKIN_SELECT: case MENUPAGE_CONTROLLER_PC: case MENUPAGE_MOUSE_CONTROLS: DisplayHelperText(); break; #ifdef CUSTOM_FRONTEND_OPTIONS default: if (aScreens[m_nCurrScreen].layout) { if (aScreens[m_nCurrScreen].layout->showLeftRightHelper) { DisplayHelperText(); } } break; #endif } if (m_nCurrScreen == MENUPAGE_CONTROLLER_SETTINGS) PrintController(); else if (m_nCurrScreen == MENUPAGE_SKIN_SELECT_OLD) { CSprite2d::DrawRect(CRect(MENU_X_LEFT_ALIGNED(180), MENU_Y(98), MENU_X_LEFT_ALIGNED(230), MENU_Y(123)), CRGBA(255, 255, 255, FadeIn(255))); CSprite2d::DrawRect(CRect(MENU_X_LEFT_ALIGNED(181), MENU_Y(99), MENU_X_LEFT_ALIGNED(229), MENU_Y(122)), CRGBA(m_PrefsPlayerRed, m_PrefsPlayerGreen, m_PrefsPlayerBlue, FadeIn(255))); } } int CMenuManager::GetNumOptionsCntrlConfigScreens(void) { int number = 0; switch (m_nCurrScreen) { case MENUPAGE_CONTROLLER_PC_OLD3: number = 2; break; case MENUPAGE_CONTROLLER_DEBUG: number = 4; break; case MENUPAGE_KEYBOARD_CONTROLS: switch (m_ControlMethod) { case CONTROL_STANDARD: number = 25; break; case CONTROL_CLASSIC: number = 30; break; } break; } return number; } void CMenuManager::DrawControllerBound(int32 yStart, int32 xStart, int32 unused, int8 column) { int controllerAction = PED_FIREWEAPON; // GetStartOptionsCntrlConfigScreens(); int numOptions = GetNumOptionsCntrlConfigScreens(); int nextY = MENU_Y(yStart); int bindingMargin = MENU_X(3.0f); float rowHeight; switch (m_ControlMethod) { case CONTROL_STANDARD: rowHeight = CONTSETUP_STANDARD_ROW_HEIGHT; break; case CONTROL_CLASSIC: rowHeight = CONTSETUP_CLASSIC_ROW_HEIGHT; break; default: break; } // MENU_Y(rowHeight * 0.0f + yStart); for (int optionIdx = 0; optionIdx < numOptions; nextY = MENU_Y(++optionIdx * rowHeight + yStart)) { int nextX = xStart; int bindingsForThisOpt = 0; int contSetOrder = SETORDER_1; CFont::SetColor(CRGBA(LIST_OPTION_COLOR.r, LIST_OPTION_COLOR.g, LIST_OPTION_COLOR.b, FadeIn(LIST_OPTION_COLOR.a))); if (column == CONTSETUP_PED_COLUMN) { switch (optionIdx) { case 0: controllerAction = PED_FIREWEAPON; break; case 1: controllerAction = PED_CYCLE_WEAPON_RIGHT; break; case 2: controllerAction = PED_CYCLE_WEAPON_LEFT; break; case 3: controllerAction = GO_FORWARD; break; case 4: controllerAction = GO_BACK; break; case 5: controllerAction = GO_LEFT; break; case 6: controllerAction = GO_RIGHT; break; case 7: controllerAction = PED_SNIPER_ZOOM_IN; break; case 8: controllerAction = PED_SNIPER_ZOOM_OUT; break; case 9: controllerAction = VEHICLE_ENTER_EXIT; break; case 10: case 11: case 12: case 16: case 18: case 19: case 20: case 21: controllerAction = -1; break; case 13: controllerAction = CAMERA_CHANGE_VIEW_ALL_SITUATIONS; break; case 14: controllerAction = PED_JUMPING; break; case 15: controllerAction = PED_SPRINT; break; case 17: controllerAction = PED_LOCK_TARGET; break; case 22: controllerAction = PED_LOOKBEHIND; break; case 23: if (m_ControlMethod == CONTROL_STANDARD) controllerAction = -1; else controllerAction = PED_1RST_PERSON_LOOK_LEFT; break; case 24: if (m_ControlMethod == CONTROL_STANDARD) controllerAction = -1; else controllerAction = PED_1RST_PERSON_LOOK_RIGHT; break; case 25: controllerAction = PED_1RST_PERSON_LOOK_UP; break; case 26: controllerAction = PED_1RST_PERSON_LOOK_DOWN; break; case 27: controllerAction = PED_CYCLE_TARGET_LEFT; break; case 28: controllerAction = PED_CYCLE_TARGET_RIGHT; break; case 29: controllerAction = PED_CENTER_CAMERA_BEHIND_PLAYER; break; default: break; } } else if (column == CONTSETUP_VEHICLE_COLUMN) { switch (optionIdx) { case 0: #ifdef BIND_VEHICLE_FIREWEAPON controllerAction = VEHICLE_FIREWEAPON; #else controllerAction = PED_FIREWEAPON; #endif break; case 1: case 2: case 7: case 8: case 14: case 15: case 17: case 25: case 26: case 27: case 28: case 29: controllerAction = -1; break; case 3: controllerAction = VEHICLE_ACCELERATE; break; case 4: controllerAction = VEHICLE_BRAKE; break; case 5: controllerAction = GO_LEFT; break; case 6: controllerAction = GO_RIGHT; break; case 9: controllerAction = VEHICLE_ENTER_EXIT; break; case 10: controllerAction = VEHICLE_CHANGE_RADIO_STATION; break; case 11: controllerAction = VEHICLE_HORN; break; case 12: controllerAction = TOGGLE_SUBMISSIONS; break; case 13: controllerAction = CAMERA_CHANGE_VIEW_ALL_SITUATIONS; break; case 16: controllerAction = VEHICLE_HANDBRAKE; break; case 18: controllerAction = VEHICLE_TURRETLEFT; break; case 19: controllerAction = VEHICLE_TURRETRIGHT; break; case 20: controllerAction = VEHICLE_TURRETUP; break; case 21: controllerAction = VEHICLE_TURRETDOWN; break; case 22: controllerAction = -2; break; case 23: controllerAction = VEHICLE_LOOKLEFT; break; case 24: controllerAction = VEHICLE_LOOKRIGHT; break; default: break; } } int bindingWhite = 155; // Highlight selected column(and make its text black) if (m_nSelectedListRow == optionIdx) { int bgY = m_nSelectedListRow * rowHeight + yStart + 1.0f; if (m_nCurrExLayer == HOVEROPTION_LIST) { if (column == CONTSETUP_PED_COLUMN && m_nSelectedContSetupColumn == CONTSETUP_PED_COLUMN) { #ifdef FIX_BUGS if (controllerAction == -1) { CSprite2d::DrawRect(CRect(nextX, MENU_Y(bgY), nextX + MENU_X(CONTSETUP_BOUND_COLUMN_WIDTH), MENU_Y(bgY + CONTSETUP_BOUND_HIGHLIGHT_HEIGHT)), CRGBA(CONTSETUP_DISABLED_HIGHLIGHTBG_COLOR.r, CONTSETUP_DISABLED_HIGHLIGHTBG_COLOR.g, CONTSETUP_DISABLED_HIGHLIGHTBG_COLOR.b, FadeIn(CONTSETUP_DISABLED_HIGHLIGHTBG_COLOR.a))); } else { CSprite2d::DrawRect(CRect(nextX, MENU_Y(bgY), nextX + MENU_X(CONTSETUP_BOUND_COLUMN_WIDTH), MENU_Y(bgY + CONTSETUP_BOUND_HIGHLIGHT_HEIGHT)), CRGBA(CONTSETUP_HIGHLIGHTBG_COLOR.r, CONTSETUP_HIGHLIGHTBG_COLOR.g, CONTSETUP_HIGHLIGHTBG_COLOR.b, FadeIn(CONTSETUP_HIGHLIGHTBG_COLOR.a))); } #else if (controllerAction == -1) { CSprite2d::DrawRect(CRect(MENU_X_LEFT_ALIGNED(210.0f), MENU_Y(bgY), MENU_X_LEFT_ALIGNED(400.0f), MENU_Y(bgY + CONTSETUP_BOUND_HIGHLIGHT_HEIGHT)), CRGBA(CONTSETUP_DISABLED_HIGHLIGHTBG_COLOR.r, CONTSETUP_DISABLED_HIGHLIGHTBG_COLOR.g, CONTSETUP_DISABLED_HIGHLIGHTBG_COLOR.b, FadeIn(CONTSETUP_DISABLED_HIGHLIGHTBG_COLOR.a))); } else { CSprite2d::DrawRect(CRect(MENU_X_LEFT_ALIGNED(210.0f), MENU_Y(bgY), MENU_X_LEFT_ALIGNED(400.0f), MENU_Y(bgY + CONTSETUP_BOUND_HIGHLIGHT_HEIGHT)), CRGBA(CONTSETUP_HIGHLIGHTBG_COLOR.r, CONTSETUP_HIGHLIGHTBG_COLOR.g, CONTSETUP_HIGHLIGHTBG_COLOR.b, FadeIn(CONTSETUP_HIGHLIGHTBG_COLOR.a))); } #endif CFont::SetColor(CRGBA(0, 0, 0, FadeIn(255))); bindingWhite = 0; } else if (column == CONTSETUP_VEHICLE_COLUMN && m_nSelectedContSetupColumn == CONTSETUP_VEHICLE_COLUMN) { #ifdef FIX_BUGS if (controllerAction == -1) { CSprite2d::DrawRect(CRect(nextX, MENU_Y(bgY), nextX + MENU_X(CONTSETUP_BOUND_COLUMN_WIDTH), MENU_Y(bgY + CONTSETUP_BOUND_HIGHLIGHT_HEIGHT)), CRGBA(CONTSETUP_DISABLED_HIGHLIGHTBG_COLOR.r, CONTSETUP_DISABLED_HIGHLIGHTBG_COLOR.g, CONTSETUP_DISABLED_HIGHLIGHTBG_COLOR.b, FadeIn(CONTSETUP_DISABLED_HIGHLIGHTBG_COLOR.a))); } else { CSprite2d::DrawRect(CRect(nextX, MENU_Y(bgY), nextX + MENU_X(CONTSETUP_BOUND_COLUMN_WIDTH), MENU_Y(bgY + CONTSETUP_BOUND_HIGHLIGHT_HEIGHT)), CRGBA(CONTSETUP_HIGHLIGHTBG_COLOR.r, CONTSETUP_HIGHLIGHTBG_COLOR.g, CONTSETUP_HIGHLIGHTBG_COLOR.b, FadeIn(CONTSETUP_HIGHLIGHTBG_COLOR.a))); } #else if (controllerAction == -1) { CSprite2d::DrawRect(CRect(MENU_X_LEFT_ALIGNED(410.0f), MENU_Y(bgY), MENU_X_LEFT_ALIGNED(600.0f), MENU_Y(bgY + 10)), CRGBA(CONTSETUP_DISABLED_HIGHLIGHTBG_COLOR.r, CONTSETUP_DISABLED_HIGHLIGHTBG_COLOR.g, CONTSETUP_DISABLED_HIGHLIGHTBG_COLOR.b, FadeIn(CONTSETUP_DISABLED_HIGHLIGHTBG_COLOR.a))); } else { CSprite2d::DrawRect(CRect(MENU_X_LEFT_ALIGNED(410.0f), MENU_Y(bgY), MENU_X_LEFT_ALIGNED(600.0f), MENU_Y(bgY + 10)), CRGBA(CONTSETUP_HIGHLIGHTBG_COLOR.r, CONTSETUP_HIGHLIGHTBG_COLOR.g, CONTSETUP_HIGHLIGHTBG_COLOR.b, FadeIn(CONTSETUP_HIGHLIGHTBG_COLOR.a))); } #endif CFont::SetColor(CRGBA(0, 0, 0, FadeIn(255))); bindingWhite = 0; } } } // Print bindings, including seperator (-) between them CFont::SetScale(MENU_X(0.25f), MENU_Y(SMALLESTTEXT_Y_SCALE)); #ifdef FIX_BUGS for (; contSetOrder < MAX_SETORDERS && controllerAction >= 0; contSetOrder++) { #else for (; contSetOrder < MAX_SETORDERS && controllerAction != -1; contSetOrder++) { #endif wchar *settingText = ControlsManager.GetControllerSettingTextWithOrderNumber((e_ControllerAction)controllerAction, (eContSetOrder)contSetOrder); if (settingText) { ++bindingsForThisOpt; if (bindingsForThisOpt > 1) { wchar *seperator = TheText.Get("FEC_IBT"); CFont::SetColor(CRGBA(20, 20, 20, FadeIn(80))); CFont::PrintString(nextX, nextY, seperator); CFont::SetColor(CRGBA(bindingWhite, bindingWhite, bindingWhite, FadeIn(255))); nextX += CFont::GetStringWidth(seperator, true) + bindingMargin; } CFont::PrintString(nextX, nextY, settingText); #ifdef MORE_LANGUAGES if (CFont::IsJapanese()) nextX += CFont::GetStringWidth_Jap(settingText) + bindingMargin; else #endif nextX += CFont::GetStringWidth(settingText, true) + bindingMargin; } } if (controllerAction == -1) { CFont::SetColor(CRGBA(20, 20, 20, FadeIn(80))); CFont::PrintString(nextX, nextY, TheText.Get("FEC_NUS")); // not used } else if (controllerAction == -2) { CFont::SetColor(CRGBA(20, 20, 20, FadeIn(80))); CFont::PrintString(nextX, nextY, TheText.Get("FEC_CMP")); // combo: l+r } else if (bindingsForThisOpt == 0) { if (m_nSelectedListRow != optionIdx) { CFont::SetColor(CRGBA(255, 255, 255, FadeIn(255))); CFont::PrintString(nextX, nextY, TheText.Get("FEC_UNB")); // unbound } else if (m_bWaitingForNewKeyBind) { if (column != m_nSelectedContSetupColumn) { CFont::SetColor(CRGBA(255, 255, 255, FadeIn(255))); CFont::PrintString(nextX, nextY, TheText.Get("FEC_UNB")); // unbound } } else { if (column != m_nSelectedContSetupColumn) { CFont::SetColor(CRGBA(255, 255, 255, FadeIn(255))); } CFont::PrintString(nextX, nextY, TheText.Get("FEC_UNB")); // unbound } } if (column == CONTSETUP_PED_COLUMN && m_nSelectedContSetupColumn == CONTSETUP_PED_COLUMN || column == CONTSETUP_VEHICLE_COLUMN && m_nSelectedContSetupColumn == CONTSETUP_VEHICLE_COLUMN) { if (optionIdx == m_nSelectedListRow && controllerAction != -1 && controllerAction != -2) { m_CurrCntrlAction = controllerAction; if (m_bWaitingForNewKeyBind) { static bool showWaitingText = false; if (bindingsForThisOpt > 0) { wchar *seperator = TheText.Get("FEC_IBT"); CFont::PrintString(nextX, nextY, seperator); nextX += CFont::GetStringWidth(seperator, true) + bindingMargin; } static uint32 lastWaitingTextFlash = 0; if (CTimer::GetTimeInMillisecondsPauseMode() - lastWaitingTextFlash > 150) { showWaitingText = !showWaitingText; lastWaitingTextFlash = CTimer::GetTimeInMillisecondsPauseMode(); } if (showWaitingText) { CFont::SetColor(CRGBA(55, 55, 55, FadeIn(255))); CFont::PrintString(nextX, nextY, TheText.Get("FEC_QUE")); // "???" } SET_FONT_FOR_HELPER_TEXT CFont::SetColor(CRGBA(255, 255, 255, FadeIn(255))); if (m_bKeyChangeNotProcessed) { CFont::PrintString(MENU_X_LEFT_ALIGNED(275.0f), SCREEN_SCALE_FROM_BOTTOM(114.0f), TheText.Get("FET_CIG")); // BACKSPACE TO CLEAR - LMB,RETURN TO CHANGE } else { CFont::PrintString(MENU_X_LEFT_ALIGNED(275.0f), SCREEN_SCALE_FROM_BOTTOM(114.0f), TheText.Get("FET_RIG")); // SELECT A NEW CONTROL FOR THIS ACTION OR ESC TO CANCEL } SET_FONT_FOR_LIST_ITEM if (!m_bKeyIsOK) DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_SETTING_CHANGE, 0); m_bKeyIsOK = true; } else { SET_FONT_FOR_HELPER_TEXT CFont::SetColor(CRGBA(255, 255, 255, FadeIn(255))); CFont::PrintString(MENU_X_LEFT_ALIGNED(275.0f), SCREEN_SCALE_FROM_BOTTOM(114.0f), TheText.Get("FET_CIG")); // BACKSPACE TO CLEAR - LMB,RETURN TO CHANGE SET_FONT_FOR_LIST_ITEM m_bKeyIsOK = false; m_bKeyChangeNotProcessed = false; } } else if (optionIdx == m_nSelectedListRow) { SET_FONT_FOR_HELPER_TEXT CFont::SetColor(CRGBA(55, 55, 55, FadeIn(255))); CFont::PrintString(MENU_X_LEFT_ALIGNED(275.0f), SCREEN_SCALE_FROM_BOTTOM(114.0f), TheText.Get("FET_EIG")); // CANNOT SET A CONTROL FOR THIS ACTION SET_FONT_FOR_LIST_ITEM } } } } void CMenuManager::DrawControllerScreenExtraText(int yStart, int xStart, int lineHeight) { int extraTextStart = GetStartOptionsCntrlConfigScreens(); int numOpts = GetNumOptionsCntrlConfigScreens(); int spacing = MENU_X(10.0f); for (int i = extraTextStart; i < extraTextStart + numOpts; i++) { int numTextsPrinted = 0; int nextX = xStart; for (int j = 1; j < 5; j++) { wchar *text = ControlsManager.GetControllerSettingTextWithOrderNumber((e_ControllerAction)i, (eContSetOrder)j); if (text) ++numTextsPrinted; if (text) { // Seperator if (numTextsPrinted > 1) { CFont::PrintString(nextX, MENU_Y(yStart), TheText.Get("FEC_IBT")); nextX = CFont::GetStringWidth(TheText.Get("FEC_IBT"), true) + spacing + nextX; } CFont::PrintString(nextX, MENU_Y(yStart), text); } if (text) nextX = CFont::GetStringWidth(text, true) + spacing + nextX; } if (m_nCurrOption == i - extraTextStart && m_bWaitingForNewKeyBind) { static bool waitingTextVisible = false; // Seperator if (numTextsPrinted > 0) { CFont::PrintString(nextX, MENU_Y(yStart), TheText.Get("FEC_IBT")); nextX = CFont::GetStringWidth(TheText.Get("FEC_IBT"), true) + spacing + nextX; } static uint32 lastStateChange = 0; if (CTimer::GetTimeInMillisecondsPauseMode() - lastStateChange > 150) { waitingTextVisible = !waitingTextVisible; lastStateChange = CTimer::GetTimeInMillisecondsPauseMode(); } if (waitingTextVisible) { CFont::SetColor(CRGBA(255, 255, 0, FadeIn(255))); CFont::PrintString(nextX, MENU_Y(yStart), TheText.Get("FEC_QUE")); CFont::SetColor(CRGBA(MENUOPTION_COLOR.r, MENUOPTION_COLOR.g, MENUOPTION_COLOR.b, FadeIn(255))); } } yStart += lineHeight; } wchar *error = nil; if (DisplayComboButtonErrMsg) error = ControlsManager.GetButtonComboText((e_ControllerAction)(m_nCurrOption + extraTextStart)); if (error) { CFont::SetColor(CRGBA(233, 22, 159, 255)); CFont::PrintString(xStart, MENU_Y(yStart + 10), error); } } void CMenuManager::DrawControllerSetupScreen() { float rowHeight; switch (m_ControlMethod) { case CONTROL_STANDARD: rowHeight = CONTSETUP_STANDARD_ROW_HEIGHT; break; case CONTROL_CLASSIC: rowHeight = CONTSETUP_CLASSIC_ROW_HEIGHT; break; default: break; } RESET_FONT_FOR_NEW_PAGE SET_FONT_FOR_MENU_HEADER switch (m_ControlMethod) { case CONTROL_STANDARD: CFont::PrintString(PAGE_NAME_X(MENUHEADER_POS_X), SCREEN_SCALE_FROM_BOTTOM(MENUHEADER_POS_Y), TheText.Get(aScreens[m_nCurrScreen].m_ScreenName)); break; case CONTROL_CLASSIC: CFont::PrintString(PAGE_NAME_X(MENUHEADER_POS_X), SCREEN_SCALE_FROM_BOTTOM(MENUHEADER_POS_Y), TheText.Get("FET_CTI")); break; default: break; } wchar *actionTexts[31]; actionTexts[0] = TheText.Get("FEC_FIR"); actionTexts[1] = TheText.Get("FEC_NWE"); actionTexts[2] = TheText.Get("FEC_PWE"); actionTexts[3] = TheText.Get("FEC_FOR"); actionTexts[4] = TheText.Get("FEC_BAC"); actionTexts[5] = TheText.Get("FEC_LEF"); actionTexts[6] = TheText.Get("FEC_RIG"); actionTexts[7] = TheText.Get("FEC_ZIN"); actionTexts[8] = TheText.Get("FEC_ZOT"); actionTexts[9] = TheText.Get("FEC_EEX"); actionTexts[10] = TheText.Get("FEC_RAD"); actionTexts[11] = TheText.Get("FEC_HRN"); actionTexts[12] = TheText.Get("FEC_SUB"); actionTexts[13] = TheText.Get("FEC_CMR"); actionTexts[14] = TheText.Get("FEC_JMP"); actionTexts[15] = TheText.Get("FEC_SPN"); actionTexts[16] = TheText.Get("FEC_HND"); actionTexts[17] = TheText.Get("FEC_TAR"); if (m_ControlMethod == CONTROL_CLASSIC) { actionTexts[18] = TheText.Get("FEC_TFL"); actionTexts[19] = TheText.Get("FEC_TFR"); actionTexts[20] = TheText.Get("FEC_TFU"); actionTexts[21] = TheText.Get("FEC_TFD"); actionTexts[22] = TheText.Get("FEC_LBA"); actionTexts[23] = TheText.Get("FEC_LOL"); actionTexts[24] = TheText.Get("FEC_LOR"); actionTexts[25] = TheText.Get("FEC_LUD"); actionTexts[26] = TheText.Get("FEC_LDU"); actionTexts[27] = TheText.Get("FEC_NTR"); actionTexts[28] = TheText.Get("FEC_PTT"); actionTexts[29] = TheText.Get("FEC_CEN"); actionTexts[30] = nil; } else { actionTexts[18] = TheText.Get("FEC_TFL"); actionTexts[19] = TheText.Get("FEC_TFR"); actionTexts[20] = TheText.Get("FEC_TFU"); actionTexts[21] = TheText.Get("FEC_TFD"); actionTexts[22] = TheText.Get("FEC_LBA"); actionTexts[23] = TheText.Get("FEC_LOL"); actionTexts[24] = TheText.Get("FEC_LOR"); actionTexts[25] = nil; } // Gray panel background CSprite2d::DrawRect(CRect(MENU_X_LEFT_ALIGNED(CONTSETUP_LIST_LEFT), MENU_Y(CONTSETUP_LIST_TOP), MENU_X_RIGHT_ALIGNED(CONTSETUP_LIST_RIGHT), SCREEN_SCALE_FROM_BOTTOM(CONTSETUP_LIST_BOTTOM)), CRGBA(LIST_BACKGROUND_COLOR.r, LIST_BACKGROUND_COLOR.g, LIST_BACKGROUND_COLOR.b, FadeIn(LIST_BACKGROUND_COLOR.a))); if (m_nCurrExLayer == HOVEROPTION_LIST) CFont::SetColor(CRGBA(SELECTEDMENUOPTION_COLOR.r, SELECTEDMENUOPTION_COLOR.g, SELECTEDMENUOPTION_COLOR.b, FadeIn(255))); else CFont::SetColor(CRGBA(MENUOPTION_COLOR.r, MENUOPTION_COLOR.g, MENUOPTION_COLOR.b, FadeIn(255))); // List header CFont::SetFontStyle(FONT_LOCALE(FONT_HEADING)); CFont::SetScale(MENU_X(MENUACTION_SCALE_MULT), MENU_Y(MENUACTION_SCALE_MULT)); CFont::SetRightJustifyOff(); CFont::PrintString(MENU_X_LEFT_ALIGNED(CONTSETUP_COLUMN_1_X), MENU_Y(CONTSETUP_LIST_TOP), TheText.Get("FET_CAC")); CFont::PrintString(MENU_X_LEFT_ALIGNED(CONTSETUP_COLUMN_2_X), MENU_Y(CONTSETUP_LIST_TOP), TheText.Get("FET_CFT")); CFont::PrintString(MENU_X_LEFT_ALIGNED(CONTSETUP_COLUMN_3_X), MENU_Y(CONTSETUP_LIST_TOP), TheText.Get("FET_CCR")); SET_FONT_FOR_LIST_ITEM int yStart; if (m_ControlMethod == CONTROL_CLASSIC) yStart = CONTSETUP_LIST_TOP + CONTSETUP_LIST_HEADER_HEIGHT + 1; else yStart = CONTSETUP_LIST_TOP + CONTSETUP_LIST_HEADER_HEIGHT + 5; float optionYBottom = yStart + rowHeight; for (int i = 0; i < ARRAY_SIZE(actionTexts); ++i) { wchar *actionText = actionTexts[i]; if (!actionText) break; if (m_nMousePosX > MENU_X_LEFT_ALIGNED(CONTSETUP_LIST_LEFT + 2.0f) && m_nMousePosX < MENU_X_LEFT_ALIGNED(CONTSETUP_COLUMN_3_X + CONTSETUP_BOUND_COLUMN_WIDTH)) { if (m_nMousePosY > MENU_Y(i * rowHeight + yStart) && m_nMousePosY < MENU_Y(i * rowHeight + optionYBottom)) { if (m_nOptionMouseHovering != i && m_nCurrExLayer == HOVEROPTION_LIST) DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_NAVIGATION, 0); m_nOptionMouseHovering = i; if (m_nMouseOldPosX != m_nMousePosX || m_nMouseOldPosY != m_nMousePosY) { m_nCurrExLayer = HOVEROPTION_LIST; m_nSelectedListRow = i; // why different number for 3rd column hovering X?? this function is a mess #ifdef FIX_BUGS if (m_nMousePosX > MENU_X_LEFT_ALIGNED(0.0f) && m_nMousePosX < MENU_X_LEFT_ALIGNED(CONTSETUP_COLUMN_2_X + CONTSETUP_BOUND_COLUMN_WIDTH)) { #else if (m_nMousePosX > MENU_X_LEFT_ALIGNED(0.0f) && m_nMousePosX < MENU_X_LEFT_ALIGNED(370.0f)) { #endif if (m_nSelectedContSetupColumn != CONTSETUP_PED_COLUMN && m_nCurrExLayer == HOVEROPTION_LIST) DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_NAVIGATION, 0); m_nSelectedContSetupColumn = CONTSETUP_PED_COLUMN; #ifdef FIX_BUGS } else if (m_nMousePosX > MENU_X_LEFT_ALIGNED(CONTSETUP_COLUMN_2_X + CONTSETUP_BOUND_COLUMN_WIDTH) && m_nMousePosX < SCREEN_WIDTH) { #else } else if (m_nMousePosX > MENU_X_LEFT_ALIGNED(370.0f) && m_nMousePosX < SCREEN_WIDTH) { #endif if (m_nSelectedContSetupColumn != CONTSETUP_VEHICLE_COLUMN && m_nCurrExLayer == HOVEROPTION_LIST) DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_NAVIGATION, 0); m_nSelectedContSetupColumn = CONTSETUP_VEHICLE_COLUMN; } } // what?? if (m_nHoverOption == HOVEROPTION_SKIN) { if (i == m_nSelectedListRow) { m_nHoverOption = HOVEROPTION_NOT_HOVERING; m_bWaitingForNewKeyBind = true; m_bStartWaitingForKeyBind = true; pControlEdit = &m_KeyPressedCode; } } else m_nHoverOption = HOVEROPTION_NOT_HOVERING; } } if (m_nSelectedListRow != i) CFont::SetColor(CRGBA(MENUOPTION_COLOR.r, MENUOPTION_COLOR.g, MENUOPTION_COLOR.b, FadeIn(255))); else if (m_nCurrExLayer == HOVEROPTION_LIST) CFont::SetColor(CRGBA(SELECTEDMENUOPTION_COLOR.r, SELECTEDMENUOPTION_COLOR.g, SELECTEDMENUOPTION_COLOR.b, FadeIn(255))); CFont::SetRightJustifyOff(); if (m_PrefsLanguage == LANGUAGE_GERMAN && (i == 20 || i == 21)) CFont::SetScale(MENU_X(0.32f), MENU_Y(SMALLESTTEXT_Y_SCALE)); else CFont::SetScale(MENU_X(SMALLESTTEXT_X_SCALE), MENU_Y(SMALLESTTEXT_Y_SCALE)); CFont::PrintString(MENU_X_LEFT_ALIGNED(CONTSETUP_COLUMN_1_X), MENU_Y(i * rowHeight + yStart), actionText); } DrawControllerBound(yStart, MENU_X_LEFT_ALIGNED(CONTSETUP_COLUMN_2_X), rowHeight, CONTSETUP_PED_COLUMN); DrawControllerBound(yStart, MENU_X_LEFT_ALIGNED(CONTSETUP_COLUMN_3_X), rowHeight, CONTSETUP_VEHICLE_COLUMN); CFont::SetScale(MENU_X(MENU_TEXT_SIZE_X), MENU_Y(MENU_TEXT_SIZE_Y)); if ((m_nMousePosX > MENU_X_RIGHT_ALIGNED(CONTSETUP_BACK_RIGHT) - CFont::GetStringWidth(TheText.Get("FEDS_TB"), true) && m_nMousePosX < MENU_X_RIGHT_ALIGNED(CONTSETUP_BACK_RIGHT) && m_nMousePosY > SCREEN_SCALE_FROM_BOTTOM(CONTSETUP_BACK_BOTTOM) && m_nMousePosY < SCREEN_SCALE_FROM_BOTTOM(CONTSETUP_BACK_BOTTOM - CONTSETUP_BACK_HEIGHT)) || m_nCurrExLayer == HOVEROPTION_BACK) { m_nHoverOption = HOVEROPTION_BACK; } else if (m_nMousePosX > MENU_X_LEFT_ALIGNED(CONTSETUP_LIST_LEFT + 2.0f) && m_nMousePosX < MENU_X_LEFT_ALIGNED(CONTSETUP_COLUMN_3_X + CONTSETUP_BOUND_COLUMN_WIDTH) && m_nMousePosY > MENU_Y(CONTSETUP_LIST_TOP + CONTSETUP_LIST_HEADER_HEIGHT) && m_nMousePosY < SCREEN_SCALE_FROM_BOTTOM(CONTSETUP_LIST_BOTTOM + 5.0f)) { m_nHoverOption = HOVEROPTION_LIST; } else { m_nHoverOption = HOVEROPTION_NOT_HOVERING; } // Back button and it's shadow CFont::SetFontStyle(FONT_LOCALE(FONT_HEADING)); CFont::SetScale(MENU_X(MENU_TEXT_SIZE_X), MENU_Y(MENU_TEXT_SIZE_Y)); CFont::SetRightJustifyOn(); CFont::SetColor(CRGBA(0, 0, 0, FadeIn(90))); for (int i = 0; i < 2; i++) { CFont::PrintString(MENU_X_RIGHT_ALIGNED(CONTSETUP_BACK_RIGHT - 2.0f - i), SCREEN_SCALE_FROM_BOTTOM(CONTSETUP_BACK_BOTTOM - 4.0f - i), TheText.Get("FEDS_TB")); if (m_nHoverOption == HOVEROPTION_BACK) CFont::SetColor(CRGBA(SELECTEDMENUOPTION_COLOR.r, SELECTEDMENUOPTION_COLOR.g, SELECTEDMENUOPTION_COLOR.b, FadeIn(255))); else CFont::SetColor(CRGBA(MENUOPTION_COLOR.r, MENUOPTION_COLOR.g, MENUOPTION_COLOR.b, FadeIn(255))); } } void CMenuManager::DrawFrontEnd() { CFont::SetAlphaFade(255.0f); #ifdef PS2_LIKE_MENU #define setBbItem(a, b, c) strcpy(a.name, b); a.screenId = c; if (m_nCurrScreen == MENUPAGE_NONE) { if (m_bGameNotLoaded) { if (bbTabCount != 6) { setBbItem(bbNames[0], "FEB_SAV",MENUPAGE_NEW_GAME) setBbItem(bbNames[1], "FEB_CON",MENUPAGE_CONTROLLER_PC) setBbItem(bbNames[2], "FEB_AUD",MENUPAGE_SOUND_SETTINGS) setBbItem(bbNames[3], "FEB_DIS",MENUPAGE_DISPLAY_SETTINGS) setBbItem(bbNames[4], "FEB_LAN",MENUPAGE_LANGUAGE_SETTINGS) setBbItem(bbNames[5], "FESZ_QU",MENUPAGE_EXIT) bbTabCount = 6; } } else { if (bbTabCount != 8) { setBbItem(bbNames[0], "FEB_STA",MENUPAGE_STATS) setBbItem(bbNames[1], "FEB_SAV",MENUPAGE_NEW_GAME) setBbItem(bbNames[2], "FEB_BRI",MENUPAGE_BRIEFS) setBbItem(bbNames[3], "FEB_CON",MENUPAGE_CONTROLLER_PC) setBbItem(bbNames[4], "FEB_AUD",MENUPAGE_SOUND_SETTINGS) setBbItem(bbNames[5], "FEB_DIS",MENUPAGE_DISPLAY_SETTINGS) setBbItem(bbNames[6], "FEB_LAN",MENUPAGE_LANGUAGE_SETTINGS) setBbItem(bbNames[7], "FESZ_QU",MENUPAGE_EXIT) bbTabCount = 8; } } m_nCurrScreen = bbNames[0].screenId; bottomBarActive = true; curBottomBarOption = 0; } #undef setBbItem #else if (m_nCurrScreen == MENUPAGE_NONE) { if (m_bGameNotLoaded) { m_nCurrScreen = MENUPAGE_START_MENU; } else { m_nCurrScreen = MENUPAGE_PAUSE_MENU; } } #endif if (m_nCurrOption == 0 && aScreens[m_nCurrScreen].m_aEntries[0].m_Action == MENUACTION_LABEL) m_nCurrOption = 1; #ifdef PS2_SAVE_DIALOG if(m_bRenderGameInMenu) DrawFrontEndSaveZone(); else #endif DrawFrontEndNormal(); PrintErrorMessage(); } #ifdef PS2_SAVE_DIALOG void CMenuManager::DrawFrontEndSaveZone() { CSprite2d::InitPerFrame(); CFont::InitPerFrame(); RwRenderStateSet(rwRENDERSTATETEXTUREFILTER, (void*)rwFILTERNEAREST); // Not original dimensions, have been changed to fit PC screen & PC menu layout. CSprite2d::DrawRect(CRect(MENU_X_LEFT_ALIGNED(30.0f), MENU_Y(50.0f), MENU_X_RIGHT_ALIGNED(30.0f), SCREEN_SCALE_FROM_BOTTOM(50.0f)), CRGBA(0, 0, 0, 175)); m_nMenuFadeAlpha = 255; RwRenderStateSet(rwRENDERSTATETEXTUREADDRESS, (void*)rwTEXTUREADDRESSCLAMP); RwRenderStateSet(rwRENDERSTATEVERTEXALPHAENABLE, (void*)FALSE); Draw(); CFont::DrawFonts(); // Draw mouse RwRenderStateSet(rwRENDERSTATETEXTUREFILTER, (void*)rwFILTERLINEAR); RwRenderStateSet(rwRENDERSTATETEXTUREADDRESS, (void*)rwTEXTUREADDRESSCLAMP); if (m_bShowMouse) { RwRenderStateSet(rwRENDERSTATESRCBLEND, (void*)rwBLENDSRCALPHA); RwRenderStateSet(rwRENDERSTATEDESTBLEND, (void*)rwBLENDINVSRCALPHA); RwRenderStateSet(rwRENDERSTATEVERTEXALPHAENABLE, (void*)TRUE); CRect mouse(0.0f, 0.0f, MENU_X(75.0f), MENU_Y(75.0f)); CRect shad(MENU_X(10.0f), MENU_Y(3.0f), MENU_X(85.0f), MENU_Y(78.0f)); mouse.Translate(m_nMousePosX, m_nMousePosY); shad.Translate(m_nMousePosX, m_nMousePosY); if(field_518 == 4){ m_aMenuSprites[MENUSPRITE_MOUSET].Draw(shad, CRGBA(100, 100, 100, 50)); RwRenderStateSet(rwRENDERSTATEVERTEXALPHAENABLE, (void*)FALSE); m_aMenuSprites[MENUSPRITE_MOUSET].Draw(mouse, CRGBA(255, 255, 255, 255)); }else{ m_aMenuSprites[MENUSPRITE_MOUSE].Draw(shad, CRGBA(100, 100, 100, 50)); RwRenderStateSet(rwRENDERSTATEVERTEXALPHAENABLE, (void*)FALSE); m_aMenuSprites[MENUSPRITE_MOUSE].Draw(mouse, CRGBA(255, 255, 255, 255)); } } } #endif #ifdef PS2_LIKE_MENU void CMenuManager::DrawFrontEndNormal() { CSprite2d::InitPerFrame(); CFont::InitPerFrame(); RwRenderStateSet(rwRENDERSTATETEXTUREFILTER, (void*)rwFILTERLINEAR); if (!m_bGameNotLoaded) { CSprite2d *bg = LoadSplash(nil); bg->Draw(CRect(0.0f, 0.0f, SCREEN_WIDTH, SCREEN_HEIGHT), CRGBA(48, 48, 48, 255)); } else { CSprite2d::DrawRect(CRect(0.0f, 0.0f, SCREEN_WIDTH, SCREEN_HEIGHT), CRGBA(0, 0, 0, 255)); } RwRenderStateSet(rwRENDERSTATETEXTUREFILTER, (void*)rwFILTERNEAREST); RwRenderStateSet(rwRENDERSTATEZTESTENABLE, (void*)FALSE); RwRenderStateSet(rwRENDERSTATEZWRITEENABLE, (void*)FALSE); RwRenderStateSet(rwRENDERSTATEVERTEXALPHAENABLE, (void*)TRUE); m_aFrontEndSprites[FE2_MAINPANEL_UL].Draw(CRect(MENU_X_LEFT_ALIGNED(0.0f), 0.0f, SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2), CRGBA(255, 255, 255, 255)); m_aFrontEndSprites[FE2_MAINPANEL_UR].Draw(CRect(SCREEN_WIDTH / 2, 0.0f, MENU_X_RIGHT_ALIGNED(0.0f), SCREEN_HEIGHT / 2), CRGBA(255, 255, 255, 255)); m_aFrontEndSprites[FE2_MAINPANEL_DL].Draw(CRect(MENU_X_LEFT_ALIGNED(0.0f), SCREEN_HEIGHT / 2, SCREEN_WIDTH / 2, SCREEN_HEIGHT), CRGBA(255, 255, 255, 255)); m_aFrontEndSprites[FE2_MAINPANEL_DR].Draw(CRect(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, MENU_X_RIGHT_ALIGNED(0.0f), SCREEN_HEIGHT), CRGBA(255, 255, 255, 255)); RwRenderStateSet(rwRENDERSTATETEXTUREFILTER, (void*)rwFILTERLINEAR); eFrontendSprites currentSprite; switch (m_nCurrScreen) { case MENUPAGE_STATS: case MENUPAGE_START_MENU: case MENUPAGE_PAUSE_MENU: case MENUPAGE_EXIT: currentSprite = FE_ICONSTATS; break; case MENUPAGE_LANGUAGE_SETTINGS: currentSprite = FE_ICONLANGUAGE; break; case MENUPAGE_CHOOSE_LOAD_SLOT: case MENUPAGE_CHOOSE_DELETE_SLOT: case MENUPAGE_NEW_GAME_RELOAD: case MENUPAGE_LOAD_SLOT_CONFIRM: case MENUPAGE_DELETE_SLOT_CONFIRM: currentSprite = FE_ICONSAVE; break; case MENUPAGE_DISPLAY_SETTINGS: currentSprite = FE_ICONDISPLAY; break; case MENUPAGE_SOUND_SETTINGS: currentSprite = FE_ICONAUDIO; break; case MENUPAGE_CONTROLLER_PC: case MENUPAGE_OPTIONS: case MENUPAGE_CONTROLLER_SETTINGS: case MENUPAGE_KEYBOARD_CONTROLS: case MENUPAGE_MOUSE_CONTROLS: currentSprite = FE_ICONCONTROLS; break; default: /*case MENUPAGE_NEW_GAME: */ /*case MENUPAGE_BRIEFS: */ currentSprite = FE_ICONBRIEF; break; } static float fadeAlpha = 0.0f; if (m_nMenuFadeAlpha < 255) { if (m_nMenuFadeAlpha == 0 && fadeAlpha > 1.0f) fadeAlpha = 0.0f; // +20 per every 33 ms (1000.f/30.f - original frame limiter fps) fadeAlpha += (frameTime) * 20.f / 33.f; m_nMenuFadeAlpha = fadeAlpha; } else { // TODO: what is this? waiting mouse? if(field_518 == 4){ if(m_nHoverOption == HOVEROPTION_3 || m_nHoverOption == HOVEROPTION_4 || m_nHoverOption == HOVEROPTION_5 || m_nHoverOption == HOVEROPTION_6 || m_nHoverOption == HOVEROPTION_7) field_518 = 2; else field_518 = 1; } } m_aFrontEndSprites[currentSprite].Draw(CRect(MENU_X_LEFT_ALIGNED(50.0f), MENU_Y(50.0f), MENU_X_RIGHT_ALIGNED(50.0f), SCREEN_SCALE_FROM_BOTTOM(95.0f)), CRGBA(255, 255, 255, m_nMenuFadeAlpha > 255 ? 255 : m_nMenuFadeAlpha)); RwRenderStateSet(rwRENDERSTATETEXTUREFILTER, (void*)rwFILTERNEAREST); RwRenderStateSet(rwRENDERSTATETEXTUREADDRESS, (void*)rwTEXTUREADDRESSCLAMP); RwRenderStateSet(rwRENDERSTATEVERTEXALPHAENABLE, (void*)FALSE); switch (m_nCurrScreen) { case MENUPAGE_SKIN_SELECT: DrawPlayerSetupScreen(); break; case MENUPAGE_KEYBOARD_CONTROLS: DrawControllerSetupScreen(); break; default: Draw(); break; } // Positions/style from PS2 menu, credits to Fire_Head /* Draw controller buttons */ CFont::SetFontStyle(FONT_BANK); CFont::SetBackgroundOff(); CFont::SetScale(SCREEN_SCALE_X(0.35f), SCREEN_SCALE_Y(0.64f)); CFont::SetPropOn(); CFont::SetCentreOff(); CFont::SetJustifyOn(); CFont::SetRightJustifyOff(); CFont::SetBackGroundOnlyTextOn(); CFont::SetWrapx(MENU_X_RIGHT_ALIGNED(MENU_X_MARGIN)); // 600.0f CFont::SetColor(CRGBA(16, 16, 16, 255)); switch (m_nCurrScreen) { // Page names overlaps buttons on those. case MENUPAGE_MOUSE_CONTROLS: case MENUPAGE_KEYBOARD_CONTROLS: break; default: { CFont::PrintString(MENU_X_LEFT_ALIGNED(52.0f), MENU_Y(360.0f), TheText.Get("FEDS_SE")); CFont::PrintString(MENU_X_LEFT_ALIGNED(52.0f), MENU_Y(372.0f), TheText.Get("FEDS_BA")); if (!m_bGameNotLoaded) CFont::PrintString(MENU_X_LEFT_ALIGNED(52.0f), MENU_Y(384.0f), TheText.Get("FEDS_ST")); if (bottomBarActive) CFont::PrintString(MENU_X_LEFT_ALIGNED(242.0f), MENU_Y(372.0f), TheText.Get("FEDS_AM")); // <>-CHANGE MENU else if (m_nCurrScreen != MENUPAGE_STATS && m_nCurrScreen != MENUPAGE_BRIEFS) { CFont::PrintString(MENU_X_LEFT_ALIGNED(242.0f), MENU_Y(360.0f + 3.5f), TheText.Get("FEA_UP")); // ; CFont::PrintString(MENU_X_LEFT_ALIGNED(242.0f), MENU_Y(384.0f - 3.5f), TheText.Get("FEA_DO")); // = CFont::PrintString(MENU_X_LEFT_ALIGNED(242.0f - 10.0f), MENU_Y(372.0f), TheText.Get("FEA_LE")); // < CFont::PrintString(MENU_X_LEFT_ALIGNED(242.0f + 11.0f), MENU_Y(372.0f), TheText.Get("FEA_RI")); // > CFont::PrintString(MENU_X_LEFT_ALIGNED(242.0f + 20.0f), MENU_Y(372.0f), TheText.Get("FEDSAS3")); // - CHANGE SELECTION } break; } } #define optionWidth MENU_X(66.0f) #define rawOptionHeight 22.0f #define optionBottom SCREEN_SCALE_FROM_BOTTOM(20.0f) #define optionTop SCREEN_SCALE_FROM_BOTTOM(20.0f + rawOptionHeight) #define leftPadding MENU_X_LEFT_ALIGNED(90.0f) wchar *str; hoveredBottomBarOption = -1; if (curBottomBarOption != -1) { // This active tab sprite is needlessly big m_aFrontEndSprites[FE2_TABACTIVE].Draw(CRect(leftPadding - MENU_X(2.0f) + (optionWidth) * curBottomBarOption, optionTop, leftPadding - MENU_X(5.0f) + optionWidth * (curBottomBarOption + 2), optionBottom + MENU_Y(rawOptionHeight - 9.0f)), CRGBA(CRGBA(255, 255, 255, 255))); for (int i = 0; i < bbTabCount; i++) { float xStart = leftPadding + optionWidth * i; if (CheckHover(xStart, xStart + optionWidth, optionTop, optionBottom)) hoveredBottomBarOption = i; CFont::SetFontStyle(FONT_LOCALE(FONT_BANK)); CFont::SetScale(MENU_X(0.35f), MENU_Y(0.7f)); CFont::SetRightJustifyOff(); if (hoveredBottomBarOption == i && hoveredBottomBarOption != curBottomBarOption) CFont::SetColor(CRGBA(MENUOPTION_COLOR.r, MENUOPTION_COLOR.g, MENUOPTION_COLOR.b, 255)); else { if(bottomBarActive || curBottomBarOption == i) CFont::SetColor(CRGBA(HEADER_COLOR.r, HEADER_COLOR.g, HEADER_COLOR.b, 255)); else CFont::SetColor(CRGBA(HEADER_COLOR.r, HEADER_COLOR.g, HEADER_COLOR.b, 110)); } str = TheText.Get(bbNames[i].name); CFont::PrintString(xStart + MENU_X(4.0f), SCREEN_SCALE_FROM_BOTTOM(39.0f), str); } } #undef optionBottom #undef optionTop #undef leftPadding #undef optionWidth #undef rawOptionHeight CFont::DrawFonts(); // Draw mouse RwRenderStateSet(rwRENDERSTATETEXTUREFILTER, (void*)rwFILTERLINEAR); RwRenderStateSet(rwRENDERSTATETEXTUREADDRESS, (void*)rwTEXTUREADDRESSCLAMP); if (m_bShowMouse) { RwRenderStateSet(rwRENDERSTATESRCBLEND, (void*)rwBLENDSRCALPHA); RwRenderStateSet(rwRENDERSTATEDESTBLEND, (void*)rwBLENDINVSRCALPHA); RwRenderStateSet(rwRENDERSTATEVERTEXALPHAENABLE, (void*)TRUE); CRect mouse(0.0f, 0.0f, MENU_X(75.0f), MENU_Y(75.0f)); CRect shad(MENU_X(10.0f), MENU_Y(3.0f), MENU_X(85.0f), MENU_Y(78.0f)); mouse.Translate(m_nMousePosX, m_nMousePosY); shad.Translate(m_nMousePosX, m_nMousePosY); if(field_518 == 4){ m_aMenuSprites[MENUSPRITE_MOUSET].Draw(shad, CRGBA(100, 100, 100, 50)); RwRenderStateSet(rwRENDERSTATEVERTEXALPHAENABLE, (void*)FALSE); m_aMenuSprites[MENUSPRITE_MOUSET].Draw(mouse, CRGBA(255, 255, 255, 255)); }else{ m_aMenuSprites[MENUSPRITE_MOUSE].Draw(shad, CRGBA(100, 100, 100, 50)); RwRenderStateSet(rwRENDERSTATEVERTEXALPHAENABLE, (void*)FALSE); m_aMenuSprites[MENUSPRITE_MOUSE].Draw(mouse, CRGBA(255, 255, 255, 255)); } } } #else void CMenuManager::DrawFrontEndNormal() { CSprite2d::InitPerFrame(); CFont::InitPerFrame(); RwRenderStateSet(rwRENDERSTATETEXTUREFILTER, (void*)rwFILTERLINEAR); LoadSplash(nil); eMenuSprites previousSprite; if (m_nMenuFadeAlpha < 255) { switch (m_nPrevScreen) { case MENUPAGE_STATS: case MENUPAGE_START_MENU: case MENUPAGE_PAUSE_MENU: previousSprite = MENUSPRITE_MAINMENU; break; case MENUPAGE_NEW_GAME: case MENUPAGE_CHOOSE_LOAD_SLOT: case MENUPAGE_CHOOSE_DELETE_SLOT: case MENUPAGE_NEW_GAME_RELOAD: case MENUPAGE_LOAD_SLOT_CONFIRM: case MENUPAGE_DELETE_SLOT_CONFIRM: case MENUPAGE_EXIT: previousSprite = MENUSPRITE_SINGLEPLAYER; break; case MENUPAGE_MULTIPLAYER_MAIN: previousSprite = MENUSPRITE_MULTIPLAYER; break; case MENUPAGE_MULTIPLAYER_MAP: case MENUPAGE_MULTIPLAYER_FIND_GAME: case MENUPAGE_SKIN_SELECT: case MENUPAGE_KEYBOARD_CONTROLS: case MENUPAGE_MOUSE_CONTROLS: previousSprite = MENUSPRITE_FINDGAME; break; case MENUPAGE_MULTIPLAYER_CONNECTION: case MENUPAGE_MULTIPLAYER_MODE: previousSprite = MENUSPRITE_CONNECTION; break; case MENUPAGE_MULTIPLAYER_CREATE: previousSprite = MENUSPRITE_HOSTGAME; break; case MENUPAGE_SKIN_SELECT_OLD: case MENUPAGE_OPTIONS: previousSprite = MENUSPRITE_PLAYERSET; break; default: #ifdef CUSTOM_FRONTEND_OPTIONS CCustomScreenLayout *custom = aScreens[m_nPrevScreen].layout; if (custom) { previousSprite = custom->sprite; break; } if (!custom) #endif previousSprite = MENUSPRITE_MAINMENU; break; } if (m_nPrevScreen == m_nCurrScreen) CSprite2d::DrawRect(CRect(0.0f, 0.0f, SCREEN_WIDTH, SCREEN_HEIGHT), CRGBA(0, 0, 0, 255 - m_nMenuFadeAlpha)); else m_aMenuSprites[previousSprite].Draw(CRect(0.0f, 0.0f, SCREEN_WIDTH, SCREEN_HEIGHT), CRGBA(255, 255, 255, 255 - m_nMenuFadeAlpha)); } RwRenderStateSet(rwRENDERSTATEZTESTENABLE, (void*)FALSE); RwRenderStateSet(rwRENDERSTATEZWRITEENABLE, (void*)FALSE); eMenuSprites currentSprite = MENUSPRITE_MAINMENU; // actually uninitialized switch (m_nCurrScreen) { case MENUPAGE_STATS: case MENUPAGE_START_MENU: case MENUPAGE_PAUSE_MENU: currentSprite = MENUSPRITE_MAINMENU; break; case MENUPAGE_NEW_GAME: case MENUPAGE_CHOOSE_LOAD_SLOT: case MENUPAGE_CHOOSE_DELETE_SLOT: case MENUPAGE_NEW_GAME_RELOAD: case MENUPAGE_LOAD_SLOT_CONFIRM: case MENUPAGE_DELETE_SLOT_CONFIRM: case MENUPAGE_EXIT: currentSprite = MENUSPRITE_SINGLEPLAYER; break; case MENUPAGE_MULTIPLAYER_MAIN: currentSprite = MENUSPRITE_MULTIPLAYER; break; case MENUPAGE_MULTIPLAYER_MAP: case MENUPAGE_MULTIPLAYER_FIND_GAME: case MENUPAGE_SKIN_SELECT: case MENUPAGE_KEYBOARD_CONTROLS: case MENUPAGE_MOUSE_CONTROLS: currentSprite = MENUSPRITE_FINDGAME; break; case MENUPAGE_MULTIPLAYER_CONNECTION: case MENUPAGE_MULTIPLAYER_MODE: currentSprite = MENUSPRITE_CONNECTION; break; case MENUPAGE_MULTIPLAYER_CREATE: currentSprite = MENUSPRITE_HOSTGAME; break; case MENUPAGE_SKIN_SELECT_OLD: case MENUPAGE_OPTIONS: currentSprite = MENUSPRITE_PLAYERSET; break; #ifdef CUSTOM_FRONTEND_OPTIONS default: CCustomScreenLayout *custom = aScreens[m_nCurrScreen].layout; if (custom) { previousSprite = custom->sprite; } break; #endif } if (m_nMenuFadeAlpha < 255) { // Famous transparent menu bug #ifdef FIX_BUGS static float fadeAlpha = 0.0f; if (m_nMenuFadeAlpha == 0 && fadeAlpha > 1.0f) fadeAlpha = 0.0f; // +20 per every 33 ms (1000.f/30.f - original frame limiter fps) fadeAlpha += (frameTime) * 20.f / 33.f; m_nMenuFadeAlpha = fadeAlpha; #else static uint32 LastFade = 0; if(CTimer::GetTimeInMillisecondsPauseMode() - LastFade > 10){ m_nMenuFadeAlpha += 20; LastFade = CTimer::GetTimeInMillisecondsPauseMode(); } #endif if (m_nMenuFadeAlpha > 255){ m_aMenuSprites[currentSprite].Draw(CRect(0.0f, 0.0f, SCREEN_WIDTH, SCREEN_HEIGHT), CRGBA(255, 255, 255, 255)); } else { RwRenderStateSet(rwRENDERSTATEVERTEXALPHAENABLE, (void*)TRUE); m_aMenuSprites[currentSprite].Draw(CRect(0.0f, 0.0f, SCREEN_WIDTH, SCREEN_HEIGHT), CRGBA(255, 255, 255, m_nMenuFadeAlpha)); } } else { m_aMenuSprites[currentSprite].Draw(CRect(0.0f, 0.0f, SCREEN_WIDTH, SCREEN_HEIGHT), CRGBA(255, 255, 255, 255)); // TODO: what is this? waiting mouse? if(field_518 == 4){ if(m_nHoverOption == HOVEROPTION_3 || m_nHoverOption == HOVEROPTION_4 || m_nHoverOption == HOVEROPTION_5 || m_nHoverOption == HOVEROPTION_6 || m_nHoverOption == HOVEROPTION_7) field_518 = 2; else field_518 = 1; } } #ifdef RED_DELETE_BACKGROUND if (m_nCurrScreen == MENUPAGE_CHOOSE_DELETE_SLOT || m_nCurrScreen == MENUPAGE_DELETE_SLOT_CONFIRM) { CSprite2d::Draw2DPolygon(SCREEN_STRETCH_X(18.0f), MENU_Y(8.0f), SCREEN_WIDTH - SCREEN_STRETCH_X(20.0f), MENU_Y(8.0f), SCREEN_STRETCH_X(12.0f), MENU_Y(11.0f), SCREEN_WIDTH - SCREEN_STRETCH_X(14.0f), MENU_Y(11.0f), CRGBA(150, 0, 0, 140)); CSprite2d::Draw2DPolygon(SCREEN_STRETCH_X(12.0f), MENU_Y(11.0f), SCREEN_WIDTH - SCREEN_STRETCH_X(14.0f), MENU_Y(11.0f), SCREEN_STRETCH_X(10.0f), MENU_Y(16.0f), SCREEN_WIDTH - SCREEN_STRETCH_X(12.0f), MENU_Y(16.0f), CRGBA(150, 0, 0, 140)); CSprite2d::Draw2DPolygon(SCREEN_STRETCH_X(10.0f), MENU_Y(16.0f), SCREEN_WIDTH - SCREEN_STRETCH_X(12.0f), MENU_Y(16.0f), SCREEN_STRETCH_X(10.0f), SCREEN_SCALE_Y(431.0f), SCREEN_WIDTH - SCREEN_STRETCH_X(12.0f), SCREEN_SCALE_Y(431.0f), CRGBA(150, 0, 0, 140)); CSprite2d::Draw2DPolygon(SCREEN_STRETCH_X(10.0f), SCREEN_SCALE_Y(431.0f), SCREEN_WIDTH - SCREEN_STRETCH_X(12.0f), SCREEN_SCALE_Y(431.0f), SCREEN_STRETCH_X(12.0f), SCREEN_SCALE_Y(435.0f), SCREEN_WIDTH - SCREEN_STRETCH_X(14.0f), SCREEN_SCALE_Y(435.0f), CRGBA(150, 0, 0, 140)); CSprite2d::Draw2DPolygon(SCREEN_STRETCH_X(12.0f), SCREEN_SCALE_Y(435.0f), SCREEN_WIDTH - SCREEN_STRETCH_X(14.0f), SCREEN_SCALE_Y(435.0f), SCREEN_STRETCH_X(18.0f), SCREEN_SCALE_Y(438.0f), SCREEN_WIDTH - SCREEN_STRETCH_X(20.0f), SCREEN_SCALE_Y(438.0f), CRGBA(150, 0, 0, 140)); // yellow bar CSprite2d::DrawRect(CRect(MENU_X(13.0f), SCREEN_STRETCH_FROM_BOTTOM(96.0f), SCREEN_STRETCH_FROM_RIGHT(11.0f), SCREEN_STRETCH_FROM_BOTTOM(59.0f)), CRGBA(235, 170, 50, 255)); } #endif // GTA LOGO RwRenderStateSet(rwRENDERSTATESRCBLEND, (void*)rwBLENDSRCALPHA); RwRenderStateSet(rwRENDERSTATEDESTBLEND, (void*)rwBLENDINVSRCALPHA); if (m_nCurrScreen == MENUPAGE_START_MENU || m_nCurrScreen == MENUPAGE_PAUSE_MENU) { if (CGame::frenchGame || CGame::germanGame || !CGame::nastyGame) m_aMenuSprites[MENUSPRITE_GTA3LOGO].Draw(CRect(MENU_X_LEFT_ALIGNED(205.0f), MENU_Y(70.0f), MENU_X_LEFT_ALIGNED(435.0f), MENU_Y(180.0f)), CRGBA(255, 255, 255, FadeIn(255))); else m_aMenuSprites[MENUSPRITE_GTALOGO].Draw(CRect(MENU_X_LEFT_ALIGNED(225.0f), MENU_Y(40.0f), MENU_X_LEFT_ALIGNED(415.0f), MENU_Y(210.0f)), CRGBA(255, 255, 255, FadeIn(255))); } RwRenderStateSet(rwRENDERSTATETEXTUREFILTER, (void*)rwFILTERNEAREST); RwRenderStateSet(rwRENDERSTATETEXTUREADDRESS, (void*)rwTEXTUREADDRESSCLAMP); RwRenderStateSet(rwRENDERSTATEVERTEXALPHAENABLE, (void*)FALSE); switch (m_nCurrScreen) { case MENUPAGE_SKIN_SELECT: DrawPlayerSetupScreen(); break; case MENUPAGE_KEYBOARD_CONTROLS: DrawControllerSetupScreen(); break; default: Draw(); break; } CFont::DrawFonts(); // Draw mouse RwRenderStateSet(rwRENDERSTATETEXTUREFILTER, (void*)rwFILTERLINEAR); RwRenderStateSet(rwRENDERSTATETEXTUREADDRESS, (void*)rwTEXTUREADDRESSCLAMP); if (m_bShowMouse) { RwRenderStateSet(rwRENDERSTATESRCBLEND, (void*)rwBLENDSRCALPHA); RwRenderStateSet(rwRENDERSTATEDESTBLEND, (void*)rwBLENDINVSRCALPHA); RwRenderStateSet(rwRENDERSTATEVERTEXALPHAENABLE, (void*)TRUE); CRect mouse(0.0f, 0.0f, MENU_X(75.0f), MENU_Y(75.0f)); CRect shad(MENU_X(10.0f), MENU_Y(3.0f), MENU_X(85.0f), MENU_Y(78.0f)); mouse.Translate(m_nMousePosX, m_nMousePosY); shad.Translate(m_nMousePosX, m_nMousePosY); if(field_518 == 4){ m_aMenuSprites[MENUSPRITE_MOUSET].Draw(shad, CRGBA(100, 100, 100, 50)); RwRenderStateSet(rwRENDERSTATEVERTEXALPHAENABLE, (void*)FALSE); m_aMenuSprites[MENUSPRITE_MOUSET].Draw(mouse, CRGBA(255, 255, 255, 255)); }else{ m_aMenuSprites[MENUSPRITE_MOUSE].Draw(shad, CRGBA(100, 100, 100, 50)); RwRenderStateSet(rwRENDERSTATEVERTEXALPHAENABLE, (void*)FALSE); m_aMenuSprites[MENUSPRITE_MOUSE].Draw(mouse, CRGBA(255, 255, 255, 255)); } } } #endif void CMenuManager::DrawPlayerSetupScreen() { RESET_FONT_FOR_NEW_PAGE SET_FONT_FOR_MENU_HEADER CFont::PrintString(PAGE_NAME_X(MENUHEADER_POS_X), SCREEN_SCALE_FROM_BOTTOM(MENUHEADER_POS_Y), TheText.Get("FET_PS")); // lstrcpy's changed with strcpy if (!m_bSkinsEnumerated) { OutputDebugString("Enumerating skin filenames from skins..."); m_pSkinListHead.nextSkin = nil; m_pSelectedSkin = &m_pSkinListHead; m_pSelectedSkin->nextSkin = new tSkinInfo; m_pSelectedSkin = m_pSelectedSkin->nextSkin; m_pSelectedSkin->skinId = 0; strcpy(m_pSelectedSkin->skinNameOriginal, DEFAULT_SKIN_NAME); strcpy(m_pSelectedSkin->skinNameDisplayed, UnicodeToAscii(TheText.Get("FET_DSN"))); int nextSkinId = 1; m_pSelectedSkin->nextSkin = nil; WIN32_FIND_DATA FindFileData; SYSTEMTIME SystemTime; HANDLE handle = FindFirstFile("skins\\*.bmp", &FindFileData); for (int i = 1; handle != INVALID_HANDLE_VALUE && i; i = FindNextFile(handle, &FindFileData)) { if (strcmp(FindFileData.cFileName, DEFAULT_SKIN_NAME) != 0) { m_pSelectedSkin->nextSkin = new tSkinInfo; m_pSelectedSkin = m_pSelectedSkin->nextSkin; m_pSelectedSkin->skinId = nextSkinId; strcpy(m_pSelectedSkin->skinNameOriginal, FindFileData.cFileName); strcpy(m_pSelectedSkin->skinNameDisplayed, FindFileData.cFileName); FileTimeToSystemTime(&FindFileData.ftLastWriteTime, &SystemTime); GetDateFormat(LOCALE_USER_DEFAULT, DATE_SHORTDATE, &SystemTime, 0, m_pSelectedSkin->date, 255); ++nextSkinId; m_pSelectedSkin->nextSkin = nil; } } FindClose(handle); m_nSkinsTotal = nextSkinId; char nameTemp[256]; for (m_pSelectedSkin = m_pSkinListHead.nextSkin; m_pSelectedSkin; m_pSelectedSkin = m_pSelectedSkin->nextSkin) { // Drop extension int oldLength = (int)strlen(m_pSelectedSkin->skinNameDisplayed); m_pSelectedSkin->skinNameDisplayed[oldLength - 4] = '\0'; m_pSelectedSkin->skinNameOriginal[oldLength - 4] = '\0'; // Fill to 40 bytes-39 chars, idk why. This is done in sepearate function in game. strncpy(nameTemp, m_pSelectedSkin->skinNameDisplayed, 39); // game doesn't do that, but in our day strncpy to same string is forbidden strncpy(m_pSelectedSkin->skinNameDisplayed, nameTemp, 39); if (oldLength - 4 > 39) m_pSelectedSkin->skinNameDisplayed[39] = '\0'; // Make string lowercase, except first letter strlwr(m_pSelectedSkin->skinNameDisplayed); strncpy(nameTemp, m_pSelectedSkin->skinNameDisplayed, 1); strupr(nameTemp); strncpy(m_pSelectedSkin->skinNameDisplayed, nameTemp, 1); // Change some chars #ifdef FIX_BUGS for (int k = 0; m_pSelectedSkin->skinNameDisplayed[k] != '\0'; ++k) { #else for (int k = 0; m_pSelectedSkin->skinNameOriginal[k] != '\0'; ++k) { #endif if (!strncmp(&m_pSelectedSkin->skinNameDisplayed[k], "_", 1)) strncpy(&m_pSelectedSkin->skinNameDisplayed[k], " ", 1); if (!strncmp(&m_pSelectedSkin->skinNameDisplayed[k], "@", 1)) strncpy(&m_pSelectedSkin->skinNameDisplayed[k], " ", 1); if (!strncmp(&m_pSelectedSkin->skinNameDisplayed[k], "{", 1)) strncpy(&m_pSelectedSkin->skinNameDisplayed[k], "(", 1); if (!strncmp(&m_pSelectedSkin->skinNameDisplayed[k], "}", 1)) strncpy(&m_pSelectedSkin->skinNameDisplayed[k], ")", 1); if (!strncmp(&m_pSelectedSkin->skinNameDisplayed[k], "£", 1)) strncpy(&m_pSelectedSkin->skinNameDisplayed[k], "$", 1); } // Make letters after whitespace uppercase for (int l = 0; m_pSelectedSkin->skinNameDisplayed[l] != '\0'; ++l) { if (!strncmp(&m_pSelectedSkin->skinNameDisplayed[l], " ", 1)) { if (m_pSelectedSkin->skinNameDisplayed[l + 1]) { strncpy(nameTemp, &m_pSelectedSkin->skinNameDisplayed[l + 1], 1); strupr(nameTemp); strncpy(&m_pSelectedSkin->skinNameDisplayed[l + 1], nameTemp, 1); } } } } OutputDebugString("Finished enumerating skin files."); m_bSkinsEnumerated = true; } CSprite2d::DrawRect(CRect(MENU_X_LEFT_ALIGNED(PLAYERSETUP_LIST_LEFT), MENU_Y(PLAYERSETUP_LIST_TOP), MENU_X_RIGHT_ALIGNED(PLAYERSETUP_LIST_RIGHT), SCREEN_SCALE_FROM_BOTTOM(PLAYERSETUP_LIST_BOTTOM)), CRGBA(LIST_BACKGROUND_COLOR.r, LIST_BACKGROUND_COLOR.g, LIST_BACKGROUND_COLOR.b, FadeIn(LIST_BACKGROUND_COLOR.a))); // Header (Skin - Date) if (m_nCurrExLayer == HOVEROPTION_LIST) { CFont::SetColor(CRGBA(SELECTEDMENUOPTION_COLOR.r, SELECTEDMENUOPTION_COLOR.g, SELECTEDMENUOPTION_COLOR.b, FadeIn(255))); } else { CFont::SetColor(CRGBA(MENUOPTION_COLOR.r, MENUOPTION_COLOR.g, MENUOPTION_COLOR.b, FadeIn(255))); } CFont::SetFontStyle(FONT_LOCALE(FONT_HEADING)); CFont::SetScale(MENU_X(MENUACTION_SCALE_MULT), MENU_Y(MENUACTION_SCALE_MULT)); CFont::SetRightJustifyOn(); CFont::PrintString(MENU_X_RIGHT_ALIGNED(PLAYERSETUP_DATE_COLUMN_RIGHT), MENU_Y(PLAYERSETUP_LIST_TOP), TheText.Get("FES_DAT")); switch (m_PrefsLanguage) { case LANGUAGE_FRENCH: case LANGUAGE_SPANISH: CFont::SetScale(MENU_X(0.6f), MENU_Y(MENUACTION_SCALE_MULT)); break; default: CFont::SetScale(MENU_X(MENUACTION_SCALE_MULT), MENU_Y(MENUACTION_SCALE_MULT)); break; } CFont::SetRightJustifyOff(); CFont::PrintString(MENU_X_LEFT_ALIGNED(PLAYERSETUP_SKIN_COLUMN_LEFT), MENU_Y(PLAYERSETUP_LIST_TOP), TheText.Get("FES_SKN")); // Skin list SET_FONT_FOR_LIST_ITEM if (m_nSkinsTotal > 0) { for (m_pSelectedSkin = m_pSkinListHead.nextSkin; m_pSelectedSkin->skinId != m_nFirstVisibleRowOnList; m_pSelectedSkin = m_pSelectedSkin->nextSkin); int rowTextY = PLAYERSETUP_LIST_BODY_TOP - 1; int orderInVisibles = 0; int rowEndY = PLAYERSETUP_LIST_BODY_TOP + PLAYERSETUP_ROW_HEIGHT + 1; int rowStartY = PLAYERSETUP_LIST_BODY_TOP; for (int rowIdx = m_nFirstVisibleRowOnList; rowIdx < m_nFirstVisibleRowOnList + MAX_VISIBLE_LIST_ROW && m_pSelectedSkin; ) { if (m_nMousePosX > MENU_X_LEFT_ALIGNED(PLAYERSETUP_LIST_LEFT) && m_nMousePosX < MENU_X_RIGHT_ALIGNED(PLAYERSETUP_LIST_RIGHT)) { if (m_nMousePosY > MENU_Y(rowStartY) && m_nMousePosY < MENU_Y(rowEndY)) { m_nOptionMouseHovering = rowIdx; if (m_nMouseOldPosX != m_nMousePosX || m_nMouseOldPosY != m_nMousePosY) { m_nCurrExLayer = HOVEROPTION_LIST; } if (m_nHoverOption == HOVEROPTION_SKIN) { if (rowIdx == m_nSelectedListRow) { m_nHoverOption = HOVEROPTION_NOT_HOVERING; if (m_nSkinsTotal > 0) { DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_SETTING_CHANGE, 0); strcpy(m_PrefsSkinFile, m_aSkinName); CWorld::Players[0].SetPlayerSkin(m_PrefsSkinFile); SaveSettings(); } } else { DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_NAVIGATION, 0); m_nCurrExLayer = HOVEROPTION_LIST; m_nSelectedListRow = rowIdx; m_nHoverOption = HOVEROPTION_NOT_HOVERING; } } } } // Preview skin/change color of row when we focused on another row. if (orderInVisibles == m_nSelectedListRow - m_nFirstVisibleRowOnList) { CFont::SetColor(CRGBA(255, 255, 255, FadeIn(255))); static int lastSelectedSkin = -1; if (m_nSelectedListRow != lastSelectedSkin) { strcpy(m_aSkinName, m_pSelectedSkin->skinNameOriginal); CWorld::Players[0].SetPlayerSkin(m_aSkinName); } lastSelectedSkin = m_nSelectedListRow; } else if (!strcmp(m_PrefsSkinFile, m_pSelectedSkin->skinNameOriginal)) { CFont::SetColor(CRGBA(255, 255, 155, FadeIn(255))); } else { CFont::SetColor(CRGBA(LIST_OPTION_COLOR.r, LIST_OPTION_COLOR.g, LIST_OPTION_COLOR.b, FadeIn(LIST_OPTION_COLOR.a))); } wchar unicodeTemp[80]; AsciiToUnicode(m_pSelectedSkin->skinNameDisplayed, unicodeTemp); CFont::SetRightJustifyOff(); CFont::PrintString(MENU_X_LEFT_ALIGNED(PLAYERSETUP_SKIN_COLUMN_LEFT), MENU_Y(rowTextY), unicodeTemp); // If not "Default skin" option if (rowIdx != 0) { char dateTemp[32]; sprintf(dateTemp, "%s", m_pSelectedSkin->date); AsciiToUnicode(dateTemp, unicodeTemp); CFont::SetRightJustifyOn(); CFont::PrintString(MENU_X_RIGHT_ALIGNED(PLAYERSETUP_DATE_COLUMN_RIGHT), MENU_Y(rowTextY), unicodeTemp); } ++orderInVisibles; rowEndY += PLAYERSETUP_ROW_HEIGHT; rowStartY += PLAYERSETUP_ROW_HEIGHT; rowTextY += PLAYERSETUP_ROW_HEIGHT; ++rowIdx; m_pSelectedSkin = m_pSelectedSkin->nextSkin; } // Scrollbar background CSprite2d::DrawRect(CRect(MENU_X_RIGHT_ALIGNED(PLAYERSETUP_LIST_RIGHT - 2), MENU_Y(PLAYERSETUP_LIST_TOP), MENU_X_RIGHT_ALIGNED(PLAYERSETUP_LIST_RIGHT - 2 - PLAYERSETUP_SCROLLBAR_WIDTH), SCREEN_SCALE_FROM_BOTTOM(PLAYERSETUP_LIST_BOTTOM)), CRGBA(100, 100, 66, FadeIn(205))); float scrollbarHeight = SCROLLBAR_MAX_HEIGHT / (m_nSkinsTotal / (float) MAX_VISIBLE_LIST_ROW); float scrollbarBottom, scrollbarTop; if (m_nSkinsTotal <= MAX_VISIBLE_LIST_ROW) { scrollbarBottom = SCREEN_SCALE_FROM_BOTTOM(PLAYERSETUP_LIST_BOTTOM + PLAYERSETUP_SCROLLBUTTON_HEIGHT + 4.0f); scrollbarTop = MENU_Y(PLAYERSETUP_LIST_BODY_TOP); // Scrollbar shadow CSprite2d::DrawRect(CRect(MENU_X_RIGHT_ALIGNED(PLAYERSETUP_LIST_RIGHT - 4), scrollbarTop, MENU_X_RIGHT_ALIGNED(PLAYERSETUP_LIST_RIGHT - 1 - PLAYERSETUP_SCROLLBAR_WIDTH), scrollbarBottom + MENU_Y(1.0f)), CRGBA(50, 50, 50, FadeIn(255))); } else { #ifdef FIX_BUGS scrollbarBottom = MENU_Y(PLAYERSETUP_LIST_BODY_TOP - 8 + m_nScrollbarTopMargin + scrollbarHeight); scrollbarTop = MENU_Y(PLAYERSETUP_LIST_BODY_TOP + m_nScrollbarTopMargin); #else scrollbarBottom = MENU_Y(PLAYERSETUP_LIST_BODY_TOP - 4 + m_nScrollbarTopMargin + scrollbarHeight - SCROLLBAR_MAX_HEIGHT / m_nSkinsTotal); scrollbarTop = MENU_Y(SCROLLBAR_MAX_HEIGHT / m_nSkinsTotal + PLAYERSETUP_LIST_BODY_TOP - 3 + m_nScrollbarTopMargin); #endif // Scrollbar shadow CSprite2d::DrawRect(CRect(MENU_X_RIGHT_ALIGNED(PLAYERSETUP_LIST_RIGHT - 4), scrollbarTop, MENU_X_RIGHT_ALIGNED(PLAYERSETUP_LIST_RIGHT - 1 - PLAYERSETUP_SCROLLBAR_WIDTH), scrollbarBottom + MENU_Y(1.0f)), CRGBA(50, 50, 50, FadeIn(255))); } // Scrollbar CSprite2d::DrawRect(CRect(MENU_X_RIGHT_ALIGNED(PLAYERSETUP_LIST_RIGHT - 4), scrollbarTop, MENU_X_RIGHT_ALIGNED(PLAYERSETUP_LIST_RIGHT - PLAYERSETUP_SCROLLBAR_WIDTH), scrollbarBottom), CRGBA(SCROLLBAR_COLOR.r, SCROLLBAR_COLOR.g, SCROLLBAR_COLOR.b, FadeIn(255))); // FIX: Scroll button dimensions are buggy, because: // 1 - stretches the original image // 2 - leaves gap between button and scrollbar if (m_nHoverOption == HOVEROPTION_CLICKED_SCROLL_UP) { #ifdef FIX_BUGS m_aMenuSprites[MENUSPRITE_UPON].Draw(CRect(MENU_X_RIGHT_ALIGNED(PLAYERSETUP_LIST_RIGHT - 2), MENU_Y(PLAYERSETUP_LIST_TOP), MENU_X_RIGHT_ALIGNED(PLAYERSETUP_LIST_RIGHT - 2 - PLAYERSETUP_SCROLLBUTTON_TXD_DIMENSION), MENU_Y(PLAYERSETUP_LIST_TOP + PLAYERSETUP_SCROLLBUTTON_TXD_DIMENSION)), CRGBA(255, 255, 255, FadeIn(255))); #else m_aMenuSprites[MENUSPRITE_UPON].Draw(CRect(MENU_X_RIGHT_ALIGNED(PLAYERSETUP_LIST_RIGHT - 2), MENU_Y(PLAYERSETUP_LIST_TOP), MENU_X_RIGHT_ALIGNED(-20.0f), MENU_Y(PLAYERSETUP_LIST_TOP + 58)), CRGBA(255, 255, 255, FadeIn(255))); #endif } else { #ifdef FIX_BUGS m_aMenuSprites[MENUSPRITE_UPOFF].Draw(CRect(MENU_X_RIGHT_ALIGNED(PLAYERSETUP_LIST_RIGHT - 3), MENU_Y(PLAYERSETUP_LIST_TOP), MENU_X_RIGHT_ALIGNED(PLAYERSETUP_LIST_RIGHT - 3 - PLAYERSETUP_SCROLLBUTTON_TXD_DIMENSION), MENU_Y(PLAYERSETUP_LIST_TOP + PLAYERSETUP_SCROLLBUTTON_TXD_DIMENSION)), CRGBA(255, 255, 255, FadeIn(255))); #else m_aMenuSprites[MENUSPRITE_UPOFF].Draw(CRect(MENU_X_RIGHT_ALIGNED(PLAYERSETUP_LIST_RIGHT - 3), MENU_Y(PLAYERSETUP_LIST_TOP), MENU_X_RIGHT_ALIGNED(-21.0f), MENU_Y(PLAYERSETUP_LIST_TOP + 58)), CRGBA(255, 255, 255, FadeIn(255))); #endif } if (m_nHoverOption == HOVEROPTION_CLICKED_SCROLL_DOWN) { #ifdef FIX_BUGS m_aMenuSprites[MENUSPRITE_DOWNON].Draw(CRect(MENU_X_RIGHT_ALIGNED(PLAYERSETUP_LIST_RIGHT - 2), SCREEN_SCALE_FROM_BOTTOM(PLAYERSETUP_LIST_BOTTOM + PLAYERSETUP_SCROLLBUTTON_HEIGHT + 1), MENU_X_RIGHT_ALIGNED(PLAYERSETUP_LIST_RIGHT - 2 - PLAYERSETUP_SCROLLBUTTON_TXD_DIMENSION), SCREEN_SCALE_FROM_BOTTOM(PLAYERSETUP_LIST_BOTTOM + PLAYERSETUP_SCROLLBUTTON_HEIGHT + 1 - PLAYERSETUP_SCROLLBUTTON_TXD_DIMENSION)), CRGBA(255, 255, 255, FadeIn(255))); #else m_aMenuSprites[MENUSPRITE_DOWNON].Draw(CRect(MENU_X_RIGHT_ALIGNED(PLAYERSETUP_LIST_RIGHT - 2), SCREEN_SCALE_FROM_BOTTOM(141.0f), MENU_X_RIGHT_ALIGNED(-20.0f), SCREEN_SCALE_FROM_BOTTOM(83.0f)), CRGBA(255, 255, 255, FadeIn(255))); #endif } else { #ifdef FIX_BUGS m_aMenuSprites[MENUSPRITE_DOWNOFF].Draw(CRect(MENU_X_RIGHT_ALIGNED(PLAYERSETUP_LIST_RIGHT - 3), SCREEN_SCALE_FROM_BOTTOM(PLAYERSETUP_LIST_BOTTOM + PLAYERSETUP_SCROLLBUTTON_HEIGHT + 1), MENU_X_RIGHT_ALIGNED(PLAYERSETUP_LIST_RIGHT - 3 - PLAYERSETUP_SCROLLBUTTON_TXD_DIMENSION), SCREEN_SCALE_FROM_BOTTOM(PLAYERSETUP_LIST_BOTTOM + PLAYERSETUP_SCROLLBUTTON_HEIGHT + 1 - PLAYERSETUP_SCROLLBUTTON_TXD_DIMENSION)), CRGBA(255, 255, 255, FadeIn(255))); #else m_aMenuSprites[MENUSPRITE_DOWNOFF].Draw(CRect(MENU_X_RIGHT_ALIGNED(PLAYERSETUP_LIST_RIGHT - 3), SCREEN_SCALE_FROM_BOTTOM(141.0f), MENU_X_RIGHT_ALIGNED(-21.0f), SCREEN_SCALE_FROM_BOTTOM(83.0f)), CRGBA(255, 255, 255, FadeIn(255))); #endif } CPlayerSkin::RenderFrontendSkinEdit(); // Big apply button if (strcmp(m_aSkinName, m_PrefsSkinFile) != 0) { CFont::SetFontStyle(FONT_LOCALE(FONT_HEADING)); switch (m_PrefsLanguage) { case LANGUAGE_FRENCH: CFont::SetScale(MENU_X(1.1f), MENU_Y(1.9f)); break; case LANGUAGE_GERMAN: CFont::SetScale(MENU_X(0.85f), MENU_Y(1.9f)); break; case LANGUAGE_ITALIAN: case LANGUAGE_SPANISH: CFont::SetScale(MENU_X(1.4f), MENU_Y(1.9f)); break; default: CFont::SetScale(MENU_X(1.9f), MENU_Y(1.9f)); break; } CFont::SetColor(CRGBA(SELECTEDMENUOPTION_COLOR.r, SELECTEDMENUOPTION_COLOR.g, SELECTEDMENUOPTION_COLOR.b, FadeIn(120))); CFont::SetRightJustifyOff(); CFont::PrintString(MENU_X_LEFT_ALIGNED(20.0f), MENU_Y(220.0f), TheText.Get("FET_APL")); } CFont::SetFontStyle(FONT_LOCALE(FONT_HEADING)); CFont::SetScale(MENU_X(SMALLTEXT_X_SCALE), MENU_Y(SMALLTEXT_Y_SCALE)); if ((m_nMousePosX > MENU_X_RIGHT_ALIGNED(PLAYERSETUP_LIST_RIGHT - 1) - CFont::GetStringWidth(TheText.Get("FEDS_TB"), true) && m_nMousePosX < MENU_X_RIGHT_ALIGNED(PLAYERSETUP_LIST_RIGHT - 1) && m_nMousePosY > SCREEN_SCALE_FROM_BOTTOM(PLAYERSETUP_LIST_BOTTOM - 3) && m_nMousePosY < SCREEN_SCALE_FROM_BOTTOM(PLAYERSETUP_LIST_BOTTOM - 26)) || m_nCurrExLayer == HOVEROPTION_BACK) { if (m_nHoverOption != HOVEROPTION_BACK) DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_NAVIGATION, 0); m_nHoverOption = HOVEROPTION_BACK; } else if ((strcmp(m_aSkinName, m_PrefsSkinFile) != 0 && m_nMousePosX > MENU_X_LEFT_ALIGNED(PLAYERSETUP_LIST_LEFT) && m_nMousePosX < MENU_X_LEFT_ALIGNED(PLAYERSETUP_LIST_LEFT) + CFont::GetStringWidth(TheText.Get("FES_SET"), true) && m_nMousePosY > SCREEN_SCALE_FROM_BOTTOM(PLAYERSETUP_LIST_BOTTOM - 3) && m_nMousePosY < SCREEN_SCALE_FROM_BOTTOM(PLAYERSETUP_LIST_BOTTOM - 26)) || m_nCurrExLayer == HOVEROPTION_USESKIN) { if (m_nHoverOption != HOVEROPTION_USESKIN) DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_NAVIGATION, 0); m_nHoverOption = HOVEROPTION_USESKIN; } else if (m_nMousePosX > MENU_X_RIGHT_ALIGNED(PLAYERSETUP_LIST_RIGHT - 2) && m_nMousePosX < MENU_X_RIGHT_ALIGNED(PLAYERSETUP_LIST_RIGHT - PLAYERSETUP_SCROLLBAR_WIDTH - 2) && m_nMousePosY > MENU_Y(PLAYERSETUP_LIST_TOP) && m_nMousePosY < MENU_Y(PLAYERSETUP_LIST_BODY_TOP - 3)) { if (m_nHoverOption != HOVEROPTION_CLICKED_SCROLL_UP && m_nHoverOption != HOVEROPTION_CLICKED_SCROLL_DOWN) m_nHoverOption = HOVEROPTION_OVER_SCROLL_UP; } else if (m_nMousePosX > MENU_X_RIGHT_ALIGNED(PLAYERSETUP_LIST_RIGHT - 2) && m_nMousePosX < MENU_X_RIGHT_ALIGNED(PLAYERSETUP_LIST_RIGHT - PLAYERSETUP_SCROLLBAR_WIDTH - 2) && m_nMousePosY > SCREEN_SCALE_FROM_BOTTOM(PLAYERSETUP_LIST_BOTTOM + PLAYERSETUP_SCROLLBUTTON_HEIGHT + 1) && m_nMousePosY < SCREEN_SCALE_FROM_BOTTOM(PLAYERSETUP_LIST_BOTTOM)) { if (m_nHoverOption != HOVEROPTION_CLICKED_SCROLL_UP && m_nHoverOption != HOVEROPTION_CLICKED_SCROLL_DOWN) m_nHoverOption = HOVEROPTION_OVER_SCROLL_DOWN; } else if (m_nMousePosX > MENU_X_RIGHT_ALIGNED(PLAYERSETUP_LIST_RIGHT - 2) && m_nMousePosX < MENU_X_RIGHT_ALIGNED(PLAYERSETUP_LIST_RIGHT - PLAYERSETUP_SCROLLBAR_WIDTH - 2) && m_nMousePosY > MENU_Y(PLAYERSETUP_LIST_BODY_TOP - 3) #ifdef FIX_BUGS && m_nMousePosY < MENU_Y(PLAYERSETUP_LIST_BODY_TOP + m_nScrollbarTopMargin)) { #else && m_nMousePosY < MENU_Y(SCROLLBAR_MAX_HEIGHT / m_nTotalListRow + PLAYERSETUP_LIST_BODY_TOP - 3 + m_nScrollbarTopMargin)) { #endif m_nHoverOption = HOVEROPTION_PAGEUP; } else if (m_nMousePosX > MENU_X_RIGHT_ALIGNED(PLAYERSETUP_LIST_RIGHT - 2) && m_nMousePosX < MENU_X_RIGHT_ALIGNED(PLAYERSETUP_LIST_RIGHT - PLAYERSETUP_SCROLLBAR_WIDTH - 2) #ifdef FIX_BUGS && m_nMousePosY > MENU_Y(PLAYERSETUP_LIST_BODY_TOP - 8 + m_nScrollbarTopMargin + scrollbarHeight) #else && m_nMousePosY > MENU_Y(PLAYERSETUP_LIST_BODY_TOP - 3 + m_nScrollbarTopMargin + scrollbarHeight - SCROLLBAR_MAX_HEIGHT / m_nTotalListRow) #endif && m_nMousePosY < SCREEN_SCALE_FROM_BOTTOM(PLAYERSETUP_LIST_BOTTOM + PLAYERSETUP_SCROLLBUTTON_HEIGHT + 1)) { m_nHoverOption = HOVEROPTION_PAGEDOWN; } else if (m_nMousePosX > MENU_X_RIGHT_ALIGNED(PLAYERSETUP_LIST_RIGHT - 4) && m_nMousePosX < MENU_X_RIGHT_ALIGNED(PLAYERSETUP_LIST_RIGHT - PLAYERSETUP_SCROLLBAR_WIDTH) #ifdef FIX_BUGS && m_nMousePosY > MENU_Y(PLAYERSETUP_LIST_BODY_TOP + m_nScrollbarTopMargin) && m_nMousePosY < MENU_Y(PLAYERSETUP_LIST_BODY_TOP - 8 + m_nScrollbarTopMargin + scrollbarHeight)) { #else && m_nMousePosY > MENU_Y(SCROLLBAR_MAX_HEIGHT / m_nTotalListRow + PLAYERSETUP_LIST_BODY_TOP - 3 + m_nScrollbarTopMargin) && m_nMousePosY < MENU_Y(PLAYERSETUP_LIST_BODY_TOP - 3 + m_nScrollbarTopMargin + scrollbarHeight - SCROLLBAR_MAX_HEIGHT / m_nTotalListRow)) { #endif m_nHoverOption = HOVEROPTION_HOLDING_SCROLLBAR; } else if (m_nMousePosX > MENU_X_LEFT_ALIGNED(PLAYERSETUP_LIST_LEFT) && m_nMousePosX < MENU_X_RIGHT_ALIGNED(PLAYERSETUP_LIST_RIGHT) && m_nMousePosY > MENU_Y(PLAYERSETUP_LIST_BODY_TOP + 1) && m_nMousePosY < SCREEN_SCALE_FROM_BOTTOM(PLAYERSETUP_LIST_BOTTOM)) { m_nHoverOption = HOVEROPTION_LIST; } else { m_nHoverOption = HOVEROPTION_NOT_HOVERING; } } CFont::SetFontStyle(FONT_LOCALE(FONT_HEADING)); CFont::SetScale(MENU_X(SMALLTEXT_X_SCALE), MENU_Y(SMALLTEXT_Y_SCALE)); CFont::SetRightJustifyOn(); CFont::SetColor(CRGBA(0, 0, 0, FadeIn(90))); // Back button for (int i = 0; i < 2; i++) { CFont::PrintString(MENU_X_RIGHT_ALIGNED(PLAYERSETUP_LIST_RIGHT - 3 - i), SCREEN_SCALE_FROM_BOTTOM(PLAYERSETUP_LIST_BOTTOM - 5 - i), TheText.Get("FEDS_TB")); if (m_nHoverOption == HOVEROPTION_BACK) { CFont::SetColor(CRGBA(SELECTEDMENUOPTION_COLOR.r, SELECTEDMENUOPTION_COLOR.g, SELECTEDMENUOPTION_COLOR.b, FadeIn(255))); } else { CFont::SetColor(CRGBA(MENUOPTION_COLOR.r, MENUOPTION_COLOR.g, MENUOPTION_COLOR.b, FadeIn(255))); } } CFont::SetRightJustifyOff(); CFont::SetColor(CRGBA(0, 0, 0, FadeIn(90))); // Use skin button for (int i = 0; i < 2; i++) { CFont::PrintString(MENU_X_LEFT_ALIGNED(i + PLAYERSETUP_LIST_LEFT), SCREEN_SCALE_FROM_BOTTOM(PLAYERSETUP_LIST_BOTTOM - 5 - i), TheText.Get("FES_SET")); if (!strcmp(m_aSkinName, m_PrefsSkinFile)) { CFont::SetColor(CRGBA(DARKMENUOPTION_COLOR.r, DARKMENUOPTION_COLOR.g, DARKMENUOPTION_COLOR.b, FadeIn(255))); } else if (m_nHoverOption == HOVEROPTION_USESKIN) { CFont::SetColor(CRGBA(SELECTEDMENUOPTION_COLOR.r, SELECTEDMENUOPTION_COLOR.g, SELECTEDMENUOPTION_COLOR.b, FadeIn(255))); } else { CFont::SetColor(CRGBA(MENUOPTION_COLOR.r, MENUOPTION_COLOR.g, MENUOPTION_COLOR.b, FadeIn(255))); } } } int CMenuManager::FadeIn(int alpha) { if (m_nCurrScreen == MENUPAGE_LOADING_IN_PROGRESS || m_nCurrScreen == MENUPAGE_SAVING_IN_PROGRESS || m_nCurrScreen == MENUPAGE_DELETING) return alpha; return Min(m_nMenuFadeAlpha, alpha); } void CMenuManager::FilterOutColorMarkersFromString(wchar *str, CRGBA &newColor) { int newIdx = 0; wchar copy[256], *c; UnicodeStrcpy(copy, str); for (c = copy; *c != '\0'; c++) { if (*c == '~') { c++; switch (*c) { case 'b': newColor = CRGBA(40, 40, 255, 255); break; case 'g': newColor = CRGBA(40, 235, 40, 255); break; // There is no case for "h", is that a mistake? case 'l': newColor = CRGBA(0, 0, 0, 255); break; case 'p': newColor = CRGBA(255, 0, 255, 255); break; case 'r': newColor = CRGBA(255, 0, 0, 255); break; case 'w': newColor = CRGBA(255, 255, 255, 255); break; case 'y': newColor = CRGBA(255, 255, 0, 255); break; } while (*c != '~') c++; } else { str[newIdx++] = *c; } } str[newIdx] = '\0'; } int CMenuManager::GetStartOptionsCntrlConfigScreens() { int number = 0; switch (m_nCurrScreen) { case MENUPAGE_CONTROLLER_PC_OLD3: number = 34; break; case MENUPAGE_CONTROLLER_DEBUG: number = 35; break; case MENUPAGE_KEYBOARD_CONTROLS: number = 0; break; default: break; } return number; } void CMenuManager::InitialiseChangedLanguageSettings() { if (m_bFrontEnd_ReloadObrTxtGxt) { m_bFrontEnd_ReloadObrTxtGxt = false; CTimer::Stop(); TheText.Unload(); TheText.Load(); CTimer::Update(); CGame::frenchGame = false; CGame::germanGame = false; #ifdef MORE_LANGUAGES CGame::russianGame = false; CGame::japaneseGame = false; switch (m_PrefsLanguage) { case LANGUAGE_POLISH: CFont::ReloadFonts(FONT_LANGSET_POLISH); break; case LANGUAGE_RUSSIAN: CFont::ReloadFonts(FONT_LANGSET_RUSSIAN); break; case LANGUAGE_JAPANESE: CFont::ReloadFonts(FONT_LANGSET_JAPANESE); break; default: CFont::ReloadFonts(FONT_LANGSET_EFIGS); break; } #endif switch (m_PrefsLanguage) { case LANGUAGE_FRENCH: CGame::frenchGame = true; break; case LANGUAGE_GERMAN: CGame::germanGame = true; break; #ifdef MORE_LANGUAGES case LANGUAGE_RUSSIAN: CGame::russianGame = true; break; case LANGUAGE_JAPANESE: CGame::japaneseGame = true; break; #endif default: break; } } } void CMenuManager::LoadAllTextures() { if (m_bSpritesLoaded) return; CentreMousePointer(); DMAudio.ChangeMusicMode(MUSICMODE_FRONTEND); DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_STARTING, 0); m_nCurrOption = 0; #ifdef FIX_BUGS static bool firstTime = true; if (firstTime) { DMAudio.SetRadioInCar(m_PrefsRadioStation); firstTime = false; } else #endif m_PrefsRadioStation = DMAudio.GetRadioInCar(); if (DMAudio.IsMP3RadioChannelAvailable()) { if (m_PrefsRadioStation > USERTRACK) m_PrefsRadioStation = CGeneral::GetRandomNumber() % (USERTRACK + 1); } else if (m_PrefsRadioStation > CHATTERBOX) m_PrefsRadioStation = CGeneral::GetRandomNumber() % (CHATTERBOX + 1); CFileMgr::SetDir(""); //CFileMgr::SetDir(""); CTimer::Stop(); CStreaming::MakeSpaceFor(350 * CDSTREAM_SECTOR_SIZE); // twice of it in mobile CStreaming::ImGonnaUseStreamingMemory(); CGame::TidyUpMemory(false, true); CTxdStore::PushCurrentTxd(); int frontendTxdSlot = CTxdStore::FindTxdSlot("frontend"); if(frontendTxdSlot == -1) frontendTxdSlot = CTxdStore::AddTxdSlot("frontend"); printf("LOAD frontend\n"); CTxdStore::LoadTxd(frontendTxdSlot, "MODELS/FRONTEND.TXD"); CTxdStore::AddRef(frontendTxdSlot); CTxdStore::SetCurrentTxd(frontendTxdSlot); #if GTA_VERSION < GTA3_PC_11 CStreaming::IHaveUsedStreamingMemory(); CTimer::Update(); #endif for (int i = 0; i < ARRAY_SIZE(FrontendFilenames); i++) { m_aFrontEndSprites[i].SetTexture(FrontendFilenames[i][0], FrontendFilenames[i][1]); m_aFrontEndSprites[i].SetAddressing(rwTEXTUREADDRESSBORDER); } #ifdef GAMEPAD_MENU LoadController(m_PrefsControllerType); #endif int menuTxdSlot = CTxdStore::FindTxdSlot("menu"); if (menuTxdSlot == -1) menuTxdSlot = CTxdStore::AddTxdSlot("menu"); printf("LOAD sprite\n"); CTxdStore::LoadTxd(menuTxdSlot, "MODELS/MENU.TXD"); CTxdStore::AddRef(menuTxdSlot); CTxdStore::SetCurrentTxd(menuTxdSlot); for (int i = 0; i < ARRAY_SIZE(MenuFilenames); i++) { m_aMenuSprites[i].SetTexture(MenuFilenames[i][0], MenuFilenames[i][1]); m_aMenuSprites[i].SetAddressing(rwTEXTUREADDRESSBORDER); } #ifdef MENU_MAP static bool menuOptionAdded = false; for (int i = 0; i < ARRAY_SIZE(MapFilenames); i++) { if (!menuOptionAdded && RwTextureRead(MapFilenames[i][0], MapFilenames[i][1])) { FrontendOptionSetCursor(MENUPAGE_PAUSE_MENU, 2, false); FrontendOptionAddBuiltinAction("FEG_MAP", MENUACTION_CHANGEMENU, MENUPAGE_MAP, SAVESLOT_NONE); menuOptionAdded = true; } m_aMapSprites[i].SetTexture(MapFilenames[i][0], MapFilenames[i][1]); m_aMapSprites[i].SetAddressing(rwTEXTUREADDRESSBORDER); } fMapSize = SCREEN_HEIGHT * 2.0f; fMapCenterX = 0.0f; fMapCenterY = 0.0f; #endif #if GTA_VERSION >= GTA3_PC_11 CStreaming::IHaveUsedStreamingMemory(); CTimer::Update(); #endif m_bSpritesLoaded = true; CTxdStore::PopCurrentTxd(); } #ifdef GAMEPAD_MENU const char* controllerTypesPaths[] = { nil, "MODELS/FRONTEND_DS3.TXD", "MODELS/FRONTEND_DS4.TXD", "MODELS/FRONTEND_X360.TXD", "MODELS/FRONTEND_XONE.TXD", }; void CMenuManager::LoadController(int8 type) { switch (type) { case CONTROLLER_DUALSHOCK2: case CONTROLLER_DUALSHOCK3: case CONTROLLER_DUALSHOCK4: CFont::LoadButtons("MODELS/PS3BTNS.TXD"); break; default: CFont::LoadButtons("MODELS/X360BTNS.TXD"); break; } // Unload current textures for (int i = FE_CONTROLLER; i <= FE_ARROWS4; i++) m_aFrontEndSprites[i].Delete(); // Unload txd int frontend_controller = CTxdStore::FindTxdSlot("frontend_controller"); if (frontend_controller != -1) CTxdStore::RemoveTxd(frontend_controller); // Find the new txd to load bool bTxdMissing = true; if (controllerTypesPaths[type]) if (int file = CFileMgr::OpenFile(controllerTypesPaths[type])) { CFileMgr::CloseFile(file); bTxdMissing = false; } int txdSlot = -1; if (bTxdMissing) // Not found, fall back to original textures txdSlot = CTxdStore::FindTxdSlot("frontend"); else { // Found, load txd txdSlot = frontend_controller; if (txdSlot == -1) txdSlot = CTxdStore::AddTxdSlot("frontend_controller"); CTxdStore::LoadTxd(txdSlot, controllerTypesPaths[type]); CTxdStore::AddRef(txdSlot); } assert(txdSlot != -1); // Load new textures CTxdStore::SetCurrentTxd(txdSlot); for (int i = FE_CONTROLLER; i <= FE_ARROWS4; i++) { m_aFrontEndSprites[i].SetTexture(FrontendFilenames[i][0], FrontendFilenames[i][1]); m_aFrontEndSprites[i].SetAddressing(rwTEXTUREADDRESSBORDER); } } #endif // GAMEPAD_MENU void CMenuManager::LoadSettings() { CFileMgr::SetDirMyDocuments(); int fileHandle = CFileMgr::OpenFile("gta3.set", "r"); int32 prevLang = m_PrefsLanguage; #if GTA_VERSION >= GTA3_PC_11 CMBlur::BlurOn = (_dwOperatingSystemVersion != OS_WIN98); #else CMBlur::BlurOn = true; #endif MousePointerStateHelper.bInvertVertically = true; // 50 is silly char Ver[50]; if (fileHandle) { CFileMgr::Read(fileHandle, Ver, 29); if (strncmp(Ver, TopLineEmptyFile, sizeof(TopLineEmptyFile) - 1)) { CFileMgr::Seek(fileHandle, 0, 0); ControlsManager.LoadSettings(fileHandle); #ifdef IMPROVED_VIDEOMODE CFileMgr::Read(fileHandle, (char*)&m_nPrefsWidth, sizeof(m_nPrefsWidth)); CFileMgr::Read(fileHandle, (char*)&m_nPrefsHeight, sizeof(m_nPrefsHeight)); CFileMgr::Read(fileHandle, (char*)&m_nPrefsDepth, sizeof(m_nPrefsDepth)); CFileMgr::Read(fileHandle, (char*)&m_nPrefsWindowed, sizeof(m_nPrefsWindowed)); CFileMgr::Read(fileHandle, (char*)&m_nPrefsSubsystem, sizeof(m_nPrefsSubsystem)); if(m_nPrefsWindowed != 0 && m_nPrefsWindowed != 1){ // garbage data from vanilla settings file // let skeleton find something m_nPrefsWidth = 0; m_nPrefsHeight = 0; m_nPrefsDepth = 0; m_nPrefsWindowed = 0; m_nPrefsSubsystem = 0; } m_nSelectedScreenMode = m_nPrefsWindowed; #else CFileMgr::Read(fileHandle, gString, 20); #endif CFileMgr::Read(fileHandle, gString, 20); CFileMgr::Read(fileHandle, gString, 4); CFileMgr::Read(fileHandle, gString, 4); CFileMgr::Read(fileHandle, gString, 1); CFileMgr::Read(fileHandle, gString, 1); CFileMgr::Read(fileHandle, gString, 1); CFileMgr::Read(fileHandle, (char*)&TheCamera.m_bHeadBob, 1); CFileMgr::Read(fileHandle, (char*)&TheCamera.m_fMouseAccelHorzntl, 4); CFileMgr::Read(fileHandle, (char*)&TheCamera.m_fMouseAccelVertical, 4); CFileMgr::Read(fileHandle, (char*)&MousePointerStateHelper.bInvertVertically, 1); CFileMgr::Read(fileHandle, (char*)&CVehicle::m_bDisableMouseSteering, 1); CFileMgr::Read(fileHandle, (char*)&m_PrefsSfxVolume, 1); CFileMgr::Read(fileHandle, (char*)&m_PrefsMusicVolume, 1); CFileMgr::Read(fileHandle, (char*)&m_PrefsRadioStation, 1); CFileMgr::Read(fileHandle, (char*)&m_PrefsSpeakers, 1); CFileMgr::Read(fileHandle, (char*)&m_nPrefsAudio3DProviderIndex, 1); CFileMgr::Read(fileHandle, (char*)&m_PrefsDMA, 1); CFileMgr::Read(fileHandle, (char*)&m_PrefsBrightness, 1); CFileMgr::Read(fileHandle, (char*)&m_PrefsLOD, 4); CFileMgr::Read(fileHandle, (char*)&m_PrefsShowSubtitles, 1); CFileMgr::Read(fileHandle, (char*)&m_PrefsUseWideScreen, 1); CFileMgr::Read(fileHandle, (char*)&m_PrefsVsyncDisp, 1); CFileMgr::Read(fileHandle, (char*)&m_PrefsFrameLimiter, 1); CFileMgr::Read(fileHandle, (char*)&m_nDisplayVideoMode, 1); CFileMgr::Read(fileHandle, (char*)&CMBlur::BlurOn, 1); CFileMgr::Read(fileHandle, m_PrefsSkinFile, 256); CFileMgr::Read(fileHandle, (char*)&m_ControlMethod, 1); CFileMgr::Read(fileHandle, (char*)&m_PrefsLanguage, 1); } } CFileMgr::CloseFile(fileHandle); CFileMgr::SetDir(""); #ifdef LOAD_INI_SETTINGS if (LoadINISettings()) { LoadINIControllerSettings(); } // if no re3.ini, create it, or update it with new values SaveINISettings(); SaveINIControllerSettings(); #endif m_PrefsVsync = m_PrefsVsyncDisp; CRenderer::ms_lodDistScale = m_PrefsLOD; if (m_nPrefsAudio3DProviderIndex == -1) m_nPrefsAudio3DProviderIndex = -2; if (m_PrefsLanguage == prevLang) m_bLanguageLoaded = false; else { m_bLanguageLoaded = true; // Already called in InitialiseChangedLanguageSettings /* TheText.Unload(); TheText.Load(); */ m_bFrontEnd_ReloadObrTxtGxt = true; InitialiseChangedLanguageSettings(); OutputDebugString("The previously saved language is now in use"); } WIN32_FIND_DATA FindFileData; char skinfile[256+16]; // Stack analysis shows 16 bits gap, but I don't trust it. It may very well be MAX_PATH(260). bool SkinFound = false; HANDLE handle = FindFirstFile("skins\\*.bmp", &FindFileData); for (int i = 1; handle != INVALID_HANDLE_VALUE && i; i = FindNextFile(handle, &FindFileData)) { strcpy(skinfile, m_PrefsSkinFile); strcat(skinfile, ".bmp"); if (strcmp(FindFileData.cFileName, skinfile) == 0) SkinFound = true; } FindClose(handle); if (!SkinFound) { OutputDebugString("Default skin set as no other skins are available OR saved skin not found!"); strcpy(m_PrefsSkinFile, DEFAULT_SKIN_NAME); strcpy(m_aSkinName, DEFAULT_SKIN_NAME); } } void CMenuManager::SaveSettings() { #ifndef LOAD_INI_SETTINGS static char RubbishString[48] = "stuffmorestuffevenmorestuff etc"; CFileMgr::SetDirMyDocuments(); int fileHandle = CFileMgr::OpenFile("gta3.set", "w+"); if (fileHandle) { ControlsManager.SaveSettings(fileHandle); #ifdef IMPROVED_VIDEOMODE CFileMgr::Write(fileHandle, (char*)&m_nPrefsWidth, sizeof(m_nPrefsWidth)); CFileMgr::Write(fileHandle, (char*)&m_nPrefsHeight, sizeof(m_nPrefsHeight)); CFileMgr::Write(fileHandle, (char*)&m_nPrefsDepth, sizeof(m_nPrefsDepth)); CFileMgr::Write(fileHandle, (char*)&m_nPrefsWindowed, sizeof(m_nPrefsWindowed)); CFileMgr::Write(fileHandle, (char*)&m_nPrefsSubsystem, sizeof(m_nPrefsSubsystem)); #else CFileMgr::Write(fileHandle, RubbishString, 20); #endif CFileMgr::Write(fileHandle, RubbishString, 20); CFileMgr::Write(fileHandle, RubbishString, 4); CFileMgr::Write(fileHandle, RubbishString, 4); CFileMgr::Write(fileHandle, RubbishString, 1); CFileMgr::Write(fileHandle, RubbishString, 1); CFileMgr::Write(fileHandle, RubbishString, 1); CFileMgr::Write(fileHandle, (char*)&TheCamera.m_bHeadBob, 1); CFileMgr::Write(fileHandle, (char*)&TheCamera.m_fMouseAccelHorzntl, 4); CFileMgr::Write(fileHandle, (char*)&TheCamera.m_fMouseAccelVertical, 4); CFileMgr::Write(fileHandle, (char*)&MousePointerStateHelper.bInvertVertically, 1); CFileMgr::Write(fileHandle, (char*)&CVehicle::m_bDisableMouseSteering, 1); CFileMgr::Write(fileHandle, (char*)&m_PrefsSfxVolume, 1); CFileMgr::Write(fileHandle, (char*)&m_PrefsMusicVolume, 1); CFileMgr::Write(fileHandle, (char*)&m_PrefsRadioStation, 1); CFileMgr::Write(fileHandle, (char*)&m_PrefsSpeakers, 1); CFileMgr::Write(fileHandle, (char*)&m_nPrefsAudio3DProviderIndex, 1); CFileMgr::Write(fileHandle, (char*)&m_PrefsDMA, 1); CFileMgr::Write(fileHandle, (char*)&m_PrefsBrightness, 1); CFileMgr::Write(fileHandle, (char*)&m_PrefsLOD, sizeof(m_PrefsLOD)); CFileMgr::Write(fileHandle, (char*)&m_PrefsShowSubtitles, 1); CFileMgr::Write(fileHandle, (char*)&m_PrefsUseWideScreen, 1); CFileMgr::Write(fileHandle, (char*)&m_PrefsVsyncDisp, 1); CFileMgr::Write(fileHandle, (char*)&m_PrefsFrameLimiter, 1); CFileMgr::Write(fileHandle, (char*)&m_nPrefsVideoMode, 1); CFileMgr::Write(fileHandle, (char*)&CMBlur::BlurOn, 1); CFileMgr::Write(fileHandle, m_PrefsSkinFile, 256); CFileMgr::Write(fileHandle, (char*)&m_ControlMethod, 1); CFileMgr::Write(fileHandle, (char*)&m_PrefsLanguage, 1); } CFileMgr::CloseFile(fileHandle); CFileMgr::SetDir(""); #else SaveINISettings(); #endif } bool DoRWStuffStartOfFrame(int16 TopRed, int16 TopGreen, int16 TopBlue, int16 BottomRed, int16 BottomGreen, int16 BottomBlue, int16 Alpha); void DoRWStuffEndOfFrame(void); void CMenuManager::MessageScreen(const char *text) { CSprite2d *splash = LoadSplash(nil); if (!DoRWStuffStartOfFrame(0, 0, 0, 0, 0, 0, 255)) return; CSprite2d::SetRecipNearClip(); CSprite2d::InitPerFrame(); CFont::InitPerFrame(); DefinedState(); RwRenderStateSet(rwRENDERSTATETEXTUREADDRESS, (void*)rwTEXTUREADDRESSCLAMP); splash->Draw(CRect(0.0f, 0.0f, SCREEN_WIDTH, SCREEN_HEIGHT), CRGBA(255, 255, 255, 255)); CFont::SetBackgroundOff(); CFont::SetPropOn(); CFont::SetJustifyOn(); CFont::SetBackGroundOnlyTextOn(); CFont::SetWrapx(SCREEN_WIDTH - StretchX(170.0f)); // unused CFont::SetRightJustifyWrap(SCREEN_WIDTH - StretchX(170.0f)); // unused CSprite2d::DrawRect(CRect(StretchX(120.0f), StretchY(150.0f), SCREEN_WIDTH - StretchX(120.0f), SCREEN_HEIGHT - StretchY(220.0f)), CRGBA(50, 50, 50, 210)); CFont::SetFontStyle(FONT_LOCALE(FONT_BANK)); CFont::SetCentreSize(SCREEN_SCALE_X(380.0f)); CFont::SetCentreOn(); CFont::SetColor(CRGBA(SELECTEDMENUOPTION_COLOR.r, SELECTEDMENUOPTION_COLOR.g, SELECTEDMENUOPTION_COLOR.b, 255)); CFont::SetScale(SCREEN_SCALE_X(SMALLTEXT_X_SCALE), SCREEN_SCALE_Y(SMALLTEXT_Y_SCALE)); CFont::PrintString(StretchX(320.0f), StretchY(170.0f), TheText.Get(text)); CFont::DrawFonts(); DoRWStuffEndOfFrame(); } void CMenuManager::PickNewPlayerColour() { m_PrefsPlayerRed = 0; m_PrefsPlayerGreen = 0; m_PrefsPlayerBlue = 0; while (true) { int sum = m_PrefsPlayerRed + m_PrefsPlayerGreen + m_PrefsPlayerBlue; if (sum >= 100 && sum <= 650) break; m_PrefsPlayerRed = CGeneral::GetRandomNumber(); m_PrefsPlayerGreen = CGeneral::GetRandomNumber(); m_PrefsPlayerBlue = CGeneral::GetRandomNumber(); } } void CMenuManager::PrintBriefs() { CFont::SetColor(CRGBA(LABEL_COLOR.r, LABEL_COLOR.g, LABEL_COLOR.b, FadeIn(255))); CFont::SetFontStyle(FONT_LOCALE(FONT_BANK)); CFont::SetRightJustifyOff(); CFont::SetScale(MENU_X(MENU_TEXT_SIZE_X * 0.7), MENU_Y(MENU_TEXT_SIZE_Y * 0.9)); // second mulipliers are double, idk why float nextY = BRIEFS_TOP_MARGIN; CRGBA newColor; for (int i = 4; i >= 0; i--) { tPreviousBrief &brief = CMessages::PreviousBriefs[i]; if (brief.m_pText) { CMessages::InsertNumberInString(brief.m_pText, brief.m_nNumber[0], brief.m_nNumber[1], brief.m_nNumber[2], brief.m_nNumber[3], brief.m_nNumber[4], brief.m_nNumber[5], gUString); CMessages::InsertStringInString(gUString, brief.m_pString); CMessages::InsertPlayerControlKeysInString(gUString); newColor = TEXT_COLOR; FilterOutColorMarkersFromString(gUString, newColor); if (newColor != TEXT_COLOR) { newColor.r /= 2; newColor.g /= 2; newColor.b /= 2; } #ifdef PS2_LIKE_MENU CFont::SetDropColor(CRGBA(0, 0, 0, FadeIn(255))); CFont::SetDropShadowPosition(1); #endif #if defined(FIX_BUGS) || defined(PS2_LIKE_MENU) newColor.a = FadeIn(255); CFont::SetColor(newColor); #endif CFont::PrintString(MENU_X_LEFT_ALIGNED(BRIEFS_LINE_X), nextY, gUString); nextY += MENU_Y(BRIEFS_LINE_HEIGHT); } } #ifdef PS2_LIKE_MENU CFont::SetDropShadowPosition(0); #endif } // Not sure about name. Not to be confused with CPad::PrintErrorMessage void CMenuManager::PrintErrorMessage() { if (!CPad::bDisplayNoControllerMessage && !CPad::bObsoleteControllerMessage) return; CSprite2d::DrawRect(CRect(SCREEN_SCALE_X(20.0f), SCREEN_SCALE_Y(140.0f), SCREEN_SCALE_FROM_RIGHT(20.0f), SCREEN_SCALE_FROM_BOTTOM(120.0f)), CRGBA(64, 16, 16, 224)); CFont::SetFontStyle(FONT_LOCALE(FONT_BANK)); CFont::SetBackgroundOff(); CFont::SetPropOn(); CFont::SetCentreOff(); CFont::SetJustifyOn(); CFont::SetRightJustifyOff(); CFont::SetBackGroundOnlyTextOn(); CFont::SetWrapx(SCREEN_SCALE_FROM_RIGHT(MENU_X_MARGIN)); #ifdef FIX_BUGS CFont::PrintString(SCREEN_SCALE_X(50.0f), SCREEN_SCALE_Y(180.0f), TheText.Get(CPad::bDisplayNoControllerMessage ? "NOCONT" : "WRCONT")); #else CFont::PrintString(SCREEN_SCALE_X(50.0f), SCREEN_SCALE_Y(40.0f), TheText.Get(CPad::bDisplayNoControllerMessage ? "NOCONT" : "WRCONT")); #endif CFont::DrawFonts(); } void CMenuManager::PrintStats() { int rowNum = ConstructStatLine(99999); #if GTA_VERSION >= GTA3_PC_11 CFont::SetFontStyle(FONT_LOCALE(FONT_BANK)); #endif CFont::SetScale(MENU_X(MENU_TEXT_SIZE_X * 0.7), MENU_Y(MENU_TEXT_SIZE_Y * 0.9)); // second mulipliers are double, idk why float nextYChange, y, alphaMult; // Scroll stats with mouse #ifdef SCROLLABLE_STATS_PAGE static float scrollY = 0; static uint32 lastChange = m_nScreenChangeDelayTimer; if (CPad::GetPad(0)->GetLeftMouse()) { scrollY += (m_nMouseOldPosY - m_nMousePosY); lastChange = CTimer::GetTimeInMillisecondsPauseMode(); } else { scrollY += MENU_Y(STATS_SLIDE_Y_PER_SECOND) / 1000.0f * (CTimer::GetTimeInMillisecondsPauseMode() - lastChange); lastChange = CTimer::GetTimeInMillisecondsPauseMode(); } #else // MENU_Y(30.0f) per second float scrollY = MENU_Y(STATS_SLIDE_Y_PER_SECOND) * (CTimer::GetTimeInMillisecondsPauseMode() - m_nScreenChangeDelayTimer) / 1000.0f; #endif for (int row = 0; row < rowNum; ++row) { // Put just got hidden text at the top back to the bottom, in circular fashion for (y = MENU_Y(STATS_ROW_HEIGHT - 1) * row + SCREEN_HEIGHT - scrollY; MENU_Y(STATS_PUT_BACK_TO_BOTTOM_Y) > y; y += nextYChange) { nextYChange = (MENU_Y(STATS_ROW_HEIGHT) + rowNum) * MENU_Y(STATS_ROW_HEIGHT - 1); } // If it's still on screen if (y > 0.0f && SCREEN_HEIGHT > y) { ConstructStatLine(row); // But about to dim from top if (y - MENU_Y(STATS_BOTTOM_MARGIN) < MENU_Y(STATS_TOP_DIMMING_AREA_LENGTH)) { if ((y - MENU_Y(STATS_BOTTOM_MARGIN)) / MENU_Y(STATS_TOP_DIMMING_AREA_LENGTH) < 0.0f) alphaMult = 0.0f; else alphaMult = (y - MENU_Y(STATS_BOTTOM_MARGIN)) / MENU_Y(STATS_TOP_DIMMING_AREA_LENGTH); // About to dim from bottom } else if (y > SCREEN_SCALE_FROM_BOTTOM(STATS_TOP_DIMMING_AREA_LENGTH) - MENU_Y(STATS_BOTTOM_DIMMING_AREA_LENGTH)) { if ((SCREEN_SCALE_FROM_BOTTOM(STATS_BOTTOM_DIMMING_AREA_LENGTH) - y) / MENU_Y(STATS_TOP_DIMMING_AREA_LENGTH) < 0.0f) alphaMult = 0.0f; else alphaMult = (SCREEN_SCALE_FROM_BOTTOM(STATS_BOTTOM_DIMMING_AREA_LENGTH) - y) / MENU_Y(STATS_TOP_DIMMING_AREA_LENGTH); } else alphaMult = 1.0f; CFont::SetColor(CRGBA(LABEL_COLOR.r, LABEL_COLOR.g, LABEL_COLOR.b, FadeIn(255.0f * alphaMult))); CFont::SetRightJustifyOff(); CFont::PrintString(MENU_X_LEFT_ALIGNED(STATS_ROW_X_MARGIN), y - MENU_Y(STATS_BOTTOM_MARGIN - STATS_TOP_MARGIN), gUString); CFont::SetRightJustifyOn(); CFont::PrintString(MENU_X_RIGHT_ALIGNED(STATS_ROW_X_MARGIN), y - MENU_Y(STATS_BOTTOM_MARGIN - STATS_TOP_MARGIN), gUString2); } } // Game doesn't do that, but it's better float nextX = MENU_X_LEFT_ALIGNED(STATS_RATING_X); CFont::SetColor(CRGBA(LABEL_COLOR.r, LABEL_COLOR.g, LABEL_COLOR.b, FadeIn(255))); CFont::SetRightJustifyOff(); CFont::PrintString(nextX, MENU_Y(STATS_RATING_Y), TheText.Get("CRIMRA")); #ifdef MORE_LANGUAGES if (CFont::IsJapanese()) nextX += MENU_X(10.0f) + CFont::GetStringWidth_Jap(TheText.Get("CRIMRA")); else #endif nextX += MENU_X(10.0f) + CFont::GetStringWidth(TheText.Get("CRIMRA"), true); UnicodeStrcpy(gUString, CStats::FindCriminalRatingString()); CFont::PrintString(nextX, MENU_Y(STATS_RATING_Y), gUString); #ifdef MORE_LANGUAGES if (CFont::IsJapanese()) nextX += MENU_X(6.0f) + CFont::GetStringWidth_Jap(gUString); else #endif nextX += MENU_X(6.0f) + CFont::GetStringWidth(gUString, true); sprintf(gString, "%d", CStats::FindCriminalRatingNumber()); AsciiToUnicode(gString, gUString); CFont::PrintString(nextX, MENU_Y(STATS_RATING_Y), gUString); // ::Draw already does that. /* SET_FONT_FOR_MENU_HEADER CFont::PrintString(PAGE_NAME_X(MENUHEADER_POS_X), SCREEN_SCALE_FROM_BOTTOM(MENUHEADER_POS_Y), TheText.Get(aScreens[m_nCurrScreen].m_ScreenName)); */ CFont::SetScale(MENU_X(MENU_TEXT_SIZE_X), MENU_Y(MENU_TEXT_SIZE_Y)); } void CMenuManager::Process(void) { m_bMenuStateChanged = false; if (!m_bSaveMenuActive && TheCamera.GetScreenFadeStatus() != FADE_0) return; m_bWantToRestart = false; InitialiseChangedLanguageSettings(); // Just a hack by R* to not make game continuously resume/pause. But we it seems we can live with it. if (CPad::GetPad(0)->GetEscapeJustDown()) RequestFrontEndStartUp(); SwitchMenuOnAndOff(); // Be able to re-open menu correctly. if (m_bMenuActive) { // Load frontend textures. LoadAllTextures(); // Set save/delete game pages. if (m_nCurrScreen == MENUPAGE_DELETING) { bool SlotPopulated = false; if (PcSaveHelper.DeleteSlot(m_nCurrSaveSlot)) { PcSaveHelper.PopulateSlotInfo(); SlotPopulated = true; } if (SlotPopulated) ChangeScreen(MENUPAGE_DELETE_SUCCESS, 0, true, false); else SaveLoadFileError_SetUpErrorScreen(); } if (m_nCurrScreen == MENUPAGE_SAVING_IN_PROGRESS) { int8 SaveSlot = PcSaveHelper.SaveSlot(m_nCurrSaveSlot); PcSaveHelper.PopulateSlotInfo(); if (SaveSlot) ChangeScreen(MENUPAGE_SAVE_SUCCESSFUL, 0, true, false); else SaveLoadFileError_SetUpErrorScreen(); } if (m_nCurrScreen == MENUPAGE_LOADING_IN_PROGRESS) { #ifdef MISSION_REPLAY if (doingMissionRetry) { RetryMission(2, 0); m_nCurrSaveSlot = SLOT_COUNT; doingMissionRetry = false; } #endif if (CheckSlotDataValid(m_nCurrSaveSlot)) { #ifdef USE_DEBUG_SCRIPT_LOADER scriptToLoad = 0; #endif #ifdef PC_PLAYER_CONTROLS TheCamera.m_bUseMouse3rdPerson = m_ControlMethod == CONTROL_STANDARD; #endif if (m_PrefsVsyncDisp != m_PrefsVsync) m_PrefsVsync = m_PrefsVsyncDisp; DMAudio.Service(); m_bWantToRestart = true; RequestFrontEndShutDown(); m_bWantToLoad = true; b_FoundRecentSavedGameWantToLoad = true; DMAudio.SetEffectsFadeVol(0); DMAudio.SetMusicFadeVol(0); DMAudio.ResetTimers(CTimer::GetTimeInMilliseconds()); } else SaveLoadFileError_SetUpErrorScreen(); } ProcessButtonPresses(); // Set binding keys. if (pEditString && CPad::EditString(pEditString, 0) == nil) { if (*pEditString == 0) strcpy(pEditString, "NoName"); pEditString = nil; SaveSettings(); } if (m_bWaitingForNewKeyBind) { if (m_bStartWaitingForKeyBind) m_bStartWaitingForKeyBind = false; else { pControlEdit = CPad::EditCodesForControls(pControlEdit, 1); JoyButtonJustClicked = false; MouseButtonJustClicked = false; if (CPad::GetPad(0)->GetLeftMouseJustDown()) MouseButtonJustClicked = rsMOUSELEFTBUTTON; else if (CPad::GetPad(0)->GetRightMouseJustUp()) MouseButtonJustClicked = rsMOUSERIGHTBUTTON; else if (CPad::GetPad(0)->GetMiddleMouseJustUp()) MouseButtonJustClicked = rsMOUSMIDDLEBUTTON; else if (CPad::GetPad(0)->GetMouseWheelUpJustUp()) MouseButtonJustClicked = rsMOUSEWHEELUPBUTTON; else if (CPad::GetPad(0)->GetMouseWheelDownJustUp()) MouseButtonJustClicked = rsMOUSEWHEELDOWNBUTTON; else if (CPad::GetPad(0)->GetMouseX1JustUp()) MouseButtonJustClicked = rsMOUSEX1BUTTON; else if (CPad::GetPad(0)->GetMouseX2JustUp()) MouseButtonJustClicked = rsMOUSEX2BUTTON; JoyButtonJustClicked = ControlsManager.GetJoyButtonJustDown(); int32 TypeOfControl = KEYBOARD; if (JoyButtonJustClicked) TypeOfControl = JOYSTICK; if (MouseButtonJustClicked) TypeOfControl = MOUSE; if (*pControlEdit != rsNULL) TypeOfControl = KEYBOARD; if (!m_bKeyIsOK) { DMAudio.PlayFrontEndSound(SOUND_FRONTEND_FAIL, 0); pControlEdit = nil; m_bWaitingForNewKeyBind = false; m_KeyPressedCode = -1; m_bStartWaitingForKeyBind = false; } else if (!m_bKeyChangeNotProcessed) { if (*pControlEdit != rsNULL || MouseButtonJustClicked || JoyButtonJustClicked) CheckCodesForControls(TypeOfControl); field_535 = true; } else { DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_SETTING_CHANGE, 0); for (int i = 0; i < 4; i++) ControlsManager.ClearSettingsAssociatedWithAction((e_ControllerAction)m_CurrCntrlAction, (eControllerType)i); m_bKeyIsOK = false; m_bKeyChangeNotProcessed = false; pControlEdit = nil; m_bWaitingForNewKeyBind = false; m_KeyPressedCode = -1; m_bStartWaitingForKeyBind = false; } } } if ((m_nCurrScreen == MENUPAGE_NO_MEMORY_CARD || m_nCurrScreen == MENUPAGE_PS2_LOAD_FAILED) && CTimer::GetTimeInMillisecondsPauseMode() > field_558) { m_nCurrScreen = m_nPrevScreen; m_nCurrOption = 0; } // Reset pad shaking. if (TimeToStopPadShaking && TimeToStopPadShaking < CTimer::GetTimeInMillisecondsPauseMode()) { CPad::StopPadsShaking(); TimeToStopPadShaking = 0; } } else { UnloadTextures(); m_bRenderGameInMenu = false; // byte_5F33E4 = 1; // unused ChangeScreen(MENUPAGE_NONE, 0, false, false); pEditString = nil; m_bWaitingForNewKeyBind = false; } if (!m_bWantToRestart) { if (m_bGameNotLoaded) DMAudio.Service(); } } void CMenuManager::ProcessButtonPresses(void) { if (pEditString || pControlEdit) return; bool goBack = false; bool optionSelected = false; bool goUp = false; bool goDown = false; #ifdef TIDY_UP_PBP bool assumeIncrease = false; #endif #ifdef USE_DEBUG_SCRIPT_LOADER if (m_nCurrScreen == MENUPAGE_START_MENU || m_nCurrScreen == MENUPAGE_NEW_GAME || m_nCurrScreen == MENUPAGE_NEW_GAME_RELOAD) { #ifdef RW_GL3 if (glfwGetKey(PSGLOBAL(window), GLFW_KEY_R) == GLFW_PRESS) { scriptToLoad = 1; DoSettingsBeforeStartingAGame(); return; } if (glfwGetKey(PSGLOBAL(window), GLFW_KEY_D) == GLFW_PRESS) { scriptToLoad = 2; DoSettingsBeforeStartingAGame(); return; } #elif defined _WIN32 if (GetAsyncKeyState('R') & 0x8000) { scriptToLoad = 1; DoSettingsBeforeStartingAGame(); return; } if (GetAsyncKeyState('D') & 0x8000) { scriptToLoad = 2; DoSettingsBeforeStartingAGame(); return; } #endif } #endif if (!m_bShowMouse && (m_nMouseOldPosX != m_nMousePosX || m_nMouseOldPosY != m_nMousePosY)) { m_bShowMouse = true; } m_nMouseOldPosX = m_nMousePosX; m_nMouseOldPosY = m_nMousePosY; m_nMousePosX = m_nMouseTempPosX; m_nMousePosY = m_nMouseTempPosY; if (m_nMousePosX < 0) m_nMousePosX = 0; if (m_nMousePosX > SCREEN_WIDTH) m_nMousePosX = SCREEN_WIDTH; if (m_nMousePosY < 0) m_nMousePosY = 0; if (m_nMousePosY > SCREEN_HEIGHT) m_nMousePosY = SCREEN_HEIGHT; if (hasNativeList(m_nCurrScreen)) { // Not split to seperate function in III as in VC, but we need it for scrollable pages :) ProcessList(goBack, optionSelected); } else if (isPlainTextScreen(m_nCurrScreen)) { #ifndef TIDY_UP_PBP if (CPad::GetPad(0)->GetEnterJustDown() || CPad::GetPad(0)->GetCrossJustDown() || CPad::GetPad(0)->GetLeftMouseJustDown()) { optionSelected = true; } if (CPad::GetPad(0)->GetEscapeJustDown() || CPad::GetPad(0)->GetBackJustUp()) { if (m_nCurrScreen != MENUPAGE_START_MENU) { goBack = true; } } #endif } else { if (CPad::GetPad(0)->GetDownJustDown() || CPad::GetPad(0)->GetAnaloguePadDown() || CPad::GetPad(0)->GetDPadDownJustDown()) { m_bShowMouse = false; DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_NAVIGATION, 0); goDown = true; } else if (CPad::GetPad(0)->GetUpJustDown() || CPad::GetPad(0)->GetAnaloguePadUp() || CPad::GetPad(0)->GetDPadUpJustDown()) { m_bShowMouse = false; DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_NAVIGATION, 0); goUp = true; } #ifndef TIDY_UP_PBP if ((m_nCurrOption == 0) && (m_nCurrScreen == MENUPAGE_PAUSE_MENU)) { if (CPad::GetPad(0)->GetEnterJustUp() || CPad::GetPad(0)->GetCrossJustUp()) { m_bShowMouse = false; optionSelected = true; } } else { if (CPad::GetPad(0)->GetEnterJustDown() || CPad::GetPad(0)->GetCrossJustDown()) { m_bShowMouse = false; optionSelected = true; } } #endif if (CPad::GetPad(0)->GetLeftMouseJustUp()) { #ifndef TIDY_UP_PBP if (((m_nCurrOption == 0) && (m_nCurrScreen == MENUPAGE_PAUSE_MENU)) && #else if (aScreens[m_nCurrScreen].m_aEntries[m_nCurrOption].m_Action == MENUACTION_RESUME && #endif (m_nHoverOption == HOVEROPTION_RANDOM_ITEM)) { m_nCurrOption = m_nOptionMouseHovering; optionSelected = true; } } else if (CPad::GetPad(0)->GetLeftMouseJustDown()) { #ifdef TIDY_UP_PBP if (m_nHoverOption >= HOVEROPTION_RADIO_0 && m_nHoverOption <= HOVEROPTION_RADIO_9) { DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_SETTING_CHANGE, 0); m_PrefsRadioStation = m_nHoverOption - HOVEROPTION_RADIO_0; SaveSettings(); DMAudio.SetRadioInCar(m_PrefsRadioStation); DMAudio.PlayFrontEndTrack(m_PrefsRadioStation, 1); OutputDebugString("FRONTEND RADIO STATION CHANGED"); } else if (m_nHoverOption == HOVEROPTION_RANDOM_ITEM && aScreens[m_nCurrScreen].m_aEntries[m_nCurrOption].m_Action != MENUACTION_RESUME) { m_nCurrOption = m_nOptionMouseHovering; optionSelected = true; } #else switch (m_nHoverOption) { case HOVEROPTION_RADIO_0: DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_SETTING_CHANGE, 0); m_PrefsRadioStation = HEAD_RADIO; SaveSettings(); DMAudio.SetRadioInCar(m_PrefsRadioStation); DMAudio.PlayFrontEndTrack(m_PrefsRadioStation, 1); OutputDebugString("FRONTEND RADIO STATION CHANGED"); break; case HOVEROPTION_RADIO_1: DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_SETTING_CHANGE, 0); m_PrefsRadioStation = DOUBLE_CLEF; SaveSettings(); DMAudio.SetRadioInCar(m_PrefsRadioStation); DMAudio.PlayFrontEndTrack(m_PrefsRadioStation, 1); OutputDebugString("FRONTEND RADIO STATION CHANGED"); break; case HOVEROPTION_RADIO_2: DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_SETTING_CHANGE, 0); m_PrefsRadioStation = JAH_RADIO; SaveSettings(); DMAudio.SetRadioInCar(m_PrefsRadioStation); DMAudio.PlayFrontEndTrack(m_PrefsRadioStation, 1); OutputDebugString("FRONTEND RADIO STATION CHANGED"); break; case HOVEROPTION_RADIO_3: DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_SETTING_CHANGE, 0); m_PrefsRadioStation = RISE_FM; SaveSettings(); DMAudio.SetRadioInCar(m_PrefsRadioStation); DMAudio.PlayFrontEndTrack(m_PrefsRadioStation, 1); OutputDebugString("FRONTEND RADIO STATION CHANGED"); break; case HOVEROPTION_RADIO_4: DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_SETTING_CHANGE, 0); m_PrefsRadioStation = LIPS_106; SaveSettings(); DMAudio.SetRadioInCar(m_PrefsRadioStation); DMAudio.PlayFrontEndTrack(m_PrefsRadioStation, 1); OutputDebugString("FRONTEND RADIO STATION CHANGED"); break; case HOVEROPTION_RADIO_5: DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_SETTING_CHANGE, 0); m_PrefsRadioStation = GAME_FM; SaveSettings(); DMAudio.SetRadioInCar(m_PrefsRadioStation); DMAudio.PlayFrontEndTrack(m_PrefsRadioStation, 1); OutputDebugString("FRONTEND RADIO STATION CHANGED"); break; case HOVEROPTION_RADIO_6: DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_SETTING_CHANGE, 0); m_PrefsRadioStation = MSX_FM; SaveSettings(); DMAudio.SetRadioInCar(m_PrefsRadioStation); DMAudio.PlayFrontEndTrack(m_PrefsRadioStation, 1); OutputDebugString("FRONTEND RADIO STATION CHANGED"); break; case HOVEROPTION_RADIO_7: DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_SETTING_CHANGE, 0); m_PrefsRadioStation = FLASHBACK; SaveSettings(); DMAudio.SetRadioInCar(m_PrefsRadioStation); DMAudio.PlayFrontEndTrack(m_PrefsRadioStation, 1); OutputDebugString("FRONTEND RADIO STATION CHANGED"); break; case HOVEROPTION_RADIO_8: DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_SETTING_CHANGE, 0); m_PrefsRadioStation = CHATTERBOX; SaveSettings(); DMAudio.SetRadioInCar(m_PrefsRadioStation); DMAudio.PlayFrontEndTrack(m_PrefsRadioStation, 1); OutputDebugString("FRONTEND RADIO STATION CHANGED"); break; case HOVEROPTION_RADIO_9: DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_SETTING_CHANGE, 0); m_PrefsRadioStation = USERTRACK; SaveSettings(); DMAudio.SetRadioInCar(m_PrefsRadioStation); DMAudio.PlayFrontEndTrack(m_PrefsRadioStation, 1); OutputDebugString("FRONTEND RADIO STATION CHANGED"); break; case HOVEROPTION_RANDOM_ITEM: if (((m_nCurrOption != 0) || (m_nCurrScreen != MENUPAGE_PAUSE_MENU)) { m_nCurrOption = m_nOptionMouseHovering; optionSelected = true; } break; } #endif } if (CPad::GetPad(0)->GetLeftMouse()) { #ifndef TIDY_UP_PBP switch (m_nHoverOption) { case HOVEROPTION_INCREASE_BRIGHTNESS: m_PrefsBrightness = m_PrefsBrightness + 32; if (m_PrefsBrightness < 0) { m_PrefsBrightness = 0; } if (510 < m_PrefsBrightness) { m_PrefsBrightness = 511; } SaveSettings(); break; case HOVEROPTION_DECREASE_BRIGHTNESS: m_PrefsBrightness = m_PrefsBrightness - 32; if (m_PrefsBrightness < 0) { m_PrefsBrightness = 0; } if (510 < m_PrefsBrightness) { m_PrefsBrightness = 511; } SaveSettings(); break; case HOVEROPTION_INCREASE_DRAWDIST: m_PrefsLOD = m_PrefsLOD + (1.0f / 16); m_PrefsLOD = min(1.8f, m_PrefsLOD); CRenderer::ms_lodDistScale = m_PrefsLOD; SaveSettings(); break; case HOVEROPTION_DECREASE_DRAWDIST: m_PrefsLOD = m_PrefsLOD - (1.0f / 16); m_PrefsLOD = max(0.8f, m_PrefsLOD); CRenderer::ms_lodDistScale = m_PrefsLOD; SaveSettings(); break; case HOVEROPTION_INCREASE_MUSICVOLUME: m_PrefsMusicVolume = m_PrefsMusicVolume + 8; m_PrefsMusicVolume = clamp(m_PrefsMusicVolume, 0, 127); DMAudio.SetMusicMasterVolume(uchar)(m_PrefsMusicVolume); SaveSettings(); break; case HOVEROPTION_DECREASE_MUSICVOLUME: m_PrefsMusicVolume = m_PrefsMusicVolume - 8; if (m_PrefsMusicVolume < 0) { m_PrefsMusicVolume = 0; } if (126 < m_PrefsMusicVolume) { m_PrefsMusicVolume = 127; } DMAudio.SetMusicMasterVolume(uchar)(m_PrefsMusicVolume); SaveSettings(); break; case HOVEROPTION_INCREASE_SFXVOLUME: m_PrefsSFXVolume = m_PrefsSFXVolume + 8; if (m_PrefsSFXVolume < 0) { m_PrefsSFXVolume = 0; } if (126 < m_PrefsSFXVolume) { m_PrefsSFXVolume = 127; } DMAudio.SetEffectsMasterVolume(uchar)(m_PrefsSFXVolume); SaveSettings(); break; case HOVEROPTION_DECREASE_SFXVOLUME: m_PrefsSFXVolume = m_PrefsSFXVolume - 8; if (m_PrefsSFXVolume < 0) { m_PrefsSFXVolume = 0; } if (126 < m_PrefsSFXVolume) { m_PrefsSFXVolume = 127; } DMAudio.SetEffectsMasterVolume(uchar)(m_PrefsSFXVolume); SaveSettings(); break; case HOVEROPTION_INCREASE_MOUSESENS: TheCamera.m_fMouseAccelHorzntl += (1.0f / 3000); TheCamera.m_fMouseAccelHorzntl = clamp(TheCamera.m_fMouseAccelHorzntl, 1.0f / 3200, 1.0f / 200); #ifdef FIX_BUGS TheCamera.m_fMouseAccelVertical = TheCamera.m_fMouseAccelHorzntl + 0.0005f; #else TheCamera.m_fMouseAccelVertical = TheCamera.m_fMouseAccelHorzntl; #endif SaveSettings(); break; case HOVEROPTION_DECREASE_MOUSESENS: TheCamera.m_fMouseAccelHorzntl -= (1.0f / 3000); TheCamera.m_fMouseAccelHorzntl = clamp(TheCamera.m_fMouseAccelHorzntl, 1.0f / 3200, 1.0f / 200); #ifdef FIX_BUGS TheCamera.m_fMouseAccelVertical = TheCamera.m_fMouseAccelHorzntl + 0.0005f; #else TheCamera.m_fMouseAccelVertical = TheCamera.m_fMouseAccelHorzntl; #endif SaveSettings(); break; } #else switch (m_nHoverOption) { case HOVEROPTION_INCREASE_BRIGHTNESS: case HOVEROPTION_INCREASE_DRAWDIST: case HOVEROPTION_INCREASE_MUSICVOLUME: case HOVEROPTION_INCREASE_SFXVOLUME: case HOVEROPTION_INCREASE_MOUSESENS: CheckSliderMovement(1); break; case HOVEROPTION_DECREASE_BRIGHTNESS: case HOVEROPTION_DECREASE_DRAWDIST: case HOVEROPTION_DECREASE_MUSICVOLUME: case HOVEROPTION_DECREASE_SFXVOLUME: case HOVEROPTION_DECREASE_MOUSESENS: CheckSliderMovement(-1); break; } #endif } #ifdef SCROLLABLE_PAGES if (m_nTotalListRow > MAX_VISIBLE_OPTION) { bool temp = false; m_nSelectedListRow = m_nCurrOption; // ignore detected back/select states, it's our screen's job ProcessList(temp, temp); // and ignore our screen's goUp/Down, now it's ProcessList's job goUp = false; goDown = false; m_nCurrOption = m_nSelectedListRow; } // Prevent sound on scroll. Mouse wheel is now belongs to us! if (!(m_nTotalListRow > MAX_VISIBLE_OPTION && (CPad::GetPad(0)->GetMouseWheelUpJustDown() || CPad::GetPad(0)->GetMouseWheelDownJustDown()))) #endif if (CPad::GetPad(0)->GetLeftMouseJustUp() || CPad::GetPad(0)->GetLeftJustUp() || CPad::GetPad(0)->GetRightJustUp() || CPad::GetPad(0)->GetDPadLeftJustUp() || CPad::GetPad(0)->GetDPadRightJustUp() || CPad::GetPad(0)->GetAnaloguePadLeftJustUp() || CPad::GetPad(0)->GetAnaloguePadRightJustUp() || CPad::GetPad(0)->GetMouseWheelUpJustDown() || CPad::GetPad(0)->GetMouseWheelDownJustDown()) { int option = aScreens[m_nCurrScreen].m_aEntries[m_nCurrOption].m_Action; if (option == MENUACTION_BRIGHTNESS || option == MENUACTION_DRAWDIST) DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_SETTING_CHANGE, 0); else if (option == MENUACTION_SFXVOLUME) DMAudio.PlayFrontEndSound(SOUND_FRONTEND_AUDIO_TEST, 0); else if (option == MENUACTION_MOUSESENS) DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_SETTING_CHANGE, 0); } #ifndef TIDY_UP_PBP if (CPad::GetPad(0)->GetBackJustDown()) { if (m_nCurrScreen != MENUPAGE_START_MENU && m_nCurrScreen != MENUPAGE_PAUSE_MENU) { m_bShowMouse = false; goBack = true; } } if (CPad::GetPad(0)->GetEscapeJustDown()) { if (m_nCurrScreen != MENUPAGE_START_MENU) { m_bShowMouse = false; goBack = true; } } if (((goDown) || (goUp)) || (optionSelected)) { goBack = false; } #endif } // Centralized enter/back (except some conditions) #ifdef TIDY_UP_PBP if (aScreens[m_nCurrScreen].m_aEntries[m_nCurrOption].m_Action != MENUACTION_RESUME) { if (CPad::GetPad(0)->GetEnterJustDown() || CPad::GetPad(0)->GetCrossJustDown() || (isPlainTextScreen(m_nCurrScreen) && CPad::GetPad(0)->GetLeftMouseJustDown())) { if (!isPlainTextScreen(m_nCurrScreen)) m_bShowMouse = false; optionSelected = true; } } else { if (CPad::GetPad(0)->GetEnterJustUp() || CPad::GetPad(0)->GetCrossJustUp()) { m_bShowMouse = false; optionSelected = true; } } if (!goDown && !goUp && !optionSelected) { if (m_nCurrScreen != MENUPAGE_START_MENU) { if (isPlainTextScreen(m_nCurrScreen)) { if (CPad::GetPad(0)->GetEscapeJustDown() || CPad::GetPad(0)->GetBackJustUp()) { goBack = true; } } else { if (CPad::GetPad(0)->GetEscapeJustDown() || (m_nCurrScreen != MENUPAGE_PAUSE_MENU && CPad::GetPad(0)->GetBackJustDown())) { m_bShowMouse = false; goBack = true; } } } } #endif #ifdef PS2_LIKE_MENU if (CPad::GetPad(0)->GetLeftMouseJustDown() && hoveredBottomBarOption != -1) { DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_NAVIGATION, 0); bottomBarActive = false; curBottomBarOption = hoveredBottomBarOption; ChangeScreen(bbNames[curBottomBarOption].screenId, 0, true, false); if (bbNames[curBottomBarOption].screenId == MENUPAGE_SOUND_SETTINGS) DMAudio.PlayFrontEndTrack(m_PrefsRadioStation, 1); return; } else if (bottomBarActive) { if (CPad::GetPad(0)->GetEnterJustDown() || CPad::GetPad(0)->GetCrossJustDown()) { DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_NAVIGATION, 0); bottomBarActive = false; if (bbNames[curBottomBarOption].screenId == MENUPAGE_SOUND_SETTINGS) DMAudio.PlayFrontEndTrack(m_PrefsRadioStation, 1); return; } else if (CPad::GetPad(0)->GetLeftJustDown() || CPad::GetPad(0)->GetAnaloguePadLeft() || CPad::GetPad(0)->GetDPadLeftJustDown() || CPad::GetPad(0)->GetUpJustDown() || CPad::GetPad(0)->GetAnaloguePadUp() || CPad::GetPad(0)->GetDPadUpJustDown()) { m_bShowMouse = false; DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_NAVIGATION, 0); curBottomBarOption = ((curBottomBarOption + bbTabCount) - 1) % bbTabCount; ChangeScreen(bbNames[curBottomBarOption].screenId, 0, true, true); return; } else if (CPad::GetPad(0)->GetRightJustDown() || CPad::GetPad(0)->GetAnaloguePadRight() || CPad::GetPad(0)->GetDPadRightJustDown() || CPad::GetPad(0)->GetDownJustDown() || CPad::GetPad(0)->GetAnaloguePadDown() || CPad::GetPad(0)->GetDPadDownJustDown()) { m_bShowMouse = false; DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_NAVIGATION, 0); curBottomBarOption = ((curBottomBarOption + bbTabCount) + 1) % bbTabCount; ChangeScreen(bbNames[curBottomBarOption].screenId, 0, true, true); return; } optionSelected = false; goDown = false; goUp = false; } #endif int prevOption = m_nCurrOption; if (goDown && (m_nCurrScreen != MENUPAGE_MULTIPLAYER_FIND_GAME)) { m_nCurrOption++; if (m_nCurrOption == NUM_MENUROWS || (aScreens[m_nCurrScreen].m_aEntries[m_nCurrOption].m_Action == MENUACTION_NOTHING)) { m_nCurrOption = 0; } } if (goUp && (m_nCurrScreen != MENUPAGE_MULTIPLAYER_FIND_GAME)) { if (m_nCurrOption == (aScreens[m_nCurrScreen].m_aEntries[0].m_Action == MENUACTION_LABEL)) { while (m_nCurrOption != NUM_MENUROWS - 1 && aScreens[m_nCurrScreen].m_aEntries[m_nCurrOption + 1].m_Action != MENUACTION_NOTHING) { m_nCurrOption++; } } else { m_nCurrOption--; } } // Hide back button #ifdef PS2_LIKE_MENU if ((goUp || goDown) && m_nCurrScreen != MENUPAGE_MULTIPLAYER_FIND_GAME && strcmp(aScreens[m_nCurrScreen].m_aEntries[m_nCurrOption].m_EntryName, "FEDS_TB") == 0) m_nCurrOption = goUp ? m_nCurrOption - 1 : (aScreens[m_nCurrScreen].m_aEntries[0].m_Action == MENUACTION_LABEL); #endif if (optionSelected) { int option = aScreens[m_nCurrScreen].m_aEntries[m_nCurrOption].m_Action; if ((option == MENUACTION_CHANGEMENU) || (option == MENUACTION_POPULATESLOTS_CHANGEMENU)) { if (strcmp(aScreens[m_nCurrScreen].m_aEntries[m_nCurrOption].m_EntryName, "FEDS_TB") != 0 && strcmp(aScreens[m_nCurrScreen].m_aEntries[m_nCurrOption].m_EntryName, "FESZ_CA") != 0) { if (m_nCurrScreen == MENUPAGE_CHOOSE_DELETE_SLOT) { if (Slots[aScreens[m_nCurrScreen].m_aEntries[m_nCurrOption].m_SaveSlot - 1] == SLOT_EMPTY) DMAudio.PlayFrontEndSound(SOUND_FRONTEND_FAIL, 0); else DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_SETTING_CHANGE, 0); } else DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_NEW_PAGE, 0); } else { // This is duplicate, back button already processed below #ifndef TIDY_UP_PBP DMAudio.PlayFrontEndSound(SOUND_FRONTEND_EXIT, 0); if (m_nCurrScreen == MENUPAGE_SOUND_SETTINGS) { DMAudio.StopFrontEndTrack(); OutputDebugString("FRONTEND AUDIO TRACK STOPPED"); } #endif } } else if (option == MENUACTION_CHECKSAVE) { if (Slots[aScreens[m_nCurrScreen].m_aEntries[m_nCurrOption].m_SaveSlot - 1] == SLOT_EMPTY) { DMAudio.PlayFrontEndSound(SOUND_FRONTEND_FAIL, 0); } else { if (m_nCurrScreen != MENUPAGE_NEW_GAME_RELOAD) { DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_SETTING_CHANGE, 0); } } } else if (option != MENUACTION_CHANGEMENU && option != MENUACTION_BRIGHTNESS && option != MENUACTION_DRAWDIST && option != MENUACTION_MUSICVOLUME && option != MENUACTION_SFXVOLUME && option != MENUACTION_CHECKSAVE && option != MENUACTION_UNK24 && option != MENUACTION_MOUSESENS && option != MENUACTION_SCREENRES) { DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_SETTING_CHANGE, 0); } if ((m_nCurrScreen == MENUPAGE_KEYBOARD_CONTROLS) || (m_nCurrScreen == MENUPAGE_SKIN_SELECT)) { switch (m_nCurrExLayer) { default: goBack = true; break; case HOVEROPTION_LIST: if (m_nCurrScreen == MENUPAGE_KEYBOARD_CONTROLS) { m_bWaitingForNewKeyBind = true; m_bStartWaitingForKeyBind = true; pControlEdit = &m_KeyPressedCode; } if (m_nCurrScreen == MENUPAGE_SKIN_SELECT) { strcpy(m_PrefsSkinFile, m_aSkinName); CWorld::Players[0].SetPlayerSkin(m_PrefsSkinFile); m_nCurrExLayer = HOVEROPTION_BACK; SaveSettings(); } m_nHoverOption = HOVEROPTION_NOT_HOVERING; break; case HOVEROPTION_USESKIN: m_nHoverOption = HOVEROPTION_NOT_HOVERING; strcpy(m_PrefsSkinFile, m_aSkinName); CWorld::Players[0].SetPlayerSkin(m_PrefsSkinFile); m_nCurrExLayer = HOVEROPTION_BACK; SaveSettings(); break; } } else if (aScreens[m_nCurrScreen].m_aEntries[m_nCurrOption].m_TargetMenu == MENUPAGE_NEW_GAME_RELOAD && m_bGameNotLoaded) { DoSettingsBeforeStartingAGame(); /* } else if (m_nCurrScreen == MENUPAGE_KEYBOARD_CONTROLS) { // .. either empty or there was some outer if. :shrug: pointless anyway, keyboard_controls is handled in first if. */ } else if (m_nCurrScreen == MENUPAGE_SKIN_SELECT) { if (m_nSkinsTotal > 0) { m_pSelectedSkin = m_pSkinListHead.nextSkin; strcpy(m_PrefsSkinFile, m_aSkinName); CWorld::Players[0].SetPlayerSkin(m_PrefsSkinFile); SaveSettings(); } else { #ifndef TIDY_UP_PBP ChangeScreen(!m_bGameNotLoaded ? aScreens[m_nCurrScreen].m_PreviousPage[1] : aScreens[m_nCurrScreen].m_PreviousPage[0], GetPreviousPageOption(), true, true); #else goBack = true; #endif } } else if (m_nCurrScreen != MENUPAGE_MULTIPLAYER_FIND_GAME) { option = aScreens[m_nCurrScreen].m_aEntries[m_nCurrOption].m_Action; switch (option) { case MENUACTION_RADIO: #ifdef TIDY_UP_PBP assumeIncrease = true; #else ++m_PrefsRadioStation; if (DMAudio.IsMP3RadioChannelAvailable()) { if (m_PrefsRadioStation > USERTRACK) m_PrefsRadioStation = HEAD_RADIO; } else if (m_PrefsRadioStation > CHATTERBOX) { m_PrefsRadioStation = USERTRACK; } SaveSettings(); DMAudio.SetRadioInCar(m_PrefsRadioStation); DMAudio.PlayFrontEndTrack(m_PrefsRadioStation, 1); OutputDebugString("FRONTEND RADIO STATION CHANGED"); #endif break; case MENUACTION_LANG_ENG: m_PrefsLanguage = LANGUAGE_AMERICAN; m_bFrontEnd_ReloadObrTxtGxt = true; InitialiseChangedLanguageSettings(); SaveSettings(); break; case MENUACTION_LANG_FRE: m_PrefsLanguage = LANGUAGE_FRENCH; m_bFrontEnd_ReloadObrTxtGxt = true; InitialiseChangedLanguageSettings(); SaveSettings(); break; case MENUACTION_LANG_GER: m_PrefsLanguage = LANGUAGE_GERMAN; m_bFrontEnd_ReloadObrTxtGxt = true; InitialiseChangedLanguageSettings(); SaveSettings(); break; case MENUACTION_LANG_ITA: m_PrefsLanguage = LANGUAGE_ITALIAN; m_bFrontEnd_ReloadObrTxtGxt = true; InitialiseChangedLanguageSettings(); SaveSettings(); break; case MENUACTION_LANG_SPA: m_PrefsLanguage = LANGUAGE_SPANISH; m_bFrontEnd_ReloadObrTxtGxt = true; InitialiseChangedLanguageSettings(); SaveSettings(); break; case MENUACTION_POPULATESLOTS_CHANGEMENU: PcSaveHelper.PopulateSlotInfo(); // fall through case MENUACTION_CHANGEMENU: { bool changeMenu = true; int saveSlot = aScreens[m_nCurrScreen].m_aEntries[m_nCurrOption].m_SaveSlot; // This should be unused. if (saveSlot >= 2 && saveSlot <= 9) { m_nCurrSaveSlot = saveSlot - 2; switch (m_nCurrScreen) { case MENUPAGE_CHOOSE_LOAD_SLOT: if (Slots[m_nCurrSaveSlot + 1] != SLOT_EMPTY) changeMenu = false; break; case MENUPAGE_CHOOSE_DELETE_SLOT: if (Slots[m_nCurrSaveSlot + 1] == SLOT_EMPTY) changeMenu = false; break; } } if (changeMenu) { if (strcmp(aScreens[m_nCurrScreen].m_aEntries[m_nCurrOption].m_EntryName, "FEDS_TB") == 0) { #ifndef TIDY_UP_PBP ResetHelperText(); ChangeScreen(!m_bGameNotLoaded ? aScreens[m_nCurrScreen].m_PreviousPage[1] : aScreens[m_nCurrScreen].m_PreviousPage[0], GetPreviousPageOption(), true, true); #else goBack = true; break; #endif } else { ChangeScreen(aScreens[m_nCurrScreen].m_aEntries[m_nCurrOption].m_TargetMenu, 0, true, true); } } break; } case MENUACTION_CHECKSAVE: { int saveSlot = aScreens[m_nCurrScreen].m_aEntries[m_nCurrOption].m_SaveSlot; if (saveSlot >= 2 && saveSlot <= 9) { m_nCurrSaveSlot = saveSlot - 2; if (Slots[m_nCurrSaveSlot + 1] != SLOT_EMPTY && Slots[m_nCurrSaveSlot + 1] != SLOT_CORRUPTED) { ChangeScreen(aScreens[m_nCurrScreen].m_aEntries[m_nCurrOption].m_TargetMenu, 0, true, true); } } break; } case MENUACTION_NEWGAME: DoSettingsBeforeStartingAGame(); break; case MENUACTION_RELOADIDE: CFileLoader::ReloadObjectTypes("GTA3.IDE"); break; case MENUACTION_RELOADIPL: CGame::ReloadIPLs(); break; case MENUACTION_SHOWCULL: gbShowCullZoneDebugStuff = !gbShowCullZoneDebugStuff; break; case MENUACTION_MEMCARDSAVECONFIRM: return; case MENUACTION_RESUME_FROM_SAVEZONE: RequestFrontEndShutDown(); break; case MENUACTION_MPMAP_LIBERTY: case MENUACTION_MPMAP_REDLIGHT: case MENUACTION_MPMAP_CHINATOWN: case MENUACTION_MPMAP_TOWER: case MENUACTION_MPMAP_SEWER: case MENUACTION_MPMAP_INDUSTPARK: case MENUACTION_MPMAP_DOCKS: case MENUACTION_MPMAP_STAUNTON: m_SelectedMap = option - MENUACTION_MPMAP_LIBERTY; SaveSettings(); ChangeScreen(aScreens[m_nCurrScreen].m_aEntries[m_nCurrOption].m_TargetMenu, 0, true, true); break; case MENUACTION_MPMAP_DEATHMATCH1: case MENUACTION_MPMAP_DEATHMATCH2: case MENUACTION_MPMAP_TEAMDEATH1: case MENUACTION_MPMAP_TEAMDEATH2: case MENUACTION_MPMAP_STASH: case MENUACTION_MPMAP_CAPTURE: case MENUACTION_MPMAP_RATRACE: case MENUACTION_MPMAP_DOMINATION: m_SelectedGameType = option - MENUACTION_MPMAP_DEATHMATCH1; SaveSettings(); ChangeScreen(aScreens[m_nCurrScreen].m_aEntries[m_nCurrOption].m_TargetMenu, 0, true, true); break; case MENUACTION_KEYBOARDCTRLS: ChangeScreen(MENUPAGE_KEYBOARD_CONTROLS, 0, true, true); m_nSelectedListRow = 0; m_nCurrExLayer = HOVEROPTION_LIST; break; case MENUACTION_GETKEY: m_CurrCntrlAction = GetStartOptionsCntrlConfigScreens() + m_nCurrOption; m_bKeyIsOK = true; m_bWaitingForNewKeyBind = true; m_bStartWaitingForKeyBind = true; pControlEdit = &m_KeyPressedCode; break; case MENUACTION_CANCELGAME: DMAudio.Service(); RsEventHandler(rsQUITAPP, nil); break; case MENUACTION_RESUME: #ifndef TIDY_UP_PBP if (m_PrefsVsyncDisp != m_PrefsVsync) { m_PrefsVsync = m_PrefsVsyncDisp; } RequestFrontEndShutDown(); #else goBack = true; #endif break; case MENUACTION_DONTCANCEL: ChangeScreen(!m_bGameNotLoaded ? aScreens[m_nCurrScreen].m_PreviousPage[1] : aScreens[m_nCurrScreen].m_PreviousPage[0], GetPreviousPageOption(), true, true); break; case MENUACTION_SCREENRES: if (m_nDisplayVideoMode != m_nPrefsVideoMode) { m_nPrefsVideoMode = m_nDisplayVideoMode; _psSelectScreenVM(m_nPrefsVideoMode); SetHelperText(0); SaveSettings(); } break; case MENUACTION_AUDIOHW: { int selectedProvider = m_nPrefsAudio3DProviderIndex; if (selectedProvider != -1) { m_nPrefsAudio3DProviderIndex = DMAudio.SetCurrent3DProvider(m_nPrefsAudio3DProviderIndex); if (selectedProvider == m_nPrefsAudio3DProviderIndex) { DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_SETTING_CHANGE, 0); SetHelperText(0); } else { DMAudio.PlayFrontEndSound(SOUND_FRONTEND_FAIL, 0); SetHelperText(4); } SaveSettings(); } break; } case MENUACTION_SPEAKERCONF: #ifndef TIDY_UP_PBP if (m_nPrefsAudio3DProviderIndex != -1) { if (--m_PrefsSpeakers < 0) m_PrefsSpeakers = 2; DMAudio.SetSpeakerConfig(m_PrefsSpeakers); SaveSettings(); } #else assumeIncrease = true; #endif break; case MENUACTION_PLAYERSETUP: CPlayerSkin::BeginFrontendSkinEdit(); ChangeScreen(MENUPAGE_SKIN_SELECT, 0, true, true); m_nCurrExLayer = HOVEROPTION_LIST; m_bSkinsEnumerated = false; break; case MENUACTION_RESTOREDEF: if (m_nCurrScreen == MENUPAGE_SOUND_SETTINGS) { m_PrefsSfxVolume = 102; m_PrefsSpeakers = 0; m_PrefsMusicVolume = 102; m_PrefsStereoMono = 0; m_PrefsRadioStation = HEAD_RADIO; DMAudio.SetMusicMasterVolume(102); DMAudio.SetEffectsMasterVolume(m_PrefsSfxVolume); DMAudio.SetRadioInCar(m_PrefsRadioStation); DMAudio.PlayFrontEndTrack(m_PrefsRadioStation, 1); SaveSettings(); } else if (m_nCurrScreen == MENUPAGE_DISPLAY_SETTINGS) { m_PrefsFrameLimiter = true; m_PrefsBrightness = 256; m_PrefsVsyncDisp = true; m_PrefsLOD = 1.2f; m_PrefsVsync = true; CRenderer::ms_lodDistScale = 1.2f; #ifdef ASPECT_RATIO_SCALE m_PrefsUseWideScreen = AR_AUTO; #else m_PrefsUseWideScreen = false; #endif m_PrefsShowSubtitles = true; m_nDisplayVideoMode = m_nPrefsVideoMode; #if GTA_VERSION >= GTA3_PC_11 if (_dwOperatingSystemVersion == OS_WIN98) { CMBlur::BlurOn = false; CMBlur::MotionBlurClose(); } else { CMBlur::BlurOn = true; CMBlur::MotionBlurOpen(Scene.camera); } #else CMBlur::BlurOn = true; #endif #ifdef CUSTOM_FRONTEND_OPTIONS extern void RestoreDefGraphics(int8); extern void RestoreDefDisplay(int8); RestoreDefGraphics(FEOPTION_ACTION_SELECT); RestoreDefDisplay(FEOPTION_ACTION_SELECT); #endif SaveSettings(); } else if ((m_nCurrScreen != MENUPAGE_SKIN_SELECT_OLD) && (m_nCurrScreen == MENUPAGE_CONTROLLER_PC)) { ControlsManager.MakeControllerActionsBlank(); ControlsManager.InitDefaultControlConfiguration(); ControlsManager.InitDefaultControlConfigMouse(MousePointerStateHelper.GetMouseSetUp()); #if !defined RW_GL3 if (AllValidWinJoys.m_aJoys[JOYSTICK1].m_bInitialised) { DIDEVCAPS devCaps; devCaps.dwSize = sizeof(DIDEVCAPS); PSGLOBAL(joy1)->GetCapabilities(&devCaps); ControlsManager.InitDefaultControlConfigJoyPad(devCaps.dwButtons); } #else if (PSGLOBAL(joy1id) != -1 && glfwJoystickPresent(PSGLOBAL(joy1id))) { int count; glfwGetJoystickButtons(PSGLOBAL(joy1id), &count); ControlsManager.InitDefaultControlConfigJoyPad(count); } #endif m_ControlMethod = CONTROL_STANDARD; #ifdef FIX_BUGS MousePointerStateHelper.bInvertVertically = true; TheCamera.m_fMouseAccelVertical = 0.003f; #else MousePointerStateHelper.bInvertVertically = false; #endif TheCamera.m_fMouseAccelHorzntl = 0.0025f; CVehicle::m_bDisableMouseSteering = true; TheCamera.m_bHeadBob = false; SaveSettings(); #ifdef LOAD_INI_SETTINGS SaveINIControllerSettings(); #endif } SetHelperText(2); break; case MENUACTION_CTRLMETHOD: #ifndef TIDY_UP_PBP if (m_ControlMethod == CONTROL_CLASSIC) { CCamera::m_bUseMouse3rdPerson = true; m_ControlMethod = CONTROL_STANDARD; } else { CCamera::m_bUseMouse3rdPerson = false; m_ControlMethod = CONTROL_CLASSIC; } SaveSettings(); #else assumeIncrease = true; #endif break; case MENUACTION_LOADRADIO: ChangeScreen(MENUPAGE_SOUND_SETTINGS, 0, true, true); DMAudio.PlayFrontEndTrack(m_PrefsRadioStation, 1); OutputDebugString("STARTED PLAYING FRONTEND AUDIO TRACK"); break; #ifdef MISSION_REPLAY case MENUACTION_REJECT_RETRY: doingMissionRetry = false; AllowMissionReplay = 0; RequestFrontEndShutDown(); break; case MENUACTION_UNK114: doingMissionRetry = false; RequestFrontEndShutDown(); RetryMission(2, 0); return; #endif #ifdef CUSTOM_FRONTEND_OPTIONS case MENUACTION_CFO_SELECT: case MENUACTION_CFO_DYNAMIC: CMenuScreenCustom::CMenuEntry &option = aScreens[m_nCurrScreen].m_aEntries[m_nCurrOption]; if (option.m_Action == MENUACTION_CFO_SELECT) { if (option.m_CFOSelect->disableIfGameLoaded && !m_bGameNotLoaded) break; if (!option.m_CFOSelect->onlyApplyOnEnter) { option.m_CFOSelect->displayedValue++; if (option.m_CFOSelect->displayedValue >= option.m_CFOSelect->numRightTexts || option.m_CFOSelect->displayedValue < 0) option.m_CFOSelect->displayedValue = 0; } int8 oldValue = *option.m_CFO->value; *option.m_CFO->value = option.m_CFOSelect->lastSavedValue = option.m_CFOSelect->displayedValue; // Now everything is saved in .ini, and LOAD_INI_SETTINGS is fundamental for CFO // if (option.m_CFOSelect->save) SaveSettings(); if (option.m_CFOSelect->displayedValue != oldValue && option.m_CFOSelect->changeFunc) option.m_CFOSelect->changeFunc(oldValue, option.m_CFOSelect->displayedValue); } else if (option.m_Action == MENUACTION_CFO_DYNAMIC) { if (option.m_CFODynamic->buttonPressFunc) option.m_CFODynamic->buttonPressFunc(FEOPTION_ACTION_SELECT); } break; #endif } } ProcessOnOffMenuOptions(); } if (goBack) { ResetHelperText(); DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_BACK, 0); #ifdef PS2_LIKE_MENU if (m_nCurrScreen == MENUPAGE_PAUSE_MENU || bottomBarActive) { #else if (m_nCurrScreen == MENUPAGE_PAUSE_MENU) { #endif if (!m_bGameNotLoaded && !m_bMenuStateChanged) { if (m_PrefsVsyncDisp != m_PrefsVsync) { m_PrefsVsync = m_PrefsVsyncDisp; } RequestFrontEndShutDown(); } // We're already resuming, we don't need further processing. #if defined(FIX_BUGS) || defined(PS2_LIKE_MENU) return; #endif } #ifdef PS2_SAVE_DIALOG else if (m_nCurrScreen == MENUPAGE_CHOOSE_SAVE_SLOT || m_nCurrScreen == MENUPAGE_SAVE) { #else else if (m_nCurrScreen == MENUPAGE_CHOOSE_SAVE_SLOT) { #endif RequestFrontEndShutDown(); } // It's now in ThingsToDoBeforeGoingBack() #ifndef TIDY_UP_PBP else if (m_nCurrScreen == MENUPAGE_SOUND_SETTINGS) { DMAudio.StopFrontEndTrack(); OutputDebugString("FRONTEND AUDIO TRACK STOPPED"); } #endif int oldScreen = !m_bGameNotLoaded ? aScreens[m_nCurrScreen].m_PreviousPage[1] : aScreens[m_nCurrScreen].m_PreviousPage[0]; int oldOption = GetPreviousPageOption(); if (oldScreen != -1) { ThingsToDoBeforeGoingBack(); #ifdef PS2_LIKE_MENU if (!bottomBarActive && (oldScreen == MENUPAGE_NONE || oldScreen == MENUPAGE_OPTIONS)) { bottomBarActive = true; } else #endif { ChangeScreen(oldScreen, oldOption, true, true); } // We will go back for sure at this point, why process other things?! #ifdef FIX_BUGS return; #endif } } #ifdef PS2_LIKE_MENU if (bottomBarActive) return; #endif int changeValueBy = 0; bool decrease = false; #ifdef TIDY_UP_PBP bool increase = assumeIncrease; #else bool increase = false; #endif if (CPad::GetPad(0)->GetLeft() || CPad::GetPad(0)->GetPedWalkLeftRight() < 0 || CPad::GetPad(0)->GetDPadLeft()) { static uint32 lastSliderDecrease = 0; if (CTimer::GetTimeInMillisecondsPauseMode() - lastSliderDecrease > 150) { CheckSliderMovement(-1); lastSliderDecrease = CTimer::GetTimeInMillisecondsPauseMode(); } } else if (CPad::GetPad(0)->GetRight() || CPad::GetPad(0)->GetPedWalkLeftRight() > 0 || CPad::GetPad(0)->GetDPadRight()) { static uint32 lastSliderIncrease = 0; if (CTimer::GetTimeInMillisecondsPauseMode() - lastSliderIncrease > 150) { CheckSliderMovement(1); lastSliderIncrease = CTimer::GetTimeInMillisecondsPauseMode(); } } if (CPad::GetPad(0)->GetRightJustDown() || CPad::GetPad(0)->GetAnaloguePadRight() || CPad::GetPad(0)->GetDPadRightJustDown()) { m_bShowMouse = false; increase = true; } else if ( #ifdef SCROLLABLE_PAGES !SCREEN_HAS_AUTO_SCROLLBAR && #endif CPad::GetPad(0)->GetMouseWheelUpJustDown() && m_nCurrScreen != MENUPAGE_KEYBOARD_CONTROLS) { increase = true; CheckSliderMovement(1); m_bShowMouse = true; } if (CPad::GetPad(0)->GetLeftJustDown() || CPad::GetPad(0)->GetAnaloguePadLeft() || CPad::GetPad(0)->GetDPadLeftJustDown()) { m_bShowMouse = false; decrease = true; } else if ( #ifdef SCROLLABLE_PAGES !SCREEN_HAS_AUTO_SCROLLBAR && #endif CPad::GetPad(0)->GetMouseWheelDownJustDown() && m_nCurrScreen != MENUPAGE_KEYBOARD_CONTROLS) { decrease = true; CheckSliderMovement(-1); m_bShowMouse = true; } if (increase) changeValueBy++; else if (decrease) changeValueBy--; if (changeValueBy != 0) { switch (aScreens[m_nCurrScreen].m_aEntries[m_nCurrOption].m_Action) { #ifdef FIX_BUGS case MENUACTION_CTRLCONFIG: CPad::GetPad(0)->Mode += changeValueBy; if (CPad::GetPad(0)->Mode > 3) CPad::GetPad(0)->Mode = 0; else if (CPad::GetPad(0)->Mode < 0) CPad::GetPad(0)->Mode = 3; SaveSettings(); DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_SETTING_CHANGE, 0); break; #endif case MENUACTION_RADIO: m_PrefsRadioStation += changeValueBy; DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_SETTING_CHANGE, 0); if (DMAudio.IsMP3RadioChannelAvailable()) { if (m_PrefsRadioStation < HEAD_RADIO) m_PrefsRadioStation = USERTRACK; if (m_PrefsRadioStation > USERTRACK) m_PrefsRadioStation = HEAD_RADIO; } else { if (m_PrefsRadioStation < HEAD_RADIO) m_PrefsRadioStation = CHATTERBOX; if (m_PrefsRadioStation > CHATTERBOX) m_PrefsRadioStation = HEAD_RADIO; } SaveSettings(); DMAudio.SetRadioInCar(m_PrefsRadioStation); DMAudio.PlayFrontEndTrack(m_PrefsRadioStation, 1); OutputDebugString("FRONTEND RADIO STATION CHANGED"); break; #ifdef ASPECT_RATIO_SCALE case MENUACTION_WIDESCREEN: if (changeValueBy > 0) { m_PrefsUseWideScreen++; if (m_PrefsUseWideScreen > AR_MAX-1) m_PrefsUseWideScreen = 0; } else { m_PrefsUseWideScreen--; if (m_PrefsUseWideScreen < 0) m_PrefsUseWideScreen = AR_MAX-1; } DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_SETTING_CHANGE, 0); SaveSettings(); break; #endif case MENUACTION_SCREENRES: if (m_bGameNotLoaded) { RwChar** videoMods = _psGetVideoModeList(); DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_NAVIGATION, 0); if (changeValueBy > 0) { do { ++m_nDisplayVideoMode; if (m_nDisplayVideoMode >= _psGetNumVideModes()) m_nDisplayVideoMode = 0; } while (!videoMods[m_nDisplayVideoMode]); } else { do { --m_nDisplayVideoMode; if (m_nDisplayVideoMode < 0) m_nDisplayVideoMode = _psGetNumVideModes() - 1; } while (!videoMods[m_nDisplayVideoMode]); } } break; case MENUACTION_AUDIOHW: if (m_nPrefsAudio3DProviderIndex != -1) { m_nPrefsAudio3DProviderIndex += changeValueBy; m_nPrefsAudio3DProviderIndex = clamp(m_nPrefsAudio3DProviderIndex, 0, DMAudio.GetNum3DProvidersAvailable() - 1); } DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_NAVIGATION, 0); break; case MENUACTION_SPEAKERCONF: if (m_nPrefsAudio3DProviderIndex != -1) { m_PrefsSpeakers -= changeValueBy; m_PrefsSpeakers = clamp(m_PrefsSpeakers, 0, 2); DMAudio.SetSpeakerConfig(m_PrefsSpeakers); SaveSettings(); DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_SETTING_CHANGE, 0); } break; case MENUACTION_CTRLMETHOD: m_ControlMethod = !m_ControlMethod; CCamera::m_bUseMouse3rdPerson = !m_ControlMethod; DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_SETTING_CHANGE, 0); SaveSettings(); break; #ifdef CUSTOM_FRONTEND_OPTIONS case MENUACTION_CFO_SELECT: case MENUACTION_CFO_DYNAMIC: CMenuScreenCustom::CMenuEntry &option = aScreens[m_nCurrScreen].m_aEntries[m_nCurrOption]; if (option.m_Action == MENUACTION_CFO_SELECT) { if (option.m_CFOSelect->disableIfGameLoaded && !m_bGameNotLoaded) break; if (changeValueBy > 0) { option.m_CFOSelect->displayedValue++; if (option.m_CFOSelect->displayedValue >= option.m_CFOSelect->numRightTexts) option.m_CFOSelect->displayedValue = 0; } else { option.m_CFOSelect->displayedValue--; if (option.m_CFOSelect->displayedValue < 0) option.m_CFOSelect->displayedValue = option.m_CFOSelect->numRightTexts - 1; } if (!option.m_CFOSelect->onlyApplyOnEnter) { int8 oldValue = *option.m_CFO->value; *option.m_CFO->value = option.m_CFOSelect->lastSavedValue = option.m_CFOSelect->displayedValue; // Now everything is saved in .ini, and LOAD_INI_SETTINGS is fundamental for CFO // if (option.m_CFOSelect->save) SaveSettings(); if (option.m_CFOSelect->displayedValue != oldValue && option.m_CFOSelect->changeFunc) option.m_CFOSelect->changeFunc(oldValue, option.m_CFOSelect->displayedValue); } } else if (option.m_Action == MENUACTION_CFO_DYNAMIC && option.m_CFODynamic->buttonPressFunc) { option.m_CFODynamic->buttonPressFunc(changeValueBy > 0 ? FEOPTION_ACTION_RIGHT : FEOPTION_ACTION_LEFT); } DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_SETTING_CHANGE, 0); break; #endif } ProcessOnOffMenuOptions(); if (m_nCurrScreen == MENUPAGE_KEYBOARD_CONTROLS) { if (changeValueBy < 1) { m_nSelectedContSetupColumn = CONTSETUP_PED_COLUMN; } else { m_nSelectedContSetupColumn = CONTSETUP_VEHICLE_COLUMN; } DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_NAVIGATION, 0); } } } void CMenuManager::ProcessOnOffMenuOptions() { switch (aScreens[m_nCurrScreen].m_aEntries[m_nCurrOption].m_Action) { case MENUACTION_CTRLVIBRATION: m_PrefsUseVibration = !m_PrefsUseVibration; if (m_PrefsUseVibration) { CPad::GetPad(0)->StartShake(350, 150); TimeToStopPadShaking = CTimer::GetTimeInMillisecondsPauseMode() + 500; } DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_SETTING_CHANGE, 0); #ifdef FIX_BUGS SaveSettings(); #endif // !FIX_BUGS break; #ifndef FIX_BUGS case MENUACTION_CTRLCONFIG: CPad::GetPad(0)->Mode++; if (CPad::GetPad(0)->Mode > 3) CPad::GetPad(0)->Mode = 0; DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_SETTING_CHANGE, 0); break; #endif // !FIX_BUGS case MENUACTION_CTRLDISPLAY: m_DisplayControllerOnFoot = !m_DisplayControllerOnFoot; DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_SETTING_CHANGE, 0); break; case MENUACTION_FRAMESYNC: m_PrefsVsyncDisp = !m_PrefsVsyncDisp; DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_SETTING_CHANGE, 0); SaveSettings(); break; case MENUACTION_FRAMELIMIT: m_PrefsFrameLimiter = !m_PrefsFrameLimiter; DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_SETTING_CHANGE, 0); SaveSettings(); break; case MENUACTION_TRAILS: CMBlur::BlurOn = !CMBlur::BlurOn; DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_SETTING_CHANGE, 0); SaveSettings(); if (CMBlur::BlurOn) CMBlur::MotionBlurOpen(Scene.camera); else CMBlur::MotionBlurClose(); break; case MENUACTION_SUBTITLES: m_PrefsShowSubtitles = !m_PrefsShowSubtitles; DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_SETTING_CHANGE, 0); SaveSettings(); break; #ifndef ASPECT_RATIO_SCALE case MENUACTION_WIDESCREEN: m_PrefsUseWideScreen = !m_PrefsUseWideScreen; DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_SETTING_CHANGE, 0); SaveSettings(); break; #endif case MENUACTION_SETDBGFLAG: CTheScripts::InvertDebugFlag(); DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_SETTING_CHANGE, 0); break; case MENUACTION_SWITCHBIGWHITEDEBUGLIGHT: gbBigWhiteDebugLightSwitchedOn = !gbBigWhiteDebugLightSwitchedOn; DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_SETTING_CHANGE, 0); break; case MENUACTION_PEDROADGROUPS: gbShowPedRoadGroups = !gbShowPedRoadGroups; DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_SETTING_CHANGE, 0); break; case MENUACTION_CARROADGROUPS: gbShowCarRoadGroups = !gbShowCarRoadGroups; DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_SETTING_CHANGE, 0); break; case MENUACTION_COLLISIONPOLYS: gbShowCollisionPolys = !gbShowCollisionPolys; DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_SETTING_CHANGE, 0); break; case MENUACTION_MP_PLAYERCOLOR: PickNewPlayerColour(); DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_SETTING_CHANGE, 0); SaveSettings(); break; case MENUACTION_SHOWHEADBOB: TheCamera.m_bHeadBob = !TheCamera.m_bHeadBob; DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_SETTING_CHANGE, 0); SaveSettings(); break; case MENUACTION_INVVERT: MousePointerStateHelper.bInvertVertically = !MousePointerStateHelper.bInvertVertically; DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_SETTING_CHANGE, 0); SaveSettings(); break; case MENUACTION_DYNAMICACOUSTIC: m_PrefsDMA = !m_PrefsDMA; DMAudio.SetDynamicAcousticModelingStatus(m_PrefsDMA); DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_SETTING_CHANGE, 0); SaveSettings(); break; case MENUACTION_MOUSESTEER: CVehicle::m_bDisableMouseSteering = !CVehicle::m_bDisableMouseSteering; DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_SETTING_CHANGE, 0); SaveSettings(); break; } } void CMenuManager::RequestFrontEndShutDown() { m_bShutDownFrontEndRequested = true; DMAudio.ChangeMusicMode(MUSICMODE_GAME); } void CMenuManager::RequestFrontEndStartUp() { m_bStartUpFrontEndRequested = true; } void CMenuManager::ResetHelperText() { m_nHelperTextMsgId = 0; m_nHelperTextAlpha = 300; } void CMenuManager::SaveLoadFileError_SetUpErrorScreen() { switch (PcSaveHelper.nErrorCode) { case SAVESTATUS_ERR_SAVE_CREATE: case SAVESTATUS_ERR_SAVE_WRITE: case SAVESTATUS_ERR_SAVE_CLOSE: ChangeScreen(MENUPAGE_SAVE_FAILED, 0, true, false); break; case SAVESTATUS_ERR_LOAD_OPEN: case SAVESTATUS_ERR_LOAD_READ: case SAVESTATUS_ERR_LOAD_CLOSE: ChangeScreen(MENUPAGE_LOAD_FAILED, 0, true, false); break; case SAVESTATUS_ERR_DATA_INVALID: ChangeScreen(MENUPAGE_LOAD_FAILED_2, 0, true, false); break; case SAVESTATUS_DELETEFAILED8: case SAVESTATUS_DELETEFAILED9: case SAVESTATUS_DELETEFAILED10: ChangeScreen(MENUPAGE_DELETE_FAILED, 0, true, false); break; default: break; } } void CMenuManager::SetHelperText(int text) { m_nHelperTextMsgId = text; m_nHelperTextAlpha = 300; } void CMenuManager::ShutdownJustMenu() { // In case we're windowed, keep mouse centered while in game. Done in main.cpp in other conditions. #if defined(RW_GL3) && defined(IMPROVED_VIDEOMODE) glfwSetInputMode(PSGLOBAL(window), GLFW_CURSOR, GLFW_CURSOR_DISABLED); #endif m_bMenuActive = false; CTimer::EndUserPause(); } float CMenuManager::StretchX(float x) { if (SCREEN_WIDTH == DEFAULT_SCREEN_WIDTH) return x; else // We won't make this SCREEN_SCALE, because many cases relies on stretching and we want the code to be portable. // Instead we will use MENU_X_LEFT_ALIGNED or SCREEN_SCALE_X when needed. return SCREEN_STRETCH_X(x); } float CMenuManager::StretchY(float y) { if (SCREEN_HEIGHT == DEFAULT_SCREEN_HEIGHT) return y; else return SCREEN_STRETCH_Y(y); } void CMenuManager::SwitchMenuOnAndOff() { bool menuWasActive = GetIsMenuActive(); // Reminder: You need REGISTER_START_BUTTON defined to make it work. if (CPad::GetPad(0)->GetStartJustDown() #ifdef FIX_BUGS && !m_bGameNotLoaded #endif || m_bShutDownFrontEndRequested || m_bStartUpFrontEndRequested) { m_bMenuActive = !m_bMenuActive; #ifdef FIX_BUGS CPad::StopPadsShaking(); #endif if (m_bShutDownFrontEndRequested) m_bMenuActive = false; if (m_bStartUpFrontEndRequested) m_bMenuActive = true; if (m_bMenuActive) { CTimer::StartUserPause(); } else { #ifdef PS2_LIKE_MENU bottomBarActive = false; #endif #ifdef FIX_BUGS ThingsToDoBeforeGoingBack(); #endif ShutdownJustMenu(); SaveSettings(); #ifdef LOAD_INI_SETTINGS SaveINIControllerSettings(); #endif m_bStartUpFrontEndRequested = false; pControlEdit = nil; m_bShutDownFrontEndRequested = false; DisplayComboButtonErrMsg = false; #ifdef REGISTER_START_BUTTON int16 start1 = CPad::GetPad(0)->PCTempJoyState.Start, start2 = CPad::GetPad(0)->PCTempKeyState.Start, start3 = CPad::GetPad(0)->OldState.Start, start4 = CPad::GetPad(0)->NewState.Start; #endif CPad::GetPad(0)->Clear(false); CPad::GetPad(1)->Clear(false); #ifdef REGISTER_START_BUTTON CPad::GetPad(0)->PCTempJoyState.Start = start1; CPad::GetPad(0)->PCTempKeyState.Start = start2; CPad::GetPad(0)->OldState.Start = start3; CPad::GetPad(0)->NewState.Start = start4; #endif m_nCurrScreen = MENUPAGE_NONE; } } // Just entered the save/safe zone if (m_bSaveMenuActive && !m_bQuitGameNoCD) { m_bSaveMenuActive = false; m_bMenuActive = true; CTimer::StartUserPause(); #ifdef PS2_SAVE_DIALOG m_nCurrScreen = MENUPAGE_SAVE; m_bRenderGameInMenu = true; #else m_nCurrScreen = MENUPAGE_CHOOSE_SAVE_SLOT; #endif PcSaveHelper.PopulateSlotInfo(); m_nCurrOption = 0; } /* // PS2 leftover if (m_nCurrScreen != MENUPAGE_SOUND_SETTINGS && gMusicPlaying) { DMAudio.StopFrontEndTrack(); OutputDebugString("FRONTEND AUDIO TRACK STOPPED"); gMusicPlaying = 0; } */ if (m_bMenuActive != menuWasActive) { m_bMenuStateChanged = true; // In case we're windowed, keep mouse centered while in game. Done in main.cpp in other conditions. #if defined(RW_GL3) && defined(IMPROVED_VIDEOMODE) glfwSetInputMode(PSGLOBAL(window), GLFW_CURSOR, m_bMenuActive && m_nPrefsWindowed ? GLFW_CURSOR_HIDDEN : GLFW_CURSOR_DISABLED); #endif } m_bStartUpFrontEndRequested = false; m_bShutDownFrontEndRequested = false; } void CMenuManager::UnloadTextures() { if (!m_bSpritesLoaded) return; printf("REMOVE frontend\n"); for (int i = 0; i < ARRAY_SIZE(FrontendFilenames); ++i) m_aFrontEndSprites[i].Delete(); int frontend = CTxdStore::FindTxdSlot("frontend"); CTxdStore::RemoveTxd(frontend); #ifdef GAMEPAD_MENU int frontend_controllerTxdSlot = CTxdStore::FindTxdSlot("frontend_controller"); if (frontend_controllerTxdSlot != -1) CTxdStore::RemoveTxd(frontend_controllerTxdSlot); #endif printf("REMOVE menu textures\n"); for (int i = 0; i < ARRAY_SIZE(MenuFilenames); ++i) m_aMenuSprites[i].Delete(); #ifdef MENU_MAP for (int i = 0; i < ARRAY_SIZE(MapFilenames); ++i) m_aMapSprites[i].Delete(); #endif int menu = CTxdStore::FindTxdSlot("menu"); CTxdStore::RemoveTxd(menu); m_bSpritesLoaded = false; } void CMenuManager::WaitForUserCD() { CSprite2d *splash; char *splashscreen = nil; #if (!(defined RANDOMSPLASH) && GTA_VERSION < GTA3_PC_11) if (CGame::frenchGame || CGame::germanGame || !CGame::nastyGame) splashscreen = "mainsc2"; else splashscreen = "mainsc1"; #endif splash = LoadSplash(splashscreen); if (RsGlobal.quit) return; HandleExit(); CPad::UpdatePads(); MessageScreen("NO_PCCD"); if (CPad::GetPad(0)->GetEscapeJustDown()) { m_bQuitGameNoCD = true; RsEventHandler(rsQUITAPP, nil); } } #ifdef GAMEPAD_MENU void CMenuManager::PrintController(void) { const float scale = 0.9f; const float CONTROLLER_SIZE_X = 235.2f; const float CONTROLLER_SIZE_Y = 175.2f; const float CONTROLLER_POS_X = (DEFAULT_SCREEN_WIDTH - CONTROLLER_SIZE_X) / 2.0f; const float CONTROLLER_POS_Y = 160.0f; float centerX = CONTROLLER_POS_X + CONTROLLER_SIZE_X / 2; float centerY = CONTROLLER_POS_Y + CONTROLLER_SIZE_Y / 2; #define X(f) ((f)*scale + centerX) #define Y(f) ((f)*scale + centerY) m_aFrontEndSprites[FE_CONTROLLERSH].Draw(MENU_X_LEFT_ALIGNED(X(-CONTROLLER_SIZE_X / 2)), MENU_Y(Y(-CONTROLLER_SIZE_Y / 2)), MENU_X((CONTROLLER_SIZE_X + 4.8f) * scale), MENU_Y((CONTROLLER_SIZE_Y + 4.8f) * scale), CRGBA(0, 0, 0, 255)); m_aFrontEndSprites[FE_CONTROLLER].Draw(MENU_X_LEFT_ALIGNED(X(-CONTROLLER_SIZE_X / 2)), MENU_Y(Y(-CONTROLLER_SIZE_Y / 2)), MENU_X(CONTROLLER_SIZE_X * scale), MENU_Y(CONTROLLER_SIZE_Y * scale), CRGBA(255, 255, 255, 255)); if (m_DisplayControllerOnFoot) { if (CTimer::GetTimeInMillisecondsPauseMode() & 0x400) m_aFrontEndSprites[FE_ARROWS1].Draw(MENU_X_LEFT_ALIGNED(X(-CONTROLLER_SIZE_X / 2)), MENU_Y(Y(-CONTROLLER_SIZE_Y / 2)), MENU_X(CONTROLLER_SIZE_X * scale), MENU_Y(CONTROLLER_SIZE_Y * scale), CRGBA(255, 255, 255, 255)); else m_aFrontEndSprites[FE_ARROWS3].Draw(MENU_X_LEFT_ALIGNED(X(-CONTROLLER_SIZE_X / 2)), MENU_Y(Y(-CONTROLLER_SIZE_Y / 2)), MENU_X(CONTROLLER_SIZE_X * scale), MENU_Y(CONTROLLER_SIZE_Y * scale), CRGBA(255, 255, 255, 255)); } else { if (CTimer::GetTimeInMillisecondsPauseMode() & 0x400) m_aFrontEndSprites[FE_ARROWS2].Draw(MENU_X_LEFT_ALIGNED(X(-CONTROLLER_SIZE_X / 2)), MENU_Y(Y(-CONTROLLER_SIZE_Y / 2)), MENU_X(CONTROLLER_SIZE_X * scale), MENU_Y(CONTROLLER_SIZE_Y * scale), CRGBA(255, 255, 255, 255)); else m_aFrontEndSprites[FE_ARROWS4].Draw(MENU_X_LEFT_ALIGNED(X(-CONTROLLER_SIZE_X / 2)), MENU_Y(Y(-CONTROLLER_SIZE_Y / 2)), MENU_X(CONTROLLER_SIZE_X * scale), MENU_Y(CONTROLLER_SIZE_Y * scale), CRGBA(255, 255, 255, 255)); } CFont::SetFontStyle(FONT_LOCALE(FONT_BANK)); CFont::SetScale(MENU_X(SMALLESTTEXT_X_SCALE * scale), MENU_Y(SMALLESTTEXT_Y_SCALE * scale)); // X // CFont::SetColor(CRGBA(128, 128, 128, FadeIn(255))); CFont::SetDropColor(CRGBA(0, 0, 0, FadeIn(255))); CFont::SetDropShadowPosition(1); CFont::SetColor(CRGBA(255, 255, 255, FadeIn(255))); CFont::SetWrapx(SCREEN_WIDTH); float TEXT_L2_X = 50.0f + CONTROLLER_POS_X - centerX, TEXT_L2_Y = -14.0f + CONTROLLER_POS_Y - centerY; float TEXT_L1_X = -4.0f + CONTROLLER_POS_X - centerX, TEXT_L1_Y = 25.0f + CONTROLLER_POS_Y - centerY, TEXT_L1_Y_VEH = 3.0f + TEXT_L1_Y; float TEXT_DPAD_X = -4.0f + CONTROLLER_POS_X - centerX, TEXT_DPAD_Y = 65.0f + CONTROLLER_POS_Y - centerY; float TEXT_LSTICK_X = -4.0f + CONTROLLER_POS_X - centerX, TEXT_LSTICK_Y = 97.0f + CONTROLLER_POS_Y - centerY; float TEXT_SELECT_X = 103.0f + CONTROLLER_POS_X - centerX, TEXT_SELECT_Y = 141.0f + CONTROLLER_POS_Y - centerY; float TEXT_START_X = 130.0f + CONTROLLER_POS_X - centerX, TEXT_START_Y = 128.0f + CONTROLLER_POS_Y - centerY; float TEXT_R2_X = 184.0F + CONTROLLER_POS_X - centerX, TEXT_R2_Y = -14.0f + CONTROLLER_POS_Y - centerY; float TEXT_R1_X = 238.0f + CONTROLLER_POS_X - centerX, TEXT_R1_Y = 25.0f + CONTROLLER_POS_Y - centerY; float TEXT_SQUARE_X = 144.0f + CONTROLLER_POS_X - centerX, TEXT_SQUARE_Y = 18.0f + CONTROLLER_POS_Y - centerY; float TEXT_TRIANGLE_X = 238.0f + CONTROLLER_POS_X - centerX, TEXT_TRIANGLE_Y = 52.0f + CONTROLLER_POS_Y - centerY; float TEXT_CIRCLE_X = 238.0f + CONTROLLER_POS_X - centerX, TEXT_CIRCLE_Y = 65.0f + CONTROLLER_POS_Y - centerY; float TEXT_CROSS_X = 238.0f + CONTROLLER_POS_X - centerX, TEXT_CROSS_Y = 78.0f + CONTROLLER_POS_Y - centerY; float TEXT_RSTICK_X = 238.0f + CONTROLLER_POS_X - centerX, TEXT_RSTICK_Y = 94.0f + CONTROLLER_POS_Y - centerY; float TEXT_R3_X = 238.0f + CONTROLLER_POS_X - centerX, TEXT_R3_Y = 109.0f + CONTROLLER_POS_Y - centerY; float TEXT_L3_X = 84.0f + CONTROLLER_POS_X - centerX, TEXT_L3_Y = 162.0f + CONTROLLER_POS_Y - centerY; float TEXT_L2R2_X = 74.0f + CONTROLLER_POS_X - centerX, TEXT_L2R2_Y = -6.0f + CONTROLLER_POS_Y - centerY; switch (m_PrefsControllerType) { case CONTROLLER_DUALSHOCK4: TEXT_L1_Y += 7.0f; TEXT_L1_Y_VEH = TEXT_L1_Y; TEXT_R1_Y += 7.0f; TEXT_TRIANGLE_Y -= 1.0f; TEXT_CIRCLE_Y -= 1.0f; TEXT_CROSS_Y -= 1.0f; TEXT_RSTICK_Y -= 4.0f; TEXT_R3_Y -= 4.0f; TEXT_DPAD_Y -= 1.0f; TEXT_LSTICK_Y -= 6.0f; TEXT_L3_X -= 2.0f; break; case CONTROLLER_XBOXONE: TEXT_L2_X -= 2.0f; TEXT_R2_X += 2.0f; TEXT_L1_Y += 15.0f; TEXT_L1_Y_VEH = TEXT_L1_Y; TEXT_R1_Y += 15.0f; TEXT_TRIANGLE_Y += 4.0f; TEXT_CIRCLE_Y += 4.0f; TEXT_CROSS_Y += 4.0f; TEXT_RSTICK_Y += 1.0f; TEXT_R3_Y += 1.0f; TEXT_DPAD_Y += 29.0f; TEXT_LSTICK_Y -= 22.0f; TEXT_L3_X -= 36.0f; TEXT_L2R2_Y += 5.0f; TEXT_SELECT_X += 4.0f; break; case CONTROLLER_XBOX360: TEXT_L2_X += 8.0f; TEXT_R2_X -= 8.0f; TEXT_L1_Y += 15.0f; TEXT_L1_Y_VEH = TEXT_L1_Y; TEXT_R1_Y += 15.0f; TEXT_TRIANGLE_Y += 4.0f; TEXT_CIRCLE_Y += 4.0f; TEXT_CROSS_Y += 4.0f; TEXT_RSTICK_Y += 4.0f; TEXT_R3_Y += 4.0f; TEXT_DPAD_Y += 30.0f; TEXT_LSTICK_Y -= 21.0f; TEXT_L3_X -= 36.0f; TEXT_L2R2_Y += 5.0f; TEXT_SELECT_X += 3.0f; break; }; if (m_DisplayControllerOnFoot) { switch (CPad::GetPad(0)->Mode) { case 0: CFont::SetRightJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_L2_X)), MENU_Y(Y(TEXT_L2_Y)), TheText.Get("FEC_CWL")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_L1_X)), MENU_Y(Y(TEXT_L1_Y)), TheText.Get("FEC_LOF")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_DPAD_X)), MENU_Y(Y(TEXT_DPAD_Y)), TheText.Get("FEC_MOV")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_LSTICK_X)), MENU_Y(Y(TEXT_LSTICK_Y)), TheText.Get("FEC_MOV")); CFont::SetJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_SELECT_X)), MENU_Y(Y(TEXT_SELECT_Y)), TheText.Get("FEC_CAM")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_START_X)), MENU_Y(Y(TEXT_START_Y)), TheText.Get("FEC_PAU")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_R2_X)), MENU_Y(Y(TEXT_R2_Y)), TheText.Get("FEC_CWR")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_R1_X)), MENU_Y(Y(TEXT_R1_Y)), TheText.Get("FEC_TAR")); CFont::SetRightJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_SQUARE_X)), MENU_Y(Y(TEXT_SQUARE_Y)), TheText.Get("FEC_JUM")); CFont::SetJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_TRIANGLE_X)), MENU_Y(Y(TEXT_TRIANGLE_Y)), TheText.Get("FEC_ENV")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_CIRCLE_X)), MENU_Y(Y(TEXT_CIRCLE_Y)), TheText.Get("FEC_ATT")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_CROSS_X)), MENU_Y(Y(TEXT_CROSS_Y)), TheText.Get("FEC_RUN")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_RSTICK_X)), MENU_Y(Y(TEXT_RSTICK_Y)), TheText.Get("FEC_FPC")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_R3_X)), MENU_Y(Y(TEXT_R3_Y)), TheText.Get("FEC_LB3")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_R3_X)), MENU_Y(Y(TEXT_R3_Y + 13.0f)), TheText.Get("FEC_R3")); break; case 1: CFont::SetRightJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_L2_X)), MENU_Y(Y(TEXT_L2_Y)), TheText.Get("FEC_CWL")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_L1_X)), MENU_Y(Y(TEXT_L1_Y)), TheText.Get("FEC_LOF")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_DPAD_X)), MENU_Y(Y(TEXT_DPAD_Y)), TheText.Get("FEC_CAM")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_LSTICK_X)), MENU_Y(Y(TEXT_LSTICK_Y)), TheText.Get("FEC_MOV")); CFont::SetJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_SELECT_X)), MENU_Y(Y(TEXT_SELECT_Y)), TheText.Get("FEC_NA")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_START_X)), MENU_Y(Y(TEXT_START_Y)), TheText.Get("FEC_PAU")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_R2_X)), MENU_Y(Y(TEXT_R2_Y)), TheText.Get("FEC_CWR")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_R1_X)), MENU_Y(Y(TEXT_R1_Y)), TheText.Get("FEC_TAR")); CFont::SetRightJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_SQUARE_X)), MENU_Y(Y(TEXT_SQUARE_Y)), TheText.Get("FEC_JUM")); CFont::SetJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_TRIANGLE_X)), MENU_Y(Y(TEXT_TRIANGLE_Y)), TheText.Get("FEC_ENV")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_CIRCLE_X)), MENU_Y(Y(TEXT_CIRCLE_Y)), TheText.Get("FEC_ATT")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_CROSS_X)), MENU_Y(Y(TEXT_CROSS_Y)), TheText.Get("FEC_RUN")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_RSTICK_X)), MENU_Y(Y(TEXT_RSTICK_Y)), TheText.Get("FEC_FPC")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_R3_X)), MENU_Y(Y(TEXT_R3_Y)), TheText.Get("FEC_LB3")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_R3_X)), MENU_Y(Y(TEXT_R3_Y + 13.0f)), TheText.Get("FEC_R3")); break; case 2: CFont::SetRightJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_L2_X)), MENU_Y(Y(TEXT_L2_Y)), TheText.Get("FEC_CWL")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_L1_X)), MENU_Y(Y(TEXT_L1_Y)), TheText.Get("FEC_ENV")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_DPAD_X)), MENU_Y(Y(TEXT_DPAD_Y)), TheText.Get("FEC_MOV")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_LSTICK_X)), MENU_Y(Y(TEXT_LSTICK_Y)), TheText.Get("FEC_MOV")); CFont::SetJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_SELECT_X)), MENU_Y(Y(TEXT_SELECT_Y)), TheText.Get("FEC_CAM")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_START_X)), MENU_Y(Y(TEXT_START_Y)), TheText.Get("FEC_PAU")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_R2_X)), MENU_Y(Y(TEXT_R2_Y)), TheText.Get("FEC_CWR")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_R1_X)), MENU_Y(Y(TEXT_R1_Y)), TheText.Get("FEC_TAR")); CFont::SetRightJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_SQUARE_X)), MENU_Y(Y(TEXT_SQUARE_Y)), TheText.Get("FEC_JUM")); CFont::SetJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_TRIANGLE_X)), MENU_Y(Y(TEXT_TRIANGLE_Y)), TheText.Get("FEC_LOF")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_CIRCLE_X)), MENU_Y(Y(TEXT_CIRCLE_Y)), TheText.Get("FEC_RUN")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_CROSS_X)), MENU_Y(Y(TEXT_CROSS_Y)), TheText.Get("FEC_ATT")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_RSTICK_X)), MENU_Y(Y(TEXT_RSTICK_Y)), TheText.Get("FEC_FPC")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_R3_X)), MENU_Y(Y(TEXT_R3_Y)), TheText.Get("FEC_LB3")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_R3_X)), MENU_Y(Y(TEXT_R3_Y + 13.0f)), TheText.Get("FEC_R3")); break; case 3: CFont::SetRightJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_L2_X)), MENU_Y(Y(TEXT_L2_Y)), TheText.Get("FEC_CWL")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_L1_X)), MENU_Y(Y(TEXT_L1_Y)), TheText.Get("FEC_TAR")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_DPAD_X)), MENU_Y(Y(TEXT_DPAD_Y)), TheText.Get("FEC_NA")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_LSTICK_X)), MENU_Y(Y(TEXT_LSTICK_Y)), TheText.Get("FEC_MOV")); CFont::SetJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_SELECT_X)), MENU_Y(Y(TEXT_SELECT_Y)), TheText.Get("FEC_CAM")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_START_X)), MENU_Y(Y(TEXT_START_Y)), TheText.Get("FEC_PAU")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_R2_X)), MENU_Y(Y(TEXT_R2_Y)), TheText.Get("FEC_CWR")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_R1_X)), MENU_Y(Y(TEXT_R1_Y)), TheText.Get("FEC_ATT")); CFont::SetRightJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_SQUARE_X)), MENU_Y(Y(TEXT_SQUARE_Y)), TheText.Get("FEC_JUM")); CFont::SetJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_TRIANGLE_X)), MENU_Y(Y(TEXT_TRIANGLE_Y)), TheText.Get("FEC_ENV")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_CIRCLE_X)), MENU_Y(Y(TEXT_CIRCLE_Y)), TheText.Get("FEC_LOF")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_CROSS_X)), MENU_Y(Y(TEXT_CROSS_Y)), TheText.Get("FEC_RUN")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_RSTICK_X)), MENU_Y(Y(TEXT_RSTICK_Y)), TheText.Get("FEC_FPC")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_R3_X)), MENU_Y(Y(TEXT_R3_Y)), TheText.Get("FEC_LB3")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_R3_X)), MENU_Y(Y(TEXT_R3_Y + 13.0f)), TheText.Get("FEC_R3")); break; default: return; } } else { CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_L2R2_X)), MENU_Y(Y(TEXT_L2R2_Y)), TheText.Get("FEC_LB")); switch (CPad::GetPad(0)->Mode) { case 0: CFont::SetRightJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_L2_X)), MENU_Y(Y(TEXT_L2_Y)), TheText.Get("FEC_LL")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_L1_X)), MENU_Y(Y(TEXT_L1_Y_VEH)), TheText.Get("FEC_RSC")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_DPAD_X)), MENU_Y(Y(TEXT_DPAD_Y)), TheText.Get("FEC_VES")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_LSTICK_X)), MENU_Y(Y(TEXT_LSTICK_Y)), TheText.Get("FEC_VES")); CFont::SetJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_L3_X)), MENU_Y(Y(TEXT_L3_Y)), TheText.Get("FEC_HO3")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_SELECT_X)), MENU_Y(Y(TEXT_SELECT_Y)), TheText.Get("FEC_CAM")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_START_X)), MENU_Y(Y(TEXT_START_Y)), TheText.Get("FEC_PAU")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_R2_X)), MENU_Y(Y(TEXT_R2_Y)), TheText.Get("FEC_LR")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_R1_X)), MENU_Y(Y(TEXT_R1_Y)), TheText.Get("FEC_HAB")); CFont::SetRightJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_SQUARE_X)), MENU_Y(Y(TEXT_SQUARE_Y)), TheText.Get("FEC_BRA")); CFont::SetJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_TRIANGLE_X)), MENU_Y(Y(TEXT_TRIANGLE_Y)), TheText.Get("FEC_EXV")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_CIRCLE_X)), MENU_Y(Y(TEXT_CIRCLE_Y)), TheText.Get("FEC_CAW")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_CROSS_X)), MENU_Y(Y(TEXT_CROSS_Y)), TheText.Get("FEC_ACC")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_RSTICK_X)), MENU_Y(Y(TEXT_RSTICK_Y)), TheText.Get("FEC_TUC")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_R3_X)), MENU_Y(Y(TEXT_R3_Y)), TheText.Get("FEC_SM3")); break; case 1: CFont::SetRightJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_L2_X)), MENU_Y(Y(TEXT_L2_Y)), TheText.Get("FEC_LL")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_L1_X)), MENU_Y(Y(TEXT_L1_Y_VEH)), TheText.Get("FEC_HOR")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_DPAD_X)), MENU_Y(Y(TEXT_DPAD_Y)), TheText.Get("FEC_CAM")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_LSTICK_X)), MENU_Y(Y(TEXT_LSTICK_Y)), TheText.Get("FEC_VES")); CFont::SetJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_L3_X)), MENU_Y(Y(TEXT_L3_Y)), TheText.Get("FEC_NA")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_SELECT_X)), MENU_Y(Y(TEXT_SELECT_Y)), TheText.Get("FEC_RSC")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_START_X)), MENU_Y(Y(TEXT_START_Y)), TheText.Get("FEC_PAU")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_R2_X)), MENU_Y(Y(TEXT_R2_Y)), TheText.Get("FEC_LR")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_R1_X)), MENU_Y(Y(TEXT_R1_Y)), TheText.Get("FEC_HAB")); CFont::SetRightJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_SQUARE_X)), MENU_Y(Y(TEXT_SQUARE_Y)), TheText.Get("FEC_BRA")); CFont::SetJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_TRIANGLE_X)), MENU_Y(Y(TEXT_TRIANGLE_Y)), TheText.Get("FEC_EXV")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_CIRCLE_X)), MENU_Y(Y(TEXT_CIRCLE_Y)), TheText.Get("FEC_CAW")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_CROSS_X)), MENU_Y(Y(TEXT_CROSS_Y)), TheText.Get("FEC_ACC")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_RSTICK_X)), MENU_Y(Y(TEXT_RSTICK_Y)), TheText.Get("FEC_TUC")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_R3_X)), MENU_Y(Y(TEXT_R3_Y)), TheText.Get("FEC_SM3")); break; case 2: CFont::SetRightJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_L2_X)), MENU_Y(Y(TEXT_L2_Y)), TheText.Get("FEC_LL")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_L1_X)), MENU_Y(Y(TEXT_L1_Y_VEH)), TheText.Get("FEC_EXV")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_DPAD_X)), MENU_Y(Y(TEXT_DPAD_Y)), TheText.Get("FEC_VES")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_LSTICK_X)), MENU_Y(Y(TEXT_LSTICK_Y)), TheText.Get("FEC_VES")); CFont::SetJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_L3_X)), MENU_Y(Y(TEXT_L3_Y)), TheText.Get("FEC_RS3")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_SELECT_X)), MENU_Y(Y(TEXT_SELECT_Y)), TheText.Get("FEC_CAM")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_START_X)), MENU_Y(Y(TEXT_START_Y)), TheText.Get("FEC_PAU")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_R2_X)), MENU_Y(Y(TEXT_R2_Y)), TheText.Get("FEC_LR")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_R1_X)), MENU_Y(Y(TEXT_R1_Y)), TheText.Get("FEC_HOR")); CFont::SetRightJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_SQUARE_X)), MENU_Y(Y(TEXT_SQUARE_Y)), TheText.Get("FEC_BRA")); CFont::SetJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_TRIANGLE_X)), MENU_Y(Y(TEXT_TRIANGLE_Y)), TheText.Get("FEC_HAB")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_CIRCLE_X)), MENU_Y(Y(TEXT_CIRCLE_Y)), TheText.Get("FEC_CAW")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_CROSS_X)), MENU_Y(Y(TEXT_CROSS_Y)), TheText.Get("FEC_ACC")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_RSTICK_X)), MENU_Y(Y(TEXT_RSTICK_Y)), TheText.Get("FEC_TUC")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_R3_X)), MENU_Y(Y(TEXT_R3_Y)), TheText.Get("FEC_SM3")); break; case 3: CFont::SetRightJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_L2_X)), MENU_Y(Y(TEXT_L2_Y)), TheText.Get("FEC_LL")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_L1_X)), MENU_Y(Y(TEXT_L1_Y_VEH)), TheText.Get("FEC_HAB")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_DPAD_X)), MENU_Y(Y(TEXT_DPAD_Y)), TheText.Get("FEC_TUC")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_LSTICK_X)), MENU_Y(Y(TEXT_LSTICK_Y)), TheText.Get("FEC_VES")); CFont::SetJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_L3_X)), MENU_Y(Y(TEXT_L3_Y)), TheText.Get("FEC_HO3")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_SELECT_X)), MENU_Y(Y(TEXT_SELECT_Y)), TheText.Get("FEC_CAM")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_START_X)), MENU_Y(Y(TEXT_START_Y)), TheText.Get("FEC_PAU")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_R2_X)), MENU_Y(Y(TEXT_R2_Y)), TheText.Get("FEC_LR")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_R1_X)), MENU_Y(Y(TEXT_R1_Y)), TheText.Get("FEC_CAW")); CFont::SetRightJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_SQUARE_X)), MENU_Y(Y(TEXT_SQUARE_Y)), TheText.Get("FEC_SMT")); CFont::SetJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_TRIANGLE_X)), MENU_Y(Y(TEXT_TRIANGLE_Y)), TheText.Get("FEC_EXV")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_CIRCLE_X)), MENU_Y(Y(TEXT_CIRCLE_Y)), TheText.Get("FEC_RSC")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_CROSS_X)), MENU_Y(Y(TEXT_CROSS_Y)), TheText.Get("FEC_NA")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_RSTICK_X)), MENU_Y(Y(TEXT_RSTICK_Y)), TheText.Get("FEC_ACC")); CFont::PrintString(MENU_X_LEFT_ALIGNED(X(TEXT_R3_X)), MENU_Y(Y(TEXT_R3_Y)), TheText.Get("FEC_BRA")); break; default: return; } } CFont::SetDropShadowPosition(0); // X #undef X #undef Y } #else void CMenuManager::PrintController(void) { // FIX: Originally this function doesn't have StretchX/Y, everything had constant pixel size (due to screen was abandoned early?) // Also texts and their alignment were very bad, so I tried to make them readable (commented out the original code, and marked the ones I added with X) m_aFrontEndSprites[FE_CONTROLLERSH].Draw(MENU_X_LEFT_ALIGNED(160.0f), MENU_Y(160.0f), MENU_X(240.0f), MENU_Y(180.0f), CRGBA(0, 0, 0, 255)); m_aFrontEndSprites[FE_CONTROLLER].Draw(MENU_X_LEFT_ALIGNED(160.0f), MENU_Y(160.0f), MENU_X(235.2f), MENU_Y(175.2f), CRGBA(255, 255, 255, 255)); if (m_DisplayControllerOnFoot) { if (CTimer::GetTimeInMillisecondsPauseMode() & 0x400) m_aFrontEndSprites[FE_ARROWS1].Draw(MENU_X_LEFT_ALIGNED(160.0f), MENU_Y(160.0f), MENU_X(235.2f), MENU_Y(175.2f), CRGBA(255, 255, 255, 255)); else m_aFrontEndSprites[FE_ARROWS3].Draw(MENU_X_LEFT_ALIGNED(160.0f), MENU_Y(160.0f), MENU_X(235.2f), MENU_Y(175.2f), CRGBA(255, 255, 255, 255)); } else { if (CTimer::GetTimeInMillisecondsPauseMode() & 0x400) m_aFrontEndSprites[FE_ARROWS2].Draw(MENU_X_LEFT_ALIGNED(160.0f), MENU_Y(160.0f), MENU_X(235.2f), MENU_Y(175.2f), CRGBA(255, 255, 255, 255)); else m_aFrontEndSprites[FE_ARROWS4].Draw(MENU_X_LEFT_ALIGNED(160.0f), MENU_Y(160.0f), MENU_X(235.2f), MENU_Y(175.2f), CRGBA(255, 255, 255, 255)); } CFont::SetFontStyle(FONT_LOCALE(FONT_BANK)); // X // CFont::SetScale(0.4f, 0.4f); CFont::SetScale(MENU_X(SMALLESTTEXT_X_SCALE), MENU_Y(SMALLESTTEXT_Y_SCALE)); // X // CFont::SetColor(CRGBA(128, 128, 128, FadeIn(255))); CFont::SetDropColor(CRGBA(0, 0, 0, FadeIn(255))); // X CFont::SetDropShadowPosition(1); // X CFont::SetColor(CRGBA(255, 255, 255, FadeIn(255))); // X if (m_DisplayControllerOnFoot) { switch (CPad::GetPad(0)->Mode) { case 0: CFont::SetRightJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(210.0f), MENU_Y(146.0f), TheText.Get("FEC_CWL")); CFont::PrintString(MENU_X_LEFT_ALIGNED(156.0f), MENU_Y(185.0f), TheText.Get("FEC_LOF")); CFont::PrintString(MENU_X_LEFT_ALIGNED(156.0f), MENU_Y(225.0f), TheText.Get("FEC_MOV")); CFont::PrintString(MENU_X_LEFT_ALIGNED(156.0f), MENU_Y(257.0f), TheText.Get("FEC_MOV")); CFont::SetJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(263.0f), MENU_Y(301.0f), TheText.Get("FEC_CAM")); CFont::PrintString(MENU_X_LEFT_ALIGNED(290.0f), MENU_Y(288.0f), TheText.Get("FEC_PAU")); CFont::PrintString(MENU_X_LEFT_ALIGNED(344.0f), MENU_Y(146.0f), TheText.Get("FEC_CWR")); CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(185.0f), TheText.Get("FEC_TAR")); CFont::SetRightJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(304.0f), MENU_Y(178.0f), TheText.Get("FEC_JUM")); CFont::SetJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(212.0f), TheText.Get("FEC_ENV")); CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(225.0f), TheText.Get("FEC_ATT")); CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(238.0f), TheText.Get("FEC_RUN")); CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(254.0f), TheText.Get("FEC_FPC")); CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(269.0f), TheText.Get("FEC_LB3")); CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(282.0f), TheText.Get("FEC_R3")); break; case 1: CFont::SetRightJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(210.0f), MENU_Y(146.0f), TheText.Get("FEC_CWL")); CFont::PrintString(MENU_X_LEFT_ALIGNED(156.0f), MENU_Y(185.0f), TheText.Get("FEC_LOF")); CFont::PrintString(MENU_X_LEFT_ALIGNED(156.0f), MENU_Y(225.0f), TheText.Get("FEC_CAM")); CFont::PrintString(MENU_X_LEFT_ALIGNED(156.0f), MENU_Y(257.0f), TheText.Get("FEC_MOV")); CFont::SetJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(263.0f), MENU_Y(301.0f), TheText.Get("FEC_NA")); CFont::PrintString(MENU_X_LEFT_ALIGNED(290.0f), MENU_Y(288.0f), TheText.Get("FEC_PAU")); CFont::PrintString(MENU_X_LEFT_ALIGNED(344.0f), MENU_Y(146.0f), TheText.Get("FEC_CWR")); CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(185.0f), TheText.Get("FEC_TAR")); CFont::SetRightJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(304.0f), MENU_Y(178.0f), TheText.Get("FEC_JUM")); CFont::SetJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(212.0f), TheText.Get("FEC_ENV")); CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(225.0f), TheText.Get("FEC_ATT")); CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(238.0f), TheText.Get("FEC_RUN")); CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(254.0f), TheText.Get("FEC_FPC")); CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(269.0f), TheText.Get("FEC_LB3")); CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(282.0f), TheText.Get("FEC_R3")); break; case 2: CFont::SetRightJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(210.0f), MENU_Y(146.0f), TheText.Get("FEC_CWL")); CFont::PrintString(MENU_X_LEFT_ALIGNED(156.0f), MENU_Y(185.0f), TheText.Get("FEC_ENV")); CFont::PrintString(MENU_X_LEFT_ALIGNED(156.0f), MENU_Y(225.0f), TheText.Get("FEC_MOV")); CFont::PrintString(MENU_X_LEFT_ALIGNED(156.0f), MENU_Y(257.0f), TheText.Get("FEC_MOV")); CFont::SetJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(263.0f), MENU_Y(301.0f), TheText.Get("FEC_CAM")); CFont::PrintString(MENU_X_LEFT_ALIGNED(290.0f), MENU_Y(288.0f), TheText.Get("FEC_PAU")); CFont::PrintString(MENU_X_LEFT_ALIGNED(344.0f), MENU_Y(146.0f), TheText.Get("FEC_CWR")); CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(185.0f), TheText.Get("FEC_TAR")); CFont::SetRightJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(304.0f), MENU_Y(178.0f), TheText.Get("FEC_JUM")); CFont::SetJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(212.0f), TheText.Get("FEC_LOF")); CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(225.0f), TheText.Get("FEC_RUN")); CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(238.0f), TheText.Get("FEC_ATT")); CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(254.0f), TheText.Get("FEC_FPC")); CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(269.0f), TheText.Get("FEC_LB3")); CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(282.0f), TheText.Get("FEC_R3")); break; case 3: CFont::SetRightJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(210.0f), MENU_Y(146.0f), TheText.Get("FEC_CWL")); CFont::PrintString(MENU_X_LEFT_ALIGNED(156.0f), MENU_Y(185.0f), TheText.Get("FEC_TAR")); CFont::PrintString(MENU_X_LEFT_ALIGNED(156.0f), MENU_Y(225.0f), TheText.Get("FEC_NA")); CFont::PrintString(MENU_X_LEFT_ALIGNED(156.0f), MENU_Y(257.0f), TheText.Get("FEC_MOV")); CFont::SetJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(263.0f), MENU_Y(301.0f), TheText.Get("FEC_CAM")); CFont::PrintString(MENU_X_LEFT_ALIGNED(290.0f), MENU_Y(288.0f), TheText.Get("FEC_PAU")); CFont::PrintString(MENU_X_LEFT_ALIGNED(344.0f), MENU_Y(146.0f), TheText.Get("FEC_CWR")); CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(185.0f), TheText.Get("FEC_TAR")); CFont::SetRightJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(304.0f), MENU_Y(178.0f), TheText.Get("FEC_JUM")); CFont::SetJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(212.0f), TheText.Get("FEC_LOF")); CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(225.0f), TheText.Get("FEC_RUN")); CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(238.0f), TheText.Get("FEC_ATT")); CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(254.0f), TheText.Get("FEC_FPC")); CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(269.0f), TheText.Get("FEC_LB3")); CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(282.0f), TheText.Get("FEC_R3")); break; default: return; } } else { switch (CPad::GetPad(0)->Mode) { case 0: CFont::SetRightJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(210.0f), MENU_Y(146.0f), TheText.Get("FEC_LL")); CFont::PrintString(MENU_X_LEFT_ALIGNED(156.0f), MENU_Y(185.0f), TheText.Get("FEC_RSC")); CFont::PrintString(MENU_X_LEFT_ALIGNED(156.0f), MENU_Y(225.0f), TheText.Get("FEC_VES")); CFont::PrintString(MENU_X_LEFT_ALIGNED(156.0f), MENU_Y(257.0f), TheText.Get("FEC_VES")); CFont::SetJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(263.0f), MENU_Y(301.0f), TheText.Get("FEC_HO3")); CFont::PrintString(MENU_X_LEFT_ALIGNED(290.0f), MENU_Y(288.0f), TheText.Get("FEC_CAM")); CFont::PrintString(MENU_X_LEFT_ALIGNED(344.0f), MENU_Y(146.0f), TheText.Get("FEC_PAU")); CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(185.0f), TheText.Get("FEC_LB")); CFont::SetRightJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(304.0f), MENU_Y(178.0f), TheText.Get("FEC_LR")); CFont::SetJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(212.0f), TheText.Get("FEC_HAB")); CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(225.0f), TheText.Get("FEC_BRA")); CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(238.0f), TheText.Get("FEC_EXV")); CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(254.0f), TheText.Get("FEC_CAW")); CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(269.0f), TheText.Get("FEC_ACC")); CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(282.0f), TheText.Get("FEC_TUC")); // FIX: Coordinates of this line is undefined in PC... CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(304.0f), TheText.Get("FEC_SM3")); break; case 1: CFont::SetRightJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(210.0f), MENU_Y(146.0f), TheText.Get("FEC_LL")); CFont::PrintString(MENU_X_LEFT_ALIGNED(156.0f), MENU_Y(185.0f), TheText.Get("FEC_HOR")); CFont::PrintString(MENU_X_LEFT_ALIGNED(156.0f), MENU_Y(225.0f), TheText.Get("FEC_CAM")); CFont::PrintString(MENU_X_LEFT_ALIGNED(156.0f), MENU_Y(257.0f), TheText.Get("FEC_VES")); CFont::SetJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(263.0f), MENU_Y(301.0f), TheText.Get("FEC_NA")); CFont::PrintString(MENU_X_LEFT_ALIGNED(290.0f), MENU_Y(288.0f), TheText.Get("FEC_RSC")); CFont::PrintString(MENU_X_LEFT_ALIGNED(344.0f), MENU_Y(146.0f), TheText.Get("FEC_PAU")); CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(185.0f), TheText.Get("FEC_LB")); CFont::SetRightJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(304.0f), MENU_Y(178.0f), TheText.Get("FEC_LR")); CFont::SetJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(212.0f), TheText.Get("FEC_HAB")); CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(225.0f), TheText.Get("FEC_BRA")); CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(238.0f), TheText.Get("FEC_EXV")); CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(254.0f), TheText.Get("FEC_CAW")); CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(269.0f), TheText.Get("FEC_ACC")); CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(282.0f), TheText.Get("FEC_TUC")); // FIX: Coordinates of this line is undefined in PC... CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(304.0f), TheText.Get("FEC_SM3")); break; case 2: CFont::SetRightJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(210.0f), MENU_Y(146.0f), TheText.Get("FEC_LL")); CFont::PrintString(MENU_X_LEFT_ALIGNED(156.0f), MENU_Y(185.0f), TheText.Get("FEC_EXV")); CFont::PrintString(MENU_X_LEFT_ALIGNED(156.0f), MENU_Y(225.0f), TheText.Get("FEC_VES")); CFont::PrintString(MENU_X_LEFT_ALIGNED(156.0f), MENU_Y(257.0f), TheText.Get("FEC_VES")); CFont::SetJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(263.0f), MENU_Y(301.0f), TheText.Get("FEC_RS3")); CFont::PrintString(MENU_X_LEFT_ALIGNED(290.0f), MENU_Y(288.0f), TheText.Get("FEC_CAM")); CFont::PrintString(MENU_X_LEFT_ALIGNED(344.0f), MENU_Y(146.0f), TheText.Get("FEC_PAU")); CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(185.0f), TheText.Get("FEC_LB")); CFont::SetRightJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(304.0f), MENU_Y(178.0f), TheText.Get("FEC_LR")); CFont::SetJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(212.0f), TheText.Get("FEC_HOR")); CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(225.0f), TheText.Get("FEC_BRA")); CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(238.0f), TheText.Get("FEC_HAB")); CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(254.0f), TheText.Get("FEC_CAW")); CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(269.0f), TheText.Get("FEC_ACC")); CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(282.0f), TheText.Get("FEC_TUC")); // FIX: Coordinates of this line is undefined in PC... CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(304.0f), TheText.Get("FEC_SM3")); break; case 3: CFont::SetRightJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(210.0f), MENU_Y(146.0f), TheText.Get("FEC_LL")); CFont::PrintString(MENU_X_LEFT_ALIGNED(156.0f), MENU_Y(185.0f), TheText.Get("FEC_HAB")); CFont::PrintString(MENU_X_LEFT_ALIGNED(156.0f), MENU_Y(225.0f), TheText.Get("FEC_TUC")); CFont::PrintString(MENU_X_LEFT_ALIGNED(156.0f), MENU_Y(257.0f), TheText.Get("FEC_VES")); CFont::SetJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(263.0f), MENU_Y(301.0f), TheText.Get("FEC_HO3")); CFont::PrintString(MENU_X_LEFT_ALIGNED(290.0f), MENU_Y(288.0f), TheText.Get("FEC_CAM")); CFont::PrintString(MENU_X_LEFT_ALIGNED(344.0f), MENU_Y(146.0f), TheText.Get("FEC_PAU")); CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(185.0f), TheText.Get("FEC_LB")); CFont::SetRightJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(304.0f), MENU_Y(178.0f), TheText.Get("FEC_LR")); CFont::SetJustifyOn(); // X CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(212.0f), TheText.Get("FEC_CAW")); CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(225.0f), TheText.Get("FEC_SMT")); CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(238.0f), TheText.Get("FEC_EXV")); CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(254.0f), TheText.Get("FEC_RSC")); CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(269.0f), TheText.Get("FEC_NA")); CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(282.0f), TheText.Get("FEC_ACC")); // FIX: Coordinates of this line is undefined in PC... CFont::PrintString(MENU_X_LEFT_ALIGNED(398.0f), MENU_Y(304.0f), TheText.Get("FEC_BRA")); break; default: return; } } CFont::SetDropShadowPosition(0); // X } #endif #ifdef MENU_MAP #define ZOOM(x, y, in) \ do { \ if(fMapSize > SCREEN_HEIGHT * 3.0f && in) \ break; \ float z2 = in? 1.1f : 1.f/1.1f; \ fMapCenterX += (x - fMapCenterX) * (1.0f - z2); \ fMapCenterY += (y - fMapCenterY) * (1.0f - z2); \ \ if (fMapSize < SCREEN_HEIGHT / 2 && !in) \ break; \ \ fMapSize *= z2; \ } while(0) \ void CMenuManager::PrintMap(void) { CFont::SetJustifyOn(); bMenuMapActive = true; CRadar::InitFrontEndMap(); if (m_nMenuFadeAlpha < 255 && fMapCenterX == 0.f && fMapCenterY == 0.f) { // Just entered. We need to do these transformations in here, because Radar knows whether map is active or not CVector2D radarSpacePlayer; CVector2D screenSpacePlayer; CRadar::TransformRealWorldPointToRadarSpace(radarSpacePlayer, CVector2D(FindPlayerCoors())); CRadar::TransformRadarPointToScreenSpace(screenSpacePlayer, radarSpacePlayer); fMapCenterX = (-screenSpacePlayer.x) + SCREEN_WIDTH / 2; fMapCenterY = (-screenSpacePlayer.y) + SCREEN_HEIGHT / 2; } // Because fMapSize is half of the map length, and map consists of 3x3 tiles. float halfTile = fMapSize / 3.0f; // Darken background a bit CSprite2d::DrawRect(CRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT), CRGBA(0, 0, 0, FadeIn(128))); RwRenderStateSet(rwRENDERSTATETEXTUREFILTER, (void*)rwFILTERLINEAR); if (SCREEN_WIDTH >= fMapCenterX - fMapSize || SCREEN_HEIGHT >= fMapCenterY - fMapSize) { m_aMapSprites[MAPTOP1].Draw(CRect(fMapCenterX - fMapSize, fMapCenterY - fMapSize, fMapCenterX - halfTile, fMapCenterY - halfTile), CRGBA(255, 255, 255, FadeIn(255))); } if (SCREEN_WIDTH >= fMapCenterX - halfTile || SCREEN_HEIGHT >= fMapCenterY - fMapSize) { m_aMapSprites[MAPTOP2].Draw(CRect(fMapCenterX - halfTile, fMapCenterY - fMapSize, fMapCenterX + halfTile, fMapCenterY - halfTile), CRGBA(255, 255, 255, FadeIn(255))); } if (SCREEN_WIDTH >= fMapCenterX + halfTile || SCREEN_HEIGHT >= fMapCenterY - fMapSize) { m_aMapSprites[MAPTOP3].Draw(CRect(fMapCenterX + halfTile, fMapCenterY - fMapSize, fMapCenterX + fMapSize, fMapCenterY - halfTile), CRGBA(255, 255, 255, FadeIn(255))); } if (SCREEN_WIDTH >= fMapCenterX - fMapSize || SCREEN_HEIGHT >= fMapCenterY - halfTile) { m_aMapSprites[MAPMID1].Draw(CRect(fMapCenterX - fMapSize, fMapCenterY - halfTile, fMapCenterX - halfTile, fMapCenterY + halfTile), CRGBA(255, 255, 255, FadeIn(255))); } if (SCREEN_WIDTH >= fMapCenterX - halfTile || SCREEN_HEIGHT >= fMapCenterY - halfTile) { m_aMapSprites[MAPMID2].Draw(CRect(fMapCenterX - halfTile, fMapCenterY - halfTile, fMapCenterX + halfTile, fMapCenterY + halfTile), CRGBA(255, 255, 255, FadeIn(255))); } if (SCREEN_WIDTH >= fMapCenterX + halfTile || SCREEN_HEIGHT >= fMapCenterY - halfTile) { m_aMapSprites[MAPMID3].Draw(CRect(fMapCenterX + halfTile, fMapCenterY - halfTile, fMapCenterX + fMapSize, fMapCenterY + halfTile), CRGBA(255, 255, 255, FadeIn(255))); } if (SCREEN_WIDTH >= fMapCenterX - fMapSize || SCREEN_HEIGHT >= fMapCenterY + halfTile) { m_aMapSprites[MAPBOT1].Draw(CRect(fMapCenterX - fMapSize, fMapCenterY + halfTile, fMapCenterX - halfTile, fMapCenterY + fMapSize), CRGBA(255, 255, 255, FadeIn(255))); } if (SCREEN_WIDTH >= fMapCenterX - halfTile || SCREEN_HEIGHT >= fMapCenterY + halfTile) { m_aMapSprites[MAPBOT2].Draw(CRect(fMapCenterX - halfTile, fMapCenterY + halfTile, fMapCenterX + halfTile, fMapCenterY + fMapSize), CRGBA(255, 255, 255, FadeIn(255))); } if (SCREEN_WIDTH >= fMapCenterX + halfTile || SCREEN_HEIGHT >= fMapCenterY + halfTile) { m_aMapSprites[MAPBOT3].Draw(CRect(fMapCenterX + halfTile, fMapCenterY + halfTile, fMapCenterX + fMapSize, fMapCenterY + fMapSize), CRGBA(255, 255, 255, FadeIn(255))); } CRadar::DrawBlips(); static CVector2D mapCrosshair; if (m_nMenuFadeAlpha != 255 && !m_bShowMouse) { mapCrosshair.x = SCREEN_WIDTH / 2; mapCrosshair.y = SCREEN_HEIGHT / 2; } else if (m_bShowMouse) { mapCrosshair.x = m_nMousePosX; mapCrosshair.y = m_nMousePosY; } CSprite2d::DrawRect(CRect(mapCrosshair.x - MENU_X(1.0f), 0.0f, mapCrosshair.x + MENU_X(1.0f), SCREEN_HEIGHT), CRGBA(0, 0, 0, 150)); CSprite2d::DrawRect(CRect(0.0f, mapCrosshair.y + MENU_X(1.0f), SCREEN_WIDTH, mapCrosshair.y - MENU_X(1.0f)), CRGBA(0, 0, 0, 150)); // Adding marker if (m_nMenuFadeAlpha >= 255) { if (CPad::GetPad(0)->GetRightMouseJustDown() || CPad::GetPad(0)->GetCrossJustDown()) { if (mapCrosshair.y > fMapCenterY - fMapSize && mapCrosshair.y < fMapCenterY + fMapSize && mapCrosshair.x > fMapCenterX - fMapSize && mapCrosshair.x < fMapCenterX + fMapSize) { float diffX = fMapCenterX - fMapSize, diffY = fMapCenterY - fMapSize; float x = ((mapCrosshair.x - diffX) / (fMapSize * 2)) * 4000.0f - 2000.0f; float y = 2000.0f - ((mapCrosshair.y - diffY) / (fMapSize * 2)) * 4000.0f; CRadar::ToggleTargetMarker(x, y); DMAudio.PlayFrontEndSound(SOUND_FRONTEND_MENU_SETTING_CHANGE, 0); } } } if (CPad::GetPad(0)->GetLeftMouse()) { fMapCenterX += m_nMousePosX - m_nMouseOldPosX; fMapCenterY += m_nMousePosY - m_nMouseOldPosY; } else if (CPad::GetPad(0)->GetLeft() || CPad::GetPad(0)->GetDPadLeft()) { fMapCenterX += 15.0f; } else if (CPad::GetPad(0)->GetRight() || CPad::GetPad(0)->GetDPadRight()) { fMapCenterX -= 15.0f; } else if (CPad::GetPad(0)->GetLeftStickX()) { fMapCenterX -= CPad::GetPad(0)->GetLeftStickX() / 128.0f * 20.0f; } if (CPad::GetPad(0)->GetUp() || CPad::GetPad(0)->GetDPadUp()) { fMapCenterY += 15.0f; } else if (CPad::GetPad(0)->GetDown() || CPad::GetPad(0)->GetDPadDown()) { fMapCenterY -= 15.0f; } else if (CPad::GetPad(0)->GetLeftStickY()) { fMapCenterY -= CPad::GetPad(0)->GetLeftStickY() / 128.0f * 20.0f; } if (CPad::GetPad(0)->GetMouseWheelDown() || CPad::GetPad(0)->GetPageDown() || CPad::GetPad(0)->GetRightShoulder2()) { if (CPad::GetPad(0)->GetMouseWheelDown()) ZOOM(mapCrosshair.x, mapCrosshair.y, false); else ZOOM(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, false); } else if (CPad::GetPad(0)->GetMouseWheelUp() || CPad::GetPad(0)->GetPageUp() || CPad::GetPad(0)->GetRightShoulder1()) { if (CPad::GetPad(0)->GetMouseWheelUp()) ZOOM(mapCrosshair.x, mapCrosshair.y, true); else ZOOM(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, true); } if (fMapCenterX - fMapSize > SCREEN_WIDTH / 2) fMapCenterX = fMapSize + SCREEN_WIDTH / 2; if (fMapCenterX + fMapSize < SCREEN_WIDTH / 2) fMapCenterX = SCREEN_WIDTH / 2 - fMapSize; if (fMapCenterY + fMapSize < SCREEN_HEIGHT - MENU_Y(60.0f)) fMapCenterY = SCREEN_HEIGHT - MENU_Y(60.0f) - fMapSize; fMapCenterY = Min(fMapCenterY, fMapSize); // To not show beyond north border bMenuMapActive = false; CSprite2d::DrawRect(CRect(MENU_X(14.0f), SCREEN_STRETCH_FROM_BOTTOM(95.0f), SCREEN_STRETCH_FROM_RIGHT(11.0f), SCREEN_STRETCH_FROM_BOTTOM(59.0f)), CRGBA(235, 170, 50, 255)); CFont::SetScale(MENU_X(0.4f), MENU_Y(0.7f)); CFont::SetFontStyle(FONT_LOCALE(FONT_BANK)); CFont::SetColor(CRGBA(HEADER_COLOR.r, HEADER_COLOR.g, HEADER_COLOR.b, FadeIn(255))); float nextX = MENU_X(30.0f), nextY = 95.0f; wchar *text; #ifdef MORE_LANGUAGES #define TEXT_PIECE(key,extraSpace) \ text = TheText.Get(key);\ CFont::PrintString(nextX, SCREEN_SCALE_FROM_BOTTOM(nextY), text);\ if (CFont::IsJapanese())\ nextX += CFont::GetStringWidth_Jap(text) + MENU_X(extraSpace);\ else\ nextX += CFont::GetStringWidth(text, true) + MENU_X(extraSpace); #else #define TEXT_PIECE(key,extraSpace) \ text = TheText.Get(key); CFont::PrintString(nextX, SCREEN_SCALE_FROM_BOTTOM(nextY), text); nextX += CFont::GetStringWidth(text, true) + MENU_X(extraSpace); #endif TEXT_PIECE("FEC_MWF", 3.0f); TEXT_PIECE("FEC_PGU", 1.0f); TEXT_PIECE("FEC_IBT", 1.0f); TEXT_PIECE("FEC_ZIN", 20.0f); TEXT_PIECE("FEC_MWB", 3.0f); TEXT_PIECE("FEC_PGD", 1.0f); TEXT_PIECE("FEC_IBT", 1.0f); CFont::PrintString(nextX, SCREEN_SCALE_FROM_BOTTOM(nextY), TheText.Get("FEC_ZOT")); nextX = MENU_X(30.0f); nextY -= 11.0f; TEXT_PIECE("FEC_UPA", 2.0f); TEXT_PIECE("FEC_DWA", 2.0f); TEXT_PIECE("FEC_LFA", 2.0f); TEXT_PIECE("FEC_RFA", 2.0f); TEXT_PIECE("FEC_MSL", 1.0f); TEXT_PIECE("FEC_IBT", 1.0f); CFont::PrintString(nextX, SCREEN_SCALE_FROM_BOTTOM(nextY), TheText.Get("FEC_MOV")); nextX = MENU_X(30.0f); nextY -= 11.0f; TEXT_PIECE("FEC_MSR", 2.0f); TEXT_PIECE("FEC_IBT", 1.0f); CFont::PrintString(nextX, SCREEN_SCALE_FROM_BOTTOM(nextY), TheText.Get("FEM_TWP")); #undef TEXT_PIECE } #undef ZOOM #endif // rowIdx 99999 returns total numbers of rows. otherwise it returns 0. int CMenuManager::ConstructStatLine(int rowIdx) { #define int_STAT_IS_FLOAT false #define float_STAT_IS_FLOAT true #define STAT_LINE_1(varType, left, right1) \ do { \ if(counter == rowIdx){ \ varType a = right1; \ BuildStatLine(left, &a, varType##_STAT_IS_FLOAT, nil); \ return 0; \ } counter++; \ } while(0) #define STAT_LINE_2(varType, left, right1, right2) \ do { \ if(counter == rowIdx){ \ varType a = right1; \ varType b = right2; \ BuildStatLine(left, &a, varType##_STAT_IS_FLOAT, &b); \ return 0; \ } counter++; \ } while(0) #define TEXT_ON_LEFT_GXT(name) \ do { \ if(counter == rowIdx){ \ BuildStatLine(name, nil, false, nil); \ return 0; \ } counter++; \ } while(0) #define TEXT_ON_RIGHT(text) \ do { \ if(counter == rowIdx){ \ gUString[0] = '\0'; \ UnicodeStrcpy(gUString2, text); \ return 0; \ } counter++; \ } while(0) // Like TEXT_ON_LEFT_GXT, but counter wasn't initialized yet I think if (rowIdx == 0) { BuildStatLine("PL_STAT", nil, false, nil); return 0; } int percentCompleted = (CStats::TotalProgressInGame == 0 ? 0 : CStats::ProgressMade * 100.0f / (CGame::nastyGame ? CStats::TotalProgressInGame : CStats::TotalProgressInGame - 1)); percentCompleted = Min(percentCompleted, 100); switch (rowIdx) { // 0 is the heading text above case 1: { BuildStatLine("PER_COM", &percentCompleted, false, nil); return 0; } case 2: { BuildStatLine("NMISON", &CStats::MissionsGiven, false, nil); return 0; } case 3: { BuildStatLine("FEST_MP", &CStats::MissionsPassed, false, &CStats::TotalNumberMissions); return 0; } } int counter = 4; if (CGame::nastyGame) STAT_LINE_2(int, "FEST_RP", CStats::NumberKillFrenziesPassed, CStats::TotalNumberKillFrenzies); CPlayerInfo &player = CWorld::Players[CWorld::PlayerInFocus]; // Hidden packages shouldn't be shown with percent #ifdef FIX_BUGS STAT_LINE_2(int, "PERPIC", player.m_nCollectedPackages, player.m_nTotalPackages); #else float packagesPercent = 0.0f; if (player.m_nTotalPackages != 0) packagesPercent = player.m_nCollectedPackages * 100.0f / player.m_nTotalPackages; STAT_LINE_2(int, "PERPIC", packagesPercent, 100); #endif STAT_LINE_2(int, "NOUNIF", CStats::NumberOfUniqueJumpsFound, CStats::TotalNumberOfUniqueJumps); STAT_LINE_1(int, "DAYSPS", CStats::DaysPassed); if (CGame::nastyGame) { STAT_LINE_1(int, "PE_WAST", CStats::PeopleKilledByPlayer); STAT_LINE_1(int, "PE_WSOT", CStats::PeopleKilledByOthers); } STAT_LINE_1(int, "CAR_EXP", CStats::CarsExploded); STAT_LINE_1(int, "TM_BUST", CStats::TimesArrested); STAT_LINE_1(int, "TM_DED", CStats::TimesDied); STAT_LINE_1(int, "GNG_WST", CStats::PedsKilledOfThisType[PEDTYPE_GANG9] + CStats::PedsKilledOfThisType[PEDTYPE_GANG8] + CStats::PedsKilledOfThisType[PEDTYPE_GANG7] + CStats::PedsKilledOfThisType[PEDTYPE_GANG6] + CStats::PedsKilledOfThisType[PEDTYPE_GANG5] + CStats::PedsKilledOfThisType[PEDTYPE_GANG4] + CStats::PedsKilledOfThisType[PEDTYPE_GANG3] + CStats::PedsKilledOfThisType[PEDTYPE_GANG2] + CStats::PedsKilledOfThisType[PEDTYPE_GANG1]); STAT_LINE_1(int, "DED_CRI", CStats::PedsKilledOfThisType[PEDTYPE_CRIMINAL]); STAT_LINE_1(int, "HEL_DST", CStats::HelisDestroyed); STAT_LINE_1(int, "KGS_EXP", CStats::KgsOfExplosivesUsed); STAT_LINE_1(int, "ACCURA", (CStats::InstantHitsFiredByPlayer == 0 ? 0 : CStats::InstantHitsHitByPlayer * 100.0f / CStats::InstantHitsFiredByPlayer)); if (CStats::ElBurroTime > 0) { STAT_LINE_1(int, "ELBURRO", CStats::ElBurroTime); } if (CStats::Record4x4One > 0) { STAT_LINE_1(int, "FEST_R1", CStats::Record4x4One); } if (CStats::Record4x4Two > 0) { STAT_LINE_1(int, "FEST_R2", CStats::Record4x4Two); } if (CStats::Record4x4Three > 0) { STAT_LINE_1(int, "FEST_R3", CStats::Record4x4Three); } if (CStats::Record4x4Mayhem > 0) { STAT_LINE_1(int, "FEST_RM", CStats::Record4x4Mayhem); } if (CStats::LongestFlightInDodo > 0) { STAT_LINE_1(int, "FEST_LF", CStats::LongestFlightInDodo); } if (CStats::TimeTakenDefuseMission > 0) { STAT_LINE_1(int, "FEST_BD", CStats::TimeTakenDefuseMission); } STAT_LINE_1(int, "CAR_CRU", CStats::CarsCrushed); if (CStats::HighestScores[0] > 0) { TEXT_ON_LEFT_GXT("FEST_BB"); STAT_LINE_1(int, "FEST_H0", CStats::HighestScores[0]); } if (CStats::HighestScores[4] + CStats::HighestScores[3] + CStats::HighestScores[2] + CStats::HighestScores[1] > 0) { TEXT_ON_LEFT_GXT("FEST_GC"); } if (CStats::HighestScores[1] > 0) { STAT_LINE_1(int, "FEST_H1", CStats::HighestScores[1]); } if (CStats::HighestScores[2] > 0) { STAT_LINE_1(int, "FEST_H2", CStats::HighestScores[2]); } if (CStats::HighestScores[3] > 0) { STAT_LINE_1(int, "FEST_H3", CStats::HighestScores[3]); } if (CStats::HighestScores[4] > 0) { STAT_LINE_1(int, "FEST_H4", CStats::HighestScores[4]); } switch (m_PrefsLanguage) { case LANGUAGE_AMERICAN: #ifndef USE_MEASUREMENTS_IN_METERS STAT_LINE_1(float, "FEST_DF", CStats::DistanceTravelledOnFoot * MILES_IN_METER); STAT_LINE_1(float, "FEST_DC", CStats::DistanceTravelledInVehicle * MILES_IN_METER); STAT_LINE_1(int, "MMRAIN", CStats::mmRain); STAT_LINE_1(float, "MXCARD", CStats::MaximumJumpDistance * FEET_IN_METER); STAT_LINE_1(float, "MXCARJ", CStats::MaximumJumpHeight * FEET_IN_METER); break; #endif case LANGUAGE_FRENCH: case LANGUAGE_GERMAN: case LANGUAGE_ITALIAN: case LANGUAGE_SPANISH: #ifdef MORE_LANGUAGES case LANGUAGE_POLISH: case LANGUAGE_RUSSIAN: case LANGUAGE_JAPANESE: #endif STAT_LINE_1(float, "FESTDFM", CStats::DistanceTravelledOnFoot); STAT_LINE_1(float, "FESTDCM", CStats::DistanceTravelledInVehicle); STAT_LINE_1(int, "MMRAIN", CStats::mmRain); STAT_LINE_1(float, "MXCARDM", CStats::MaximumJumpDistance); STAT_LINE_1(float, "MXCARJM", CStats::MaximumJumpHeight); break; default: break; } STAT_LINE_1(int, "MXFLIP", CStats::MaximumJumpFlips); STAT_LINE_1(int, "MXJUMP", CStats::MaximumJumpSpins); TEXT_ON_LEFT_GXT("BSTSTU"); switch (CStats::BestStuntJump) { case 1: TEXT_ON_RIGHT(TheText.Get("INSTUN")); break; case 2: TEXT_ON_RIGHT(TheText.Get("PRINST")); break; case 3: TEXT_ON_RIGHT(TheText.Get("DBINST")); break; case 4: TEXT_ON_RIGHT(TheText.Get("DBPINS")); break; case 5: TEXT_ON_RIGHT(TheText.Get("TRINST")); break; case 6: TEXT_ON_RIGHT(TheText.Get("PRTRST")); break; case 7: TEXT_ON_RIGHT(TheText.Get("QUINST")); break; case 8: TEXT_ON_RIGHT(TheText.Get("PQUINS")); break; default: TEXT_ON_RIGHT(TheText.Get("NOSTUC")); break; } STAT_LINE_1(int, "PASDRO", CStats::PassengersDroppedOffWithTaxi); STAT_LINE_1(int, "MONTAX", CStats::MoneyMadeWithTaxi); STAT_LINE_1(int, "FEST_LS", CStats::LivesSavedWithAmbulance); STAT_LINE_1(int, "FEST_HA", CStats::HighestLevelAmbulanceMission); STAT_LINE_1(int, "FEST_CC", CStats::CriminalsCaught); STAT_LINE_1(int, "FEST_FE", CStats::FiresExtinguished); STAT_LINE_1(int, "DAYPLC", CTimer::GetTimeInMilliseconds() + 100); return counter; #undef STAT_LINE_1 #undef STAT_LINE_2 #undef TEXT_ON_LEFT_GXT #undef TEXT_ON_RIGHT #undef int_STAT_IS_FLOAT #undef float_STAT_IS_FLOAT } #undef GetBackJustUp #undef GetBackJustDown #undef ChangeScreen #endif
37.254045
297
0.73025
gameblabla
4f3fd3b9026e1bdd9e65bbbf17431c749e9254ef
1,808
hpp
C++
include/boost/spirit/iterator/position_iterator_fwd.hpp
dstrigl/mcotf
92a9caf6173b1241a2f9ed45cd379469762b7178
[ "BSL-1.0" ]
1
2016-05-17T03:36:52.000Z
2016-05-17T03:36:52.000Z
include/boost/spirit/iterator/position_iterator_fwd.hpp
dstrigl/mcotf
92a9caf6173b1241a2f9ed45cd379469762b7178
[ "BSL-1.0" ]
null
null
null
include/boost/spirit/iterator/position_iterator_fwd.hpp
dstrigl/mcotf
92a9caf6173b1241a2f9ed45cd379469762b7178
[ "BSL-1.0" ]
null
null
null
/*============================================================================= Copyright (c) 2006 Tobias Schwinger Copyright (c) 2002-2006 Hartmut Kaiser http://spirit.sourceforge.net/ Use, modification and distribution is subject to the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #if !defined(BOOST_SPIRIT_POSITION_ITERATOR_FWD_HPP) #define BOOST_SPIRIT_POSITION_ITERATOR_FWD_HPP #include <string> #include <boost/detail/iterator.hpp> // for boost::detail::iterator_traits #include <boost/spirit/core/nil.hpp> namespace boost { namespace spirit { template <typename String = std::string> struct file_position_base; typedef file_position_base<std::string> file_position; template <typename String = std::string> struct file_position_without_column_base; typedef file_position_without_column_base<std::string> file_position_without_column; template < typename ForwardIteratorT, typename PositionT = file_position_base< std::basic_string< typename boost::detail::iterator_traits<ForwardIteratorT>::value_type > >, typename SelfT = nil_t > class position_iterator; template < typename ForwardIteratorT, typename PositionT = file_position_base< std::basic_string< typename boost::detail::iterator_traits<ForwardIteratorT>::value_type > > > class position_iterator2; template <typename PositionT> class position_policy; }} // namespace boost::spirit #endif
31.719298
89
0.615044
dstrigl
4f425a192d854d1a445168fc2446794b75e3215c
11,164
cpp
C++
QuantExt/test/blackvariancesurfacesparse.cpp
PiotrSiejda/Engine
8360b5de32408f2a37da5ac3ca7b4e913bf67e9f
[ "BSD-3-Clause" ]
null
null
null
QuantExt/test/blackvariancesurfacesparse.cpp
PiotrSiejda/Engine
8360b5de32408f2a37da5ac3ca7b4e913bf67e9f
[ "BSD-3-Clause" ]
null
null
null
QuantExt/test/blackvariancesurfacesparse.cpp
PiotrSiejda/Engine
8360b5de32408f2a37da5ac3ca7b4e913bf67e9f
[ "BSD-3-Clause" ]
1
2022-02-07T02:04:10.000Z
2022-02-07T02:04:10.000Z
/* Copyright (C) 2019 Quaternion Risk Management Ltd All rights reserved. This file is part of ORE, a free-software/open-source library for transparent pricing and risk analysis - http://opensourcerisk.org ORE is free software: you can redistribute it and/or modify it under the terms of the Modified BSD License. You should have received a copy of the license along with this program. The license is also available online at <http://opensourcerisk.org> This program is distributed on the basis that it will form a useful contribution to risk analytics and model standardisation, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ #include "toplevelfixture.hpp" #include <boost/make_shared.hpp> #include <boost/test/unit_test.hpp> #include <ql/time/calendars/target.hpp> #include <ql/time/daycounters/actualactual.hpp> #include <qle/termstructures/blackvariancesurfacesparse.hpp> using namespace boost::unit_test_framework; using namespace QuantLib; using namespace QuantExt; using namespace std; BOOST_FIXTURE_TEST_SUITE(QuantExtTestSuite, qle::test::TopLevelFixture) BOOST_AUTO_TEST_SUITE(BlackVarianceSurfaceSparse) BOOST_AUTO_TEST_CASE(testBlackVarianceSurface) { BOOST_TEST_MESSAGE("Testing QuantExt::BlackVarianceSurfaceSparse with market data..."); SavedSettings backup; // using data from https://papers.ssrn.com/sol3/papers.cfm?abstract_id=1694972 // Appendix A: Tables and Figures // Table 1: SX5E Implied Volatility Quotes Settings::instance().evaluationDate() = Date(1, Mar, 2010); Date today = Settings::instance().evaluationDate(); Real spot = 2772.70; // vector of 12 times vector<Time> all_times ({0.025,0.101,0.197,0.274,0.523,0.772,1.769,2.267,2.784,3.781,4.778,5.774}); // strike (%) and vols. // Data is stored here as per the table (vector of vectors, first element is strike, then we have // vols. Empty cells are 0.0. This data is re-organised below vector<vector<Real>> volData ({ { 51.31, 00.00, 00.00, 00.00, 00.00, 00.00, 00.00, 00.00, 00.00, 33.66, 32.91}, { 58.64, 00.00, 00.00, 00.00, 00.00, 00.00, 00.00, 00.00, 00.00, 31.78, 31.29, 30.08}, { 65.97, 00.00, 00.00, 00.00, 00.00, 00.00, 00.00, 00.00, 00.00, 30.19, 29.76, 29.75}, { 73.30, 00.00, 00.00, 00.00, 00.00, 00.00, 00.00, 00.00, 00.00, 28.63, 28.48, 28.48}, { 76.97, 00.00, 00.00, 00.00, 32.62, 30.79, 30.01, 28.43}, { 80.63, 00.00, 00.00, 00.00, 30.58, 29.36, 28.76, 27.53, 27.13, 27.11, 27.11, 27.22, 28.09}, { 84.30, 00.00, 00.00, 00.00, 28.87, 27.98, 27.50, 26.66}, { 86.13, 33.65}, { 87.96, 32.16, 29.06, 27.64, 27.17, 26.63, 26.37, 25.75, 25.55, 25.80, 25.85, 26.11, 26.93}, { 89.79, 30.43, 27.97, 26.72}, { 91.63, 28.80, 26.90, 25.78, 25.57, 25.31, 25.19, 24.97}, { 93.46, 27.24, 25.90, 24.89}, { 95.29, 25.86, 24.88, 24.05, 24.07, 24.04, 24.11, 24.18, 24.10, 24.48, 24.69, 25.01, 25.84}, { 97.12, 24.66, 23.90, 23.29}, { 98.96, 23.58, 23.00, 22.53, 22.69, 22.84, 22.99, 23.47}, { 100.79, 22.47, 22.13, 21.84}, { 102.62, 21.59, 21.40, 21.23, 21.42, 21.73, 21.98, 22.83, 22.75, 23.22, 23.84, 23.92, 24.86}, { 104.45, 20.91, 20.76, 20.69}, { 106.29, 20.56, 20.24, 20.25, 20.39, 20.74, 21.04, 22.13}, { 108.12, 20.45, 19.82, 19.84}, { 109.95, 20.25, 19.59, 19.44, 19.62, 19.88, 20.22, 21.51, 21.61, 22.19, 22.69, 23.05, 23.99}, { 111.78, 19.33, 19.29, 19.20}, { 113.62, 00.00, 00.00, 00.00, 19.02, 19.14, 19.50, 20.91}, { 117.28, 00.00, 00.00, 00.00, 18.85, 18.54, 18.88, 20.39, 20.58, 21.22, 21.86, 22.23, 23.21}, { 120.95, 00.00, 00.00, 00.00, 18.67, 18.11, 18.39, 19.90}, { 124.61, 00.00, 00.00, 00.00, 18.71, 17.85, 17.93, 19.45, 00.00, 20.54, 21.03, 21.64, 22.51}, { 131.94, 00.00, 00.00, 00.00, 00.00, 00.00, 00.00, 00.00, 00.00, 19.88, 20.54, 21.05, 21.90}, { 139.27, 00.00, 00.00, 00.00, 00.00, 00.00, 00.00, 00.00, 00.00, 19.30, 20.02, 20.54, 21.35}, { 146.60, 00.00, 00.00, 00.00, 00.00, 00.00, 00.00, 00.00, 00.00, 18.49, 19.64, 20.12} }); // the 3 vectors we pass into the vol term structure vector<Date> dates; vector<Real> strikes; vector<Volatility> vols; // populate them with the above table for (auto vd: volData) { Real strike = spot * vd[0]; for (Size i = 1; i < vd.size(); i++) { Volatility vol = vd[i] / 100.0; if (vol > 0.0001) { Date d = today + int(all_times[i-1]*365); // Roughly correct // we have a triple dates.push_back(d); strikes.push_back(strike); vols.push_back(vol); } } } Calendar cal = TARGET(); DayCounter dc = ActualActual(); auto surface = boost::make_shared<QuantExt::BlackVarianceSurfaceSparse>(today, cal, dates, strikes, vols, dc); // 1. Check that we recover all of the above inputs for (auto vd: volData) { Real strike = spot * vd[0]; for (Size i = 1; i < vd.size(); i++) { Volatility expectedVol = vd[i] / 100.0; if (expectedVol > 0.0001) { Date d = today + int(all_times[i-1]*365); // Same as above Volatility vol = surface->blackVol(d, strike); BOOST_CHECK_CLOSE(vol, expectedVol, 1e-12); } } } // 2. Check we don't throw for all points and get a positive vol vector<Real> all_strikes; vector<Date> all_dates; for (auto vd: volData) all_strikes.push_back(spot * vd[0]); for (auto t : all_times) all_dates.push_back(today + int(t*365)); for (auto strike : all_strikes) { for(auto d : all_dates) BOOST_CHECK(surface->blackVol(d, strike) > 0.0001); for(auto t : all_times) BOOST_CHECK(surface->blackVol(t, strike) > 0.0001); } } BOOST_AUTO_TEST_CASE(testBlackVarianceSurfaceConstantVol) { BOOST_TEST_MESSAGE("Testing QuantExt::BlackVarianceSurfaceSparse with constant vol data..."); SavedSettings backup; Settings::instance().evaluationDate() = Date(1, Mar, 2010); Date today = Settings::instance().evaluationDate(); // the 3 vectors we pass into the vol term structure // We setup a small grid with 10% everywhere, this should return 10% vol for // any point, i.e. a flat surface vector<Date> dates = { Date(1, Mar, 2011), Date(1, Mar, 2011), Date(1, Mar, 2012), Date(1, Mar, 2012), Date(1, Mar, 2013) }; vector<Real> strikes = { 2000, 3000, 2500, 3500, 3000 }; vector<Volatility> vols(strikes.size(), 0.1); // 10% everywhere Calendar cal = TARGET(); DayCounter dc = ActualActual(); auto surface = QuantExt::BlackVarianceSurfaceSparse(today, cal, dates, strikes, vols, dc); // Check we don't throw for all points and get a vol of 10% for (Time t = 0.2; t < 20; t += 0.2) { for (Real strike = 1500; strike < 6000; strike += 100) { BOOST_CHECK_CLOSE(surface.blackVol(t, strike), 0.1, 1e-12); } } } BOOST_AUTO_TEST_CASE(testBlackVarianceSurfaceInputs) { BOOST_TEST_MESSAGE("Testing QuantExt::BlackVarianceSurfaceSparse with erroneous inputs"); SavedSettings backup; Settings::instance().evaluationDate() = Date(1, Mar, 2010); Date today = Settings::instance().evaluationDate(); // the 3 vectors we pass into the vol term structure // We insure that the vectors don't match in size. vector<Date> dates = { Date(1, Mar, 2011), Date(1, Mar, 2011), Date(1, Mar, 2012), Date(1, Mar, 2012)}; vector<Real> strikes = { 2000, 3000, 2500, 3500, 3000 }; vector<Volatility> vols(strikes.size(), 0.1); Calendar cal = TARGET(); DayCounter dc = ActualActual(); BOOST_CHECK_THROW(QuantExt::BlackVarianceSurfaceSparse(today, cal, dates, strikes, vols, dc), QuantLib::Error); } BOOST_AUTO_TEST_CASE(testBalckVarianceEdgeCases) { // Asking on/past first/last points on strikes/expiries BOOST_TEST_MESSAGE("Testing edge cases"); SavedSettings backup; Settings::instance().evaluationDate() = Date(1, Mar, 2010); Date today = Settings::instance().evaluationDate(); // the 3 vectors we pass into the vol term structure // We setup a small grid with 10% everywhere, this should return 10% vol for // any point, i.e. a flat surface vector<Date> dates = { Date(1, Mar, 2011), Date(1, Mar, 2011), Date(1, Mar, 2012), Date(1, Mar, 2012), Date(1, Mar, 2013) }; vector<Real> strikes = { 2000, 3000, 2500, 3500, 3000 }; vector<Volatility> vols(strikes.size(), 0.1); // 10% everywhere Calendar cal = TARGET(); DayCounter dc = ActualActual(); Time t = 0.0; // vol at reference should be 0 Real strike1 = 0.0; // 0 strike Real strike2 = strikes.front(); // lowest strike given Real strike3 = 1500.0; // between strikes strike Real strike4 = strikes.back(); // highest strike Real strikeNeg = -1000; // at reference date auto surface = QuantExt::BlackVarianceSurfaceSparse(today, cal, dates, strikes, vols, dc); BOOST_CHECK_CLOSE(surface.blackVol(t, strike1), 0.1, 1e-12); BOOST_CHECK_CLOSE(surface.blackVol(t, strike2), 0.1, 1e-12); BOOST_CHECK_CLOSE(surface.blackVol(t, strike3), 0.1, 1e-12); BOOST_CHECK_CLOSE(surface.blackVol(t, strike4), 0.1, 1e-12); // passed reference date Time t1 = surface.timeFromReference(Date(1, Mar, 2014)); Real expectedVol = 0.1; BOOST_CHECK_CLOSE(surface.blackVol(t1, strike2), expectedVol, 1e-12); // negative strike BOOST_CHECK_THROW(surface.blackVol(t, strikeNeg), QuantLib::Error); } BOOST_AUTO_TEST_CASE(testBalckVarianceSinglePoint) { BOOST_TEST_MESSAGE("Testing surface from single point"); // Given a single point, every request should be expected extrapolated value. SavedSettings backup; Settings::instance().evaluationDate() = Date(1, Mar, 2010); Date today = Settings::instance().evaluationDate(); // the 3 vectors we pass into the vol term structure // We setup a single point with 10% - should be a flat surface vector<Date> dates = { Date(1, Mar, 2011) }; vector<Real> strikes = { 2500 }; vector<Volatility> vols(strikes.size(), 0.1); // 10% everywhere Calendar cal = TARGET(); DayCounter dc = ActualActual(); auto surface = QuantExt::BlackVarianceSurfaceSparse(today, cal, dates, strikes, vols, dc); // Check we don't throw for all points and get a vol of 10% for (Time t = 0.0; t < 20; t += 0.2) { for (Real strike = 1500; strike < 6000; strike += 100) { BOOST_CHECK_CLOSE(surface.blackVol(t, strike), 0.1, 1e-12); } } } BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE_END()
40.893773
115
0.617879
PiotrSiejda
4f4c1ff57e5c81af749253f7588a26ce3b03094a
35,098
cpp
C++
src/qt/qmake/generators/makefiledeps.cpp
martende/phantomjs
5cecd7dde7b8fd04ad2c036d16f09a8d2a139854
[ "BSD-3-Clause" ]
1
2015-03-16T20:49:09.000Z
2015-03-16T20:49:09.000Z
src/qt/qmake/generators/makefiledeps.cpp
firedfox/phantomjs
afb0707c9db7b5e693ad1b216a50081565c08ebb
[ "BSD-3-Clause" ]
null
null
null
src/qt/qmake/generators/makefiledeps.cpp
firedfox/phantomjs
afb0707c9db7b5e693ad1b216a50081565c08ebb
[ "BSD-3-Clause" ]
null
null
null
/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the qmake application of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "makefiledeps.h" #include "option.h" #include <qdir.h> #include <qdatetime.h> #include <qfileinfo.h> #include <qbuffer.h> #include <qplatformdefs.h> #if defined(Q_OS_UNIX) # include <unistd.h> #else # include <io.h> #endif #include <qdebug.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #if defined(_MSC_VER) && _MSC_VER >= 1400 #include <share.h> #endif QT_BEGIN_NAMESPACE #if 1 #define qmake_endOfLine(c) (c == '\r' || c == '\n') #else inline bool qmake_endOfLine(const char &c) { return (c == '\r' || c == '\n'); } #endif //#define QMAKE_USE_CACHE QMakeLocalFileName::QMakeLocalFileName(const QString &name) : is_null(name.isNull()) { if(!name.isEmpty()) { if(name.at(0) == QLatin1Char('"') && name.at(name.length()-2) == QLatin1Char('"')) real_name = name.mid(1, name.length()-2); else real_name = name; } } const QString &QMakeLocalFileName::local() const { if(!is_null && local_name.isNull()) local_name = Option::fixPathToLocalOS(real_name, true); return local_name; } struct SourceDependChildren; struct SourceFile { SourceFile() : deps(0), type(QMakeSourceFileInfo::TYPE_UNKNOWN), mocable(0), traversed(0), exists(1), moc_checked(0), dep_checked(0), included_count(0) { } ~SourceFile(); QMakeLocalFileName file; SourceDependChildren *deps; QMakeSourceFileInfo::SourceFileType type; uint mocable : 1, traversed : 1, exists : 1; uint moc_checked : 1, dep_checked : 1; uchar included_count; }; struct SourceDependChildren { SourceFile **children; int num_nodes, used_nodes; SourceDependChildren() : children(0), num_nodes(0), used_nodes(0) { } ~SourceDependChildren() { if(children) free(children); children = 0; } void addChild(SourceFile *s) { if(num_nodes <= used_nodes) { num_nodes += 200; children = (SourceFile**)realloc(children, sizeof(SourceFile*)*(num_nodes)); } children[used_nodes++] = s; } }; SourceFile::~SourceFile() { delete deps; } class SourceFiles { int hash(const char *); public: SourceFiles(); ~SourceFiles(); SourceFile *lookupFile(const char *); inline SourceFile *lookupFile(const QString &f) { return lookupFile(f.toLatin1().constData()); } inline SourceFile *lookupFile(const QMakeLocalFileName &f) { return lookupFile(f.local().toLatin1().constData()); } void addFile(SourceFile *, const char *k=0, bool own=true); struct SourceFileNode { SourceFileNode() : key(0), next(0), file(0), own_file(1) { } ~SourceFileNode() { delete [] key; if(own_file) delete file; } char *key; SourceFileNode *next; SourceFile *file; uint own_file : 1; } **nodes; int num_nodes; }; SourceFiles::SourceFiles() { nodes = (SourceFileNode**)malloc(sizeof(SourceFileNode*)*(num_nodes=3037)); for(int n = 0; n < num_nodes; n++) nodes[n] = 0; } SourceFiles::~SourceFiles() { for(int n = 0; n < num_nodes; n++) { for(SourceFileNode *next = nodes[n]; next;) { SourceFileNode *next_next = next->next; delete next; next = next_next; } } free(nodes); } int SourceFiles::hash(const char *file) { uint h = 0, g; while (*file) { h = (h << 4) + *file; if ((g = (h & 0xf0000000)) != 0) h ^= g >> 23; h &= ~g; file++; } return h; } SourceFile *SourceFiles::lookupFile(const char *file) { int h = hash(file) % num_nodes; for(SourceFileNode *p = nodes[h]; p; p = p->next) { if(!strcmp(p->key, file)) return p->file; } return 0; } void SourceFiles::addFile(SourceFile *p, const char *k, bool own_file) { QByteArray ba = p->file.local().toLatin1(); if(!k) k = ba; int h = hash(k) % num_nodes; SourceFileNode *pn = new SourceFileNode; pn->own_file = own_file; pn->key = qstrdup(k); pn->file = p; pn->next = nodes[h]; nodes[h] = pn; } void QMakeSourceFileInfo::dependTreeWalker(SourceFile *node, SourceDependChildren *place) { if(node->traversed || !node->exists) return; place->addChild(node); node->traversed = true; //set flag if(node->deps) { for(int i = 0; i < node->deps->used_nodes; i++) dependTreeWalker(node->deps->children[i], place); } } void QMakeSourceFileInfo::setDependencyPaths(const QList<QMakeLocalFileName> &l) { // Ensure that depdirs does not contain the same paths several times, to minimize the stats QList<QMakeLocalFileName> ll; for (int i = 0; i < l.count(); ++i) { if (!ll.contains(l.at(i))) ll.append(l.at(i)); } depdirs = ll; } QStringList QMakeSourceFileInfo::dependencies(const QString &file) { QStringList ret; if(!files) return ret; if(SourceFile *node = files->lookupFile(QMakeLocalFileName(file))) { if(node->deps) { /* I stick them into a SourceDependChildren here because it is faster to just iterate over the list to stick them in the list, and reset the flag, then it is to loop over the tree (about 50% faster I saw) --Sam */ SourceDependChildren place; for(int i = 0; i < node->deps->used_nodes; i++) dependTreeWalker(node->deps->children[i], &place); if(place.children) { for(int i = 0; i < place.used_nodes; i++) { place.children[i]->traversed = false; //reset flag ret.append(place.children[i]->file.real()); } } } } return ret; } int QMakeSourceFileInfo::included(const QString &file) { if (!files) return 0; if(SourceFile *node = files->lookupFile(QMakeLocalFileName(file))) return node->included_count; return 0; } bool QMakeSourceFileInfo::mocable(const QString &file) { if(SourceFile *node = files->lookupFile(QMakeLocalFileName(file))) return node->mocable; return false; } QMakeSourceFileInfo::QMakeSourceFileInfo(const QString &cf) { //dep_mode dep_mode = Recursive; //quick project lookups includes = files = 0; files_changed = false; //buffer spare_buffer = 0; spare_buffer_size = 0; //cache cachefile = cf; if(!cachefile.isEmpty()) loadCache(cachefile); } QMakeSourceFileInfo::~QMakeSourceFileInfo() { //cache if(!cachefile.isEmpty() /*&& files_changed*/) saveCache(cachefile); //buffer if(spare_buffer) { free(spare_buffer); spare_buffer = 0; spare_buffer_size = 0; } //quick project lookup delete files; delete includes; } void QMakeSourceFileInfo::setCacheFile(const QString &cf) { cachefile = cf; loadCache(cachefile); } void QMakeSourceFileInfo::addSourceFiles(const QStringList &l, uchar seek, QMakeSourceFileInfo::SourceFileType type) { for(int i=0; i<l.size(); ++i) addSourceFile(l.at(i), seek, type); } void QMakeSourceFileInfo::addSourceFile(const QString &f, uchar seek, QMakeSourceFileInfo::SourceFileType type) { if(!files) files = new SourceFiles; QMakeLocalFileName fn(f); SourceFile *file = files->lookupFile(fn); if(!file) { file = new SourceFile; file->file = fn; files->addFile(file); } else { if(file->type != type && file->type != TYPE_UNKNOWN && type != TYPE_UNKNOWN) warn_msg(WarnLogic, "%s is marked as %d, then %d!", f.toLatin1().constData(), file->type, type); } if(type != TYPE_UNKNOWN) file->type = type; if(seek & SEEK_MOCS && !file->moc_checked) findMocs(file); if(seek & SEEK_DEPS && !file->dep_checked) findDeps(file); } bool QMakeSourceFileInfo::containsSourceFile(const QString &f, SourceFileType type) { if(SourceFile *file = files->lookupFile(QMakeLocalFileName(f))) return (file->type == type || file->type == TYPE_UNKNOWN || type == TYPE_UNKNOWN); return false; } char *QMakeSourceFileInfo::getBuffer(int s) { if(!spare_buffer || spare_buffer_size < s) spare_buffer = (char *)realloc(spare_buffer, spare_buffer_size=s); return spare_buffer; } #ifndef S_ISDIR #define S_ISDIR(x) (x & _S_IFDIR) #endif QMakeLocalFileName QMakeSourceFileInfo::fixPathForFile(const QMakeLocalFileName &f, bool) { return f; } QMakeLocalFileName QMakeSourceFileInfo::findFileForDep(const QMakeLocalFileName &/*dep*/, const QMakeLocalFileName &/*file*/) { return QMakeLocalFileName(); } QFileInfo QMakeSourceFileInfo::findFileInfo(const QMakeLocalFileName &dep) { return QFileInfo(dep.real()); } bool QMakeSourceFileInfo::findDeps(SourceFile *file) { if(file->dep_checked || file->type == TYPE_UNKNOWN) return true; files_changed = true; file->dep_checked = true; const QMakeLocalFileName sourceFile = fixPathForFile(file->file, true); struct stat fst; char *buffer = 0; int buffer_len = 0; { int fd; #if defined(_MSC_VER) && _MSC_VER >= 1400 if (_sopen_s(&fd, sourceFile.local().toLatin1().constData(), _O_RDONLY, _SH_DENYNO, _S_IREAD) != 0) fd = -1; #else fd = open(sourceFile.local().toLatin1().constData(), O_RDONLY); #endif if(fd == -1 || fstat(fd, &fst) || S_ISDIR(fst.st_mode)) return false; buffer = getBuffer(fst.st_size); for(int have_read = 0; (have_read = QT_READ(fd, buffer + buffer_len, fst.st_size - buffer_len)); buffer_len += have_read) ; QT_CLOSE(fd); } if(!buffer) return false; if(!file->deps) file->deps = new SourceDependChildren; int line_count = 1; for(int x = 0; x < buffer_len; ++x) { bool try_local = true; char *inc = 0; if(file->type == QMakeSourceFileInfo::TYPE_UI) { // skip whitespaces while(x < buffer_len && (*(buffer+x) == ' ' || *(buffer+x) == '\t')) ++x; if(*(buffer + x) == '<') { ++x; if(buffer_len >= x + 12 && !strncmp(buffer + x, "includehint", 11) && (*(buffer + x + 11) == ' ' || *(buffer + x + 11) == '>')) { for(x += 11; *(buffer + x) != '>'; ++x) ; int inc_len = 0; for(x += 1 ; *(buffer + x + inc_len) != '<'; ++inc_len) ; *(buffer + x + inc_len) = '\0'; inc = buffer + x; } else if(buffer_len >= x + 13 && !strncmp(buffer + x, "customwidget", 12) && (*(buffer + x + 12) == ' ' || *(buffer + x + 12) == '>')) { for(x += 13; *(buffer + x) != '>'; ++x) ; //skip up to > while(x < buffer_len) { for(x++; *(buffer + x) != '<'; ++x) ; //skip up to < x++; if(buffer_len >= x + 7 && !strncmp(buffer+x, "header", 6) && (*(buffer + x + 6) == ' ' || *(buffer + x + 6) == '>')) { for(x += 7; *(buffer + x) != '>'; ++x) ; //skip up to > int inc_len = 0; for(x += 1 ; *(buffer + x + inc_len) != '<'; ++inc_len) ; *(buffer + x + inc_len) = '\0'; inc = buffer + x; break; } else if(buffer_len >= x + 14 && !strncmp(buffer+x, "/customwidget", 13) && (*(buffer + x + 13) == ' ' || *(buffer + x + 13) == '>')) { x += 14; break; } } } else if(buffer_len >= x + 8 && !strncmp(buffer + x, "include", 7) && (*(buffer + x + 7) == ' ' || *(buffer + x + 7) == '>')) { for(x += 8; *(buffer + x) != '>'; ++x) { if(buffer_len >= x + 9 && *(buffer + x) == 'i' && !strncmp(buffer + x, "impldecl", 8)) { for(x += 8; *(buffer + x) != '='; ++x) ; if(*(buffer + x) != '=') continue; for(++x; *(buffer+x) == '\t' || *(buffer+x) == ' '; ++x) ; char quote = 0; if(*(buffer+x) == '\'' || *(buffer+x) == '"') { quote = *(buffer + x); ++x; } int val_len; for(val_len = 0; true; ++val_len) { if(quote) { if(*(buffer+x+val_len) == quote) break; } else if(*(buffer + x + val_len) == '>' || *(buffer + x + val_len) == ' ') { break; } } //? char saved = *(buffer + x + val_len); *(buffer + x + val_len) = '\0'; if(!strcmp(buffer+x, "in implementation")) { //### do this } } } int inc_len = 0; for(x += 1 ; *(buffer + x + inc_len) != '<'; ++inc_len) ; *(buffer + x + inc_len) = '\0'; inc = buffer + x; } } //read past new line now.. for(; x < buffer_len && !qmake_endOfLine(*(buffer + x)); ++x) ; ++line_count; } else if(file->type == QMakeSourceFileInfo::TYPE_QRC) { } else if(file->type == QMakeSourceFileInfo::TYPE_C) { for(int beginning=1; x < buffer_len; ++x) { // whitespace comments and line-endings for(; x < buffer_len; ++x) { if(*(buffer+x) == ' ' || *(buffer+x) == '\t') { // keep going } else if(*(buffer+x) == '/') { ++x; if(buffer_len >= x) { if(*(buffer+x) == '/') { //c++ style comment for(; x < buffer_len && !qmake_endOfLine(*(buffer + x)); ++x) ; beginning = 1; } else if(*(buffer+x) == '*') { //c style comment for(++x; x < buffer_len; ++x) { if(*(buffer+x) == '*') { if(x+1 < buffer_len && *(buffer + (x+1)) == '/') { ++x; break; } } else if(qmake_endOfLine(*(buffer+x))) { ++line_count; } } } } } else if(qmake_endOfLine(*(buffer+x))) { ++line_count; beginning = 1; } else { break; } } if(x >= buffer_len) break; // preprocessor directive if(beginning && *(buffer+x) == '#') break; // quoted strings if(*(buffer+x) == '\'' || *(buffer+x) == '"') { const char term = *(buffer+(x++)); for(; x < buffer_len; ++x) { if(*(buffer+x) == term) { ++x; break; } else if(*(buffer+x) == '\\') { ++x; } else if(qmake_endOfLine(*(buffer+x))) { ++line_count; } } } beginning = 0; } if(x >= buffer_len) break; //got a preprocessor symbol ++x; while(x < buffer_len) { if(*(buffer+x) != ' ' && *(buffer+x) != '\t') break; ++x; } int keyword_len = 0; const char *keyword = buffer+x; while(x+keyword_len < buffer_len) { if(((*(buffer+x+keyword_len) < 'a' || *(buffer+x+keyword_len) > 'z')) && *(buffer+x+keyword_len) != '_') { for(x+=keyword_len; //skip spaces after keyword x < buffer_len && (*(buffer+x) == ' ' || *(buffer+x) == '\t'); x++) ; break; } else if(qmake_endOfLine(*(buffer+x+keyword_len))) { x += keyword_len-1; keyword_len = 0; break; } keyword_len++; } if((keyword_len == 7 && !strncmp(keyword, "include", 7)) // C & Obj-C || (keyword_len == 6 && !strncmp(keyword, "import", 6))) { // Obj-C char term = *(buffer + x); if(term == '<') { try_local = false; term = '>'; } else if(term != '"') { //wtf? continue; } x++; int inc_len; for(inc_len = 0; *(buffer + x + inc_len) != term && !qmake_endOfLine(*(buffer + x + inc_len)); ++inc_len) ; *(buffer + x + inc_len) = '\0'; inc = buffer + x; x += inc_len; } else if(keyword_len == 13 && !strncmp(keyword, "qmake_warning", keyword_len)) { char term = 0; if(*(buffer + x) == '"') term = '"'; if(*(buffer + x) == '\'') term = '\''; if(term) x++; int msg_len; for(msg_len = 0; (term && *(buffer + x + msg_len) != term) && !qmake_endOfLine(*(buffer + x + msg_len)); ++msg_len) ; *(buffer + x + msg_len) = '\0'; debug_msg(0, "%s:%d %s -- %s", file->file.local().toLatin1().constData(), line_count, keyword, buffer+x); x += msg_len; } else if(*(buffer+x) == '\'' || *(buffer+x) == '"') { const char term = *(buffer+(x++)); while(x < buffer_len) { if(*(buffer+x) == term) break; if(*(buffer+x) == '\\') { x+=2; } else { if(qmake_endOfLine(*(buffer+x))) ++line_count; ++x; } } } else { --x; } } if(inc) { if(!includes) includes = new SourceFiles; SourceFile *dep = includes->lookupFile(inc); if(!dep) { bool exists = false; QMakeLocalFileName lfn(inc); if(QDir::isRelativePath(lfn.real())) { if(try_local) { QDir sourceDir = findFileInfo(sourceFile).dir(); QMakeLocalFileName f(sourceDir.absoluteFilePath(lfn.local())); if(findFileInfo(f).exists()) { lfn = fixPathForFile(f); exists = true; } } if(!exists) { //path lookup for(QList<QMakeLocalFileName>::Iterator it = depdirs.begin(); it != depdirs.end(); ++it) { QMakeLocalFileName f((*it).real() + Option::dir_sep + lfn.real()); QFileInfo fi(findFileInfo(f)); if(fi.exists() && !fi.isDir()) { lfn = fixPathForFile(f); exists = true; break; } } } if(!exists) { //heuristic lookup lfn = findFileForDep(QMakeLocalFileName(inc), file->file); if((exists = !lfn.isNull())) lfn = fixPathForFile(lfn); } } else { exists = QFile::exists(lfn.real()); } if(!lfn.isNull()) { dep = files->lookupFile(lfn); if(!dep) { dep = new SourceFile; dep->file = lfn; dep->type = QMakeSourceFileInfo::TYPE_C; files->addFile(dep); includes->addFile(dep, inc, false); } dep->exists = exists; } } if(dep && dep->file != file->file) { dep->included_count++; if(dep->exists) { debug_msg(5, "%s:%d Found dependency to %s", file->file.real().toLatin1().constData(), line_count, dep->file.local().toLatin1().constData()); file->deps->addChild(dep); } } } } if(dependencyMode() == Recursive) { //done last because buffer is shared for(int i = 0; i < file->deps->used_nodes; i++) { if(!file->deps->children[i]->deps) findDeps(file->deps->children[i]); } } return true; } bool QMakeSourceFileInfo::findMocs(SourceFile *file) { if(file->moc_checked) return true; files_changed = true; file->moc_checked = true; int buffer_len; char *buffer = 0; { struct stat fst; int fd; #if defined(_MSC_VER) && _MSC_VER >= 1400 if (_sopen_s(&fd, fixPathForFile(file->file, true).local().toLocal8Bit().constData(), _O_RDONLY, _SH_DENYRW, _S_IREAD) != 0) fd = -1; #else fd = open(fixPathForFile(file->file, true).local().toLocal8Bit().constData(), O_RDONLY); #endif if(fd == -1 || fstat(fd, &fst) || S_ISDIR(fst.st_mode)) return false; //shouldn't happen buffer = getBuffer(fst.st_size); for(int have_read = buffer_len = 0; (have_read = QT_READ(fd, buffer + buffer_len, fst.st_size - buffer_len)); buffer_len += have_read) ; QT_CLOSE(fd); } debug_msg(2, "findMocs: %s", file->file.local().toLatin1().constData()); int line_count = 1; bool ignore_qobject = false, ignore_qgadget = false; /* qmake ignore Q_GADGET */ /* qmake ignore Q_OBJECT */ for(int x = 0; x < buffer_len; x++) { if(*(buffer + x) == '/') { ++x; if(buffer_len >= x) { if(*(buffer + x) == '/') { //c++ style comment for(;x < buffer_len && !qmake_endOfLine(*(buffer + x)); ++x) ; } else if(*(buffer + x) == '*') { //c style comment for(++x; x < buffer_len; ++x) { if(*(buffer + x) == 't' || *(buffer + x) == 'q') { //ignore if(buffer_len >= (x + 20) && !strncmp(buffer + x + 1, "make ignore Q_OBJECT", 20)) { debug_msg(2, "Mocgen: %s:%d Found \"qmake ignore Q_OBJECT\"", file->file.real().toLatin1().constData(), line_count); x += 20; ignore_qobject = true; } else if(buffer_len >= (x + 20) && !strncmp(buffer + x + 1, "make ignore Q_GADGET", 20)) { debug_msg(2, "Mocgen: %s:%d Found \"qmake ignore Q_GADGET\"", file->file.real().toLatin1().constData(), line_count); x += 20; ignore_qgadget = true; } } else if(*(buffer + x) == '*') { if(buffer_len >= (x+1) && *(buffer + (x+1)) == '/') { ++x; break; } } else if(Option::debug_level && qmake_endOfLine(*(buffer + x))) { ++line_count; } } } } } else if(*(buffer+x) == '\'' || *(buffer+x) == '"') { const char term = *(buffer+(x++)); while(x < buffer_len) { if(*(buffer+x) == term) break; if(*(buffer+x) == '\\') { x+=2; } else { if(qmake_endOfLine(*(buffer+x))) ++line_count; ++x; } } } if(Option::debug_level && qmake_endOfLine(*(buffer+x))) ++line_count; if(((buffer_len > x+2 && *(buffer+x+1) == 'Q' && *(buffer+x+2) == '_') || (buffer_len > x+4 && *(buffer+x+1) == 'Q' && *(buffer+x+2) == 'O' && *(buffer+x+3) == 'M' && *(buffer+x+4) == '_')) && *(buffer + x) != '_' && (*(buffer + x) < 'a' || *(buffer + x) > 'z') && (*(buffer + x) < 'A' || *(buffer + x) > 'Z') && (*(buffer + x) < '0' || *(buffer + x) > '9')) { ++x; int match = 0; static const char *interesting[] = { "OBJECT", "GADGET", "M_OBJECT" }; for(int interest = 0, m1, m2; interest < 3; ++interest) { if(interest == 0 && ignore_qobject) continue; else if(interest == 1 && ignore_qgadget) continue; for(m1 = 0, m2 = 0; *(interesting[interest]+m1); ++m1) { if(*(interesting[interest]+m1) != *(buffer+x+2+m1)) { m2 = -1; break; } ++m2; } if(m1 == m2) { match = m2 + 2; break; } } if(match && *(buffer+x+match) != '_' && (*(buffer+x+match) < 'a' || *(buffer+x+match) > 'z') && (*(buffer+x+match) < 'A' || *(buffer+x+match) > 'Z') && (*(buffer+x+match) < '0' || *(buffer+x+match) > '9')) { if(Option::debug_level) { *(buffer+x+match) = '\0'; debug_msg(2, "Mocgen: %s:%d Found MOC symbol %s", file->file.real().toLatin1().constData(), line_count, buffer+x); } file->mocable = true; return true; } } } return true; } void QMakeSourceFileInfo::saveCache(const QString &cf) { #ifdef QMAKE_USE_CACHE if(cf.isEmpty()) return; QFile file(QMakeLocalFileName(cf).local()); if(file.open(QIODevice::WriteOnly)) { QTextStream stream(&file); stream << qmake_version() << endl << endl; //version { //cache verification QMap<QString, QStringList> verify = getCacheVerification(); stream << verify.count() << endl; for(QMap<QString, QStringList>::iterator it = verify.begin(); it != verify.end(); ++it) { stream << it.key() << endl << it.value().join(";") << endl; } stream << endl; } if(files->nodes) { for(int file = 0; file < files->num_nodes; ++file) { for(SourceFiles::SourceFileNode *node = files->nodes[file]; node; node = node->next) { stream << node->file->file.local() << endl; //source stream << node->file->type << endl; //type //depends stream << ";"; if(node->file->deps) { for(int depend = 0; depend < node->file->deps->used_nodes; ++depend) { if(depend) stream << ";"; stream << node->file->deps->children[depend]->file.local(); } } stream << endl; stream << node->file->mocable << endl; //mocable stream << endl; //just for human readability } } } stream.flush(); file.close(); } #else Q_UNUSED(cf); #endif } void QMakeSourceFileInfo::loadCache(const QString &cf) { if(cf.isEmpty()) return; #ifdef QMAKE_USE_CACHE QMakeLocalFileName cache_file(cf); int fd = open(QMakeLocalFileName(cf).local().toLatin1(), O_RDONLY); if(fd == -1) return; QFileInfo cache_fi = findFileInfo(cache_file); if(!cache_fi.exists() || cache_fi.isDir()) return; QFile file; if(!file.open(QIODevice::ReadOnly, fd)) return; QTextStream stream(&file); if(stream.readLine() == qmake_version()) { //version check stream.skipWhiteSpace(); bool verified = true; { //cache verification QMap<QString, QStringList> verify; int len = stream.readLine().toInt(); for(int i = 0; i < len; ++i) { QString var = stream.readLine(); QString val = stream.readLine(); verify.insert(var, val.split(';', QString::SkipEmptyParts)); } verified = verifyCache(verify); } if(verified) { stream.skipWhiteSpace(); if(!files) files = new SourceFiles; while(!stream.atEnd()) { QString source = stream.readLine(); QString type = stream.readLine(); QString depends = stream.readLine(); QString mocable = stream.readLine(); stream.skipWhiteSpace(); QMakeLocalFileName fn(source); QFileInfo fi = findFileInfo(fn); SourceFile *file = files->lookupFile(fn); if(!file) { file = new SourceFile; file->file = fn; files->addFile(file); file->type = (SourceFileType)type.toInt(); file->exists = fi.exists(); } if(fi.exists() && fi.lastModified() < cache_fi.lastModified()) { if(!file->dep_checked) { //get depends if(!file->deps) file->deps = new SourceDependChildren; file->dep_checked = true; QStringList depend_list = depends.split(";", QString::SkipEmptyParts); for(int depend = 0; depend < depend_list.size(); ++depend) { QMakeLocalFileName dep_fn(depend_list.at(depend)); QFileInfo dep_fi(findFileInfo(dep_fn)); SourceFile *dep = files->lookupFile(dep_fn); if(!dep) { dep = new SourceFile; dep->file = dep_fn; dep->exists = dep_fi.exists(); dep->type = QMakeSourceFileInfo::TYPE_UNKNOWN; files->addFile(dep); } dep->included_count++; file->deps->addChild(dep); } } if(!file->moc_checked) { //get mocs file->moc_checked = true; file->mocable = mocable.toInt(); } } } } } #endif } QMap<QString, QStringList> QMakeSourceFileInfo::getCacheVerification() { return QMap<QString, QStringList>(); } bool QMakeSourceFileInfo::verifyCache(const QMap<QString, QStringList> &v) { return v == getCacheVerification(); } QT_END_NAMESPACE
36.446521
123
0.448544
martende
4f4e283295606eedac7b16d65824079da45d6cb5
862
cc
C++
src/job_server/job_handlers/job_handler.cc
varqox/sim
b115a4e858dda1288917243e511751b835c28482
[ "MIT" ]
12
2017-11-05T21:02:58.000Z
2022-03-28T23:11:51.000Z
src/job_server/job_handlers/job_handler.cc
varqox/sim
b115a4e858dda1288917243e511751b835c28482
[ "MIT" ]
11
2017-01-05T18:11:41.000Z
2019-11-01T12:40:55.000Z
src/job_server/job_handlers/job_handler.cc
krzyk240/sim
b115a4e858dda1288917243e511751b835c28482
[ "MIT" ]
6
2016-12-25T11:22:34.000Z
2020-10-20T16:03:51.000Z
#include "src/job_server/job_handlers/job_handler.hh" #include "sim/jobs/job.hh" #include "src/job_server/main.hh" using sim::jobs::Job; namespace job_server::job_handlers { void JobHandler::job_canceled() { STACK_UNWINDING_MARK; mysql.prepare("UPDATE jobs SET status=?, data=? WHERE id=?") .bind_and_execute(EnumVal(Job::Status::CANCELED), get_log(), job_id_); } void JobHandler::job_done() { STACK_UNWINDING_MARK; mysql.prepare("UPDATE jobs SET status=?, data=? WHERE id=?") .bind_and_execute(EnumVal(Job::Status::DONE), get_log(), job_id_); } void JobHandler::job_done(StringView new_info) { STACK_UNWINDING_MARK; mysql.prepare("UPDATE jobs SET status=?, info=?, data=? WHERE id=?") .bind_and_execute(EnumVal(Job::Status::DONE), new_info, get_log(), job_id_); } } // namespace job_server::job_handlers
27.806452
84
0.704176
varqox
4f4e6389223987dbc6a42c6cb74bad32d1c59ffe
410
cpp
C++
src/Game/JavaScriptApp.cpp
pixelpicosean/mural
d6fbacbce2da39af25b44cd5861030573ca8709a
[ "Unlicense", "MIT" ]
33
2016-03-26T01:16:49.000Z
2022-02-23T10:46:31.000Z
src/Game/JavaScriptApp.cpp
pixelpicosean/mural
d6fbacbce2da39af25b44cd5861030573ca8709a
[ "Unlicense", "MIT" ]
4
2015-10-06T01:32:27.000Z
2015-10-06T01:35:41.000Z
src/Game/JavaScriptApp.cpp
pixelpicosean/mural
d6fbacbce2da39af25b44cd5861030573ca8709a
[ "Unlicense", "MIT" ]
14
2016-01-02T18:03:10.000Z
2022-01-29T03:47:53.000Z
// // JavaScriptApp.cpp // Mural // // Created by Sean on 10/22/15. // // #include "JavaScriptApp.hpp" JavaScriptApp::JavaScriptApp() { jsContext = duk_create_heap_default(); } JavaScriptApp::~JavaScriptApp() { duk_destroy_heap(jsContext); } static void register_MuImage(duk_context *jsContext) { duk_push_global_object(jsContext); } void JavaScriptApp::init() { register_MuImage(jsContext); }
15.769231
54
0.72439
pixelpicosean
4f4e895bec194a85ce445f437043005bbcc3e7ef
493
hpp
C++
Noxis/Sprite.hpp
mr-linch/noxis
7b8015bc36f478a81aafa3fb7ef84156ff642343
[ "MIT" ]
null
null
null
Noxis/Sprite.hpp
mr-linch/noxis
7b8015bc36f478a81aafa3fb7ef84156ff642343
[ "MIT" ]
3
2017-07-28T12:56:52.000Z
2017-07-28T12:56:52.000Z
Noxis/Sprite.hpp
mr-linch/noxis
7b8015bc36f478a81aafa3fb7ef84156ff642343
[ "MIT" ]
null
null
null
#pragma once #include "ns.hpp" #include "Node.hpp" #include <string> NOXIS_NS_BEGIN; class Texture; class Renderer; class Sprite : public Node { Texture *texture; public: /** * @brief Load sprite by path */ Sprite(const std::string &path, Node *parent = nullptr); /** * @brief Load sprite from texture */ Sprite(Texture *texture, Node *parent = nullptr); void onRender(Renderer *renderer) override; virtual ~Sprite(); }; NOXIS_NS_END;
15.40625
60
0.638945
mr-linch
4f523bde93bd4b27c3820e60c214b7900ae1bd5e
7,433
cpp
C++
Game/Source/App.cpp
UriKurae/PlatformerGame
a4ff867c8e1eac4df4086c16f7b50bd2ce320926
[ "MIT" ]
1
2020-10-07T10:42:49.000Z
2020-10-07T10:42:49.000Z
Game/Source/App.cpp
UriKurae/PlatformerGame
a4ff867c8e1eac4df4086c16f7b50bd2ce320926
[ "MIT" ]
null
null
null
Game/Source/App.cpp
UriKurae/PlatformerGame
a4ff867c8e1eac4df4086c16f7b50bd2ce320926
[ "MIT" ]
null
null
null
#include "App.h" #include "Window.h" #include "Input.h" #include "Render.h" #include "Fonts.h" #include "Textures.h" #include "Audio.h" #include "Map.h" #include "EntityManager.h" #include "SceneManager.h" #include "Pathfinding.h" #include "Defs.h" #include "Log.h" #include <iostream> #include <sstream> // Constructor App::App(int argc, char* args[]) : argc(argc), args(args) { input = new Input(); win = new Window(); render = new Render(); tex = new Textures(); audio = new Audio(); map = new Map(); entityManager = new EntityManager(); sceneManager = new SceneManager(); pathFinding = new PathFinding(); fonts = new Fonts(); // Ordered for awake / Start / Update // Reverse order of CleanUp AddModule(win, true); AddModule(audio, true); AddModule(input,true); AddModule(tex, true); AddModule(map, false); AddModule(sceneManager, true); AddModule(entityManager, false); AddModule(fonts, true); AddModule(pathFinding, false); // Render last to swap buffer AddModule(render, true); } // Destructor App::~App() { // Release modules ListItem<Module*>* item = modules.end; while(item != NULL) { RELEASE(item->data); item = item->prev; } modules.Clear(); } void App::AddModule(Module* module, bool active) { module->Init(active); modules.Add(module); } // Called before render is available bool App::Awake() { PERF_START(ptimer); pugi::xml_document configFile; pugi::xml_node config; pugi::xml_node configApp; bool ret = false; config = LoadConfig(configFile); if (config.empty() == false) { ret = true; configApp = config.child("app"); title.Create(configApp.child("title").child_value()); organization.Create(configApp.child("organization").child_value()); cappedMs = configApp.attribute("framerate_cap").as_float(); } if(ret == true) { ListItem<Module*>* item; item = modules.start; while(item != NULL && ret == true) { ret = item->data->Awake(config.child(item->data->name.GetString())); item = item->next; } } PERF_PEEK(ptimer); return ret; } // Called before the first frame bool App::Start() { PERF_START(ptimer); bool ret = true; ListItem<Module*>* item; item = modules.start; while(item != NULL && ret == true) { ret = item->data->Start(); item = item->next; } PERF_PEEK(ptimer); return ret; } // Called each loop iteration bool App::Update() { PERF_START(ptimer); bool ret = true; PrepareUpdate(); if(input->GetWindowEvent(WE_QUIT) == true) ret = false; if(ret == true) ret = PreUpdate(); if(ret == true) ret = DoUpdate(); if(ret == true) ret = PostUpdate(); FinishUpdate(); return ret; } // Load config from XML file pugi::xml_node App::LoadConfig(pugi::xml_document& configFile) const { pugi::xml_node ret; pugi::xml_parse_result result = configFile.load_file(CONFIG_FILENAME); if (result == NULL) LOG("Could not load xml file: %s. pugi error: %s", CONFIG_FILENAME, result.description()); else ret = configFile.child("config"); return ret; } // --------------------------------------------- void App::PrepareUpdate() { ++frameCount; ++lastSecFrameCount; if (input->GetKey(SDL_SCANCODE_F11) == KEY_DOWN) { changeMs = !changeMs; if (changeMs) { cappedMs = 1000 / 30; } else if (!changeMs) cappedMs = 1000 / 60; } dt = frameTime.ReadSec(); frameTime.Start(); } // --------------------------------------------- void App::FinishUpdate() { if (saveGameRequested) SaveGame(); if (loadGameRequested) LoadGame(); // Frame rate and dt control if (lastSecFrameTime.Read() > 1000) { lastSecFrameTime.Start(); prevLastSecFrameCount = lastSecFrameCount; lastSecFrameCount = 0; } float averageFps = float(frameCount) / startupTime.ReadSec(); float secondsSinceStartup = startupTime.ReadSec(); uint32 lastFrameMs = frameTime.Read(); uint32 framesOnLastUpdate = prevLastSecFrameCount; SString vsyncChar; if(render->vsync) vsyncChar.Create("on"); else vsyncChar.Create("off"); static char title[256]; sprintf_s(title, 256, "FPS: %i / Av.FPS: %.2f / Last Frame Ms: %02u / Vsync: %s", framesOnLastUpdate, averageFps, lastFrameMs, vsyncChar.GetString()); app->win->SetTitle(title); if ((cappedMs > 0) && (lastFrameMs < cappedMs)) { PERF_START(ptimer); SDL_Delay(cappedMs - lastFrameMs); //LOG("We waited for %i ms and got back in %f", cappedMs, ptimer.ReadMs()); } } // Call modules before each loop iteration bool App::PreUpdate() { bool ret = true; ListItem<Module*>* item; item = modules.start; Module* pModule = NULL; for(item = modules.start; item != NULL && ret == true; item = item->next) { pModule = item->data; if(pModule->active == false) { continue; } ret = item->data->PreUpdate(); } return ret; } // Call modules on each loop iteration bool App::DoUpdate() { bool ret = true; ListItem<Module*>* item; item = modules.start; Module* pModule = NULL; for(item = modules.start; item != NULL && ret == true; item = item->next) { pModule = item->data; if(pModule->active == false) { continue; } ret = item->data->Update(dt); } return ret; } // Call modules after each loop iteration bool App::PostUpdate() { bool ret = true; ListItem<Module*>* item; Module* pModule = NULL; for(item = modules.start; item != NULL && ret == true; item = item->next) { pModule = item->data; if(pModule->active == false) { continue; } ret = item->data->PostUpdate(); } return ret; } // Called before quitting bool App::CleanUp() { bool ret = true; ListItem<Module*>* item; item = modules.end; while(item != NULL && ret == true) { ret = item->data->CleanUp(); item = item->prev; } return ret; } // --------------------------------------- int App::GetArgc() const { return argc; } // --------------------------------------- const char* App::GetArgv(int index) const { if(index < argc) return args[index]; else return NULL; } // --------------------------------------- const char* App::GetTitle() const { return title.GetString(); } // --------------------------------------- const char* App::GetOrganization() const { return organization.GetString(); } void App::RequestLoadGame() { loadGameRequested = true; } void App::RequestSaveGame() { saveGameRequested = true; } bool App::LoadGame() { loadGameRequested = false; bool ret = true; pugi::xml_parse_result resul = saveLoadFile.load_file("save_game.xml"); if (resul == NULL) { LOG("Could not load save and load xml file. pugi error: %s", resul.description()); return false; } else { saveState = saveLoadFile.child("save_status"); ListItem<Module*>* item; item = modules.start; while (item != NULL && ret) { ret = item->data->Load(saveState.child(item->data->name.GetString())); item = item->next; } LOG("File loaded successfully!"); } return true; } bool App::SaveGame() { LOG("Saving Results!!"); saveGameRequested = false; bool ret = true; ListItem<Module*>* item = modules.start; pugi::xml_document file; auto root = file.append_child("save_status"); while (item != NULL) { root.append_child(item->data->name.GetString()); ret = item->data->Save(root.child(item->data->name.GetString())); item = item->next; } bool saveSucceed = file.save_file("save_game.xml", PUGIXML_TEXT(" ")); if (saveSucceed == false) { LOG("Couldn't save the file. pugi error: %s", pugi::status_internal_error); } return ret; }
18.041262
151
0.640118
UriKurae
4f5342d750c5ffda6e6e5e1937ca7d0cfe0a6f8e
1,893
hpp
C++
render/include/storm/render/pipeline/RenderPassDescription.hpp
Arthapz/StormKit
7c8dead874734d04b97776287b25bf2ebe9be617
[ "MIT" ]
17
2019-02-12T14:40:06.000Z
2021-12-21T12:54:17.000Z
render/include/storm/render/pipeline/RenderPassDescription.hpp
Arthapz/StormKit
7c8dead874734d04b97776287b25bf2ebe9be617
[ "MIT" ]
null
null
null
render/include/storm/render/pipeline/RenderPassDescription.hpp
Arthapz/StormKit
7c8dead874734d04b97776287b25bf2ebe9be617
[ "MIT" ]
2
2019-02-21T10:07:42.000Z
2020-05-08T19:49:10.000Z
// Copyright (C) 2021 Arthur LAURENT <arthur.laurent4@gmail.com> // This file is subject to the license terms in the LICENSE file // found in the top-level of this distribution #pragma once /////////// - STL - /////////// #include <vector> /////////// - StormKit::core - /////////// #include <storm/core/Hash.hpp> /////////// - StormKit::render - /////////// #include <storm/render/core/Enums.hpp> namespace storm::render { struct AttachmentDescription { PixelFormat format; SampleCountFlag samples = SampleCountFlag::C1_BIT; AttachmentLoadOperation load_op = AttachmentLoadOperation::Clear; AttachmentStoreOperation store_op = AttachmentStoreOperation::Store; AttachmentLoadOperation stencil_load_op = AttachmentLoadOperation::Dont_Care; AttachmentStoreOperation stencil_store_op = AttachmentStoreOperation::Dont_Care; TextureLayout source_layout = TextureLayout::Undefined; TextureLayout destination_layout = TextureLayout::Present_Src; bool resolve = false; }; using AttachmentDescriptions = std::vector<AttachmentDescription>; struct Subpass { struct Ref { core::UInt32 attachment_id; TextureLayout layout = TextureLayout::Color_Attachment_Optimal; }; PipelineBindPoint bind_point; std::vector<Ref> attachment_refs; }; using Subpasses = std::vector<Subpass>; struct RenderPassDescription { AttachmentDescriptions attachments; Subpasses subpasses; bool isCompatible(const RenderPassDescription &description) const noexcept; }; } // namespace storm::render HASH_FUNC(storm::render::AttachmentDescription) HASH_FUNC(storm::render::Subpass::Ref) HASH_FUNC(storm::render::Subpass) HASH_FUNC(storm::render::RenderPassDescription)
32.637931
89
0.672478
Arthapz
4f534b57fa6b44542a5f864d69198af1bff27b1f
2,286
hpp
C++
ql/time/calendars/mexico.hpp
reder2000/QuantLib
1d58c3859a0872722aa570283c6571aeb64f6f39
[ "BSD-3-Clause" ]
null
null
null
ql/time/calendars/mexico.hpp
reder2000/QuantLib
1d58c3859a0872722aa570283c6571aeb64f6f39
[ "BSD-3-Clause" ]
2
2020-12-28T06:52:54.000Z
2021-04-07T09:41:08.000Z
ql/time/calendars/mexico.hpp
reder2000/QuantLib
1d58c3859a0872722aa570283c6571aeb64f6f39
[ "BSD-3-Clause" ]
null
null
null
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2005 StatPro Italia srl This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <quantlib-dev@lists.sf.net>. The license is also available online at <http://quantlib.org/license.shtml>. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ /*! \file mexico.hpp \brief Mexican calendars */ #ifndef quantlib_mexico_calendar_hpp #define quantlib_mexico_calendar_hpp #include <ql/time/calendar.hpp> namespace QuantLib { //! %Mexican calendars /*! Holidays for the Mexican stock exchange (data from <http://www.bmv.com.mx/>): <ul> <li>Saturdays</li> <li>Sundays</li> <li>New Year's Day, January 1st</li> <li>Constitution Day, first Monday in February (February 5th before 2006)</li> <li>Birthday of Benito Juarez, third Monday in February (March 21st before 2006)</li> <li>Holy Thursday</li> <li>Good Friday</li> <li>Labour Day, May 1st</li> <li>National Day, September 16th</li> <li>All Souls Day, November 2nd (bank holiday, not a public one)</li> <li>Revolution Day, third Monday in November (November 20th before 2006)</li> <li>Our Lady of Guadalupe, December 12th</li> <li>Christmas, December 25th</li> </ul> \ingroup calendars */ class Mexico : public Calendar { private: class BmvImpl : public Calendar::WesternImpl { public: std::string name() const { return "Mexican stock exchange"; } bool isBusinessDay(const ExtDate&) const; }; public: enum Market { BMV //!< Mexican stock exchange }; Mexico(Market m = BMV); }; } #endif
31.75
79
0.646107
reder2000
4f5581187d1018ad704ae31538a7144ac2b0c5ef
216
cpp
C++
PRACTICE/seriesX1.cpp
prasantmahato/CP-Practice
54ca79117fcb0e2722bfbd1007b972a3874bef03
[ "MIT" ]
null
null
null
PRACTICE/seriesX1.cpp
prasantmahato/CP-Practice
54ca79117fcb0e2722bfbd1007b972a3874bef03
[ "MIT" ]
null
null
null
PRACTICE/seriesX1.cpp
prasantmahato/CP-Practice
54ca79117fcb0e2722bfbd1007b972a3874bef03
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { int testCases,x,i; long int result; cin>>testCases; while(testCases--) { cin>>x; result=((x*x*x)+x); cout<<result<<endl; } }
13.5
27
0.555556
prasantmahato
4f57322c8be696f55f021a6ddbf41b3c29ce0109
85,664
cpp
C++
mlir/tools/mlir-linalg-ods-gen/mlir-linalg-ods-gen.cpp
Kvarnefalk/llvm-project
8b5f5798aaa24074609d151ea906d114cf5337c2
[ "Apache-2.0" ]
1
2021-02-17T04:40:38.000Z
2021-02-17T04:40:38.000Z
mlir/tools/mlir-linalg-ods-gen/mlir-linalg-ods-gen.cpp
Kvarnefalk/llvm-project
8b5f5798aaa24074609d151ea906d114cf5337c2
[ "Apache-2.0" ]
null
null
null
mlir/tools/mlir-linalg-ods-gen/mlir-linalg-ods-gen.cpp
Kvarnefalk/llvm-project
8b5f5798aaa24074609d151ea906d114cf5337c2
[ "Apache-2.0" ]
null
null
null
//===- mlir-linalg-ods-gen.cpp - Linalg ODS generation from math form -----===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file contains the implementation for the Tensor Comprehension-inspired // parser and ODS pretty-printer for specifying Linalg "named ops" from a // mathematical form. // //===----------------------------------------------------------------------===// #include "mlir/IR/AffineExpr.h" #include "mlir/IR/AffineMap.h" #include "mlir/IR/MLIRContext.h" #include "mlir/IR/OpImplementation.h" #include "mlir/Support/FileUtilities.h" #include "mlir/Support/LLVM.h" #include "mlir/Support/LogicalResult.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SetVector.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/ADT/Twine.h" #include "llvm/Support/Casting.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/FormatVariadic.h" #include "llvm/Support/ToolOutputFile.h" #include <map> #define DEBUG_TYPE "linalg-ods-gen" static llvm::cl::OptionCategory ODSGenCat("Linalg ODS Gen"); // Commandline options static llvm::cl::opt<std::string> inputFilename(llvm::cl::Positional, llvm::cl::desc("<input file>"), llvm::cl::init("-"), llvm::cl::value_desc("filename")); static llvm::cl::opt<std::string> outputFilename("o", llvm::cl::desc("Output filename"), llvm::cl::value_desc("filename"), llvm::cl::init("-")); static llvm::cl::opt<bool> genODSDecl("gen-ods-decl", llvm::cl::desc("Emit the ODS ops declarations."), llvm::cl::cat(ODSGenCat)); static llvm::cl::opt<bool> genODSImpl("gen-impl", llvm::cl::desc("Emit the ops implementations"), llvm::cl::init(false), llvm::cl::cat(ODSGenCat)); static llvm::cl::opt<bool> testEmitIncludeTdHeader( "test-emit-include-td-header", llvm::cl::desc("Include LinalgStructuredOps.td for end-to-end " "tblgen testing."), llvm::cl::init(false), llvm::cl::cat(ODSGenCat)); using llvm::SetVector; using llvm::SMLoc; using llvm::StringRef; using llvm::Twine; using namespace mlir; //===----------------------------------------------------------------------===// // Lexer //===----------------------------------------------------------------------===// namespace { /// This class represents a specific token in the input format. class Token { public: enum class Kind { // Markers. eof, error, // Tokens with no info. colon, comma, doc_str, equal, gt, l_brace, l_paren, l_square, lt, minus, plus, question, r_brace, r_paren, r_square, semicolon, star, // Keywords. kw_def, FIRST_KEYWORD = kw_def, kw_ods_def, kw_implements_interface, kw_attr_def, kw_floordiv, kw_ceildiv, kw_mod, LAST_KEYWORD = kw_mod, // String valued tokens. id, integer, }; Token(Kind kind, StringRef spelling) : kind(kind), spelling(spelling) {} /// Return the bytes that make up this token. StringRef getSpelling() const { return spelling; } /// Return the kind of this token. Kind getKind() const { return kind; } /// Return a location for this token. llvm::SMLoc getLoc() const { return llvm::SMLoc::getFromPointer(spelling.data()); } /// Return if this token is a keyword. bool isKeyword() const { return kind >= Kind::FIRST_KEYWORD && kind <= Kind::LAST_KEYWORD; } bool is(Kind k) const { return kind == k; } bool isNot(Kind k) const { return kind != k; } Optional<uint64_t> getUInt64IntegerValue() const { bool isHex = spelling.size() > 1 && spelling[1] == 'x'; uint64_t result = 0; if (spelling.getAsInteger(isHex ? 0 : 10, result)) return None; return result; } private: /// Discriminator that indicates the kind of token this is. Kind kind; /// A reference to the entire token contents; this is always a pointer into /// a memory buffer owned by the source manager. StringRef spelling; }; /// This class implements a simple lexer. class Lexer { public: Lexer(llvm::SourceMgr &mgr); /// Lex the next token and return it. Token lexToken(); /// Emit an error to the lexer with the given location and message. Token emitError(llvm::SMLoc loc, const Twine &msg); Token emitError(const char *loc, const Twine &msg); /// Change the position of the lexer cursor. The next token we lex will start /// at the designated point in the input. void resetPointer(const char *newPtr) { curPtr = newPtr; } private: Token formToken(Token::Kind kind, const char *tokStart) { return Token(kind, StringRef(tokStart, curPtr - tokStart)); } /// Return the next character in the stream. int getNextChar(); /// Lex an identifier. Token lexIdentifier(const char *tokStart); // Lex an integer. Token lexInteger(const char *tokStart); // Lex a string. Token lexString(const char *tokStart); // Skip a comment line, starting with a '//'. void skipComment(); llvm::SourceMgr &srcMgr; StringRef curBuffer; const char *curPtr; }; } // end anonymous namespace Lexer::Lexer(llvm::SourceMgr &mgr) : srcMgr(mgr) { curBuffer = srcMgr.getMemoryBuffer(mgr.getMainFileID())->getBuffer(); curPtr = curBuffer.begin(); } Token Lexer::emitError(llvm::SMLoc loc, const Twine &msg) { srcMgr.PrintMessage(loc, llvm::SourceMgr::DK_Error, msg); return formToken(Token::Kind::error, loc.getPointer()); } Token Lexer::emitError(const char *loc, const Twine &msg) { return emitError(llvm::SMLoc::getFromPointer(loc), msg); } int Lexer::getNextChar() { char curChar = *curPtr++; switch (curChar) { default: return (unsigned char)curChar; case 0: { // A nul character in the stream is either the end of the current buffer // or a random nul in the file. Disambiguate that here. if (curPtr - 1 != curBuffer.end()) return 0; // Otherwise, return end of file. --curPtr; return EOF; } case '\n': case '\r': // Handle the newline character by ignoring it and incrementing the line // count. However, be careful about 'dos style' files with \n\r in them. // Only treat a \n\r or \r\n as a single line. if ((*curPtr == '\n' || (*curPtr == '\r')) && *curPtr != curChar) ++curPtr; return '\n'; } } Token Lexer::lexToken() { while (true) { const char *tokStart = curPtr; // This always consumes at least one character. int curChar = getNextChar(); switch (curChar) { default: // Handle identifiers: [a-zA-Z_] if (isalpha(curChar) || curChar == '_') return lexIdentifier(tokStart); // Handle integers: [0-9] if (isdigit(curChar)) return lexInteger(tokStart); // Unknown character, emit an error. return emitError(tokStart, "unexpected character"); case EOF: // Return EOF denoting the end of lexing. return formToken(Token::Kind::eof, tokStart); // Lex punctuation. case ':': return formToken(Token::Kind::colon, tokStart); case ',': return formToken(Token::Kind::comma, tokStart); case '=': return formToken(Token::Kind::equal, tokStart); case '{': return formToken(Token::Kind::l_brace, tokStart); case '(': return formToken(Token::Kind::l_paren, tokStart); case '[': return formToken(Token::Kind::l_square, tokStart); case '}': return formToken(Token::Kind::r_brace, tokStart); case ')': return formToken(Token::Kind::r_paren, tokStart); case ']': return formToken(Token::Kind::r_square, tokStart); case '<': return formToken(Token::Kind::lt, tokStart); case '>': return formToken(Token::Kind::gt, tokStart); case '+': return formToken(Token::Kind::plus, tokStart); case '-': return formToken(Token::Kind::minus, tokStart); case ';': return formToken(Token::Kind::semicolon, tokStart); case '*': return formToken(Token::Kind::star, tokStart); case '?': return formToken(Token::Kind::question, tokStart); case '"': return lexString(tokStart); case '/': if (*curPtr == '/') { skipComment(); continue; } // Unknown character, emit an error. return emitError(tokStart, "unexpected character: not a comment"); // Ignore whitespace characters. case 0: case ' ': case '\t': case '\n': return lexToken(); } } } Token Lexer::lexIdentifier(const char *tokStart) { // Match the rest of the identifier regex: [0-9a-zA-Z_\-]* while (isalnum(*curPtr) || *curPtr == '_' || *curPtr == '-') ++curPtr; // Check to see if this identifier is a keyword. StringRef str(tokStart, curPtr - tokStart); Token::Kind kind = StringSwitch<Token::Kind>(str) .Case("attr", Token::Kind::kw_attr_def) .Case("def", Token::Kind::kw_def) .Case("ods_def", Token::Kind::kw_ods_def) .Case("implements_interface", Token::Kind::kw_implements_interface) .Case("floordiv", Token::Kind::kw_floordiv) .Case("ceildiv", Token::Kind::kw_ceildiv) .Case("mod", Token::Kind::kw_mod) .Default(Token::Kind::id); return Token(kind, str); } Token Lexer::lexInteger(const char *tokStart) { // Match the rest of the identifier regex: [0-9a-zA-Z_\-]* while (isdigit(*curPtr)) ++curPtr; StringRef str(tokStart, curPtr - tokStart); return Token(Token::Kind::integer, str); } Token Lexer::lexString(const char *tokStart) { assert(curPtr[-1] == '"'); if (*curPtr == '"' && *(curPtr + 1) == '"') { curPtr += 2; while (true) { switch (*curPtr++) { case '"': if (*curPtr == '"' && *(curPtr + 1) == '"') { Token token(Token::Kind::doc_str, StringRef(tokStart + 3, curPtr - tokStart - 4)); curPtr += 2; return token; } continue; case 0: // If this is a random nul character in the middle of the doc string, // just include it. If it is the end of file, then it is an error. if (curPtr - 1 != curBuffer.end()) continue; return emitError(curPtr - 1, "expected '\"\"\"' to end doc string"); default: continue; } } } return emitError(curPtr - 1, "expected '\"\"\"' to start doc string"); } /// Skip a comment line, starting with a '//'. void Lexer::skipComment() { // Advance over the second '/' in a '//' comment. assert(*curPtr == '/'); ++curPtr; while (true) { switch (*curPtr++) { case '\n': case '\r': // Newline is end of comment. return; case 0: // If this is the end of the buffer, end the comment. if (curPtr - 1 == curBuffer.end()) { --curPtr; return; } LLVM_FALLTHROUGH; default: // Skip over other characters. break; } } } namespace { class Parser { public: Parser(llvm::SourceMgr &mgr, MLIRContext *ctx) : lexer(mgr), curToken(lexer.lexToken()), context(ctx) {} //===--------------------------------------------------------------------===// // Lexer Utilities //===--------------------------------------------------------------------===// LogicalResult parseInteger(uint64_t &value) { if (!curToken.is(Token::Kind::integer)) return emitError(curToken.getLoc(), "expected integer"); value = curToken.getUInt64IntegerValue().getValue(); consumeToken(); return success(); } /// Advance the current lexer onto the next token. void consumeToken() { assert(curToken.getKind() != Token::Kind::eof && curToken.getKind() != Token::Kind::error && "shouldn't advance past EOF or errors"); curToken = lexer.lexToken(); } void consumeToken(Token::Kind kind) { assert(curToken.getKind() == kind && "unexpected token"); curToken = lexer.lexToken(); } LogicalResult parseToken(Token::Kind kind, const Twine &msg) { if (curToken.getKind() != kind) return emitError(curToken.getLoc(), msg); consumeToken(); return success(); } /// Parses an optional token and returns failure if failed to parse. LogicalResult parseOptionalToken(Token::Kind kind) { return success(consumeIf(kind)); } LogicalResult emitError(llvm::SMLoc loc, const Twine &msg) { lexer.emitError(loc, msg); return failure(); } LogicalResult emitError(const Twine &msg) { return emitError(curToken.getLoc(), msg); } bool consumeIf(Token::Kind kind) { if (curToken.isNot(kind)) return false; consumeToken(kind); return true; } LogicalResult parseCommaSeparatedList(llvm::function_ref<ParseResult()> parseElement) { // Non-empty case starts with an element. if (parseElement()) return failure(); // Otherwise we have a list of comma separated elements. while (consumeIf(Token::Kind::comma)) { if (parseElement()) return failure(); } return success(); } LogicalResult parseCommaSeparatedListUntil(Token::Kind rightToken, llvm::function_ref<ParseResult()> parseElement, bool allowEmptyList) { // Handle the empty case. if (curToken.is(rightToken)) { if (!allowEmptyList) return emitError("expected list element"); consumeToken(rightToken); return success(); } if (failed(parseCommaSeparatedList(parseElement)) || failed( parseToken(rightToken, "expected ',' or right-terminating token"))) return failure(); return success(); } Lexer lexer; Token curToken; MLIRContext *context; }; } // namespace /// Encodes an attribute use of the form: /// /// index-list ::= integer-literal (`,` integer-literal)* /// attr-use ::= bare-id `[` index-list `]` struct AttrUse { // Referenced attribute StringRef attrName; // Indices into the attribute SmallVector<uint64_t, 4> indices; /// Affine symbol for this usage. /// This is represented as an affine symbol because at the time of parsing the /// spec and generating the op's ODS/C++, we don't know the concrete constant /// value. But they should be replaced with constants read from the attribute /// and thus folded away for concrete op instances. AffineExpr symbol; std::string getKey() { SmallVector<std::string, 4> indexStrs; for (uint64_t index : indices) indexStrs.push_back(std::to_string(index)); return llvm::formatv("{0}[{1}]", attrName, llvm::join(indexStrs, ",")); } }; //===----------------------------------------------------------------------===// // Affine parsing. //===----------------------------------------------------------------------===// namespace { /// Lower precedence ops (all at the same precedence level). LNoOp is false in /// the boolean sense. enum AffineLowPrecOp { /// Null value. LNoOp, Add, Sub }; /// Higher precedence ops - all at the same precedence level. HNoOp is false /// in the boolean sense. enum AffineHighPrecOp { /// Null value. HNoOp, Mul, FloorDiv, CeilDiv, Mod }; using AffineDimList = SmallVector<std::pair<StringRef, AffineExpr>, 4>; using AffineSymbolList = SmallVector<std::pair<StringRef, AffineExpr>, 4>; /// This is a specialized parser for affine expressions. class AffineParser { public: /// Creates an affine parser that parses tokens from `p`. /// /// The affine parser introduces new dimensions and symbols eagerly as new /// `id` are discovered. To additionally support attribute use `id`s, for a /// parsed `id`, the resolution mechanism proceeds as follows: /// 1. Try to parse `id` as an attribute use (using the `attrUseParsingHook`). /// 2. If unsuccessful, try to match `id` to a known dim or symbol. /// 3. If still unsuccessful, eagerly create a new dim or symbol and add it to /// the known dims or symbols (using the `bareIdParsingHook`). explicit AffineParser( Parser &p, std::function<AffineExpr(StringRef)> bareIdParsingHook, std::function<llvm::Optional<AffineExpr>()> attrUseParsingHook, AffineDimList &dimList, AffineSymbolList &symbolList) : parser(p), bareIdFallback(bareIdParsingHook), attrUseCallback(attrUseParsingHook), dims(dimList), symbols(symbolList) {} /// Parse a comma-separated list of affine exprs. SmallVector<AffineExpr, 4> parseAffineExprs(Token::Kind lDelim = Token::Kind::l_paren, Token::Kind rDelim = Token::Kind::r_paren); /// Parse a single affine expr.`. AffineExpr parseAffineExpr(); private: // Binary affine op parsing. AffineLowPrecOp consumeIfLowPrecOp(); AffineHighPrecOp consumeIfHighPrecOp(); // AffineExpr parsing. AffineExpr parseParentheticalExpr(); AffineExpr parseNegateExpression(AffineExpr lhs); AffineExpr parseIntegerExpr(); AffineExpr parseAttrUseOrBareIdExpr(); AffineExpr parseBareIdExpr(); AffineExpr getAffineBinaryOpExpr(AffineHighPrecOp op, AffineExpr lhs, AffineExpr rhs, SMLoc opLoc); AffineExpr getAffineBinaryOpExpr(AffineLowPrecOp op, AffineExpr lhs, AffineExpr rhs); AffineExpr parseAffineOperandExpr(AffineExpr lhs); AffineExpr parseAffineLowPrecOpExpr(AffineExpr llhs, AffineLowPrecOp llhsOp); AffineExpr parseAffineHighPrecOpExpr(AffineExpr llhs, AffineHighPrecOp llhsOp, SMLoc llhsOpLoc); Parser &parser; std::function<AffineExpr(StringRef)> bareIdFallback; std::function<llvm::Optional<AffineExpr>()> attrUseCallback; AffineDimList &dims; AffineSymbolList &symbols; }; } // end anonymous namespace /// Create an affine binary high precedence op expression (mul's, div's, mod). /// opLoc is the location of the op token to be used to report errors /// for non-conforming expressions. AffineExpr AffineParser::getAffineBinaryOpExpr(AffineHighPrecOp op, AffineExpr lhs, AffineExpr rhs, SMLoc opLoc) { switch (op) { case Mul: if (!lhs.isSymbolicOrConstant() && !rhs.isSymbolicOrConstant()) { (void)parser.emitError( opLoc, "non-affine expression: at least one of the multiply " "operands has to be either a constant or symbolic"); return nullptr; } return lhs * rhs; case FloorDiv: if (!rhs.isSymbolicOrConstant()) { (void)parser.emitError(opLoc, "non-affine expression: right operand of floordiv " "has to be either a constant or symbolic"); return nullptr; } return lhs.floorDiv(rhs); case CeilDiv: if (!rhs.isSymbolicOrConstant()) { (void)parser.emitError(opLoc, "non-affine expression: right operand of ceildiv " "has to be either a constant or symbolic"); return nullptr; } return lhs.ceilDiv(rhs); case Mod: if (!rhs.isSymbolicOrConstant()) { (void)parser.emitError(opLoc, "non-affine expression: right operand of mod " "has to be either a constant or symbolic"); return nullptr; } return lhs % rhs; case HNoOp: llvm_unreachable("can't create affine expression for null high prec op"); return nullptr; } llvm_unreachable("Unknown AffineHighPrecOp"); } /// Create an affine binary low precedence op expression (add, sub). AffineExpr AffineParser::getAffineBinaryOpExpr(AffineLowPrecOp op, AffineExpr lhs, AffineExpr rhs) { switch (op) { case AffineLowPrecOp::Add: return lhs + rhs; case AffineLowPrecOp::Sub: return lhs - rhs; case AffineLowPrecOp::LNoOp: llvm_unreachable("can't create affine expression for null low prec op"); return nullptr; } llvm_unreachable("Unknown AffineLowPrecOp"); } /// Consume this token if it is a lower precedence affine op (there are only /// two precedence levels). AffineLowPrecOp AffineParser::consumeIfLowPrecOp() { switch (parser.curToken.getKind()) { case Token::Kind::plus: parser.consumeToken(); return AffineLowPrecOp::Add; case Token::Kind::minus: parser.consumeToken(); return AffineLowPrecOp::Sub; default: return AffineLowPrecOp::LNoOp; } } /// Consume this token if it is a higher precedence affine op (there are only /// two precedence levels) AffineHighPrecOp AffineParser::consumeIfHighPrecOp() { switch (parser.curToken.getKind()) { case Token::Kind::star: parser.consumeToken(Token::Kind::star); return Mul; case Token::Kind::kw_floordiv: parser.consumeToken(Token::Kind::kw_floordiv); return FloorDiv; case Token::Kind::kw_ceildiv: parser.consumeToken(Token::Kind::kw_ceildiv); return CeilDiv; case Token::Kind::kw_mod: parser.consumeToken(Token::Kind::kw_mod); return Mod; default: return HNoOp; } } /// Parse a high precedence op expression list: mul, div, and mod are high /// precedence binary ops, i.e., parse a /// expr_1 op_1 expr_2 op_2 ... expr_n /// where op_1, op_2 are all a AffineHighPrecOp (mul, div, mod). /// All affine binary ops are left associative. /// Given llhs, returns (llhs llhsOp lhs) op rhs, or (lhs op rhs) if llhs is /// null. If no rhs can be found, returns (llhs llhsOp lhs) or lhs if llhs is /// null. llhsOpLoc is the location of the llhsOp token that will be used to /// report an error for non-conforming expressions. AffineExpr AffineParser::parseAffineHighPrecOpExpr(AffineExpr llhs, AffineHighPrecOp llhsOp, SMLoc llhsOpLoc) { AffineExpr lhs = parseAffineOperandExpr(llhs); if (!lhs) return nullptr; // Found an LHS. Parse the remaining expression. auto opLoc = parser.curToken.getLoc(); if (AffineHighPrecOp op = consumeIfHighPrecOp()) { if (llhs) { AffineExpr expr = getAffineBinaryOpExpr(llhsOp, llhs, lhs, opLoc); if (!expr) return nullptr; return parseAffineHighPrecOpExpr(expr, op, opLoc); } // No LLHS, get RHS return parseAffineHighPrecOpExpr(lhs, op, opLoc); } // This is the last operand in this expression. if (llhs) return getAffineBinaryOpExpr(llhsOp, llhs, lhs, llhsOpLoc); // No llhs, 'lhs' itself is the expression. return lhs; } /// Parse an affine expression inside parentheses. /// /// affine-expr ::= `(` affine-expr `)` AffineExpr AffineParser::parseParentheticalExpr() { if (failed(parser.parseToken(Token::Kind::l_paren, "expected '('"))) return nullptr; if (parser.curToken.is(Token::Kind::r_paren)) return ((void)parser.emitError("no expression inside parentheses"), nullptr); auto expr = parseAffineExpr(); if (!expr) return nullptr; if (failed(parser.parseToken(Token::Kind::r_paren, "expected ')'"))) return nullptr; return expr; } /// Parse the negation expression. /// /// affine-expr ::= `-` affine-expr AffineExpr AffineParser::parseNegateExpression(AffineExpr lhs) { if (failed(parser.parseToken(Token::Kind::minus, "expected '-'"))) return nullptr; AffineExpr operand = parseAffineOperandExpr(lhs); // Since negation has the highest precedence of all ops (including high // precedence ops) but lower than parentheses, we are only going to use // parseAffineOperandExpr instead of parseAffineExpr here. if (!operand) // Extra error message although parseAffineOperandExpr would have // complained. Leads to a better diagnostic. return ((void)parser.emitError("missing operand of negation"), nullptr); return (-1) * operand; } AffineExpr AffineParser::parseAttrUseOrBareIdExpr() { if (llvm::Optional<AffineExpr> attrUse = attrUseCallback()) return attrUse.getValue(); return parseBareIdExpr(); } /// Parse a bare id that may appear in an affine expression. /// /// affine-expr ::= bare-id AffineExpr AffineParser::parseBareIdExpr() { if (parser.curToken.isNot(Token::Kind::id)) return ((void)parser.emitError("expected id"), nullptr); StringRef sRef = parser.curToken.getSpelling(); for (auto &list : {dims, symbols}) { for (auto entry : list) { if (entry.first == sRef) { parser.consumeToken(Token::Kind::id); return entry.second; } } } // Not found, check fallback path. AffineExpr expr = bareIdFallback(sRef); if (expr) { parser.consumeToken(Token::Kind::id); return expr; } return ((void)parser.emitError("use of undeclared id"), nullptr); } /// Parse a positive integral constant appearing in an affine expression. /// /// affine-expr ::= integer-literal AffineExpr AffineParser::parseIntegerExpr() { auto val = parser.curToken.getUInt64IntegerValue(); if (!val.hasValue() || (int64_t)val.getValue() < 0) return ((void)parser.emitError("constant too large for index"), nullptr); parser.consumeToken(Token::Kind::integer); return getAffineConstantExpr((int64_t)val.getValue(), parser.context); } /// Parses an expression that can be a valid operand of an affine expression. /// lhs: if non-null, lhs is an affine expression that is the lhs of a binary /// operator, the rhs of which is being parsed. This is used to determine /// whether an error should be emitted for a missing right operand. // Eg: for an expression without parentheses (like i + j + k + l), each // of the four identifiers is an operand. For i + j*k + l, j*k is not an // operand expression, it's an op expression and will be parsed via // parseAffineHighPrecOpExpression(). However, for i + (j*k) + -l, (j*k) and // -l are valid operands that will be parsed by this function. AffineExpr AffineParser::parseAffineOperandExpr(AffineExpr lhs) { switch (parser.curToken.getKind()) { case Token::Kind::id: return parseAttrUseOrBareIdExpr(); case Token::Kind::integer: return parseIntegerExpr(); case Token::Kind::l_paren: return parseParentheticalExpr(); case Token::Kind::minus: return parseNegateExpression(lhs); case Token::Kind::kw_ceildiv: case Token::Kind::kw_floordiv: case Token::Kind::kw_mod: case Token::Kind::plus: case Token::Kind::star: if (lhs) (void)parser.emitError("missing right operand of binary operator"); else (void)parser.emitError("missing left operand of binary operator"); return nullptr; default: if (lhs) (void)parser.emitError("missing right operand of binary operator"); else (void)parser.emitError("expected affine expression"); return nullptr; } } /// Parse affine expressions that are bare-id's, integer constants, /// parenthetical affine expressions, and affine op expressions that are a /// composition of those. /// /// All binary op's associate from left to right. /// /// {add, sub} have lower precedence than {mul, div, and mod}. /// /// Add, sub'are themselves at the same precedence level. Mul, floordiv, /// ceildiv, and mod are at the same higher precedence level. Negation has /// higher precedence than any binary op. /// /// llhs: the affine expression appearing on the left of the one being parsed. /// This function will return ((llhs llhsOp lhs) op rhs) if llhs is non null, /// and lhs op rhs otherwise; if there is no rhs, llhs llhsOp lhs is returned /// if llhs is non-null; otherwise lhs is returned. This is to deal with left /// associativity. /// /// Eg: when the expression is e1 + e2*e3 + e4, with e1 as llhs, this function /// will return the affine expr equivalent of (e1 + (e2*e3)) + e4, where /// (e2*e3) will be parsed using parseAffineHighPrecOpExpr(). AffineExpr AffineParser::parseAffineLowPrecOpExpr(AffineExpr llhs, AffineLowPrecOp llhsOp) { AffineExpr lhs; if (!(lhs = parseAffineOperandExpr(llhs))) return nullptr; // Found an LHS. Deal with the ops. if (AffineLowPrecOp lOp = consumeIfLowPrecOp()) { if (llhs) { AffineExpr sum = getAffineBinaryOpExpr(llhsOp, llhs, lhs); return parseAffineLowPrecOpExpr(sum, lOp); } // No LLHS, get RHS and form the expression. return parseAffineLowPrecOpExpr(lhs, lOp); } auto opLoc = parser.curToken.getLoc(); if (AffineHighPrecOp hOp = consumeIfHighPrecOp()) { // We have a higher precedence op here. Get the rhs operand for the llhs // through parseAffineHighPrecOpExpr. AffineExpr highRes = parseAffineHighPrecOpExpr(lhs, hOp, opLoc); if (!highRes) return nullptr; // If llhs is null, the product forms the first operand of the yet to be // found expression. If non-null, the op to associate with llhs is llhsOp. AffineExpr expr = llhs ? getAffineBinaryOpExpr(llhsOp, llhs, highRes) : highRes; // Recurse for subsequent low prec op's after the affine high prec op // expression. if (AffineLowPrecOp nextOp = consumeIfLowPrecOp()) return parseAffineLowPrecOpExpr(expr, nextOp); return expr; } // Last operand in the expression list. if (llhs) return getAffineBinaryOpExpr(llhsOp, llhs, lhs); // No llhs, 'lhs' itself is the expression. return lhs; } /// Parse an affine expression. /// affine-expr ::= `(` affine-expr `)` /// | `-` affine-expr /// | affine-expr `+` affine-expr /// | affine-expr `-` affine-expr /// | affine-expr `*` affine-expr /// | affine-expr `floordiv` affine-expr /// | affine-expr `ceildiv` affine-expr /// | affine-expr `mod` affine-expr /// | bare-id /// | integer-literal /// /// Additional conditions are checked depending on the production. For eg., /// one of the operands for `*` has to be either constant/symbolic; the second /// operand for floordiv, ceildiv, and mod has to be a positive integer. AffineExpr AffineParser::parseAffineExpr() { return parseAffineLowPrecOpExpr(nullptr, AffineLowPrecOp::LNoOp); } SmallVector<AffineExpr, 4> AffineParser::parseAffineExprs(Token::Kind lDelim, Token::Kind rDelim) { if (failed(parser.parseToken(lDelim, "expected lDelim at start of affine expr list"))) return {}; SmallVector<AffineExpr, 4> exprs; auto parseElt = [&]() -> LogicalResult { auto elt = parseAffineExpr(); exprs.push_back(elt); return elt ? success() : failure(); }; if (failed(parser.parseCommaSeparatedListUntil(rDelim, parseElt, /*allowEmptyList=*/true))) llvm_unreachable("Failed AffineExpr parsing"); return exprs; } //===----------------------------------------------------------------------===// // TC parsing. //===----------------------------------------------------------------------===// namespace { /// Base class for expressions involved in TC parsing. struct Expression { enum class Kind { Uninitialized = 0, TensorExpr = 1, TensorUse = 2, }; explicit Expression(Kind k = Kind::Uninitialized) : kind(k) {} virtual ~Expression() = default; operator bool() const { return kind != Kind::Uninitialized; } Kind kind; }; /// Encodes a tensor use of the form: /// /// affine-expr-list ::= affine-expr (`,` affine-expr)* /// tensor-use ::= bare-id `(` `)` /// | bare-id `(` affine-expr-list `)` /// /// The affine-expr-list is stored as an AffineMap. struct TensorUse : public Expression { TensorUse() : TensorUse("", AffineMap()) {} TensorUse(StringRef name, AffineMap map) : Expression(Kind::TensorUse), tensorId(name), indexingMap(map) {} TensorUse(const TensorUse &use) = default; static bool classof(const Expression *e) { return e->kind == Kind::TensorUse; } bool operator==(const TensorUse &other) const { return tensorId == other.tensorId && indexingMap == other.indexingMap; } /// Visitation function. Performs preorder or postorder traversal depending on /// `PreOrder` and applies `callback` on each node. template <typename Lambda, bool PreOrder> void visit(Lambda callback) const; StringRef tensorId; AffineMap indexingMap; }; /// Encodes a tensor expression of the form: /// /// op-spec ::= bare-id `<` reduction-dims-list `>` /// | bare-id /// op-arg ::= tensor-expr /// | tensor-use /// op-arg-list ::= op-arg (`,` op-arg)* /// tensor-expr ::= op-spec `(` op-arg-list `)` /// /// Underlying op-arg are stored by unique_ptr to base class. struct TensorExpr : public Expression { TensorExpr(StringRef name, SmallVectorImpl<std::unique_ptr<Expression>> &&exprs, ArrayRef<unsigned> reductionDims) : Expression(Kind::TensorExpr), operationName(name), expressions(std::move(exprs)), reductionDimensions(reductionDims.begin(), reductionDims.end()) {} static bool classof(const Expression *e) { return e->kind == Kind::TensorExpr; } bool operator==(const TensorExpr &other) const { if (operationName != other.operationName) return false; if (expressions.size() != other.expressions.size()) return false; for (unsigned i = 0, e = expressions.size(); i < e; ++i) if (*expressions[i] != *other.expressions[i]) return false; for (unsigned i = 0, e = reductionDimensions.size(); i < e; ++i) if (reductionDimensions[i] != other.reductionDimensions[i]) return false; return true; } /// Visitation function. Performs preorder or postorder traversal depending on /// `PreOrder` and applies `callback` on each node. template <typename Lambda, bool PreOrder> void visit(Lambda callback) const; StringRef operationName; SmallVector<std::unique_ptr<Expression>, 4> expressions; SetVector<unsigned> reductionDimensions; }; /// This is a specialized parser for a TCDef. /// This maintains the dims it finds in an eager fashion. class TCParser { enum class EagerDiscoveryMode { None = 0, Symbols, Dimensions }; public: explicit TCParser(Parser &p); /// Uses the AffineParser to parse the affine exprs used in a tensor /// definition. If `discoveryMode` is set to Symbols (resp. Dimensions), new /// symbols (resp. dimensions) are added eagerly. Otherwise, an error is /// emitted on new identifiers. SmallVector<AffineExpr, 4> parseAffineExprs(EagerDiscoveryMode discoveryMode, AffineDimList &dims, Token::Kind lDelim = Token::Kind::l_paren, Token::Kind rDelim = Token::Kind::r_paren); /// Parse the information for a tensor def. /// All the affine-expr must be dimensionless (i.e. contain only expressions /// involving symbols and constants), but can otherwise contain arbitrary /// affine expressions. LogicalResult parseTensorDef(bool isOutput); /// Parses a tensor use. struct ComprehensionParsingState { AffineDimList dims; SmallVector<std::unique_ptr<Expression>, 4> expressions; llvm::DenseMap<TensorUse, unsigned> orderedTensorArgs; }; LogicalResult parseTensorUse(TensorUse &result, ComprehensionParsingState &state); /// Parses an attribute definition. LogicalResult parseAttrDef(); /// Parses an optional attribute use. LogicalResult parseAttrUse(AttrUse &result); /// Parses a tensor expression. LogicalResult parseExpression(TensorUse currentDefinition, std::unique_ptr<Expression> &result, ComprehensionParsingState &state); /// Parse a single comprehension. LogicalResult parseOneComprehension(StringRef cppOpName, StringRef linalgOpName, ComprehensionParsingState &state); /// Parse and print the information for a TC def. /// When `gen-ods-decl` is used, this prints the ODS declaration for the TC. /// When `gen-impl` is used, this prints the C++ implementation for the extra /// methods defined in ODS (`iterator_types`, `indexing_maps` and /// `regionBuilder`). LogicalResult parseAndEmitODSDef(llvm::raw_ostream &os); /// Print the ODS class that defines a new `cppOpName` for a `linalgOpName`. void printODS(llvm::raw_ostream &os, StringRef cppOpName, StringRef linalgOpName, ArrayRef<StringRef> interfaces, ComprehensionParsingState &state); /// Print the C++ StructuredOpsInterface impl of `iterator_types`. void printReferenceIterators(llvm::raw_ostream &os, StringRef cppOpName, ComprehensionParsingState &state); /// Print methods related to indexing map required attributes. /// /// Specifically, this prints the definitions for the following methods: /// bool hasDynamicIndexingMaps(); /// LogicalResult verifyIndexingMapRequiredAttributes(); void printIndexingMapRequiredAttrMethods(llvm::raw_ostream &os, StringRef cppOpName, ComprehensionParsingState &state); /// Print the C++ StructuredOpsInterface impl of `indexing_maps`. void printReferenceIndexingMaps(llvm::raw_ostream &os, StringRef cppOpName, ComprehensionParsingState &state); /// Print the C++ StructuredOpsInterface impl of `regionBuilder`. void printRegionBuilder(llvm::raw_ostream &os, StringRef cppOpName, ComprehensionParsingState &state); /// Print the C++ impl for named ops canonicalizers and folders. void printCanonicalizersAndFolders(llvm::raw_ostream &os, StringRef cppOpName); private: //===--------------------------------------------------------------------===// // Internal bookkeeping of tensors. //===--------------------------------------------------------------------===// struct RegisteredTensor { StringRef type; AffineMap shape; bool isOutput; AffineMap indexingMap; unsigned index; }; //===--------------------------------------------------------------------===// // Internal bookkeeping of attributes. //===--------------------------------------------------------------------===// struct RegisteredAttr { StringRef elementType; SmallVector<uint64_t, 4> vectorDims; bool isArray; bool isOptional; // Returns the function to get values at the given indices from this // attribute. std::string getValueFn(ArrayRef<uint64_t> indices) const; }; //===--------------------------------------------------------------------===// // Per-TC def state. //===--------------------------------------------------------------------===// /// Symbols are per TC def. AffineSymbolList symbols; /// Attribute usages in all affine expressions. SmallVector<AttrUse, 8> attrUses; /// Tensors are per TC def. llvm::StringMap<RegisteredTensor> registeredTensors; unsigned nextRegisteredTensorIndex; /// Attributes are per TC def. std::map<std::string, RegisteredAttr> registeredAttrs; StringRef docString; Parser &parser; }; } // namespace namespace llvm { template <> struct DenseMapInfo<TensorUse> { static TensorUse getEmptyKey() { return TensorUse("", AffineMap()); } static TensorUse getTombstoneKey() { return TensorUse(DenseMapInfo<StringRef>::getTombstoneKey(), DenseMapInfo<AffineMap>::getTombstoneKey()); } static unsigned getHashValue(const TensorUse &val) { return ::llvm::hash_value(val.tensorId); // don't care about collisions. } static bool isEqual(const TensorUse &LHS, const TensorUse &RHS) { return LHS == RHS; } }; } // namespace llvm //===----------------------------------------------------------------------===// // Visitation functions. //===----------------------------------------------------------------------===// template <typename Lambda, bool PreOrder> void visit(const Expression &expr, Lambda callback) { switch (expr.kind) { default: llvm_unreachable("Unexpected kind"); case Expression::Kind::TensorExpr: static_cast<const TensorExpr &>(expr).visit<Lambda, PreOrder>(callback); break; case Expression::Kind::TensorUse: static_cast<const TensorUse &>(expr).visit<Lambda, PreOrder>(callback); break; } } template <typename Lambda> void visitPreorder(const Expression &expr, Lambda callback) { visit<Lambda, false>(expr, callback); } template <typename Lambda> void visitPostorder(Expression &expr, Lambda callback) { visit<Lambda, true>(expr, callback); } template <typename Lambda, bool PreOrder> void TensorExpr::visit(Lambda callback) const { if (!PreOrder) callback(*this); for (auto &e : expressions) ::visit<Lambda, PreOrder>(*e, callback); if (PreOrder) callback(*this); } template <typename Lambda, bool PreOrder> void TensorUse::visit(Lambda callback) const { callback(*this); } //===----------------------------------------------------------------------===// // TC parsing functions. //===----------------------------------------------------------------------===// TCParser::TCParser(Parser &p) : symbols(), registeredTensors(), nextRegisteredTensorIndex(0), parser(p) {} /// Uses the AffineParser to parse the affine exprs used in a tensor /// definition. All identifiers are interpreted as symbols, new symbols are /// added eagerly. SmallVector<AffineExpr, 4> TCParser::parseAffineExprs(EagerDiscoveryMode discoveryMode, AffineDimList &dims, Token::Kind lDelim, Token::Kind rDelim) { auto createAffineBareId = [&](StringRef sRef) { AffineExpr expr; if (discoveryMode == EagerDiscoveryMode::Symbols) { expr = getAffineSymbolExpr(symbols.size(), parser.context); symbols.emplace_back(sRef, expr); } else if (discoveryMode == EagerDiscoveryMode::Dimensions) { expr = getAffineDimExpr(dims.size(), parser.context); dims.emplace_back(sRef, expr); } return expr; }; auto tryToParseAttrUse = [&]() -> llvm::Optional<AffineExpr> { if (!parser.curToken.is(Token::Kind::id)) return llvm::None; StringRef attrName = parser.curToken.getSpelling(); auto it = registeredAttrs.find(attrName.str()); if (it == registeredAttrs.end()) return llvm::None; AttrUse result; if (failed(parseAttrUse(result))) return llvm::None; // We create a new symbol for each attribute usage without reuse. This is // fine given these symbols will be replaced with constants and folded away // for concrete op instances. result.symbol = getAffineSymbolExpr(symbols.size(), parser.context); // Merely for taking the index. We don't reuse anyway. symbols.emplace_back("<attr-use>", result.symbol); attrUses.push_back(result); return result.symbol; }; AffineParser affineParser(parser, createAffineBareId, tryToParseAttrUse, dims, symbols); return affineParser.parseAffineExprs(lDelim, rDelim); } /// Parse the information for a tensor def of the form: /// /// affine-expr-list ::= affine-expr (`,` affine-expr )* /// tensor-typedef ::= type `(` `)` /// | type `(` affine-expr-list `)` /// tensor-def ::= bare-id `:` tensor-typedef LogicalResult TCParser::parseTensorDef(bool isOutput) { StringRef tensorId = parser.curToken.getSpelling(); if (failed(parser.parseToken(Token::Kind::id, "expected an id")) || failed(parser.parseToken(Token::Kind::colon, "expected colon"))) return failure(); StringRef tensorType = parser.curToken.getSpelling(); if (failed(parser.parseToken(Token::Kind::id, "expected an id"))) return failure(); AffineDimList emptyDims; auto exprs = parseAffineExprs(EagerDiscoveryMode::Symbols, emptyDims); assert(emptyDims.empty() && "Unexpected dimension in tensor def"); AffineMap map = AffineMap::get(/*dimCount=*/0, symbols.size(), exprs, parser.context); auto iterBoolPair = registeredTensors.try_emplace( tensorId, RegisteredTensor{tensorType, map, isOutput, AffineMap(), nextRegisteredTensorIndex++}); (void)iterBoolPair; assert(iterBoolPair.second && "Could not emplace tensor registration"); LLVM_DEBUG(llvm::dbgs() << "Recorded: " << tensorId << " " << "with typeString: " << tensorType << " " << "and shape: " << map << "\n"); return success(); } /// Parses a tensor use of the form: /// /// affine-expr-list ::= affine-expr (`,` affine-expr)* /// tensor-use ::= bare-id `(` `)` /// | bare-id `(` affine-expr-list `)` LogicalResult TCParser::parseTensorUse(TensorUse &result, ComprehensionParsingState &state) { StringRef tensorId = parser.curToken.getSpelling(); if (failed(parser.parseToken(Token::Kind::id, "expected an id"))) return failure(); auto exprs = parseAffineExprs(EagerDiscoveryMode::Dimensions, state.dims); AffineMap map = AffineMap::get(state.dims.size(), symbols.size(), exprs, parser.context); LLVM_DEBUG(llvm::dbgs() << "Use of tensor: " << tensorId << " map: " << map << "\n"); result = TensorUse(tensorId, map); return success(); } /// Parse the information for an attribute def of the form: /// /// affine-expr-list ::= affine-expr (`,` affine-expr )* /// attr-id ::= bare-id (`?`)? /// dim-list ::= (integer-literal 'x')+ /// attr-typedef ::= dim-list? type (`[` `]`)? /// attr-def ::= attr-id `:` attr-typedef LogicalResult TCParser::parseAttrDef() { auto attrLoc = parser.curToken.getLoc(); StringRef attrName = parser.curToken.getSpelling(); if (failed(parser.parseToken(Token::Kind::id, "expected an id"))) return failure(); bool isOptional = succeeded(parser.parseOptionalToken(Token::Kind::question)); if (failed(parser.parseToken(Token::Kind::colon, "expected colon"))) return failure(); // Parse the attribute's type. We don't expect the type to be arbitrary // complex, so just use this ad-hoc handling here. // Parse potential dimension list SmallVector<uint64_t, 4> vectorDims; while (parser.curToken.is(Token::Kind::integer)) { uint64_t value; if (failed(parser.parseInteger(value))) return failure(); vectorDims.push_back(value); StringRef spelling = parser.curToken.getSpelling(); if (spelling[0] != 'x') return parser.emitError(parser.curToken.getLoc(), "expected 'x' in dimension list"); // If we had a prefix of 'x', lex the next token immediately after the 'x'. if (spelling.size() != 1) parser.lexer.resetPointer(spelling.data() + 1); parser.consumeToken(); } StringRef elementType = parser.curToken.getSpelling(); if (failed(parser.parseToken(Token::Kind::id, "expected an id"))) return failure(); bool isArray = false; auto arrayLoc = parser.curToken.getLoc(); if (succeeded(parser.parseOptionalToken(Token::Kind::l_square))) { isArray = true; if (failed(parser.parseToken(Token::Kind::r_square, "expected ']'"))) return failure(); } if (!vectorDims.empty() && isArray) return parser.emitError(arrayLoc, "unsupported vector array attribute"); auto iterBoolPair = registeredAttrs.emplace( attrName.str(), RegisteredAttr{elementType, vectorDims, isArray, isOptional}); if (!iterBoolPair.second) return parser.emitError(attrLoc, "Failed to register attribute '" + attrName + "'"); LLVM_DEBUG(llvm::dbgs() << "Recorded: " << (isOptional ? "[optional]" : "") << " " << attrName << " " << "with type: " << elementType << (isArray ? "[]" : "") << "\n"); return success(); } LogicalResult TCParser::parseAttrUse(AttrUse &result) { result.attrName = parser.curToken.getSpelling(); if (failed(parser.parseToken(Token::Kind::id, "expected an id"))) return failure(); auto it = registeredAttrs.find(result.attrName.str()); assert(it != registeredAttrs.end()); const RegisteredAttr &attr = it->second; if (!attr.vectorDims.empty() || attr.isArray) { // This is a vector/array attribute. Parse indices for it. auto indexLoc = parser.curToken.getLoc(); if (failed(parser.parseToken(Token::Kind::l_square, "expected '['"))) return failure(); auto parseIndex = [&]() { uint64_t value; if (failed(parser.parseInteger(value))) return failure(); result.indices.push_back(value); return success(); }; if (failed(parser.parseCommaSeparatedListUntil( Token::Kind::r_square, parseIndex, /*allowEmptyList=*/false))) return failure(); size_t rank = attr.isArray ? 1 : attr.vectorDims.size(); if (result.indices.size() != rank) return parser.emitError(indexLoc, "number of indices mismatch: expected " + std::to_string(rank) + ", but found " + std::to_string(result.indices.size())); } return success(); } /// Parses a tensor expression of the form: /// /// op-spec ::= bare-id `<` reduction-dims-list `>` /// | bare-id /// op-arg ::= tensor-expr /// | tensor-use /// op-arg-list ::= op-arg (`,` op-arg)* /// tensor-expr ::= op-spec `(` op-arg-list `)` LogicalResult TCParser::parseExpression(TensorUse currentDefinition, std::unique_ptr<Expression> &result, ComprehensionParsingState &state) { StringRef opOrTensor = parser.curToken.getSpelling(); if (registeredTensors.count(opOrTensor) > 0) { TensorUse use; auto res = parseTensorUse(use, state); if (failed(res)) return res; result = std::make_unique<TensorUse>(use); return success(); } if (failed(parser.parseToken(Token::Kind::id, "expected an operation"))) return failure(); // This is an op. SmallVector<unsigned, 4> reductionDims; SmallVector<std::unique_ptr<Expression>, 4> expressions; // Check if it has a reduction set, discover dimensions eagerly. if (parser.curToken.is(Token::Kind::lt)) { auto iters = parseAffineExprs(EagerDiscoveryMode::Dimensions, state.dims, Token::Kind::lt, Token::Kind::gt); for (auto iter : iters) reductionDims.push_back(iter.cast<AffineDimExpr>().getPosition()); } // If this op is a reduction, it's first argument is the `currentDefinition` // tensor use. if (!reductionDims.empty()) expressions.push_back(std::make_unique<TensorUse>(currentDefinition)); LLVM_DEBUG(llvm::dbgs() << "op: " << opOrTensor << "\n"); auto parseExpr = [&]() -> LogicalResult { std::unique_ptr<Expression> e; if (failed(parseExpression(currentDefinition, e, state))) return failure(); expressions.push_back(std::move(e)); return success(); }; if (failed(parser.parseToken(Token::Kind::l_paren, "expected '('")) || failed(parser.parseCommaSeparatedListUntil( Token::Kind::r_paren, parseExpr, /*allowEmptyList=*/true))) return failure(); result = std::make_unique<TensorExpr>(opOrTensor, std::move(expressions), reductionDims); return success(); } //===----------------------------------------------------------------------===// // Parse and Emit functions. //===----------------------------------------------------------------------===// /// Parse the information for a single comprehension. /// /// tensor-def-list ::= tensor-def (`,` tensor-def)* /// tensor-expr-list ::= tensor-expr (`,` tensor-expr)* /// comprehension ::= tensor-def-list `=` tensor-expr-list `;` LogicalResult TCParser::parseOneComprehension(StringRef cppOpName, StringRef linalgOpName, ComprehensionParsingState &state) { // 1. Parse LHS of `=`, these become the definitions that appear as the output // tensors or read/write buffers. SmallVector<TensorUse, 4> definitions; auto parseUse = [&]() -> LogicalResult { TensorUse use; if (failed(parseTensorUse(use, state))) return failure(); definitions.push_back(use); return success(); }; if (failed(parser.parseCommaSeparatedListUntil(Token::Kind::equal, parseUse, /*allowEmptyList=*/true))) return failure(); // 2. Parse RHS of `=`, this becomes the expressions from which we emit // computations. unsigned idx = 0; auto parseExpr = [&]() -> LogicalResult { std::unique_ptr<Expression> expr; if (idx >= definitions.size()) return parser.emitError("Fewer LHS definitions than RHS expressions"); if (failed(parseExpression(definitions[idx++], expr, state))) return failure(); state.expressions.push_back(std::move(expr)); return success(); }; if (failed(parser.parseCommaSeparatedListUntil( Token::Kind::semicolon, parseExpr, /*allowEmptyList=*/true))) return failure(); if (idx != definitions.size()) return parser.emitError("Fewer RHS expressions than LHS definitions"); // 3. Postprocess. // 3.a. Normalize all maps to the proper state.dims and symbols counts. SmallVector<TensorUse, 4> allUses; allUses.reserve(registeredTensors.size()); for (auto &def : definitions) allUses.push_back(def); for (auto &pExpr : state.expressions) visitPostorder(*pExpr, [&](const Expression &e) { if (auto *use = dyn_cast<TensorUse>(&e)) allUses.push_back(*use); }); for (auto &use : allUses) use.indexingMap = AffineMap::get(state.dims.size(), symbols.size(), use.indexingMap.getResults(), parser.context); // 3.b. Traverse definitions llvm::DenseSet<StringRef> seenDefs; for (auto &def : definitions) { if (seenDefs.count(def.tensorId) > 0) return parser.emitError("Unexpected multi-write to a single tensor"); seenDefs.insert(def.tensorId); auto tensorIter = registeredTensors.find(def.tensorId); assert(tensorIter != registeredTensors.end() && "unregistered tensor"); auto &tensor = tensorIter->getValue(); tensor.indexingMap = def.indexingMap; state.orderedTensorArgs[def] = tensor.index; } bool failed = false; for (auto &pExpr : state.expressions) visitPostorder(*pExpr, [&](const Expression &e) { auto *pUse = dyn_cast<TensorUse>(&e); if (failed || !pUse) return; auto &use = *pUse; LLVM_DEBUG(llvm::dbgs() << "\nuse: " << use.tensorId << " map: " << use.indexingMap); auto tensorIter = registeredTensors.find(use.tensorId); assert(tensorIter != registeredTensors.end() && "unregistered tensor"); auto &tensor = tensorIter->getValue(); if (tensor.indexingMap && state.orderedTensorArgs.count(use) == 0) { LLVM_DEBUG(llvm::dbgs() << "\nexisting: " << tensor.indexingMap); (void)parser.emitError( "Unexpected multi-read of a tensor with different accesses"); failed = true; return; } seenDefs.insert(use.tensorId); tensor.indexingMap = use.indexingMap; state.orderedTensorArgs[use] = tensor.index; }); if (failed) return failure(); return success(); } /// Parse and print the information for a ODS def. /// /// tensor-def-list ::= tensor-def (`,` tensor-def )* /// attr-def-list ::= attr-def (`,` attr-def )* /// /// comprehension-list ::= comprehension comprehension* /// /// tc-attr-def ::= `attr` `(` attr-def-list `)` /// tc-def ::= `def` bare-id `(`tensor-def-list`)` `->` `(` tensor-def-list`)` /// (tc-attr-def)? /// `{` comprehension-list `}` /// /// implements-interface ::= /// `implements_interface` `<` bare-id (`,` bare-id)* `>` `:` tc-def /// /// ods-def ::= `ods_def` `<` bare-id `>` /// (implements-interface)? `:` /// tc-def /// /// All the affine-expr in a `tensor-typedef` must be dimensionless (i.e. /// contain only expressions involving symbols and constants), but can /// otherwise contain arbitrary affine expressions. LogicalResult TCParser::parseAndEmitODSDef(llvm::raw_ostream &os) { // Parse ods-def header (including C++ op name) if (failed(parser.parseToken(Token::Kind::kw_ods_def, "expected 'ods_def' to define a TC ODS")) || failed(parser.parseToken(Token::Kind::lt, "expected '<'"))) return failure(); StringRef cppOpName = parser.curToken.getSpelling(); LLVM_DEBUG(llvm::dbgs() << "\n\nStart parsing ODS: " << cppOpName << "\n"); if (failed(parser.parseToken(Token::Kind::id, "expected id")) || failed(parser.parseToken(Token::Kind::gt, "expected '>'"))) return failure(); // Parse optional implements-interface header (including C++ op names) SmallVector<StringRef> interfaces; bool implementsInterface = succeeded( parser.parseOptionalToken(Token::Kind::kw_implements_interface)); if (implementsInterface) { auto parseInterfaceString = [&]() -> LogicalResult { StringRef interfaceName = parser.curToken.getSpelling(); if (failed(parser.parseToken(Token::Kind::id, "expected id"))) return failure(); interfaces.push_back(interfaceName); return success(); }; if (failed(parser.parseToken(Token::Kind::lt, "expected '<'")) || failed(parser.parseCommaSeparatedListUntil( Token::Kind::gt, parseInterfaceString, /*allowEmptyList=*/false))) return failure(); } // Parse column. if (failed(parser.parseToken(Token::Kind::colon, "expected ':'"))) return failure(); // Parse TC op name. if (failed(parser.parseToken(Token::Kind::kw_def, "expected 'def' to define a TC"))) return failure(); StringRef tcName = parser.curToken.getSpelling(); LLVM_DEBUG(llvm::dbgs() << "\n\nStart parsing TC: " << tcName << "\n"); // Parse input/output tensor definitions if (failed(parser.parseToken(Token::Kind::id, "expected id")) || failed(parser.parseToken(Token::Kind::l_paren, "expected '('"))) return failure(); auto parseInputDef = [&]() -> LogicalResult { return parseTensorDef(/*isOutput=*/false); }; if (failed(parser.parseCommaSeparatedListUntil( Token::Kind::r_paren, parseInputDef, /*allowEmptyList=*/false))) return failure(); if (failed(parser.parseToken(Token::Kind::minus, "expected '-'")) || failed(parser.parseToken(Token::Kind::gt, "expected '>'")) || failed(parser.parseToken(Token::Kind::l_paren, "expected '('"))) return failure(); auto parseOutputDef = [&]() -> LogicalResult { return parseTensorDef(/*isOutput=*/true); }; if (failed(parser.parseCommaSeparatedListUntil( Token::Kind::r_paren, parseOutputDef, /*allowEmptyList=*/false))) return failure(); // Parse optional attribute definitions if (succeeded(parser.parseOptionalToken(Token::Kind::kw_attr_def))) { if (failed(parser.parseToken(Token::Kind::l_paren, "expected '('"))) return failure(); if (failed(parser.parseCommaSeparatedListUntil( Token::Kind::r_paren, std::bind(&TCParser::parseAttrDef, this), /*allowEmptyList=*/false))) return failure(); } // Parse optional doc string if (parser.curToken.is(Token::Kind::doc_str)) { docString = parser.curToken.getSpelling(); parser.consumeToken(); LLVM_DEBUG(llvm::dbgs() << "parsed doc string: '''" << docString << "'''\n"); } // Since we don't declare symbols separately, we discover them eagerly: each // newly encountered id in a tensor shape expression is treated as a new // symbolic. At this point, all tensors have been parsed and all the symbols // that could be discovered eagerly are now known. Resize all AffineMaps to // normalize the number of eagerly discovered symbols. for (auto &tensor : registeredTensors) { auto &map = tensor.getValue().shape; map = AffineMap::get(/*dimCount=*/0, symbols.size(), map.getResults(), parser.context); } if (failed(parser.parseToken(Token::Kind::l_brace, "expected '{'"))) return failure(); SmallVector<ComprehensionParsingState, 4> perComprehensionStates; while (parser.curToken.isNot(Token::Kind::r_brace)) { perComprehensionStates.push_back(ComprehensionParsingState()); if (failed(parseOneComprehension(cppOpName, tcName, perComprehensionStates.back()))) return failure(); }; if (failed(parser.parseToken(Token::Kind::r_brace, "expected '}'"))) return failure(); // Print. auto nComprehensions = perComprehensionStates.size(); if (nComprehensions != 1) return parser.emitError("only 1 comprehension supported for now, got: " + llvm::Twine(nComprehensions)); if (genODSDecl) { auto &state = perComprehensionStates.back(); printODS(os, cppOpName, tcName, interfaces, state); os << "\n"; } if (genODSImpl) { auto &state = perComprehensionStates.back(); std::string extraMethods; llvm::raw_string_ostream ss(extraMethods); printReferenceIterators(ss, cppOpName, state); printIndexingMapRequiredAttrMethods(ss, cppOpName, state); printReferenceIndexingMaps(ss, cppOpName, state); printRegionBuilder(ss, cppOpName, state); printCanonicalizersAndFolders(ss, cppOpName); ss.flush(); os << extraMethods << "\n"; } return success(); } //===----------------------------------------------------------------------===// // Printing functions //===----------------------------------------------------------------------===// /// Print the ODS class that defines a new `cppOpName` for a `linalgOpName`. void TCParser::printODS(llvm::raw_ostream &os, StringRef cppOpName, StringRef linalgOpName, ArrayRef<StringRef> interfaces, ComprehensionParsingState &state) { SmallVector<std::string, 4> attributes; for (const auto &attr : registeredAttrs) { llvm::StringRef name = attr.first; llvm::StringRef elementType = attr.second.elementType; std::string odsType = llvm::StringSwitch<std::string>(elementType) .Case("f32", "F32") .Case("i32", "I32") .Case("i64", "I64") .Default(""); if (odsType.empty()) { (void)parser.emitError( "unimplemented support for attribute element type: " + elementType); return; } const auto &dims = attr.second.vectorDims; if (!dims.empty()) { SmallVector<std::string, 4> dimStrs; for (uint64_t dim : dims) dimStrs.push_back(std::to_string(dim)); odsType = llvm::formatv("Ranked{0}ElementsAttr<[{1}]>", odsType, llvm::join(dimStrs, ", ")); } assert(dims.empty() || !attr.second.isArray); if (attr.second.isArray) odsType = llvm::formatv("{0}ArrayAttr", odsType); if (attr.second.isOptional) odsType = llvm::formatv("OptionalAttr<{0}>", odsType); attributes.push_back(llvm::formatv("{0}:${1}", odsType, name)); } std::string attrList = llvm::join(attributes, ",\n"); if (!attrList.empty()) attrList = ",\n" + attrList; // Template for Linalg named ops' ODS definitions. Parameters: // {0}: ODS/C++ op name // {1}: assembly op mnemonic // {2}: op interface list // {3}: documentation (summary + description) // {4}: op attribute list // {5}: the number of arguments for the op region // {6}: builder methods taking standalone attribute parameters // {7}: additional methods for attributes used by indexing maps const char *header = R"FMT( def {0} : LinalgStructuredBase_Op<"{1}", [ AttrSizedOperandSegments, DeclareOpInterfaceMethods<MemoryEffectsOpInterface>, SingleBlockImplicitTerminator<"YieldOp"> /*extraInterfaces=*/{2}]> { {3} let arguments = (ins Variadic<AnyShaped>:$inputs, Variadic<AnyShaped>:$outputs{4} ); let results = (outs Variadic<AnyRankedTensor>:$result_tensors); let regions = (region AnyRegion:$region); let skipDefaultBuilders = 1; let builders = [ OpBuilderDAG< (ins "ValueRange":$inputs, "ValueRange":$outputs), [{{ $_state.addOperands(inputs); $_state.addOperands(outputs); $_state.addAttribute( "operand_segment_sizes", $_builder.getI32VectorAttr({{ static_cast<int32_t>(inputs.size()), static_cast<int32_t>(outputs.size())})); createAndFillStructuredOpRegion<{0}>( $_builder, $_state, TypeRange(inputs), TypeRange(outputs)/*, TODO: support captures*/); }]>, OpBuilderDAG< (ins "TypeRange":$resultTensorTypes, "ValueRange":$inputs, "ValueRange":$outputs), [{{ $_state.addOperands(inputs); $_state.addOperands(outputs); $_state.addTypes(resultTensorTypes); $_state.addAttribute( "operand_segment_sizes", $_builder.getI32VectorAttr({{ static_cast<int32_t>(inputs.size()), static_cast<int32_t>(outputs.size())})); createAndFillStructuredOpRegion<{0}>( $_builder, $_state, TypeRange(inputs), TypeRange(outputs)/*, TODO: support captures*/); }]>, OpBuilderDAG< (ins "TypeRange":$resultTensorTypes, "ValueRange":$operands, CArg<"ArrayRef<NamedAttribute>", "{{}">:$attributes), [{{ $_state.addOperands(operands); $_state.addAttributes(attributes); $_state.addTypes(resultTensorTypes); (void)$_state.addRegion(); }]> {6} ]; let printer = [{{ return ::printNamedStructuredOp(p, *this); }]; let parser = [{{ return ::parseNamedStructuredOp<{0}>(parser, result/*TODO:, captures*/); }]; let hasFolder = 1; let hasCanonicalizer = 1; let extraClassDeclaration = structuredOpsBaseDecls # [{{ // Auto-generated. ArrayAttr iterator_types(); ArrayAttr indexing_maps(); static void regionBuilder(Block &block, ValueRange captures); static std::function<void(Block &, ValueRange)> getRegionBuilder() {{ return regionBuilder; } // Generic methods. static unsigned getNumRegionArgs() {{ return {5}; } std::string getLibraryCallName() {{ return generateLibraryCallName(getOperation()); } {7} }]; })FMT"; // Generate the list of extra implemented interfaces. std::string interfaceNameList; if (!interfaces.empty()) { llvm::raw_string_ostream ss(interfaceNameList); ss << ", "; // Leading comma to concat to existing list of interfaces. llvm::interleaveComma(interfaces, ss); ss.flush(); } // Generate documentation. std::string doc; if (!docString.empty()) { const char *docFmt = R"FMT( let summary = [{ {0} }]; let description = [{ {1} }]; )FMT"; StringRef summary, description; std::tie(summary, description) = docString.trim().split('\n'); doc = llvm::formatv(docFmt, summary.trim(), description.trim()); } // Generate an additional builder that has parameters for attributes. std::string attrBuilder; if (!registeredAttrs.empty()) { SmallVector<std::string, 4> attrParams, attrStmts; for (const auto &attr : registeredAttrs) { llvm::StringRef name = attr.first; attrParams.push_back(llvm::formatv("\"Attribute\":${0}", name)); attrStmts.push_back( llvm::formatv("$_state.addAttribute(\"{0}\", {0});", name)); } std::string attrParamsList = llvm::join(attrParams, ", "); std::string attrStmtsList = llvm::join(attrStmts, "\n"); const char *builderFmt = R"FMT( , OpBuilderDAG< (ins "TypeRange":$resultTensorTypes, "ValueRange":$inputs, "ValueRange":$outputs, {1}), [{{ $_state.addOperands(inputs); $_state.addOperands(outputs); $_state.addTypes(resultTensorTypes); $_state.addAttribute( "operand_segment_sizes", $_builder.getI32VectorAttr({{ static_cast<int32_t>(inputs.size()), static_cast<int32_t>(outputs.size())})); createAndFillStructuredOpRegion<{0}>( $_builder, $_state, TypeRange(inputs), TypeRange(outputs)/*, TODO: support captures*/); {2} }]> )FMT"; attrBuilder = llvm::formatv(builderFmt, cppOpName, attrParamsList, attrStmtsList); } std::string attrMethods; if (!registeredAttrs.empty()) { attrMethods = R"( bool hasDynamicIndexingMaps(); LogicalResult verifyIndexingMapRequiredAttributes(); )"; } // Finally put everything together. os << llvm::formatv(header, cppOpName, linalgOpName, interfaceNameList, doc, attrList, state.orderedTensorArgs.size(), attrBuilder, attrMethods); } /// Print the C++ StructuredOpsInterface impl of `iterator_types`. void TCParser::printReferenceIterators(llvm::raw_ostream &os, StringRef cppOpName, ComprehensionParsingState &state) { const char *referenceReferenceIteratorsFmt = R"FMT( ArrayAttr {0}::iterator_types() { return Builder(getContext()).getStrArrayAttr(SmallVector<StringRef, 8>{{ {1} }); })FMT"; std::string iteratorsStr; llvm::raw_string_ostream ss(iteratorsStr); unsigned pos = 0; llvm::interleaveComma( state.dims, ss, [&](std::pair<StringRef, AffineExpr> p) { bool reduction = false; for (auto &expr : state.expressions) { visitPostorder(*expr, [&](const Expression &e) { if (auto *pTensorExpr = dyn_cast<TensorExpr>(&e)) { if (pTensorExpr->reductionDimensions.count(pos) > 0) reduction = true; } }); if (reduction) break; } ss << (reduction ? "getReductionIteratorTypeName()" : "getParallelIteratorTypeName()"); pos++; }); ss.flush(); os << llvm::formatv(referenceReferenceIteratorsFmt, cppOpName, iteratorsStr); } void TCParser::printCanonicalizersAndFolders(llvm::raw_ostream &os, StringRef cppOpName) { const char *canonicalizersAndFoldersFmt = R"FMT( void {0}::getCanonicalizationPatterns( OwningRewritePatternList &results, MLIRContext *context) {{ results.insert<EraseDeadLinalgOp>(); results.insert<FoldTensorCastOp>(); } LogicalResult {0}::fold(ArrayRef<Attribute>, SmallVectorImpl<OpFoldResult> &) {{ return foldMemRefCast(*this); } void {0}::getEffects(SmallVectorImpl< SideEffects::EffectInstance<MemoryEffects::Effect> >&effects) {{ getGenericEffectsImpl(effects, getOperation()->getResults(), getInputBuffers(), getOutputBuffers()); })FMT"; os << llvm::formatv(canonicalizersAndFoldersFmt, cppOpName); } // Prints methods for querying whether the current named op has attributes that // are used by its indexing maps and for verifying those attributes have the // expected type. void TCParser::printIndexingMapRequiredAttrMethods( llvm::raw_ostream &os, StringRef cppOpName, ComprehensionParsingState &state) { // If there are no attribute used by the whole definition, then we are done. if (registeredAttrs.empty()) return; // Otherwise, go through each attribute and generate code to verify it's // valid per the spec. SmallVector<std::string, 4> attributes; for (const auto &attr : registeredAttrs) { if (attr.second.isOptional) continue; llvm::StringRef name = attr.first; llvm::StringRef elementType = attr.second.elementType; const auto &dims = attr.second.vectorDims; // Get the method call to check the element type is of the expected kind. std::string elemTypeCheck = llvm::StringSwitch<std::string>(elementType) .Case("f32", "isF32()") .Case("i32", "isInteger(32)") .Case("i64", "isInteger(64)") .Default(""); if (elemTypeCheck.empty()) { (void)parser.emitError( "unimplemented support for attribute element type: " + elementType); return; } // Scalar case. if (dims.empty() && !attr.second.isArray) { const char *attrFmt = R"FMT( if (auto attr = op->getAttr("{0}")) {{ if (!attr.getType().{1}) return op->emitError( "incorrect type for indexing map required attribute '{0}'"); } else {{ return op->emitError( "missing indexing map required attribute '{0}'"); } )FMT"; attributes.push_back(llvm::formatv(attrFmt, name, elemTypeCheck)); continue; } // Vector case. if (!dims.empty()) { SmallVector<std::string, 4> dimStrs; for (uint64_t dim : dims) dimStrs.push_back(std::to_string(dim)); const char *attrFmt = R"FMT( if (auto attr = op->getAttrOfType<DenseElementsAttr>("{0}")) {{ if (!attr.getType().getElementType().{1}) return op->emitError( "incorrect element type for indexing map required attribute '{0}'"); if (attr.getType().getShape() != ArrayRef<int64_t>{{ {2} }) return op->emitError( "incorrect shape for indexing map required attribute '{0}'"); } else { return op->emitError( "missing indexing map required attribute '{0}'"); } )FMT"; attributes.push_back(llvm::formatv(attrFmt, name, elemTypeCheck, llvm::join(dimStrs, ", "))); continue; } // Array case. { const char *attrFmt = R"FMT( if (auto attr = op->getAttrOfType<ArrayAttr>("{0}")) {{ for (Attribute element : attr) {{ if (!element.getType().{1}) return emitError( "incorrect element type for indexing map required attribute '{0}'"); } } else {{ return op->emitError( "missing indexing map required attribute '{0}'"); } )FMT"; attributes.push_back(llvm::formatv(attrFmt, name, elemTypeCheck)); } } const char *methodFmt = R"FMT( bool {0}::hasDynamicIndexingMaps() {{ return true; } LogicalResult {0}::verifyIndexingMapRequiredAttributes() {{ Operation *op = getOperation(); {1} return success(); } )FMT"; // Print everything out. os << llvm::formatv(methodFmt, cppOpName, llvm::join(attributes, "\n")); } /// Print the C++ StructuredOpsInterface impl of `referenceIndexingMaps`. void TCParser::printReferenceIndexingMaps(llvm::raw_ostream &os, StringRef cppOpName, ComprehensionParsingState &state) { // 1. Generic string template for specifying reference indexing maps. const char *referenceIndexingMapsFmt = R"FMT( // This is temporary until we transition out of manually specified ops that // should be auto-generated with linalg-ods-gen. ArrayAttr {0}::indexing_maps() { MLIRContext *context = getContext(); AffineExpr {1}; bindDims(context, {1}); {2} return Builder(context).getAffineMapArrayAttr({ {3} }); })FMT"; // 2. Print a comma-separated list of identifiers for the AffineExpr in // `state.dims`. These will replace the `{1}` placeholder in both // `AffineExpr {1}` and `bindDims(context, {1})` ensuring the AffineExpr // identifiers are bound in the right order to the proper AffineDimExpr. std::string dimsStr; llvm::raw_string_ostream ss(dimsStr); llvm::interleaveComma( state.dims, ss, [&](std::pair<StringRef, AffineExpr> p) { ss << p.second; }); ss.flush(); // 3. Get the list of affine maps for each input/output. The AffineExpr use // the common arithmetic operators on AffineExpr. These affine maps will // replace the `{2}` placeholder. std::string mapsStr; llvm::raw_string_ostream mapsStringStream(mapsStr); SmallVector<TensorUse, 4> orderedUses(state.orderedTensorArgs.size()); for (const auto &it : state.orderedTensorArgs) orderedUses[it.second] = it.first; // Create a list of all symbols. SmallVector<std::string, 4> symbolReplacements; symbolReplacements.reserve(symbols.size()); for (unsigned i = 0; i < symbols.size(); ++i) { const char *symFmt = "\n\tauto s{0} = getAffineSymbolExpr({0}, context); (void)s{0};"; mapsStringStream << llvm::formatv(symFmt, i); symbolReplacements.push_back(llvm::formatv("s{0}", i)); } // Create the affine constant expressions to replace symbols for attributes. for (auto attrUse : llvm::enumerate(attrUses)) { StringRef attrName = attrUse.value().attrName; auto it = registeredAttrs.find(attrName.str()); assert(it != registeredAttrs.end() && "uses should point to valid attr!"); std::string getValueFn = it->second.getValueFn(attrUse.value().indices); if (getValueFn.empty()) { (void)parser.emitError("unimplemented getValueFn for attribute: " + attrName); return; } std::string cstVal = llvm::formatv("{0}().{1}", attrName, getValueFn); const char *cstFmt = "\n\tauto cst{0} = getAffineConstantExpr({1}, context);"; mapsStringStream << llvm::formatv(cstFmt, attrUse.index(), cstVal); unsigned position = attrUse.value().symbol.cast<AffineSymbolExpr>().getPosition(); symbolReplacements[position] = llvm::formatv("cst{0}", attrUse.index()); } // For each tensor use, construct the affine map, replace symbols by the // corresponding attribute values, and simplify the affine map. for (auto tensorUse : llvm::enumerate(orderedUses)) { auto indexingMap = tensorUse.value().indexingMap; const char *mapFmt = "\n\tauto map{0} = AffineMap::get({1}, {2}, {3}, context);"; std::string exprsStr; llvm::raw_string_ostream exprsStringStream(exprsStr); exprsStringStream << "{"; llvm::interleaveComma(indexingMap.getResults(), exprsStringStream); exprsStringStream << "}"; exprsStringStream.flush(); mapsStringStream << llvm::formatv(mapFmt, tensorUse.index(), state.dims.size(), indexingMap.getNumSymbols(), exprsStr); std::string replaceSymbolList = llvm::formatv("{ {0} }", llvm::join(symbolReplacements, ", ")); // Note that we use `0` as the result affine map's number of symbols. All // symbols representing attribute usages should be folded away. But there // may exist additional symbols for tensor dimension upper bounds. Linalg // does not handle such cases right now. This needs to be fixed once we // need that. const char *replaceFmt = "\n\tmap{0} = map{0}.replaceDimsAndSymbols({{}, {1}, {2}, 0);"; mapsStringStream << llvm::formatv(replaceFmt, tensorUse.index(), replaceSymbolList, state.dims.size()); const char *simplifyFmt = "\n\tmap{0} = simplifyAffineMap(map{0});"; mapsStringStream << llvm::formatv(simplifyFmt, tensorUse.index()); } mapsStringStream.flush(); SmallVector<std::string, 4> mapList; mapList.reserve(orderedUses.size()); for (unsigned i = 0; i < orderedUses.size(); ++i) mapList.push_back(llvm::formatv("map{0}", i)); // 4. Apply format to 1. using 2. and 3. os << llvm::formatv(referenceIndexingMapsFmt, cppOpName, dimsStr, mapsStr, llvm::join(mapList, ", ")); } /// Print the C++ StructuredOpsInterface impl of `regionBuilder`. void TCParser::printRegionBuilder(llvm::raw_ostream &os, StringRef cppOpName, ComprehensionParsingState &state) { unsigned count = state.orderedTensorArgs.size(); llvm::DenseMap<const TensorExpr *, unsigned> subExprsMap; std::function<void(llvm::raw_ostream & os, const Expression &)> printExpr; printExpr = [&](llvm::raw_ostream &os, const Expression &e) -> void { if (auto *pUse = dyn_cast<TensorUse>(&e)) { os << "_" << state.orderedTensorArgs.find(*pUse)->second; return; } auto *pTensorExpr = cast<TensorExpr>(&e); if (subExprsMap.count(pTensorExpr) > 0) { os << "_" << subExprsMap[pTensorExpr]; } else { std::string subExprs; llvm::raw_string_ostream subExprsStringStream(subExprs); llvm::interleaveComma(pTensorExpr->expressions, subExprsStringStream, [&](const std::unique_ptr<Expression> &e) { printExpr(subExprsStringStream, *e); }); subExprsStringStream.flush(); const char *tensorExprFmt = "\n Value _{0} = {1}({2});"; os << llvm::formatv(tensorExprFmt, ++count, pTensorExpr->operationName, subExprs); subExprsMap[pTensorExpr] = count; } }; const char *regionBuilderFmt = R"FMT( void {0}::regionBuilder(Block &block, ValueRange captures) { using namespace edsc; using namespace intrinsics; auto args = block.getArguments(); Value {1}; {2} (linalg_yield(ValueRange{ {3} })); })FMT"; unsigned idx = 0; std::string valueHandleStr; llvm::raw_string_ostream valueHandleStringStream(valueHandleStr); llvm::interleaveComma( state.orderedTensorArgs, valueHandleStringStream, [&](auto) { valueHandleStringStream << "_" << idx << "(args[" << idx << "])"; idx++; }); std::string expressionsStr; llvm::raw_string_ostream expressionStringStream(expressionsStr); for (auto &expr : state.expressions) visitPostorder(*expr, [&](const Expression &e) { if (e.kind == Expression::Kind::TensorExpr) printExpr(expressionStringStream, e); }); std::string yieldStr; llvm::raw_string_ostream yieldStringStream(yieldStr); llvm::interleaveComma(state.expressions, yieldStringStream, [&](const std::unique_ptr<Expression> &e) { printExpr(yieldStringStream, *e); }); valueHandleStringStream.flush(); expressionStringStream.flush(); yieldStringStream.flush(); os << llvm::formatv(regionBuilderFmt, cppOpName, valueHandleStr, expressionsStr, yieldStr); } std::string TCParser::RegisteredAttr::getValueFn(ArrayRef<uint64_t> indices) const { if (isArray) return ""; if (!vectorDims.empty()) { SmallVector<std::string, 4> indexStrs; for (uint64_t index : indices) indexStrs.push_back(std::to_string(index)); std::string indexList = llvm::join(indexStrs, ", "); if (elementType == "f32") return llvm::formatv("getValue<float>({ {0} })", indexList); if (elementType == "i32") return llvm::formatv("getValue<int>({ {0} })", indexList); if (elementType == "i64") return llvm::formatv("getValue<int64_t>({ {0} })", indexList); return ""; } if (elementType == "f32") return "getValue().convertToFloat()"; if (elementType == "i32" || elementType == "i64") return "getInt()"; return ""; } /// Iterate over each Tensor Comprehension def. LogicalResult parseAndEmitAllTensorComprehensions(llvm::raw_ostream &os, Parser &parser) { while (parser.curToken.getKind() != Token::Kind::eof) { TCParser tcParser(parser); if (failed(tcParser.parseAndEmitODSDef(os))) return failure(); } return success(); } int main(int argc, char **argv) { llvm::cl::ParseCommandLineOptions(argc, argv, "Linalg ODS Gen"); // Set up the input file. std::string errorMessage; std::unique_ptr<llvm::MemoryBuffer> file = mlir::openInputFile(inputFilename, &errorMessage); if (!file) { llvm::errs() << errorMessage << "\n"; return 1; } std::unique_ptr<llvm::ToolOutputFile> output = openOutputFile(outputFilename, &errorMessage); if (!output) { llvm::errs() << errorMessage << "\n"; exit(1); } // Include the proper Linalg header for end-to-end tblgen testing without // resorting to non-portable shell manipulations. if (testEmitIncludeTdHeader) output->os() << "include \"mlir/Dialect/Linalg/IR/LinalgStructuredOps.td\""; MLIRContext context; llvm::SourceMgr mgr; mgr.AddNewSourceBuffer(std::move(file), llvm::SMLoc()); Parser parser(mgr, &context); (void)parseAndEmitAllTensorComprehensions(output->os(), parser); output->keep(); return 0; }
35.281713
86
0.626471
Kvarnefalk
4f57f215b3901633f5add7a4e1fc35148c099e66
3,807
cpp
C++
src/ripple/protocol/impl/BuildInfo.cpp
Py9595/Backpack-Travel-Underlying-Code
c5758792eba7cdd62cb6ff46e642e8e4e4e5417e
[ "BSL-1.0" ]
null
null
null
src/ripple/protocol/impl/BuildInfo.cpp
Py9595/Backpack-Travel-Underlying-Code
c5758792eba7cdd62cb6ff46e642e8e4e4e5417e
[ "BSL-1.0" ]
null
null
null
src/ripple/protocol/impl/BuildInfo.cpp
Py9595/Backpack-Travel-Underlying-Code
c5758792eba7cdd62cb6ff46e642e8e4e4e5417e
[ "BSL-1.0" ]
null
null
null
//------------------------------------------------------------------------------ /* This file is part of rippled: https://github.com/ripple/rippled Copyright (c) 2012, 2013 Ripple Labs Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ //============================================================================== #include <BeastConfig.h> #include <ripple/basics/contract.h> #include <ripple/beast/core/SemanticVersion.h> #include <ripple/protocol/BuildInfo.h> namespace ripple { namespace BuildInfo { //------------------------------------------------------------------------------ char const* const versionString = //-------------------------------------------------------------------------- // The build version number. You must edit this for each release // and follow the format described at http://semver.org/ // "0.10.1" #if defined(DEBUG) || defined(SANITIZER) "+" #ifdef DEBUG "DEBUG" #ifdef SANITIZER "." #endif #endif #ifdef SANITIZER BEAST_PP_STR1_(SANITIZER) #endif #endif //-------------------------------------------------------------------------- ; ProtocolVersion const& getCurrentProtocol () { static ProtocolVersion currentProtocol ( //-------------------------------------------------------------------------- // // The protocol version we speak and prefer (edit this if necessary) // 1, // major 2 // minor // //-------------------------------------------------------------------------- ); return currentProtocol; } ProtocolVersion const& getMinimumProtocol () { static ProtocolVersion minimumProtocol ( //-------------------------------------------------------------------------- // // The oldest protocol version we will accept. (edit this if necessary) // 1, // major 2 // minor // //-------------------------------------------------------------------------- ); return minimumProtocol; } // // // Don't touch anything below this line // //------------------------------------------------------------------------------ std::string const& getVersionString () { static std::string const value = [] { std::string const s = versionString; beast::SemanticVersion v; if (!v.parse (s) || v.print () != s) LogicError (s + ": Bad server version string"); return s; }(); return value; } std::string const& getFullVersionString () { static std::string const value = "backpacktravelalliancesd-" + getVersionString(); return value; } ProtocolVersion make_protocol (std::uint32_t version) { return ProtocolVersion( static_cast<std::uint16_t> ((version >> 16) & 0xffff), static_cast<std::uint16_t> (version & 0xffff)); } } std::string to_string (ProtocolVersion const& p) { return std::to_string (p.first) + "." + std::to_string (p.second); } std::uint32_t to_packed (ProtocolVersion const& p) { return (static_cast<std::uint32_t> (p.first) << 16) + p.second; } } // ripple
27.388489
80
0.520357
Py9595
4f58ea592e68e55ee75ef24fc4230d0e6362d51e
5,465
cpp
C++
libs/spirit/repository/test/karma/subrule.cpp
anarthal/boost-unix-mirror
8c34eb2fe471d6c3113c680c1fbef29e7a8063a0
[ "BSL-1.0" ]
106
2015-08-07T04:23:50.000Z
2020-12-27T18:25:15.000Z
libs/spirit/repository/test/karma/subrule.cpp
anarthal/boost-unix-mirror
8c34eb2fe471d6c3113c680c1fbef29e7a8063a0
[ "BSL-1.0" ]
130
2016-06-22T22:11:25.000Z
2020-11-29T20:24:09.000Z
Libs/boost_1_76_0/libs/spirit/repository/test/karma/subrule.cpp
Antd23rus/S2DE
47cc7151c2934cd8f0399a9856c1e54894571553
[ "MIT" ]
41
2015-07-08T19:18:35.000Z
2021-01-14T16:39:56.000Z
// Copyright (c) 2001-2010 Hartmut Kaiser // Copyright (c) 2009 Francois Barel // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <boost/config/warning_disable.hpp> #include <boost/detail/lightweight_test.hpp> #include <boost/spirit/include/karma_operator.hpp> #include <boost/spirit/include/karma_char.hpp> #include <boost/spirit/include/karma_auxiliary.hpp> #include <boost/spirit/include/karma_string.hpp> #include <boost/spirit/include/karma_numeric.hpp> #include <boost/spirit/include/karma_nonterminal.hpp> #include <boost/spirit/include/karma_action.hpp> #include <boost/spirit/include/phoenix_core.hpp> #include <boost/spirit/include/phoenix_operator.hpp> #include <boost/spirit/include/phoenix_statement.hpp> #include <boost/spirit/include/phoenix_fusion.hpp> #include <boost/spirit/repository/include/karma_subrule.hpp> #include "test.hpp" using namespace spirit_test; /////////////////////////////////////////////////////////////////////////////// int main() { using namespace boost; using namespace boost::spirit; using namespace boost::spirit::karma; // using namespace boost::spirit::ascii; using boost::spirit::repository::karma::subrule; typedef spirit_test::output_iterator<char>::type outiter_type; // basic tests { rule<outiter_type> start; subrule<0> sr; start = ( sr = char_[_1 = 'a'] << int_[_1 = 10] << double_[_1 = 12.4] ); BOOST_TEST(test("a1012.4", start)); BOOST_TEST(test("a1012.4", ( sr = (char_ << int_ << double_)[(_1 = 'a', _2 = 10, _3 = 12.4)] ))); subrule<1> a; subrule<2> b; subrule<3> c; start = ( sr = a << b << c , a = char_[_1 = 'a'] , b = int_[_1 = 10] , c = double_[_1 = 12.4] ); BOOST_TEST(test("a1012.4", start)); } // basic tests with delimiter { rule<outiter_type, space_type> start; subrule<0> sr; start = ( sr = char_[_1 = 'a'] << int_[_1 = 10] << double_[_1 = 12.4] ); BOOST_TEST(test_delimited("a 10 12.4 ", start, space)); BOOST_TEST(test_delimited("a 10 12.4 ", ( sr = (char_ << int_ << double_)[(_1 = 'a', _2 = 10, _3 = 12.4)] ), space)); subrule<1> a; subrule<2> b; subrule<3> c; start = ( sr = a << b << c , a = char_[_1 = 'a'] , b = int_[_1 = 10] , c = double_[_1 = 12.4] ); BOOST_TEST(test_delimited("a 10 12.4 ", start, space)); } // basic tests involving a direct parameter { typedef variant<char, int, double> var_type; rule<outiter_type, var_type()> start; subrule<0, var_type()> sr; start = ( sr = (char_ | int_ | double_)[_1 = _r0] )[_1 = _val]; var_type v ('a'); BOOST_TEST(test("a", start, v)); v = 10; BOOST_TEST(test("10", start, v)); v = 12.4; BOOST_TEST(test("12.4", start, v)); } { typedef variant<char, int, double> var_type; rule<outiter_type, space_type, var_type()> start; subrule<0, var_type()> sr; start %= ( sr = (char_ | int_ | double_)[_1 = _r0] ); var_type v ('a'); BOOST_TEST(test_delimited("a ", start, v, space)); v = 10; BOOST_TEST(test_delimited("10 ", start, v, space)); v = 12.4; BOOST_TEST(test_delimited("12.4 ", start, v, space)); } { rule<outiter_type, void(char, int, double)> start; subrule<0, void(char, int, double)> sr; start = ( sr = char_[_1 = _r1] << int_[_1 = _r2] << double_[_1 = _r3] )(_r1, _r2, _r3); BOOST_TEST(test("a1012.4", start('a', 10, 12.4))); BOOST_TEST(test("a1012.4", ( sr = (char_ << int_ << double_)[(_1 = _r1, _2 = _r2, _3 = _r3)] )('a', 10, 12.4))); subrule<1, void(char, int, double)> entry; subrule<2, void(char)> a; subrule<3, void(int)> b; subrule<4, void(double)> c; start = ( entry = a(_r1) << b(_r2) << c(_r3) , a = char_[_1 = _r1] , b = int_[_1 = _r1] , c = double_[_1 = _r1] )(_r1, _r2, _r3); BOOST_TEST(test("a1012.4", start('a', 10, 12.4))); } { rule<outiter_type, space_type, void(char, int, double)> start; subrule<0, void(char, int, double)> sr; start = ( sr = char_[_1 = _r1] << int_[_1 = _r2] << double_[_1 = _r3] )(_r1, _r2, _r3); BOOST_TEST(test_delimited("a 10 12.4 ", start('a', 10, 12.4), space)); BOOST_TEST(test_delimited("a 10 12.4 ", ( sr = (char_ << int_ << double_)[(_1 = _r1, _2 = _r2, _3 = _r3)] )('a', 10, 12.4), space)); subrule<1, void(char, int, double)> entry; subrule<2, void(char)> a; subrule<3, void(int)> b; subrule<4, void(double)> c; start = ( entry = a(_r1) << b(_r2) << c(_r3) , a = char_[_1 = _r1] , b = int_[_1 = _r1] , c = double_[_1 = _r1] )(_r1, _r2, _r3); BOOST_TEST(test_delimited("a 10 12.4 ", start('a', 10, 12.4), space)); } return boost::report_errors(); }
29.224599
80
0.526624
anarthal
4f5a88805eb6699012adc8c240d45d64c730b2d9
32,197
cc
C++
tensorflow/lite/kernels/transpose_conv_test.cc
massimobernava/tensorflow
0a68ff9a205e14dd80fa0c51a0f6954d965f825e
[ "Apache-2.0" ]
1
2022-03-29T11:36:50.000Z
2022-03-29T11:36:50.000Z
tensorflow/lite/kernels/transpose_conv_test.cc
massimobernava/tensorflow
0a68ff9a205e14dd80fa0c51a0f6954d965f825e
[ "Apache-2.0" ]
1
2020-08-01T05:40:12.000Z
2020-08-01T05:40:12.000Z
tensorflow/lite/kernels/transpose_conv_test.cc
massimobernava/tensorflow
0a68ff9a205e14dd80fa0c51a0f6954d965f825e
[ "Apache-2.0" ]
null
null
null
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <stddef.h> #include <stdint.h> #include <initializer_list> #include <map> #include <memory> #include <string> #include <tuple> #include <type_traits> #include <vector> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/memory/memory.h" #include "tensorflow/lite/interpreter.h" #include "tensorflow/lite/kernels/test_util.h" #include "tensorflow/lite/schema/schema_generated.h" #include "tensorflow/lite/string_type.h" namespace tflite { namespace ops { namespace builtin { TfLiteRegistration* Register_TRANSPOSECONV_REF(); TfLiteRegistration* Register_TRANSPOSECONV_GENERIC_OPT(); } // namespace builtin } // namespace ops namespace { using ::testing::ElementsAreArray; enum class TestType { kConst = 0, kDynamic = 1, }; template <typename InputType> class BaseTransposeConvOpModel : public SingleOpModel { public: BaseTransposeConvOpModel(TfLiteRegistration* registration, std::initializer_list<int> output_shape_data, const TensorData& filter, std::initializer_list<InputType> filter_data, const TensorData& input, const TensorData& output, Padding padding, int stride_w, int stride_h, TestType test_type, int version = 1) { // Just to be confusing, transpose_conv has an _input_ named "output_shape" // that sets the shape of the output tensor of the op :). It must always be // an int32 1D four element tensor. if (test_type == TestType::kDynamic) { output_shape_ = AddInput({TensorType_INT32, {4}}); filter_ = AddInput(filter); } else { output_shape_ = AddConstInput(TensorType_INT32, output_shape_data, {4}); filter_ = AddConstInput(filter, filter_data); } input_ = AddInput(input); output_ = AddOutput(output); SetBuiltinOp( BuiltinOperator_TRANSPOSE_CONV, BuiltinOptions_TransposeConvOptions, CreateTransposeConvOptions(builder_, padding, stride_w, stride_h) .Union()); resolver_ = absl::make_unique<SingleOpResolver>( BuiltinOperator_TRANSPOSE_CONV, registration, version); BuildInterpreter( {GetShape(output_shape_), GetShape(filter_), GetShape(input_)}); if (test_type == TestType::kDynamic) { PopulateTensor<int32_t>(output_shape_, output_shape_data); if (!std::is_same<InputType, int16_t>::value && !std::is_same<InputType, int8_t>::value) { PopulateTensor<InputType>(filter_, filter_data); } } } void SetInput(std::initializer_list<float> data) { if (std::is_same<InputType, uint8_t>::value) { QuantizeAndPopulate<uint8_t>(input_, data); } else if (std::is_same<InputType, int8_t>::value) { QuantizeAndPopulate<int8_t>(input_, data); } else if (std::is_same<InputType, int16_t>::value) { QuantizeAndPopulate<int16_t>(input_, data); } else { PopulateTensor(input_, data); } } std::vector<int> GetOutputShape() { return GetTensorShape(output_); } protected: int output_shape_; int filter_; int input_; int output_; }; class TransposeConvOpModel : public BaseTransposeConvOpModel<float> { public: using BaseTransposeConvOpModel::BaseTransposeConvOpModel; std::vector<float> GetOutput() { return ExtractVector<float>(output_); } }; const auto kKernelMap = new std::map<string, TfLiteRegistration*>({ {"Reference", ops::builtin::Register_TRANSPOSECONV_REF()}, {"GenericOptimized", ops::builtin::Register_TRANSPOSECONV_GENERIC_OPT()}, }); class TransposeConvOpTest : public ::testing::TestWithParam<std::tuple<string, TestType>> { public: TfLiteRegistration* GetRegistration() { return kKernelMap->at(std::get<0>(GetParam())); } TestType GetTestType() { return std::get<1>(GetParam()); } }; // Test case: // output = tf.nn.conv2d_backprop_input( // tf.constant([ 1, 4, 4, 1 ]), // tf.constant(np.arange(1, 10), shape=[ 3, 3, 1, 1 ], dtype=tf.float32), // tf.constant(np.arange(1, 17), shape=[ 1, 4, 4, 1 ], dtype=tf.float32), // [1, 1, 1, 1 ], // "SAME") TEST_P(TransposeConvOpTest, SimpleTest) { TransposeConvOpModel model( GetRegistration(), {1, 4, 4, 1}, {TensorType_FLOAT32, {1, 3, 3, 1}}, {1, 2, 3, 4, 5, 6, 7, 8, 9}, {TensorType_FLOAT32, {1, 4, 4, 1}}, {TensorType_FLOAT32, {}}, Padding_SAME, 1, 1, GetTestType()); model.SetInput({1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}); ASSERT_EQ(model.InvokeUnchecked(), kTfLiteOk); EXPECT_THAT(model.GetOutput(), ElementsAreArray({29, 62, 83, 75, 99, 192, 237, 198, 207, 372, 417, 330, 263, 446, 485, 365})); // GetOutputShape() should always be same as model.SetOutputShape(...); EXPECT_THAT(model.GetOutputShape(), ElementsAreArray({1, 4, 4, 1})); } // Test case: // filter = tf.constant(np.arange(1, 19), // shape=[ 3, 3, 1, 2 ], // dtype=tf.float32) // output = tf.nn.conv2d_backprop_input( // tf.constant([ 1, 4, 4, 1 ]), // filter, // tf.constant(np.arange(1, 33), shape=[ 1, 4, 4, 2 ], dtype=tf.float32), // [1, 1, 1, 1 ], // "SAME") // And filter value is derived by: // filter = tf.reshape(tf.transpose(filter, perm=[3, 0, 1, 2]), shape=[18, 1]) TEST_P(TransposeConvOpTest, TwoFiltersTest) { TransposeConvOpModel model( GetRegistration(), {1, 4, 4, 1}, {TensorType_FLOAT32, {1, 3, 3, 2}}, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18}, {TensorType_FLOAT32, {1, 4, 4, 2}}, {TensorType_FLOAT32, {}}, Padding_SAME, 1, 1, GetTestType()); model.SetInput({1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32}); ASSERT_EQ(model.InvokeUnchecked(), kTfLiteOk); EXPECT_THAT(model.GetOutput(), ElementsAreArray({184, 412, 568, 528, 678, 1347, 1689, 1434, 1494, 2715, 3057, 2442, 1968, 3352, 3652, 2760})); EXPECT_THAT(model.GetOutputShape(), ElementsAreArray({1, 4, 4, 1})); } // Test case: // filter = tf.constant(np.arange(1, 19), // shape=[ 3, 3, 1, 2 ], // dtype=tf.float32) // output = tf.nn.conv2d_backprop_input( // tf.constant([ 1, 6, 6, 1 ]), // filter, // tf.constant(np.arange(1, 33), shape=[ 1, 4, 4, 2 ], dtype=tf.float32), // [1, 1, 1, 1 ], // "VALID") // And filter value is derived by: // filter = tf.reshape(tf.transpose(filter, perm=[3, 0, 1, 2]), shape=[1, 18]) TEST_P(TransposeConvOpTest, PaddingValidTest) { TransposeConvOpModel model( GetRegistration(), {1, 6, 6, 1}, {TensorType_FLOAT32, {1, 3, 3, 2}}, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18}, {TensorType_FLOAT32, {1, 4, 4, 2}}, {TensorType_FLOAT32, {}}, Padding_VALID, 1, 1, GetTestType()); model.SetInput({1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32}); ASSERT_EQ(model.InvokeUnchecked(), kTfLiteOk); EXPECT_THAT( model.GetOutput(), ElementsAreArray({5, 22, 59, 101, 114, 83, 52, 184, 412, 568, 528, 344, 237, 678, 1347, 1689, 1434, 879, 597, 1494, 2715, 3057, 2442, 1431, 856, 1968, 3352, 3652, 2760, 1548, 689, 1534, 2543, 2729, 2010, 1103})); EXPECT_THAT(model.GetOutputShape(), ElementsAreArray({1, 6, 6, 1})); } // Test case: // filter = tf.constant(np.arange(1, 10), // shape=[ 3, 3, 1, 1 ], // dtype=tf.float32) // output = tf.nn.conv2d_backprop_input( // tf.constant([ 1, 5, 5, 1 ]), // filter, // tf.constant(np.arange(1, 5), shape=[ 1, 2, 2, 1 ], dtype=tf.float32), // [1, 2, 2, 1 ], // "VALID") TEST_P(TransposeConvOpTest, StrideValidTest) { TransposeConvOpModel model( GetRegistration(), {1, 5, 5, 1}, {TensorType_FLOAT32, {1, 3, 3, 1}}, {1, 2, 3, 4, 5, 6, 7, 8, 9}, {TensorType_FLOAT32, {1, 2, 2, 1}}, {TensorType_FLOAT32, {}}, Padding_VALID, 2, 2, GetTestType()); model.SetInput({1, 2, 3, 4}); ASSERT_EQ(model.InvokeUnchecked(), kTfLiteOk); EXPECT_THAT( model.GetOutput(), ElementsAreArray({1, 2, 5, 4, 6, 4, 5, 14, 10, 12, 10, 14, 36, 24, 30, 12, 15, 34, 20, 24, 21, 24, 55, 32, 36})); EXPECT_THAT(model.GetOutputShape(), ElementsAreArray({1, 5, 5, 1})); } // Test case: // filter = tf.constant(np.arange(1, 19), // shape=[ 3, 3, 2, 1 ], // dtype=tf.float32) // output = tf.nn.conv2d_backprop_input( // tf.constant([ 1, 5, 5, 2 ]), // filter, // tf.constant(np.arange(1, 5), shape=[ 1, 2, 2, 1 ], dtype=tf.float32), // [1, 2, 2, 1 ], // "VALID") TEST_P(TransposeConvOpTest, MultiChannelTest) { TransposeConvOpModel model( GetRegistration(), {1, 5, 5, 2}, {TensorType_FLOAT32, {2, 3, 3, 1}}, {1, 3, 5, 7, 9, 11, 13, 15, 17, 2, 4, 6, 8, 10, 12, 14, 16, 18}, {TensorType_FLOAT32, {1, 2, 2, 1}}, {TensorType_FLOAT32, {}}, Padding_VALID, 2, 2, GetTestType()); model.SetInput({1, 2, 3, 4}); ASSERT_EQ(model.InvokeUnchecked(), kTfLiteOk); EXPECT_THAT( model.GetOutput(), ElementsAreArray({1, 2, 3, 4, 7, 10, 6, 8, 10, 12, 7, 8, 9, 10, 25, 28, 18, 20, 22, 24, 16, 20, 24, 28, 62, 72, 42, 48, 54, 60, 21, 24, 27, 30, 61, 68, 36, 40, 44, 48, 39, 42, 45, 48, 103, 110, 60, 64, 68, 72})); EXPECT_THAT(model.GetOutputShape(), ElementsAreArray({1, 5, 5, 2})); } // Test case: // filter = tf.constant(np.random.randint(1, 10, size=9), // shape=[ 3, 3, 1, 1 ], // dtype=tf.float32) // output = tf.nn.conv2d_backprop_input( // tf.constant([ 1, 3, 4, 1 ]), // filter, // tf.constant([323, 521], shape=[ 1, 1, 2, 1], dtype=tf.float32), // [1, 3, 3, 1 ], // "SAME") // And filter value is derived by: // filter = tf.reshape(tf.transpose(filter, perm=[3, 0, 1, 2]), shape=[-1]) TEST_P(TransposeConvOpTest, AccuracyTest) { TransposeConvOpModel model( GetRegistration(), {1, 3, 4, 1}, {TensorType_FLOAT32, {1, 3, 3, 1}}, {9, 5, 6, 9, 8, 5, 3, 1, 4}, {TensorType_FLOAT32, {1, 1, 2, 1}}, {TensorType_FLOAT32, {}}, Padding_SAME, 3, 3, GetTestType()); model.SetInput({323, 521}); ASSERT_EQ(model.InvokeUnchecked(), kTfLiteOk); EXPECT_THAT(model.GetOutput(), ElementsAreArray( ArrayFloatNear({1615., 1938., 4689., 2605., 2584., 1615., 4689., 4168., 323., 1292., 1563., 521.}))); EXPECT_THAT(model.GetOutputShape(), ElementsAreArray({1, 3, 4, 1})); } class QuantizedTransposeConvOpModel : public BaseTransposeConvOpModel<uint8_t> { public: using BaseTransposeConvOpModel::BaseTransposeConvOpModel; std::vector<float> GetDequantizedOutput() { return Dequantize<uint8_t>(ExtractVector<uint8_t>(output_), GetScale(output_), GetZeroPoint(output_)); } }; TEST_P(TransposeConvOpTest, SimpleTestQuantized) { // Float would be {1, 2, 3, 4, 5, 6, 7, 8, 9} std::initializer_list<uint8_t> filter_data = {129, 131, 133, 135, 137, 139, 141, 143, 145}; QuantizedTransposeConvOpModel model( GetRegistration(), {1, 4, 4, 1}, {TensorType_UINT8, {1, 3, 3, 1}, -63.5, 64}, filter_data, {TensorType_UINT8, {1, 4, 4, 1}, -63.5, 64}, {TensorType_UINT8, {}, -508, 512}, Padding_SAME, 1, 1, GetTestType()); model.SetInput({1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}); ASSERT_EQ(model.InvokeUnchecked(), kTfLiteOk); EXPECT_THAT( model.GetDequantizedOutput(), ElementsAreArray(ArrayFloatNear({28, 64, 84, 76, 100, 192, 236, 200, 208, 372, 416, 332, 264, 448, 484, 364}, 1e-5))); // GetOutputShape() should always be same as model.SetOutputShape(...); EXPECT_THAT(model.GetOutputShape(), ElementsAreArray({1, 4, 4, 1})); } TEST_P(TransposeConvOpTest, TwoFiltersTestQuantized) { // Float would be {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, // 18} std::initializer_list<uint8_t> filter_data = {129, 131, 133, 135, 137, 139, 141, 143, 145, 147, 149, 151, 153, 155, 157, 159, 161, 163}; QuantizedTransposeConvOpModel model( GetRegistration(), {1, 4, 4, 1}, {TensorType_UINT8, {1, 3, 3, 2}, -63.5, 64}, filter_data, {TensorType_UINT8, {1, 4, 4, 2}, -63.5, 64}, {TensorType_UINT8, {}, -4064, 4096}, Padding_SAME, 1, 1, GetTestType()); model.SetInput({1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32}); ASSERT_EQ(model.InvokeUnchecked(), kTfLiteOk); EXPECT_THAT(model.GetDequantizedOutput(), ElementsAreArray(ArrayFloatNear( {192, 416, 576, 544, 672, 1344, 1696, 1440, 1504, 2720, 3072, 2432, 1984, 3360, 3648, 2752}, 1e-5))); EXPECT_THAT(model.GetOutputShape(), ElementsAreArray({1, 4, 4, 1})); } TEST_P(TransposeConvOpTest, PaddingValidTestQuantized) { // Float would be {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, // 18} std::initializer_list<uint8_t> filter_data = {129, 131, 133, 135, 137, 139, 141, 143, 145, 147, 149, 151, 153, 155, 157, 159, 161, 163}; QuantizedTransposeConvOpModel model( GetRegistration(), {1, 6, 6, 1}, {TensorType_UINT8, {1, 3, 3, 2}, -63.5, 64}, filter_data, {TensorType_UINT8, {1, 4, 4, 2}, -63.5, 64}, {TensorType_UINT8, {}, -4064, 4096}, Padding_VALID, 1, 1, GetTestType()); model.SetInput({1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32}); ASSERT_EQ(model.InvokeUnchecked(), kTfLiteOk); EXPECT_THAT(model.GetDequantizedOutput(), ElementsAreArray(ArrayFloatNear( {0, 32, 64, 96, 128, 96, 64, 192, 416, 576, 544, 352, 224, 672, 1344, 1696, 1440, 864, 608, 1504, 2720, 3072, 2432, 1440, 864, 1984, 3360, 3648, 2752, 1536, 704, 1536, 2528, 2720, 2016, 1088}, 1e-5))); EXPECT_THAT(model.GetOutputShape(), ElementsAreArray({1, 6, 6, 1})); } class PerChannelQuantizedTransposeConvOpModel : public BaseTransposeConvOpModel<int8_t> { public: using BaseTransposeConvOpModel::BaseTransposeConvOpModel; std::vector<float> GetDequantizedOutput() { return Dequantize<int8_t>(ExtractVector<int8_t>(output_), GetScale(output_), GetZeroPoint(output_)); } void SetFilter(const std::initializer_list<float>& data) { PerChannelSymmetricQuantizeAndPopulate(filter_, data); } }; TEST_P(TransposeConvOpTest, SimpleTestQuantizedPerChannelSingleChannel) { const std::initializer_list<float> filter_data = {1, 2, 3, 4, 5, 6, 7, 8, 9}; const std::initializer_list<int8_t> const_filter_data = {14, 28, 42, 56, 71, 85, 99, 113, 127}; PerChannelQuantizedTransposeConvOpModel model( GetRegistration(), {1, 4, 4, 1}, {TensorType_INT8, {1, 3, 3, 1}, 0, 0, 0, 0, true, {9.0 / 127}, {0}, 0}, const_filter_data, {TensorType_INT8, {1, 4, 4, 1}, 0, 0, 16.0 / 255, -128}, {TensorType_INT8, {}, 0, 0, 2, -128}, Padding_SAME, 1, 1, GetTestType(), /* version */ 2); model.SetInput({1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}); if (GetTestType() == TestType::kDynamic) { model.SetFilter(filter_data); } ASSERT_EQ(model.InvokeUnchecked(), kTfLiteOk); EXPECT_THAT( model.GetDequantizedOutput(), ElementsAreArray(ArrayFloatNear({28, 62, 82, 76, 98, 192, 238, 198, 206, 372, 416, 330, 262, 446, 486, 366}, 1e-5))); // GetOutputShape() should always be same as model.SetOutputShape(...); EXPECT_THAT(model.GetOutputShape(), ElementsAreArray({1, 4, 4, 1})); } // Test data copied from the float multi-channel test above. TEST_P(TransposeConvOpTest, TestQuantizedPerChannelMultiChannel) { const std::initializer_list<float> filter_data = { 1, 3, 5, 7, 9, 11, 13, 15, 17, 2, 4, 6, 8, 10, 12, 14, 16, 18}; const std::initializer_list<int8_t> const_filter_data = { 7, 22, 37, 52, 67, 82, 97, 112, 127, 14, 28, 42, 56, 71, 85, 99, 113, 127}; PerChannelQuantizedTransposeConvOpModel model( GetRegistration(), {1, 5, 5, 2}, {TensorType_INT8, {2, 3, 3, 1}, 0, 0, 0, 0, true, {17.0 / 127, 18.0 / 127}, {0, 0}, 0}, const_filter_data, {TensorType_INT8, {1, 2, 2, 1}, 0, 0, 4.0 / 255, -128}, {TensorType_INT8, {}, 0, 0, 1, -128}, Padding_VALID, 2, 2, GetTestType(), /* version */ 2); model.SetInput({1, 2, 3, 4}); if (GetTestType() == TestType::kDynamic) { model.SetFilter(filter_data); } ASSERT_EQ(model.InvokeUnchecked(), kTfLiteOk); EXPECT_THAT( model.GetDequantizedOutput(), ElementsAreArray(ArrayFloatNear( {1, 2, 3, 4, 7, 10, 6, 8, 10, 12, 7, 8, 9, 10, 25, 28, 18, 20, 22, 24, 16, 20, 24, 28, 62, 72, 42, 48, 54, 60, 21, 24, 27, 30, 61, 68, 36, 40, 44, 48, 39, 42, 45, 48, 103, 110, 60, 64, 68, 72}, 1e-5))); // GetOutputShape() should always be same as model.SetOutputShape(...); EXPECT_THAT(model.GetOutputShape(), ElementsAreArray({1, 5, 5, 2})); } // Test data copied from the float multi-channel test above. TEST_P(TransposeConvOpTest, TestQuantizedPerTensorMultiChannel) { const std::initializer_list<float> filter_data = { 1, 3, 5, 7, 9, 11, 13, 15, 17, 2, 4, 6, 8, 10, 12, 14, 16, 18}; const std::initializer_list<int8_t> const_filter_data = { 7, 21, 35, 49, 64, 78, 92, 106, 120, 14, 28, 42, 56, 71, 85, 99, 113, 127}; PerChannelQuantizedTransposeConvOpModel model( GetRegistration(), {1, 5, 5, 2}, {TensorType_INT8, {2, 3, 3, 1}, 0, 0, 0, 0, true, {18.0 / 127, 18.0 / 127}, {0, 0}, 0}, const_filter_data, {TensorType_INT8, {1, 2, 2, 1}, 0, 0, 4.0 / 255, -128}, {TensorType_INT8, {}, 0, 0, 1, -128}, Padding_VALID, 2, 2, GetTestType(), /* version */ 2); model.SetInput({1, 2, 3, 4}); if (GetTestType() == TestType::kDynamic) { model.SetFilter(filter_data); } ASSERT_EQ(model.InvokeUnchecked(), kTfLiteOk); EXPECT_THAT( model.GetDequantizedOutput(), ElementsAreArray(ArrayFloatNear( {1, 2, 3, 4, 7, 10, 6, 8, 10, 12, 7, 8, 9, 10, 25, 28, 18, 20, 22, 24, 16, 20, 24, 28, 62, 72, 42, 48, 54, 60, 21, 24, 27, 30, 61, 68, 36, 40, 44, 48, 39, 42, 45, 48, 103, 110, 60, 64, 68, 72}, 1e-5))); // GetOutputShape() should always be same as model.SetOutputShape(...); EXPECT_THAT(model.GetOutputShape(), ElementsAreArray({1, 5, 5, 2})); } class PerChannelQuantizedTransposeConvOpModel16x8 : public BaseTransposeConvOpModel<int16_t> { public: using BaseTransposeConvOpModel::BaseTransposeConvOpModel; std::vector<float> GetDequantizedOutput() { return Dequantize<int16_t>(ExtractVector<int16_t>(output_), GetScale(output_), GetZeroPoint(output_)); } void SetFilter(const std::initializer_list<float>& data) { PerChannelSymmetricQuantizeAndPopulate(filter_, data); } }; TEST_P(TransposeConvOpTest, SimpleTestQuantizedPerChannel16x8) { const std::initializer_list<float> filter_data = { // [2 * 2 * 2 * 2] as [output_channel, y, x, input_channel] 1, 2, // out channel = 0, y = 0, x = 0 3, 4, // out channel = 0, y = 0, x = 1 3, 4, // out channel = 0, y = 1, x = 0 5, 6, // out channel = 0, y = 1, x = 1 7, 8, // out channel = 1, y = 0, x = 0 5, 6, // out channel = 1, y = 0, x = 1 3, 4, // out channel = 1, y = 1, x = 0 1, 2, // out channel = 1, y = 1, x = 1 }; PerChannelQuantizedTransposeConvOpModel16x8 model( GetRegistration(), /*output_shape_data=*/{1, 2, 3, 2}, /*filter=*/ {TensorType_INT8, /*shape=*/{2, 2, 2, 2}, /*min=*/-64, /*max=*/64, /*scale=*/0, /*zero_point=*/0, /*per_channel_quantization=*/true, /*per_channel_quantization_scales=*/{7.0 / 127, 8.0 / 127}, /*per_channel_quantization_offsets=*/{0, 0}, /*channel_index=*/0}, /*filter_data=*/{}, /*input=*/ {TensorType_INT16, /*shape=*/{1, 2, 3, 2}, /*min=*/0, /*max=*/0, /*scale=*/4.0 / 127, /*zero_point=*/0}, /*output=*/ {TensorType_INT16, /*shape=*/{}, /*min=*/0, /*max=*/0, /*scale=*/1.0, /*zero_point=*/0}, /*padding=*/Padding_SAME, /*stride_w=*/1, /*stride_h=*/1, GetTestType()); model.SetInput({ // [1 * 2 * 3 * 2] as [batch, y, x, input_channel] 3, 2, // batch = 0, y = 0, x = 0 1, -1, // batch = 0, y = 0, x = 1 -2, -3, // batch = 0, y = 0, x = 2 4, 3, // batch = 0, y = 1, x = 0 2, -2, // batch = 0, y = 1, x = 1 -3, -4, // batch = 0, y = 1, x = 2 }); model.SetFilter(filter_data); ASSERT_EQ(model.InvokeUnchecked(), kTfLiteOk); EXPECT_THAT(model.GetDequantizedOutput(), ElementsAreArray(ArrayFloatNear( {7, 37, 16, 26, -9, -39, 27, 69, 48, 42, -32, -74}, 1e-5))); // GetOutputShape() should always be same as model.SetOutputShape(...); EXPECT_THAT(model.GetOutputShape(), ElementsAreArray({1, 2, 3, 2})); } template <typename InputType> class BaseTransposeConvBiasOpModel : public SingleOpModel { public: BaseTransposeConvBiasOpModel(TfLiteRegistration* registration, std::initializer_list<int> output_shape_data, const TensorData& filter, std::initializer_list<InputType> filter_data, const TensorData& input, const TensorData& output, Padding padding, int stride_w, int stride_h, TestType test_type, int version = 3) { if (test_type == TestType::kDynamic) { output_shape_ = AddInput({TensorType_INT32, {4}}); filter_ = AddInput(filter); } else { output_shape_ = AddConstInput(TensorType_INT32, output_shape_data, {4}); filter_ = AddConstInput(filter, filter_data); } input_ = AddInput(input); int bias_size = GetShape(filter_)[0]; if (input.type == TensorType_FLOAT32) { bias_ = AddInput({TensorType_FLOAT32, {bias_size}}); } else if (input.type == TensorType_INT8) { // per channel quantization. std::vector<float> bias_scale( filter.per_channel_quantization_scales.size()); std::vector<int64_t> bias_zero_points( filter.per_channel_quantization_scales.size()); for (size_t i = 0; i < filter.per_channel_quantization_scales.size(); ++i) { bias_scale[i] = input.scale * filter.per_channel_quantization_scales[i]; bias_zero_points[i] = 0; } TensorData bias{TensorType_INT32, {bias_size}, /*min=*/0, /*max=*/0, /*scale=*/0, /*zero_point=*/0, true, /*per_channel_quantization_scales=*/bias_scale, /*per_channel_quantization_offsets=*/bias_zero_points, /*channel_index==*/0}; bias_ = AddInput(bias); } else { // per tensor quantization. auto bias_scale = GetScale(input_) * GetScale(filter_); TensorData bias{TensorType_INT32, {bias_size}, 0, 0, bias_scale}; bias_ = AddInput(bias); } output_ = AddOutput(output); SetBuiltinOp( BuiltinOperator_TRANSPOSE_CONV, BuiltinOptions_TransposeConvOptions, CreateTransposeConvOptions(builder_, padding, stride_w, stride_h) .Union()); resolver_ = absl::make_unique<SingleOpResolver>( BuiltinOperator_TRANSPOSE_CONV, registration, version); BuildInterpreter({GetShape(output_shape_), GetShape(filter_), GetShape(input_), GetShape(bias_)}); if (test_type == TestType::kDynamic) { PopulateTensor<int32_t>(output_shape_, output_shape_data); PopulateTensor<InputType>(filter_, filter_data); } } void SetInput(std::initializer_list<float> data) { if (std::is_same<InputType, uint8_t>::value) { QuantizeAndPopulate<uint8_t>(input_, data); } else if (std::is_same<InputType, int8_t>::value) { QuantizeAndPopulate<int8_t>(input_, data); } else { PopulateTensor(input_, data); } } void SetBias(std::initializer_list<float> bias) { if (std::is_same<InputType, uint8_t>::value) { QuantizeAndPopulate<int32_t>(bias_, bias); } else if (std::is_same<InputType, int8_t>::value) { PerChannelQuantizeBias(bias_, bias); } else { PopulateTensor(bias_, bias); } } std::vector<int> GetOutputShape() { return GetTensorShape(output_); } protected: int output_shape_; int filter_; int input_; int bias_; int output_; }; class TransposeConvOpBiasModel : public BaseTransposeConvBiasOpModel<float> { public: using BaseTransposeConvBiasOpModel::BaseTransposeConvBiasOpModel; std::vector<float> GetOutput() { return ExtractVector<float>(output_); } }; // Test case: // input_data = np.arange(1, 5).reshape(1,2,2,1).astype(np.float32) // filter_data = np.arange(1, 19).reshape(3,3,2,1).astype(np.float32) // bias_data = np.array([3,4]) // input = tf.keras.layers.Input(shape=(2, 2, 1)) // output = tf.keras.layers.Convolution2DTranspose(filters=2, // kernel_size=[3, 3], // strides=[2, 2], // padding="valid")(input) // model = tf.keras.models.Model(input, output) // model.layers[1].set_weights([filter_data, bias_data]) // output = model.predict(input_data) TEST_P(TransposeConvOpTest, MultiChannelBiasTest) { TransposeConvOpBiasModel model( GetRegistration(), /*output_shape=*/{1, 5, 5, 2}, /*filter=*/{TensorType_FLOAT32, {2, 3, 3, 1}}, /*filter_data=*/ {1, 3, 5, 7, 9, 11, 13, 15, 17, 2, 4, 6, 8, 10, 12, 14, 16, 18}, /*input=*/{TensorType_FLOAT32, {1, 2, 2, 1}}, /*output=*/{TensorType_FLOAT32, {}}, Padding_VALID, /*stride_w=*/2, /*stride_h=*/2, GetTestType(), /* version */ 3); model.SetInput({1, 2, 3, 4}); model.SetBias({3, 4}); ASSERT_EQ(model.InvokeUnchecked(), kTfLiteOk); EXPECT_THAT( model.GetOutput(), ElementsAreArray({4, 6, 6, 8, 10, 14, 9, 12, 13, 16, 10, 12, 12, 14, 28, 32, 21, 24, 25, 28, 19, 24, 27, 32, 65, 76, 45, 52, 57, 64, 24, 28, 30, 34, 64, 72, 39, 44, 47, 52, 42, 46, 48, 52, 106, 114, 63, 68, 71, 76})); EXPECT_THAT(model.GetOutputShape(), ElementsAreArray({1, 5, 5, 2})); } class QuantizedTransposeConvBiasOpModel : public BaseTransposeConvBiasOpModel<uint8_t> { public: using BaseTransposeConvBiasOpModel::BaseTransposeConvBiasOpModel; std::vector<float> GetDequantizedOutput() { return Dequantize<uint8_t>(ExtractVector<uint8_t>(output_), GetScale(output_), GetZeroPoint(output_)); } }; TEST_P(TransposeConvOpTest, SimpleBiasTestQuantized) { // Float would be {1, 2, 3, 4, 5, 6, 7, 8, 9} std::initializer_list<uint8_t> filter_data = {129, 131, 133, 135, 137, 139, 141, 143, 145}; QuantizedTransposeConvBiasOpModel model( GetRegistration(), {1, 4, 4, 1}, {TensorType_UINT8, {1, 3, 3, 1}, -63.5, 64}, filter_data, {TensorType_UINT8, {1, 4, 4, 1}, -63.5, 64}, {TensorType_UINT8, {}, -508, 512}, Padding_SAME, 1, 1, GetTestType(), /* version */ 3); model.SetInput({1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}); model.SetBias({1}); ASSERT_EQ(model.InvokeUnchecked(), kTfLiteOk); EXPECT_THAT( model.GetDequantizedOutput(), ElementsAreArray(ArrayFloatNear({32, 64, 84, 76, 100, 192, 240, 200, 208, 372, 420, 332, 264, 448, 488, 368}, 1e-5))); // GetOutputShape() should always be same as model.SetOutputShape(...); EXPECT_THAT(model.GetOutputShape(), ElementsAreArray({1, 4, 4, 1})); } class PerChannelQuantizedTransposeConvBiasOpModel : public BaseTransposeConvBiasOpModel<int8_t> { public: using BaseTransposeConvBiasOpModel::BaseTransposeConvBiasOpModel; std::vector<float> GetDequantizedOutput() { return Dequantize<int8_t>(ExtractVector<int8_t>(output_), GetScale(output_), GetZeroPoint(output_)); } void SetInput(const std::initializer_list<float>& data) { QuantizeAndPopulate<int8_t>(input_, data); } void SetFilter(const std::initializer_list<float>& data) { PerChannelSymmetricQuantizeAndPopulate(filter_, data); } }; TEST_P(TransposeConvOpTest, SimpleBiasTestQuantizedPerChannelSingleChannel) { const std::initializer_list<float> filter_data = {1, 2, 3, 4, 5, 6, 7, 8, 9}; const std::initializer_list<int8_t> const_filter_data = {14, 28, 42, 56, 71, 85, 99, 113, 127}; PerChannelQuantizedTransposeConvBiasOpModel model( GetRegistration(), {1, 4, 4, 1}, {TensorType_INT8, {1, 3, 3, 1}, 0, 0, 0, 0, true, {9.0 / 127}, {0}, 0}, const_filter_data, {TensorType_INT8, {1, 4, 4, 1}, 0, 0, 16.0 / 255, -128}, {TensorType_INT8, {}, 0, 0, 2, -128}, Padding_SAME, 1, 1, GetTestType(), /* version */ 3); model.SetInput({1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}); if (GetTestType() == TestType::kDynamic) { model.SetFilter(filter_data); } model.SetBias({1}); ASSERT_EQ(model.InvokeUnchecked(), kTfLiteOk); EXPECT_THAT( model.GetDequantizedOutput(), ElementsAreArray(ArrayFloatNear({30, 62, 84, 76, 100, 194, 238, 200, 208, 372, 418, 330, 264, 446, 486, 366}, 1e-5))); // GetOutputShape() should always be same as model.SetOutputShape(...); EXPECT_THAT(model.GetOutputShape(), ElementsAreArray({1, 4, 4, 1})); } INSTANTIATE_TEST_SUITE_P( TransposeConvOpTest, TransposeConvOpTest, ::testing::Combine( ::testing::ValuesIn(SingleOpTest::GetKernelTags(*kKernelMap)), ::testing::Values(TestType::kConst, TestType::kDynamic))); } // namespace } // namespace tflite
39.798517
80
0.583967
massimobernava
4f5dc340417125c53fd371fd0fb4fc5db39e028d
5,008
cc
C++
compator/road/distidxloader.cc
yuchenECNU/VTree
32f98206b85cc9ac96f352c346c6316cf81efdca
[ "Unlicense" ]
null
null
null
compator/road/distidxloader.cc
yuchenECNU/VTree
32f98206b85cc9ac96f352c346c6316cf81efdca
[ "Unlicense" ]
null
null
null
compator/road/distidxloader.cc
yuchenECNU/VTree
32f98206b85cc9ac96f352c346c6316cf81efdca
[ "Unlicense" ]
null
null
null
/* ---------------------------------------------------------------------------- Author: Ken C. K. Lee Email: cklee@cse.psu.edu Web: http://www.cse.psu.edu/~cklee Date: Jan, 2008 Copyright(c) Ken C. K. Lee 2008 This program is for non-commerical use only. This program builds a distance index. Suggested arguments: > (prog name) -i graph.idx -o object.dat -d dist.idx -v explanations: -i: graph index file (input) -o: object file -d: distance index -v: turn verbose mode on (default: off) ---------------------------------------------------------------------------- */ #include "graph.h" #include "segfmem.h" #include "param.h" #include "collection.h" #include "distsign.h" #include "distidx.h" #include "distidxsearch.h" #include "graphsearch.h" #include "access.h" #include "iomeasure.h" #include <sys/types.h> #include <sys/timeb.h> #include <string.h> #include <stdlib.h> #include <iostream> #include <fstream> using namespace std; #define PAGESIZE 4096 void helpmsg(const char* pgm) { cerr << "Suggested arguments:" << endl; cerr << "> " << pgm << " "; cerr << "-h graph.idx -o object.dat -d dist.idx -v" << endl; cerr << "explanations:" << endl; cerr << "-i: graph index file" << endl; cerr << "-o: object file" << endl; cerr << "-d: distance index" << endl; cerr << "-v: turn verbose mode on (default: off)" << endl; } int main(const int a_argc, const char** a_argv) { if (a_argc == 1) { helpmsg(a_argv[0]); return -1; } cerr << "build distance index" << endl; //------------------------------------------------------------------------- // initialization //------------------------------------------------------------------------- const char* idxflname = Param::read(a_argc, a_argv, "-i", ""); const char* objflname = Param::read(a_argc, a_argv, "-o", ""); const char* didxflname= Param::read(a_argc, a_argv, "-d", ""); const char* vrbs = Param::read(a_argc, a_argv, "-v", "null"); bool verbose = strcmp(vrbs,"null") != 0; //------------------------------------------------------------------------- // access graph index file //------------------------------------------------------------------------- cerr << "loading a graph index ... "; SegFMemory segmem(idxflname, PAGESIZE*10, PAGESIZE, 32, false); Graph graph(segmem); cerr << "[DONE]" << endl; //------------------------------------------------------------------------- // access object file and create distance index //------------------------------------------------------------------------- cerr << "loading objects ... "; struct timeb starttime, endtime; float idxtime=0; int numobj=0; int numnodes=0; Hash nodedistsign; // keep distance signatures as an array for each node Array nodes; // keep node ids fstream fobj; fobj.open(objflname, ios::in); ftime(&starttime); // time the the object index creation while (true) { int nodeid, objid; fobj >> nodeid; if (fobj.eof()) break; fobj >> objid; // find object distance to every node segmem.m_history.clean(); Array toAllNodes(graph.m_nodes.size()); GraphSearch::spanSearch(graph, nodeid, toAllNodes); for (int i=0; i<toAllNodes.size(); i++) { GraphSearchResult* res = (GraphSearchResult*)toAllNodes.get(i); int nid = res->m_nid; int prev= (long)res->m_path.get(0); float cost = res->m_cost; Array* a = (Array*)nodedistsign.get(nid); if (a == 0) { nodedistsign.put(nid, a = new Array); nodes.append((void*)nid); } a->append(new DistSignature(objid, cost, prev)); delete res; // clean up } toAllNodes.clean(); numobj++; } ftime(&endtime); // time the the object index creation idxtime = ((endtime.time*1000 + endtime.millitm) - (starttime.time*1000 + starttime.millitm)) / 1000.0f; cerr << "[DONE]" << endl; //------------------------------------------------------------------------- // write distance index to memory //------------------------------------------------------------------------- SegFMemory segfmem(didxflname, PAGESIZE*10, PAGESIZE, 32, true); DistIndex didx(segfmem); for (int i=0; i<nodes.size(); i++) { int nid = (long)nodes.get(i); Array* a = (Array*)nodedistsign.get(nid); didx.writeNode(nid, *a); delete a; } //------------------------------------------------------------------------- // clean up //------------------------------------------------------------------------- nodedistsign.clean(); nodes.clean(); cout << "#object:," << numobj; cout << ",idxtime:," << idxtime << endl; return 0; }
31.3
79
0.465855
yuchenECNU
4f5e749457807efbcd4e88ab5680aae845e0f9fa
1,061
hpp
C++
Kronos/src/Kronos/Application.hpp
razerx100/Kronos
37ee8a63a7b47a9046e1a17dd64ef69ea3d4e798
[ "Apache-2.0" ]
null
null
null
Kronos/src/Kronos/Application.hpp
razerx100/Kronos
37ee8a63a7b47a9046e1a17dd64ef69ea3d4e798
[ "Apache-2.0" ]
null
null
null
Kronos/src/Kronos/Application.hpp
razerx100/Kronos
37ee8a63a7b47a9046e1a17dd64ef69ea3d4e798
[ "Apache-2.0" ]
null
null
null
#ifndef __APPLICATION_HPP__ #define __APPLICATION_HPP__ #include "Core.hpp" #include "Window.hpp" #include "LayerStack.hpp" #include "Events/Event.hpp" #include "Events/ApplicationEvent.hpp" #include "Events/KeyEvent.hpp" #include "Events/MouseEvent.hpp" #include "Log.hpp" #include "Renderer/Renderer.hpp" namespace Kronos { class Application { private: static Application* s_Instance; Window* m_Window; Renderer* m_Renderer; bool m_Running; LayerStack m_LayerStack; bool OnWindowDestroy(WindowDestroyEvent& event); bool OnMouseMove(MouseMovedEvent& event); public: Application(); virtual ~Application(); void Run(); void OnEvent(Event& event); void PushLayer(Layer* layer); void PushOverlay(Layer* overlay); virtual bool OnWindowClose(WindowCloseEvent& event); static Application& GetApp() { return *s_Instance; } inline Window* GetWindow() { return m_Window; } inline Renderer& GetRenderer() { return *m_Renderer; } }; Application* CreateApplication(); } #endif
24.674419
57
0.713478
razerx100
4f60b3c775dfa9083074815d99c2eef2498907ad
34,809
cpp
C++
src/Native/Runtime/RuntimeInstance.cpp
OceanYan/corert
bc9671edca37502794c01647215519d4254d3ad4
[ "MIT" ]
null
null
null
src/Native/Runtime/RuntimeInstance.cpp
OceanYan/corert
bc9671edca37502794c01647215519d4254d3ad4
[ "MIT" ]
null
null
null
src/Native/Runtime/RuntimeInstance.cpp
OceanYan/corert
bc9671edca37502794c01647215519d4254d3ad4
[ "MIT" ]
null
null
null
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #include "common.h" #include "CommonTypes.h" #include "CommonMacros.h" #include "daccess.h" #include "PalRedhawkCommon.h" #include "PalRedhawk.h" #include "rhassert.h" #include "slist.h" #include "holder.h" #include "Crst.h" #include "rhbinder.h" #include "RWLock.h" #include "RuntimeInstance.h" #include "event.h" #include "regdisplay.h" #include "StackFrameIterator.h" #include "thread.h" #include "threadstore.h" #include "threadstore.inl" #include "gcrhinterface.h" #include "shash.h" #include "module.h" #include "eetype.h" #include "GenericInstance.h" #include "varint.h" #include "DebugEventSource.h" #include "CommonMacros.inl" #include "slist.inl" #include "eetype.inl" #include "OptionalFields.inl" #ifdef FEATURE_GC_STRESS enum HijackType { htLoop, htCallsite }; bool ShouldHijackForGcStress(UIntNative CallsiteIP, HijackType ht); #endif // FEATURE_GC_STRESS #include "shash.inl" #ifndef DACCESS_COMPILE COOP_PINVOKE_HELPER(UInt8 *, RhSetErrorInfoBuffer, (UInt8 * pNewBuffer)) { return (UInt8 *) PalSetWerDataBuffer(pNewBuffer); } #endif // DACCESS_COMPILE RuntimeInstance::ModuleIterator::ModuleIterator() : m_readHolder(&GetRuntimeInstance()->m_ModuleListLock), m_pCurrentPosition(GetRuntimeInstance()->GetModuleList()->GetHead()) { } SList<Module>* RuntimeInstance::GetModuleList() { return dac_cast<DPTR(SList<Module>)>( dac_cast<TADDR>(this) + offsetof(RuntimeInstance, m_ModuleList)); } RuntimeInstance::ModuleIterator::~ModuleIterator() { } PTR_Module RuntimeInstance::ModuleIterator::GetNext() { PTR_Module pResult = m_pCurrentPosition; if (NULL != pResult) m_pCurrentPosition = pResult->m_pNext; return pResult; } ThreadStore * RuntimeInstance::GetThreadStore() { return m_pThreadStore; } Module * RuntimeInstance::FindModuleByAddress(PTR_VOID pvAddress) { FOREACH_MODULE(pModule) { if (pModule->ContainsCodeAddress(pvAddress) || pModule->ContainsDataAddress(pvAddress) || pModule->ContainsReadOnlyDataAddress(pvAddress) || pModule->ContainsStubAddress(pvAddress)) { return pModule; } } END_FOREACH_MODULE; return NULL; } Module * RuntimeInstance::FindModuleByCodeAddress(PTR_VOID pvAddress) { FOREACH_MODULE(pModule) { if (pModule->ContainsCodeAddress(pvAddress)) return pModule; } END_FOREACH_MODULE; return NULL; } Module * RuntimeInstance::FindModuleByDataAddress(PTR_VOID pvAddress) { FOREACH_MODULE(pModule) { if (pModule->ContainsDataAddress(pvAddress)) return pModule; } END_FOREACH_MODULE; return NULL; } Module * RuntimeInstance::FindModuleByReadOnlyDataAddress(PTR_VOID pvAddress) { FOREACH_MODULE(pModule) { if (pModule->ContainsReadOnlyDataAddress(pvAddress)) return pModule; } END_FOREACH_MODULE; return NULL; } void RuntimeInstance::EnumerateModulesUnderLock(EnumerateModulesCallbackPFN pCallback, void *pvContext) { ASSERT(pCallback != NULL); FOREACH_MODULE(pModule) { (*pCallback)(pModule, pvContext); } END_FOREACH_MODULE; } COOP_PINVOKE_HELPER(UInt8 *, RhFindMethodStartAddress, (void * codeAddr)) { return dac_cast<UInt8 *>(GetRuntimeInstance()->FindMethodStartAddress(dac_cast<PTR_VOID>(codeAddr))); } PTR_UInt8 RuntimeInstance::FindMethodStartAddress(PTR_VOID ControlPC) { FOREACH_MODULE(pModule) { if (pModule->ContainsCodeAddress(ControlPC)) { return pModule->FindMethodStartAddress(ControlPC); } } END_FOREACH_MODULE; return NULL; } ICodeManager * RuntimeInstance::FindCodeManagerByAddress(PTR_VOID pvAddress) { ReaderWriterLock::ReadHolder read(&m_ModuleListLock); for (Module * pModule = m_ModuleList.GetHead(); pModule != NULL; pModule = pModule->m_pNext) { if (pModule->ContainsCodeAddress(pvAddress)) return pModule; } // TODO: JIT support in DAC #ifndef DACCESS_COMPILE #ifdef FEATURE_DYNAMIC_CODE for (CodeManagerEntry * pEntry = m_CodeManagerList.GetHead(); pEntry != NULL; pEntry = pEntry->m_pNext) { if (dac_cast<TADDR>(pvAddress) - dac_cast<TADDR>(pEntry->m_pvStartRange) < pEntry->m_cbRange) return pEntry->m_pCodeManager; } #endif #endif return NULL; } GPTR_DECL(RuntimeInstance, g_pTheRuntimeInstance); PTR_RuntimeInstance GetRuntimeInstance() { return g_pTheRuntimeInstance; } void RuntimeInstance::EnumGenericStaticGCRefs(PTR_GenericInstanceDesc pInst, void * pfnCallback, void * pvCallbackData, Module *pModule) { while (pInst) { if (pInst->HasGcStaticFields()) Module::EnumStaticGCRefsBlock(pfnCallback, pvCallbackData, pInst->GetGcStaticFieldDesc(), pInst->GetGcStaticFieldData()); // Thread local statics. if (pInst->HasThreadStaticFields()) { // Special case for dynamic types: TLS storage managed manually by runtime UInt32 uiFieldsStartOffset = pInst->GetThreadStaticFieldStartOffset(); if (uiFieldsStartOffset & DYNAMIC_TYPE_TLS_OFFSET_FLAG) { FOREACH_THREAD(pThread) { PTR_UInt8 pTLSStorage = pThread->GetThreadLocalStorageForDynamicType(uiFieldsStartOffset); if (pTLSStorage != NULL) { Module::EnumStaticGCRefsBlock(pfnCallback, pvCallbackData, pInst->GetThreadStaticFieldDesc(), pTLSStorage); } } END_FOREACH_THREAD } else { // See RhGetThreadStaticFieldAddress for details on where TLS fields live. UInt32 uiTlsIndex; UInt32 uiFieldOffset; if (pModule != NULL) { ModuleHeader * pModuleHeader = pModule->GetModuleHeader(); uiTlsIndex = *pModuleHeader->PointerToTlsIndex; uiFieldOffset = pModuleHeader->TlsStartOffset + uiFieldsStartOffset; } else { uiTlsIndex = pInst->GetThreadStaticFieldTlsIndex(); uiFieldOffset = uiFieldsStartOffset; } FOREACH_THREAD(pThread) { Module::EnumStaticGCRefsBlock(pfnCallback, pvCallbackData, pInst->GetThreadStaticFieldDesc(), pThread->GetThreadLocalStorage(uiTlsIndex, uiFieldOffset)); } END_FOREACH_THREAD } } pInst = pInst->GetNextGidWithGcRoots(); } } void RuntimeInstance::EnumAllStaticGCRefs(void * pfnCallback, void * pvCallbackData) { FOREACH_MODULE(pModule) { pModule->EnumStaticGCRefs(pfnCallback, pvCallbackData); EnumGenericStaticGCRefs(pModule->GetGidsWithGcRootsList(), pfnCallback, pvCallbackData, pModule); } END_FOREACH_MODULE EnumGenericStaticGCRefs(m_genericInstReportList, pfnCallback, pvCallbackData, NULL); } static UInt32 HashEETypeByPointerValue(PTR_EEType pEEType) { return (UInt32)dac_cast<TADDR>(pEEType) >> 3; } struct GenericTypeTraits : public DefaultSHashTraits<PTR_GenericInstanceDesc> { typedef PTR_EEType key_t; static key_t GetKey(const element_t e) { return e->GetEEType(); } static bool Equals(key_t k1, key_t k2) { return (k1 == k2); } static count_t Hash(key_t k) { return HashEETypeByPointerValue(k); } static bool IsNull(const element_t e) { return (e == NULL); } static const element_t Null() { return NULL; } }; class GenericTypeHashTable : public SHash< NoRemoveSHashTraits < GenericTypeTraits > > { }; #ifndef DACCESS_COMPILE bool RuntimeInstance::BuildGenericTypeHashTable() { UInt32 nTotalCount = 0; FOREACH_MODULE(pModule) { nTotalCount += pModule->GetGenericInstanceDescCount(Module::GenericInstanceDescKind::VariantGenericInstances); } END_FOREACH_MODULE; GenericTypeHashTable * pTable = new (nothrow) GenericTypeHashTable(); if (pTable == NULL) return false; // Preallocate the table to make rehashing unnecessary if(!pTable->CheckGrowth(nTotalCount)) { delete pTable; return false; } FOREACH_MODULE(pModule) { Module::GenericInstanceDescEnumerator gidEnumerator(pModule, Module::GenericInstanceDescKind::VariantGenericInstances); GenericInstanceDesc * pGid; while ((pGid = gidEnumerator.Next()) != NULL) { if (!pTable->Add(pGid)) { delete pTable; return false; } } } END_FOREACH_MODULE; // The hash table is initialized. Attempt to publish this version of the table to other threads. If we // lose (another thread has already updated m_pGenericTypeHashTable) then we deallocate our version and // use theirs for the lookup. if (PalInterlockedCompareExchangePointer((void**)&m_pGenericTypeHashTable, pTable, NULL) != NULL) { delete pTable; } return true; } Module * RuntimeInstance::FindModuleByOsHandle(HANDLE hOsHandle) { FOREACH_MODULE(pModule) { if (pModule->IsContainedBy(hOsHandle)) return pModule; } END_FOREACH_MODULE; return NULL; } RuntimeInstance::RuntimeInstance() : m_pThreadStore(NULL), m_fStandaloneExeMode(false), m_pStandaloneExeModule(NULL), m_pGenericTypeHashTable(NULL), m_conservativeStackReportingEnabled(false) { } RuntimeInstance::~RuntimeInstance() { if (m_pGenericTypeHashTable != NULL) { delete m_pGenericTypeHashTable; m_pGenericTypeHashTable = NULL; } if (NULL != m_pThreadStore) { delete m_pThreadStore; m_pThreadStore = NULL; } } HANDLE RuntimeInstance::GetPalInstance() { return m_hPalInstance; } bool RuntimeInstance::EnableConservativeStackReporting() { m_conservativeStackReportingEnabled = true; return true; } EXTERN_C void REDHAWK_CALLCONV RhpSetHaveNewClasslibs(); bool RuntimeInstance::RegisterModule(ModuleHeader *pModuleHeader) { // Determine whether we're in standalone exe mode. If we are we'll see the runtime module load followed by // exactly one additional module (the exe itself). The exe module will have a standalone flag set in its // header. ASSERT(m_fStandaloneExeMode == false); if (pModuleHeader->Flags & ModuleHeader::StandaloneExe) m_fStandaloneExeMode = true; CreateHolder<Module> pModule = Module::Create(pModuleHeader); if (NULL == pModule) return false; { // WARNING: This region must be kept small and must not callout // to arbitrary code. See Thread::Hijack for more details. ReaderWriterLock::WriteHolder write(&m_ModuleListLock); m_ModuleList.PushHead(pModule); } if (m_fStandaloneExeMode) m_pStandaloneExeModule = pModule; if (pModule->IsClasslibModule()) RhpSetHaveNewClasslibs(); #ifdef FEATURE_PROFILING InitProfiling(pModuleHeader); #endif // FEATURE_PROFILING { // Support for late-loaded modules: flush the generic hashtable to force its regeneration // including the new module. // @TODO: This is obviously not ideal, we would be better of by incrementally adding // types in the new module to the existing hashtable. Unfortunately today implementation // doesn't expect the table to be growable. ReaderWriterLock::WriteHolder write(&m_GenericHashTableLock); if (m_pGenericTypeHashTable != nullptr) { delete m_pGenericTypeHashTable; m_pGenericTypeHashTable = nullptr; } } pModule.SuppressRelease(); // This event must occur after the module is added to the enumeration DebugEventSource::SendModuleLoadEvent(pModule); return true; } void RuntimeInstance::UnregisterModule(Module *pModule) { { // WARNING: This region must be kept small and must not callout // to arbitrary code. See Thread::Hijack for more details. ReaderWriterLock::WriteHolder write(&m_ModuleListLock); ASSERT(rh::std::count(m_ModuleList.Begin(), m_ModuleList.End(), pModule) == 1); m_ModuleList.RemoveFirst(pModule); } // This event needs to occur after the module has been removed from enumeration. // However it should come before the data is destroyed to make certain the pointer doesn't get recycled. DebugEventSource::SendModuleUnloadEvent(pModule); pModule->Destroy(); } #ifdef FEATURE_DYNAMIC_CODE bool RuntimeInstance::RegisterCodeManager(ICodeManager * pCodeManager, PTR_VOID pvStartRange, UInt32 cbRange) { CodeManagerEntry * pEntry = new (nothrow) CodeManagerEntry(); if (NULL == pEntry) return false; pEntry->m_pvStartRange = pvStartRange; pEntry->m_cbRange = cbRange; pEntry->m_pCodeManager = pCodeManager; { ReaderWriterLock::WriteHolder write(&m_ModuleListLock); m_CodeManagerList.PushHead(pEntry); } return true; } void RuntimeInstance::UnregisterCodeManager(ICodeManager * pCodeManager) { CodeManagerEntry * pEntry = NULL; { ReaderWriterLock::WriteHolder write(&m_ModuleListLock); for (CodeManagerList::Iterator i = m_CodeManagerList.Begin(), end = m_CodeManagerList.End(); i != end; i++) { if (i->m_pCodeManager == pCodeManager) { pEntry = *i; m_CodeManagerList.Remove(i); break; } } } ASSERT(pEntry != NULL); delete pEntry; } extern "C" bool __stdcall RegisterCodeManager(ICodeManager * pCodeManager, PTR_VOID pvStartRange, UInt32 cbRange) { return GetRuntimeInstance()->RegisterCodeManager(pCodeManager, pvStartRange, cbRange); } extern "C" void __stdcall UnregisterCodeManager(ICodeManager * pCodeManager) { return GetRuntimeInstance()->UnregisterCodeManager(pCodeManager); } #endif // static RuntimeInstance * RuntimeInstance::Create(HANDLE hPalInstance) { NewHolder<RuntimeInstance> pRuntimeInstance = new (nothrow) RuntimeInstance(); if (NULL == pRuntimeInstance) return NULL; CreateHolder<ThreadStore> pThreadStore = ThreadStore::Create(pRuntimeInstance); if (NULL == pThreadStore) return NULL; pThreadStore.SuppressRelease(); pRuntimeInstance->m_pThreadStore = pThreadStore; pRuntimeInstance->m_hPalInstance = hPalInstance; pRuntimeInstance->m_genericInstReportList = NULL; #ifdef FEATURE_PROFILING pRuntimeInstance->m_fProfileThreadCreated = false; #endif pRuntimeInstance.SuppressRelease(); return pRuntimeInstance; } void RuntimeInstance::Destroy() { delete this; } bool RuntimeInstance::ShouldHijackLoopForGcStress(UIntNative CallsiteIP) { #if defined(FEATURE_GC_STRESS) & !defined(DACCESS_COMPILE) return ShouldHijackForGcStress(CallsiteIP, htLoop); #else // FEATURE_GC_STRESS & !DACCESS_COMPILE UNREFERENCED_PARAMETER(CallsiteIP); return false; #endif // FEATURE_GC_STRESS & !DACCESS_COMPILE } bool RuntimeInstance::ShouldHijackCallsiteForGcStress(UIntNative CallsiteIP) { #if defined(FEATURE_GC_STRESS) & !defined(DACCESS_COMPILE) return ShouldHijackForGcStress(CallsiteIP, htCallsite); #else // FEATURE_GC_STRESS & !DACCESS_COMPILE UNREFERENCED_PARAMETER(CallsiteIP); return false; #endif // FEATURE_GC_STRESS & !DACCESS_COMPILE } // This method should only be called during DllMain for modules with GcStress enabled. The locking done by // the loader is used to make it OK to call UnsynchronizedHijackAllLoops. void RuntimeInstance::EnableGcPollStress() { FOREACH_MODULE(pModule) { pModule->UnsynchronizedHijackAllLoops(); } END_FOREACH_MODULE; } // Only called from thread suspension code while all threads are still synchronized. void RuntimeInstance::UnsychronizedResetHijackedLoops() { FOREACH_MODULE(pModule) { pModule->UnsynchronizedResetHijackedLoops(); } END_FOREACH_MODULE; } // Given the EEType* for an instantiated generic type retrieve the GenericInstanceDesc associated with that // type. This is legal only for types that are guaranteed to have this metadata at runtime; generic types // which have variance over one or more of their type parameters and generic interfaces on array). GenericInstanceDesc * RuntimeInstance::LookupGenericInstance(EEType * pEEType) { // EETypes we will attempt to match against will always be the canonical version. Canonicalize our input // EEType as well if required. if (pEEType->IsCloned()) pEEType = pEEType->get_CanonicalEEType(); if (m_pGenericTypeHashTable == NULL) { if (!BuildGenericTypeHashTable()) { // We failed the allocation but we don't want to fail the call (because we build this table lazily // we're doing the allocation at a point the caller doesn't expect can fail). So fall back to the // slow linear scan of all variant GIDs in this case. FOREACH_MODULE(pModule) { Module::GenericInstanceDescEnumerator gidEnumerator(pModule, Module::GenericInstanceDescKind::VariantGenericInstances); GenericInstanceDesc * pGid; while ((pGid = gidEnumerator.Next()) != NULL) { if (pGid->GetEEType() == pEEType) return pGid; } } END_FOREACH_MODULE; // It is not legal to call this API unless you know there is a matching GenericInstanceDesc. UNREACHABLE(); } } ReaderWriterLock::ReadHolder read(&m_GenericHashTableLock); const PTR_GenericInstanceDesc * ppGid = m_pGenericTypeHashTable->LookupPtr(pEEType); if (ppGid != NULL) return *ppGid; // It is not legal to call this API unless you know there is a matching GenericInstanceDesc. UNREACHABLE(); } // Given the EEType* for an instantiated generic type retrieve instantiation information (generic type // definition EEType, arity, type arguments and variance info for each type parameter). Has the same // limitations on usage as LookupGenericInstance above. EEType * RuntimeInstance::GetGenericInstantiation(EEType * pEEType, UInt32 * pArity, EEType *** ppInstantiation, GenericVarianceType ** ppVarianceInfo) { GenericInstanceDesc * pInst = LookupGenericInstance(pEEType); ASSERT(pInst != NULL && pInst->HasInstantiation()); *pArity = pInst->GetArity(); *ppInstantiation = (EEType**)((UInt8*)pInst + pInst->GetParameterTypeOffset(0)); if (pInst->HasVariance()) *ppVarianceInfo = (GenericVarianceType*)((UInt8*)pInst + pInst->GetParameterVarianceOffset(0)); else *ppVarianceInfo = NULL; return pInst->GetGenericTypeDef().GetValue(); } bool RuntimeInstance::CreateGenericInstanceDesc(EEType * pEEType, EEType * pTemplateType, UInt32 arity, UInt32 nonGcStaticDataSize, UInt32 nonGCStaticDataOffset, UInt32 gcStaticDataSize, UInt32 threadStaticOffset, StaticGcDesc * pGcStaticsDesc, StaticGcDesc * pThreadStaticsDesc, UInt32* pGenericVarianceFlags) { if (m_pGenericTypeHashTable == NULL) { if (!BuildGenericTypeHashTable()) return false; } GenericInstanceDesc::OptionalFieldTypes flags = GenericInstanceDesc::GID_Instantiation; if (pTemplateType->HasGenericVariance()) flags |= GenericInstanceDesc::GID_Variance; if (gcStaticDataSize > 0) flags |= GenericInstanceDesc::GID_GcStaticFields | GenericInstanceDesc::GID_GcRoots; if (nonGcStaticDataSize > 0) flags |= GenericInstanceDesc::GID_NonGcStaticFields; if (threadStaticOffset != 0) flags |= GenericInstanceDesc::GID_ThreadStaticFields | GenericInstanceDesc::GID_GcRoots; // Note: arity is limited to a maximum value of 65535 on the managed layer before CreateGenericInstanceDesc // gets called. With this value, cbGidSize will not exceed 600K, so no need to use safe integers size_t cbGidSize = GenericInstanceDesc::GetSize(flags, arity); NewArrayHolder<UInt8> pGidMemory = new (nothrow) UInt8[cbGidSize]; if (pGidMemory == NULL) return false; GenericInstanceDesc * pGid = (GenericInstanceDesc *)(UInt8 *)pGidMemory; memset(pGid, 0, cbGidSize); pGid->Init(flags); pGid->SetEEType(pEEType); pGid->SetArity(arity); NewArrayHolder<UInt8> pNonGcStaticData; if (nonGcStaticDataSize > 0) { // The value of nonGcStaticDataSize is read from native layout info in the managed layer, where // there is also a check that it does not exceed the max value of a signed Int32 ASSERT(nonGCStaticDataOffset <= nonGcStaticDataSize); pNonGcStaticData = new (nothrow) UInt8[nonGcStaticDataSize]; if (pNonGcStaticData == NULL) return false; memset(pNonGcStaticData, 0, nonGcStaticDataSize); pGid->SetNonGcStaticFieldData(pNonGcStaticData + nonGCStaticDataOffset); } NewArrayHolder<UInt8> pGcStaticData; if (gcStaticDataSize > 0) { // The value of gcStaticDataSize is read from native layout info in the managed layer, where // there is also a check that it does not exceed the max value of a signed Int32 pGcStaticData = new (nothrow) UInt8[gcStaticDataSize]; if (pGcStaticData == NULL) return false; memset(pGcStaticData, 0, gcStaticDataSize); pGid->SetGcStaticFieldData(pGcStaticData); pGid->SetGcStaticFieldDesc(pGcStaticsDesc); } if (threadStaticOffset != 0) { // Note: TLS index not used for dynamically created types pGid->SetThreadStaticFieldTlsIndex(0); pGid->SetThreadStaticFieldStartOffset(threadStaticOffset); // Note: pThreadStaticsDesc can possibly be NULL if the type doesn't have any thread-static reference types pGid->SetThreadStaticFieldDesc(pThreadStaticsDesc); } if (pTemplateType->HasGenericVariance()) { ASSERT(pGenericVarianceFlags != NULL); for (UInt32 i = 0; i < arity; i++) { GenericVarianceType variance = (GenericVarianceType)pGenericVarianceFlags[i]; pGid->SetParameterVariance(i, variance); } } ReaderWriterLock::WriteHolder write(&m_GenericHashTableLock); if (!m_pGenericTypeHashTable->Add(pGid)) return false; if (gcStaticDataSize > 0 || pGid->HasThreadStaticFields()) { pGid->SetNextGidWithGcRoots(m_genericInstReportList); m_genericInstReportList = pGid; } pGidMemory.SuppressRelease(); pNonGcStaticData.SuppressRelease(); pGcStaticData.SuppressRelease(); return true; } bool RuntimeInstance::SetGenericInstantiation(EEType * pEEType, EEType * pEETypeDef, UInt32 arity, EEType ** pInstantiation) { ASSERT(pEEType->IsGeneric()); ASSERT(pEEType->IsDynamicType()); ASSERT(m_pGenericTypeHashTable != NULL) GenericInstanceDesc * pGid = LookupGenericInstance(pEEType); ASSERT(pGid != NULL); pGid->SetGenericTypeDef((EETypeRef&)pEETypeDef); // Arity should have been set during the GID creation time ASSERT(pGid->GetArity() == arity); for (UInt32 iArg = 0; iArg < arity; iArg++) pGid->SetParameterType(iArg, (EETypeRef&)pInstantiation[iArg]); return true; } COOP_PINVOKE_HELPER(EEType *, RhGetGenericInstantiation, (EEType * pEEType, UInt32 * pArity, EEType *** ppInstantiation, GenericVarianceType ** ppVarianceInfo)) { #if CORERT *pArity = pEEType->get_GenericArity(); *ppInstantiation = pEEType->get_GenericArguments(); if (pEEType->HasGenericVariance()) *ppVarianceInfo = pEEType->get_GenericVariance(); else *ppVarianceInfo = NULL; return pEEType->get_GenericDefinition(); #else return GetRuntimeInstance()->GetGenericInstantiation(pEEType, pArity, ppInstantiation, ppVarianceInfo); #endif } COOP_PINVOKE_HELPER(bool, RhSetGenericInstantiation, (EEType * pEEType, EEType * pEETypeDef, UInt32 arity, EEType ** pInstantiation)) { return GetRuntimeInstance()->SetGenericInstantiation(pEEType, pEETypeDef, arity, pInstantiation); } COOP_PINVOKE_HELPER(bool, RhCreateGenericInstanceDescForType2, (EEType * pEEType, UInt32 arity, UInt32 nonGcStaticDataSize, UInt32 nonGCStaticDataOffset, UInt32 gcStaticDataSize, UInt32 threadStaticsOffset, StaticGcDesc * pGcStaticsDesc, StaticGcDesc * pThreadStaticsDesc, UInt32* pGenericVarianceFlags)) { ASSERT(pEEType->IsDynamicType()); EEType * pTemplateType = pEEType->get_DynamicTemplateType(); return GetRuntimeInstance()->CreateGenericInstanceDesc(pEEType, pTemplateType, arity, nonGcStaticDataSize, nonGCStaticDataOffset, gcStaticDataSize, threadStaticsOffset, pGcStaticsDesc, pThreadStaticsDesc, pGenericVarianceFlags); } COOP_PINVOKE_HELPER(UInt32, RhGetGCDescSize, (EEType* pEEType)) { return RedhawkGCInterface::GetGCDescSize(pEEType); } // Keep in sync with ndp\fxcore\src\System.Private.CoreLib\system\runtime\runtimeimports.cs enum RuntimeHelperKind { AllocateObject, IsInst, CastClass, AllocateArray, CheckArrayElementType, }; // The dictionary codegen expects a pointer that points at a memory location that points to the method pointer // Create indirections for all helpers used below #define DECLARE_INDIRECTION(HELPER_NAME) \ EXTERN_C void * HELPER_NAME; \ const PTR_VOID indirection_##HELPER_NAME = (PTR_VOID)&HELPER_NAME #define INDIRECTION(HELPER_NAME) ((PTR_VOID)&indirection_##HELPER_NAME) DECLARE_INDIRECTION(RhpNewFast); DECLARE_INDIRECTION(RhpNewFinalizable); DECLARE_INDIRECTION(RhpNewArray); DECLARE_INDIRECTION(RhTypeCast_IsInstanceOfClass); DECLARE_INDIRECTION(RhTypeCast_CheckCastClass); DECLARE_INDIRECTION(RhTypeCast_IsInstanceOfArray); DECLARE_INDIRECTION(RhTypeCast_CheckCastArray); DECLARE_INDIRECTION(RhTypeCast_IsInstanceOfInterface); DECLARE_INDIRECTION(RhTypeCast_CheckCastInterface); DECLARE_INDIRECTION(RhTypeCast_CheckVectorElemAddr); #ifdef _ARM_ DECLARE_INDIRECTION(RhpNewFinalizableAlign8); DECLARE_INDIRECTION(RhpNewFastMisalign); DECLARE_INDIRECTION(RhpNewFastAlign8); DECLARE_INDIRECTION(RhpNewArrayAlign8); #endif COOP_PINVOKE_HELPER(PTR_VOID, RhGetRuntimeHelperForType, (EEType * pEEType, int helperKind)) { // This implementation matches what the binder does (MetaDataEngine::*() in rh\src\tools\rhbind\MetaDataEngine.cpp) // If you change the binder's behavior, change this implementation too switch (helperKind) { case RuntimeHelperKind::AllocateObject: #ifdef _ARM_ if ((pEEType->get_RareFlags() & EEType::RareFlags::RequiresAlign8Flag) == EEType::RareFlags::RequiresAlign8Flag) { if (pEEType->HasFinalizer()) return INDIRECTION(RhpNewFinalizableAlign8); else if (pEEType->get_IsValueType()) // returns true for enum types as well return INDIRECTION(RhpNewFastMisalign); else return INDIRECTION(RhpNewFastAlign8); } #endif if (pEEType->HasFinalizer()) return INDIRECTION(RhpNewFinalizable); else return INDIRECTION(RhpNewFast); case RuntimeHelperKind::IsInst: if (pEEType->IsArray()) return INDIRECTION(RhTypeCast_IsInstanceOfArray); else if (pEEType->IsInterface()) return INDIRECTION(RhTypeCast_IsInstanceOfInterface); else return INDIRECTION(RhTypeCast_IsInstanceOfClass); case RuntimeHelperKind::CastClass: if (pEEType->IsArray()) return INDIRECTION(RhTypeCast_CheckCastArray); else if (pEEType->IsInterface()) return INDIRECTION(RhTypeCast_CheckCastInterface); else return INDIRECTION(RhTypeCast_CheckCastClass); case RuntimeHelperKind::AllocateArray: #ifdef _ARM_ if (pEEType->RequiresAlign8()) return INDIRECTION(RhpNewArrayAlign8); #endif return INDIRECTION(RhpNewArray); case RuntimeHelperKind::CheckArrayElementType: return INDIRECTION(RhTypeCast_CheckVectorElemAddr); default: UNREACHABLE(); } } #undef DECLARE_INDIRECTION #undef INDIRECTION #ifdef FEATURE_CACHED_INTERFACE_DISPATCH EXTERN_C void * RhpInitialDynamicInterfaceDispatch; COOP_PINVOKE_HELPER(void *, RhNewInterfaceDispatchCell, (EEType * pInterface, Int32 slotNumber)) { InterfaceDispatchCell * pCell = new (nothrow) InterfaceDispatchCell[2]; if (pCell == NULL) return NULL; // Due to the synchronization mechanism used to update this indirection cell we must ensure the cell's alignment is twice that of a pointer. // Fortunately, Windows heap guarantees this aligment. ASSERT(IS_ALIGNED(pCell, 2 * POINTER_SIZE)); ASSERT(IS_ALIGNED(pInterface, (InterfaceDispatchCell::IDC_CachePointerMask + 1))); pCell[0].m_pStub = (UIntNative)&RhpInitialDynamicInterfaceDispatch; pCell[0].m_pCache = ((UIntNative)pInterface) | InterfaceDispatchCell::IDC_CachePointerIsInterfacePointer; pCell[1].m_pStub = 0; pCell[1].m_pCache = (UIntNative)slotNumber; return pCell; } #endif // FEATURE_CACHED_INTERFACE_DISPATCH COOP_PINVOKE_HELPER(PTR_UInt8, RhGetThreadLocalStorageForDynamicType, (UInt32 uOffset, UInt32 tlsStorageSize, UInt32 numTlsCells)) { Thread * pCurrentThread = ThreadStore::GetCurrentThread(); PTR_UInt8 pResult = pCurrentThread->GetThreadLocalStorageForDynamicType(uOffset); if (pResult != NULL || tlsStorageSize == 0 || numTlsCells == 0) return pResult; ASSERT(tlsStorageSize > 0 && numTlsCells > 0); return pCurrentThread->AllocateThreadLocalStorageForDynamicType(uOffset, tlsStorageSize, numTlsCells); } COOP_PINVOKE_HELPER(void *, RhGetNonGcStaticFieldData, (EEType * pEEType)) { // We shouldn't be attempting to get the gc/non-gc statics data for non-dynamic types... // For non-dynamic types, that info should have been hashed in a table and stored in its corresponding blob in the image. // The reason we don't want to do the lookup for non-dynamic types is that LookupGenericInstance will do the lookup in // a hashtable that *only* has the GIDs with variance. If we were to store all GIDs in that hashtable, we'd be violating // pay-for-play principles ASSERT(pEEType->IsDynamicType()); GenericInstanceDesc * pGid = GetRuntimeInstance()->LookupGenericInstance(pEEType); ASSERT(pGid != NULL); if (pGid->HasNonGcStaticFields()) { return dac_cast<DPTR(TgtPTR_UInt8)>(pGid + pGid->GetNonGcStaticFieldDataOffset()); } return NULL; } COOP_PINVOKE_HELPER(void *, RhGetGcStaticFieldData, (EEType * pEEType)) { // We shouldn't be attempting to get the gc/non-gc statics data for non-dynamic types... // For non-dynamic types, that info should have been hashed in a table and stored in its corresponding blob in the image. // The reason we don't want to do the lookup for non-dynamic types is that LookupGenericInstance will do the lookup in // a hashtable that *only* has the GIDs with variance. If we were to store all GIDs in that hashtable, we'd be violating // pay-for-play principles ASSERT(pEEType->IsDynamicType()); GenericInstanceDesc * pGid = GetRuntimeInstance()->LookupGenericInstance(pEEType); ASSERT(pGid != NULL); if (pGid->HasGcStaticFields()) { return dac_cast<DPTR(TgtPTR_UInt8)>(pGid + pGid->GetGcStaticFieldDataOffset()); } return NULL; } COOP_PINVOKE_HELPER(void *, RhAllocateThunksFromTemplate, (PTR_UInt8 moduleBase, UInt32 templateRva, UInt32 templateSize)) { void* pThunkMap = NULL; if (PalAllocateThunksFromTemplate((HANDLE)moduleBase, templateRva, templateSize, &pThunkMap) == FALSE) return NULL; return pThunkMap; } #endif
33.631884
151
0.652676
OceanYan
4f60bffbea5a49d327875527f745a419e50b9cd6
4,972
cc
C++
aku/Lattice.cc
phsmit/AaltoASR
33cb58b288cc01bcdff0d6709a296d0dfcc7f74a
[ "BSD-3-Clause" ]
null
null
null
aku/Lattice.cc
phsmit/AaltoASR
33cb58b288cc01bcdff0d6709a296d0dfcc7f74a
[ "BSD-3-Clause" ]
null
null
null
aku/Lattice.cc
phsmit/AaltoASR
33cb58b288cc01bcdff0d6709a296d0dfcc7f74a
[ "BSD-3-Clause" ]
null
null
null
#include "Lattice.hh" Lattice::Lattice() { resize(0, 0, 0); } void Lattice::reset() { for (int f = 0; f < m_frames; f++) { if (m_ranges[f].unused()) break; reset_frame(f); } } void Lattice::resize(int frames, int positions, int block_size) { m_cells.resize(frames); m_ranges.resize(frames); m_blocks.resize(frames); m_block_size = block_size; for (int i = 0; i < frames; i++) { m_cells[i].resize(m_block_size); m_blocks[i].size = m_cells[i].size(); } m_frames = frames; m_positions = positions; } // NOTES: // - all frames after an unused frame must be unused // - cells in unused frames should have cell.from = -1 // - removes the paths which do not go through the given (frame,position) void Lattice::move(int frame, int position) { assert(position >= 0); // REMOVE assert(frame > 0); // REMOVE // Clear ranges before frame for (int f = 0; f < frame; f++) { Range &range = m_ranges[f]; // All frames after an unused range are unused if (range.unused()) return; reset_frame(f); } // Move active part of the lattice and ranges for (int source_f = frame; source_f < m_frames; source_f++) { int target_f = source_f - frame; Range &source_range = m_ranges[source_f]; // All ranges after an unused range are unused if (source_range.unused()) { return; } // Lets swap the frames swap(source_f, target_f); Range &target_range = m_ranges[target_f]; Block &target_block = m_blocks[target_f]; // Clear the bottom source part which falls out of border if (target_range.start < position) reset_frame(target_f, position, target_range.end); // Update from -pointers // At left we keep from -pointers -1 // and at bottom 0 for (int i = target_range.start; i < target_range.end; i++) { at(target_f,i).from -= position; if (target_f == 0) at(target_f,i).from = -1; else if (i - position == 0) at(target_f,i).from = 0; } // Update ranges // FIXME: this way block.min can be below zero..is this a problem? target_range.start -= position; target_range.end -= position; target_block.min -= position; target_block.max -=position; } } void Lattice::check_active() { // Checks if active area is consistent for (int f = 0; f < m_frames; f++) { Range &range = m_ranges[f]; if (range.unused()) continue; for (int p = range.start; p < range.end; p++) { Cell &cell = at(f, p); // Check pointer if (f == 0) { if (cell.from >= 0) assert(false); } else { if (cell.from < 0) assert(false); Range &prev_range = m_ranges[f - 1]; if (cell.from < prev_range.start || cell.from >= prev_range.end) assert(false); } } } } void Lattice::check_empty(int frame) { // Checks if cells after (and including) frame are cleared // properly. for (int f = frame; f < m_frames; f++) { if (range(f).start >= 0 || range(f).end >= 0) assert(false); } } /// On Implementation: no vector is ever resized; /// a new one is instead created in order to keep /// each frame completely in one memory page (?) /// resize-method was tested and seemed to be much slower void Lattice::add_block(int frame) { assert(frame >= 0 && frame < m_frames); Block &block = m_blocks[frame]; // Initialize new vector int old_size = block.size; int old_min = block.min; int old_max = block.max; int new_size = old_size + m_block_size; std::vector<Cell> new_cells; new_cells.resize(new_size); // Raise the upper limit block.max += m_block_size; // Copy old contents to the new vector if (old_min != -1) for (int i = old_min; i < old_max; i++) new_cells[i - block.min] = at(frame, i); // Swap old <-> new m_cells[frame].swap(new_cells); block.size += m_block_size; } Lattice::Block& Lattice::block(int frame) { return m_blocks[frame]; } void Lattice::frame_stats(int frame) { std::cout << std::endl << "statistics for frame " << frame << std::endl << "range: " << m_ranges[frame].start << " - " << m_ranges[frame].end << ", block: " << m_blocks[frame].min << " - " << m_blocks[frame].max << ", size: " << m_blocks[frame].size << ", actual: " << m_cells[frame].size() << std::endl; } void Lattice::stats() { std::cout << std::endl << "statistics for the whole lattice" << std::endl << "m_frames = " << m_frames << " actual = " << m_cells.size() << std::endl << "m_positions = " << m_positions << std::endl << "m_block_size = " << m_block_size << std::endl; } void Lattice::swap(int frame_1, int frame_2) { Range temp_range = m_ranges[frame_1]; Block temp_block = m_blocks[frame_1]; m_cells[frame_1].swap(m_cells[frame_2]); m_ranges[frame_1] = m_ranges[frame_2]; m_blocks[frame_1] = m_blocks[frame_2]; m_ranges[frame_2] = temp_range; m_blocks[frame_2] = temp_block; }
23.67619
80
0.617056
phsmit
4f6142310a48ea745dfa45240e0435f07882e0c3
2,588
hh
C++
server/core/internal/admin.hh
mariadb-ThienLy/MaxScale
0ba6fb79b930ba90c544594e3580fc46054f6666
[ "MIT" ]
null
null
null
server/core/internal/admin.hh
mariadb-ThienLy/MaxScale
0ba6fb79b930ba90c544594e3580fc46054f6666
[ "MIT" ]
null
null
null
server/core/internal/admin.hh
mariadb-ThienLy/MaxScale
0ba6fb79b930ba90c544594e3580fc46054f6666
[ "MIT" ]
null
null
null
/* * Copyright (c) 2018 MariaDB Corporation Ab * * Use of this software is governed by the Business Source License included * in the LICENSE.TXT file and at www.mariadb.com/bsl11. * * Change Date: 2026-01-04 * * On the date above, in accordance with the Business Source License, use * of this software will be governed by version 2 or later of the General * Public License. */ #pragma once #include <maxscale/ccdefs.hh> #include <string> #include <microhttpd.h> class Client { Client(const Client&); Client& operator=(const Client&); public: enum state { OK, FAILED, INIT, CLOSED }; /** * @brief Create a new client * * @param connection The connection handle for this client */ Client(MHD_Connection* connection) : m_connection(connection) , m_state(INIT) { } ~Client() { } /** * @brief Process a client request * * This function can be called multiple times if a PUT/POST/PATCH * uploads a large amount of data. * * @param url Requested URL * @param method Request method * @param data Pointer to request data * @param size Size of request data * * @return MHD_YES on success, MHD_NO on error */ int process(std::string url, std::string method, const char* data, size_t* size); /** * @brief Authenticate the client * * @param connection The MHD connection object * @param url Requested URL * @param method The request method * * @return True if authentication was successful */ bool auth(MHD_Connection* connection, const char* url, const char* method); /** * Get client state * * @return The client state */ state get_state() const { return m_state; } /** * Close the client connection * * All further requests will be rejected immediately */ void close() { m_state = CLOSED; } private: MHD_Connection* m_connection; /**< Connection handle */ std::string m_data; /**< Uploaded data */ state m_state; /**< Client state */ }; /** * @brief Start the administrative interface * * @return True if the interface was successfully started */ bool mxs_admin_init(); /** * @brief Shutdown the administrative interface */ void mxs_admin_shutdown(); /** * @brief Check if admin interface uses HTTPS protocol * * @return True if HTTPS is enabled */ bool mxs_admin_https_enabled();
21.566667
85
0.612056
mariadb-ThienLy
4f6156a2f90a788b6d0b20117d25ab155a13d878
4,994
cpp
C++
independent_cng/src/spl_sqrt.cpp
zhang-ray/audio-processing-module
3e779965e1316dbc07c1bd5c547646de8c4350bb
[ "BSD-3-Clause" ]
25
2018-10-11T10:43:52.000Z
2021-11-28T12:43:40.000Z
independent_cng/src/spl_sqrt.cpp
zhang-ray/audio-processing-module
3e779965e1316dbc07c1bd5c547646de8c4350bb
[ "BSD-3-Clause" ]
1
2018-08-25T14:55:07.000Z
2018-08-25T14:55:07.000Z
independent_cng/src/spl_sqrt.cpp
zhang-ray/audio-processing-module
3e779965e1316dbc07c1bd5c547646de8c4350bb
[ "BSD-3-Clause" ]
7
2018-08-20T11:32:14.000Z
2021-11-10T07:07:42.000Z
/* * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ /* * This file contains the function WebRtcSpl_Sqrt(). * The description header can be found in signal_processing_library.h * */ #include "signal_processing_library.hpp" #include <assert.h> int32_t WebRtcSpl_SqrtLocal(int32_t in); int32_t WebRtcSpl_SqrtLocal(int32_t in) { int16_t x_half, t16; int32_t A, B, x2; /* The following block performs: y=in/2 x=y-2^30 x_half=x/2^31 t = 1 + (x_half) - 0.5*((x_half)^2) + 0.5*((x_half)^3) - 0.625*((x_half)^4) + 0.875*((x_half)^5) */ B = in / 2; B = B - ((int32_t)0x40000000); // B = in/2 - 1/2 x_half = (int16_t)(B >> 16); // x_half = x/2 = (in-1)/2 B = B + ((int32_t)0x40000000); // B = 1 + x/2 B = B + ((int32_t)0x40000000); // Add 0.5 twice (since 1.0 does not exist in Q31) x2 = ((int32_t)x_half) * ((int32_t)x_half) * 2; // A = (x/2)^2 A = -x2; // A = -(x/2)^2 B = B + (A >> 1); // B = 1 + x/2 - 0.5*(x/2)^2 A >>= 16; A = A * A * 2; // A = (x/2)^4 t16 = (int16_t)(A >> 16); B += -20480 * t16 * 2; // B = B - 0.625*A // After this, B = 1 + x/2 - 0.5*(x/2)^2 - 0.625*(x/2)^4 A = x_half * t16 * 2; // A = (x/2)^5 t16 = (int16_t)(A >> 16); B += 28672 * t16 * 2; // B = B + 0.875*A // After this, B = 1 + x/2 - 0.5*(x/2)^2 - 0.625*(x/2)^4 + 0.875*(x/2)^5 t16 = (int16_t)(x2 >> 16); A = x_half * t16 * 2; // A = x/2^3 B = B + (A >> 1); // B = B + 0.5*A // After this, B = 1 + x/2 - 0.5*(x/2)^2 + 0.5*(x/2)^3 - 0.625*(x/2)^4 + 0.875*(x/2)^5 B = B + ((int32_t)32768); // Round off bit return B; } int32_t WebRtcSpl_Sqrt(int32_t value) { /* Algorithm: Six term Taylor Series is used here to compute the square root of a number y^0.5 = (1+x)^0.5 where x = y-1 = 1+(x/2)-0.5*((x/2)^2+0.5*((x/2)^3-0.625*((x/2)^4+0.875*((x/2)^5) 0.5 <= x < 1 Example of how the algorithm works, with ut=sqrt(in), and with in=73632 and ut=271 (even shift value case): in=73632 y= in/131072 x=y-1 t = 1 + (x/2) - 0.5*((x/2)^2) + 0.5*((x/2)^3) - 0.625*((x/2)^4) + 0.875*((x/2)^5) ut=t*(1/sqrt(2))*512 or: in=73632 in2=73632*2^14 y= in2/2^31 x=y-1 t = 1 + (x/2) - 0.5*((x/2)^2) + 0.5*((x/2)^3) - 0.625*((x/2)^4) + 0.875*((x/2)^5) ut=t*(1/sqrt(2)) ut2=ut*2^9 which gives: in = 73632 in2 = 1206386688 y = 0.56176757812500 x = -0.43823242187500 t = 0.74973506527313 ut = 0.53014274874797 ut2 = 2.714330873589594e+002 or: in=73632 in2=73632*2^14 y=in2/2 x=y-2^30 x_half=x/2^31 t = 1 + (x_half) - 0.5*((x_half)^2) + 0.5*((x_half)^3) - 0.625*((x_half)^4) + 0.875*((x_half)^5) ut=t*(1/sqrt(2)) ut2=ut*2^9 which gives: in = 73632 in2 = 1206386688 y = 603193344 x = -470548480 x_half = -0.21911621093750 t = 0.74973506527313 ut = 0.53014274874797 ut2 = 2.714330873589594e+002 */ int16_t x_norm, nshift, t16, sh; int32_t A; int16_t k_sqrt_2 = 23170; // 1/sqrt2 (==5a82) A = value; // The convention in this function is to calculate sqrt(abs(A)). Negate the // input if it is negative. if (A < 0) { if (A == WEBRTC_SPL_WORD32_MIN) { // This number cannot be held in an int32_t after negating. // Map it to the maximum positive value. A = WEBRTC_SPL_WORD32_MAX; } else { A = -A; } } else if (A == 0) { return 0; // sqrt(0) = 0 } sh = WebRtcSpl_NormW32(A); // # shifts to normalize A A = WEBRTC_SPL_LSHIFT_W32(A, sh); // Normalize A if (A < (WEBRTC_SPL_WORD32_MAX - 32767)) { A = A + ((int32_t)32768); // Round off bit } else { A = WEBRTC_SPL_WORD32_MAX; } x_norm = (int16_t)(A >> 16); // x_norm = AH nshift = (sh / 2); assert(nshift >= 0); A = (int32_t)WEBRTC_SPL_LSHIFT_W32((int32_t)x_norm, 16); A = WEBRTC_SPL_ABS_W32(A); // A = abs(x_norm<<16) A = WebRtcSpl_SqrtLocal(A); // A = sqrt(A) if (2 * nshift == sh) { // Even shift value case t16 = (int16_t)(A >> 16); // t16 = AH A = k_sqrt_2 * t16 * 2; // A = 1/sqrt(2)*t16 A = A + ((int32_t)32768); // Round off A = A & ((int32_t)0x7fff0000); // Round off A >>= 15; // A = A>>16 } else { A >>= 16; // A = A>>16 } A = A & ((int32_t)0x0000ffff); A >>= nshift; // De-normalize the result. return A; }
25.479592
90
0.515819
zhang-ray
4f6255012e9a049ee51ccc1ee4608839014d214e
69,397
cxx
C++
TENDER/TenderSupplies/AliEMCALTenderSupply.cxx
aknospe/AliPhysics
bf2fb13800e25e98a1848ddc893301bb9da3828b
[ "BSD-3-Clause" ]
null
null
null
TENDER/TenderSupplies/AliEMCALTenderSupply.cxx
aknospe/AliPhysics
bf2fb13800e25e98a1848ddc893301bb9da3828b
[ "BSD-3-Clause" ]
null
null
null
TENDER/TenderSupplies/AliEMCALTenderSupply.cxx
aknospe/AliPhysics
bf2fb13800e25e98a1848ddc893301bb9da3828b
[ "BSD-3-Clause" ]
null
null
null
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ #include <TClonesArray.h> #include <TFile.h> #include <TGeoGlobalMagField.h> #include <TGeoManager.h> #include <TInterpreter.h> #include <TObjArray.h> #include <TROOT.h> #include <TTree.h> #include "AliAODEvent.h" #include "AliAODMCParticle.h" #include "AliAnalysisManager.h" #include "AliDataFile.h" #include "AliEMCALAfterBurnerUF.h" #include "AliEMCALClusterizer.h" #include "AliEMCALClusterizerNxN.h" #include "AliEMCALClusterizerv1.h" #include "AliEMCALClusterizerv2.h" #include "AliEMCALDigit.h" #include "AliEMCALGeometry.h" #include "AliEMCALRecParam.h" #include "AliEMCALRecParam.h" #include "AliEMCALRecPoint.h" #include "AliEMCALRecoUtils.h" #include "AliESDCaloCluster.h" #include "AliESDEvent.h" #include "AliLog.h" #include "AliMagF.h" #include "AliOADBContainer.h" #include "AliTender.h" #include "AliEMCALTenderSupply.h" ClassImp(AliEMCALTenderSupply) AliEMCALTenderSupply::AliEMCALTenderSupply() : AliTenderSupply() ,fTask(0) ,fRun(0) ,fEMCALGeo(0x0) ,fEMCALGeoName("") ,fEMCALRecoUtils(0) ,fConfigName("") ,fDebugLevel(0) ,fNonLinearFunc(-1) ,fNonLinearThreshold(-1) ,fReCalibCluster(kFALSE) ,fUpdateCell(kFALSE) ,fCalibrateEnergy(kFALSE) ,fCalibrateTime(kFALSE) ,fCalibrateTimeParamAvailable(kFALSE) ,fCalibrateTimeL1Phase(kFALSE) ,fDoNonLinearity(kFALSE) ,fBadCellRemove(kFALSE) ,fRejectExoticCells(kFALSE) ,fRejectExoticClusters(kFALSE) ,fClusterBadChannelCheck(kFALSE) ,fRecalClusPos(kFALSE) ,fFiducial(kFALSE) ,fNCellsFromEMCALBorder(-1) ,fRecalDistToBadChannels(kFALSE) ,fRecalShowerShape(kFALSE) ,fInputTree(0) ,fInputFile(0) ,fGetPassFromFileName(kTRUE) ,fFilepass(0) ,fMass(-1) ,fStep(-1) ,fCutEtaPhiSum(kTRUE) ,fCutEtaPhiSeparate(kFALSE) ,fRcut(-1) ,fEtacut(-1) ,fPhicut(-1) ,fBasePath("") ,fCustomBC("") ,fReClusterize(kFALSE) ,fClusterizer(0) ,fGeomMatrixSet(kFALSE) ,fLoadGeomMatrices(kFALSE) ,fRecParam(0x0) ,fDoTrackMatch(kFALSE) ,fDoUpdateOnly(kFALSE) ,fUnfolder(0) ,fDigitsArr(0) ,fClusterArr(0) ,fMisalignSurvey(kdefault) ,fExoticCellFraction(-1) ,fExoticCellDiffTime(-1) ,fExoticCellMinAmplitude(-1) ,fSetCellMCLabelFromCluster(0) ,fSetCellMCLabelFromEdepFrac(0) ,fTempClusterArr(0) ,fRemapMCLabelForAODs(0) ,fUseAutomaticRecalib(1) ,fUseAutomaticRunDepRecalib(1) ,fUseAutomaticTimeCalib(1) ,fUseAutomaticRecParam(1) { // Default constructor. for(Int_t i = 0; i < AliEMCALGeoParams::fgkEMCALModules; i++) fEMCALMatrix[i] = 0 ; for(Int_t j = 0; j < fgkTotalCellNumber; j++) { fOrgClusterCellId[j] =-1; fCellLabels[j] =-1 ; } } //_____________________________________________________ AliEMCALTenderSupply::AliEMCALTenderSupply(const char *name, const AliTender *tender) : AliTenderSupply(name,tender) ,fTask(0) ,fRun(0) ,fEMCALGeo(0x0) ,fEMCALGeoName("") ,fEMCALRecoUtils(0) ,fConfigName("") ,fDebugLevel(0) ,fNonLinearFunc(-1) ,fNonLinearThreshold(-1) ,fReCalibCluster(kFALSE) ,fUpdateCell(kFALSE) ,fCalibrateEnergy(kFALSE) ,fCalibrateTime(kFALSE) ,fCalibrateTimeParamAvailable(kFALSE) ,fCalibrateTimeL1Phase(kFALSE) ,fDoNonLinearity(kFALSE) ,fBadCellRemove(kFALSE) ,fRejectExoticCells(kFALSE) ,fRejectExoticClusters(kFALSE) ,fClusterBadChannelCheck(kFALSE) ,fRecalClusPos(kFALSE) ,fFiducial(kFALSE) ,fNCellsFromEMCALBorder(-1) ,fRecalDistToBadChannels(kFALSE) ,fRecalShowerShape(kFALSE) ,fInputTree(0) ,fInputFile(0) ,fGetPassFromFileName(kTRUE) ,fFilepass("") ,fMass(-1) ,fStep(-1) ,fCutEtaPhiSum(kTRUE) ,fCutEtaPhiSeparate(kFALSE) ,fRcut(-1) ,fEtacut(-1) ,fPhicut(-1) ,fBasePath("") ,fCustomBC("") ,fReClusterize(kFALSE) ,fClusterizer(0) ,fGeomMatrixSet(kFALSE) ,fLoadGeomMatrices(kFALSE) ,fRecParam(0x0) ,fDoTrackMatch(kFALSE) ,fDoUpdateOnly(kFALSE) ,fUnfolder(0) ,fDigitsArr(0) ,fClusterArr(0) ,fMisalignSurvey(kdefault) ,fExoticCellFraction(-1) ,fExoticCellDiffTime(-1) ,fExoticCellMinAmplitude(-1) ,fSetCellMCLabelFromCluster(0) ,fSetCellMCLabelFromEdepFrac(0) ,fTempClusterArr(0) ,fRemapMCLabelForAODs(0) ,fUseAutomaticRecalib(1) ,fUseAutomaticRunDepRecalib(1) ,fUseAutomaticTimeCalib(1) ,fUseAutomaticRecParam(1) { // Named constructor for(Int_t i = 0; i < AliEMCALGeoParams::fgkEMCALModules; i++) fEMCALMatrix[i] = 0 ; for(Int_t j = 0; j < fgkTotalCellNumber; j++) { fOrgClusterCellId[j] =-1; fCellLabels[j] =-1 ; } } //_____________________________________________________ AliEMCALTenderSupply::AliEMCALTenderSupply(const char *name, AliAnalysisTaskSE *task) : AliTenderSupply(name) ,fTask(task) ,fRun(0) ,fEMCALGeo(0x0) ,fEMCALGeoName("") ,fEMCALRecoUtils(0) ,fConfigName("") ,fDebugLevel(0) ,fNonLinearFunc(-1) ,fNonLinearThreshold(-1) ,fReCalibCluster(kFALSE) ,fUpdateCell(kFALSE) ,fCalibrateEnergy(kFALSE) ,fCalibrateTime(kFALSE) ,fCalibrateTimeParamAvailable(kFALSE) ,fCalibrateTimeL1Phase(kFALSE) ,fDoNonLinearity(kFALSE) ,fBadCellRemove(kFALSE) ,fRejectExoticCells(kFALSE) ,fRejectExoticClusters(kFALSE) ,fClusterBadChannelCheck(kFALSE) ,fRecalClusPos(kFALSE) ,fFiducial(kFALSE) ,fNCellsFromEMCALBorder(-1) ,fRecalDistToBadChannels(kFALSE) ,fRecalShowerShape(kFALSE) ,fInputTree(0) ,fInputFile(0) ,fGetPassFromFileName(kTRUE) ,fFilepass("") ,fMass(-1) ,fStep(-1) ,fCutEtaPhiSum(kTRUE) ,fCutEtaPhiSeparate(kFALSE) ,fRcut(-1) ,fEtacut(-1) ,fPhicut(-1) ,fBasePath("") ,fCustomBC("") ,fReClusterize(kFALSE) ,fClusterizer(0) ,fGeomMatrixSet(kFALSE) ,fLoadGeomMatrices(kFALSE) ,fRecParam(0x0) ,fDoTrackMatch(kFALSE) ,fDoUpdateOnly(kFALSE) ,fUnfolder(0) ,fDigitsArr(0) ,fClusterArr(0) ,fMisalignSurvey(kdefault) ,fExoticCellFraction(-1) ,fExoticCellDiffTime(-1) ,fExoticCellMinAmplitude(-1) ,fSetCellMCLabelFromCluster(0) ,fSetCellMCLabelFromEdepFrac(0) ,fTempClusterArr(0) ,fRemapMCLabelForAODs(0) ,fUseAutomaticRecalib(1) ,fUseAutomaticRunDepRecalib(1) ,fUseAutomaticTimeCalib(1) ,fUseAutomaticRecParam(1) { // Named constructor. for(Int_t i = 0; i < AliEMCALGeoParams::fgkEMCALModules; i++) fEMCALMatrix[i] = 0 ; for(Int_t j = 0; j < fgkTotalCellNumber; j++) { fOrgClusterCellId[j] =-1; fCellLabels[j] =-1 ; } } //_____________________________________________________ AliEMCALTenderSupply::~AliEMCALTenderSupply() { //Destructor if (!AliAnalysisManager::GetAnalysisManager()) return; if (!AliAnalysisManager::GetAnalysisManager()->IsProofMode()) { delete fEMCALRecoUtils; delete fRecParam; delete fUnfolder; if (!fClusterizer) { if (fDigitsArr) { fDigitsArr->Clear("C"); delete fDigitsArr; } } else { delete fClusterizer; fDigitsArr = 0; } } } //_____________________________________________________ void AliEMCALTenderSupply::SetDefaults() { // Set default settings. SwitchOnReclustering(); SwitchOnTrackMatch(); } //_____________________________________________________ Bool_t AliEMCALTenderSupply::RunChanged() const { // Get run number. return (fTender && fTender->RunChanged()) || (fTask && fRun != fTask->InputEvent()->GetRunNumber()); } //_____________________________________________________ void AliEMCALTenderSupply::Init() { // Initialise EMCAL tender. if (fDebugLevel>0) { AliWarning("Init EMCAL Tender supply"); AliWarning("======================================================================================"); AliWarning("--------------------------------------------------------------------------------------"); AliWarning("============ The EMCal Tender is no longer supported for development! =============="); AliWarning("========= It is recommended to use the new EMCal Correction Framework! ============="); AliWarning("=== See http://alidoc.cern.ch/AliPhysics/master/_r_e_a_d_m_eemc_corrections.html ==="); AliWarning("--------------------------------------------------------------------------------------"); AliWarning("======================================================================================"); } if (fConfigName.Length()>0 && gROOT->LoadMacro(fConfigName) >=0) { AliDebug(1, Form("Loading settings from macro %s", fConfigName.Data())); AliEMCALTenderSupply *tender = (AliEMCALTenderSupply*)gInterpreter->ProcessLine("ConfigEMCALTenderSupply()"); fDebugLevel = tender->fDebugLevel; fEMCALGeoName = tender->fEMCALGeoName; fEMCALRecoUtils = tender->fEMCALRecoUtils; fConfigName = tender->fConfigName; fNonLinearFunc = tender->fNonLinearFunc; fNonLinearThreshold = tender->fNonLinearThreshold; fReCalibCluster = tender->fReCalibCluster; fUpdateCell = tender->fUpdateCell; fRecalClusPos = tender->fRecalClusPos; fCalibrateEnergy = tender->fCalibrateEnergy; fCalibrateTime = tender->fCalibrateTime; fCalibrateTimeParamAvailable = tender->fCalibrateTimeParamAvailable; fCalibrateTimeL1Phase = tender->fCalibrateTimeL1Phase; fFiducial = tender->fFiducial; fNCellsFromEMCALBorder = tender->fNCellsFromEMCALBorder; fRecalDistToBadChannels = tender->fRecalDistToBadChannels; fRecalShowerShape = tender->fRecalShowerShape; fClusterBadChannelCheck = tender->fClusterBadChannelCheck; fBadCellRemove = tender->fBadCellRemove; fRejectExoticCells = tender->fRejectExoticCells; fRejectExoticClusters = tender->fRejectExoticClusters; fMass = tender->fMass; fStep = tender->fStep; fCutEtaPhiSum = tender->fCutEtaPhiSum; fCutEtaPhiSeparate = tender->fCutEtaPhiSeparate; fRcut = tender->fRcut; fEtacut = tender->fEtacut; fPhicut = tender->fPhicut; fReClusterize = tender->fReClusterize; fLoadGeomMatrices = tender->fLoadGeomMatrices; fRecParam = tender->fRecParam; fDoNonLinearity = tender->fDoNonLinearity; fDoTrackMatch = tender->fDoTrackMatch; fDoUpdateOnly = tender->fDoUpdateOnly; fMisalignSurvey = tender->fMisalignSurvey; fExoticCellFraction = tender->fExoticCellFraction; fExoticCellDiffTime = tender->fExoticCellDiffTime; fExoticCellMinAmplitude = tender->fExoticCellMinAmplitude; for(Int_t i = 0; i < AliEMCALGeoParams::fgkEMCALModules; i++) fEMCALMatrix[i] = tender->fEMCALMatrix[i] ; } if (fDebugLevel>0){ AliInfo("Emcal Tender settings:"); AliInfo("------------ Switches --------------------------"); AliInfo(Form("BadCellRemove : %d", fBadCellRemove)); AliInfo(Form("ExoticCellRemove : %d", fRejectExoticCells)); AliInfo(Form("CalibrateEnergy : %d", fCalibrateEnergy)); AliInfo(Form("CalibrateTime : %d", fCalibrateTime)); AliInfo(Form("CalibrateTimeL1Phase : %d", fCalibrateTimeL1Phase)); AliInfo(Form("UpdateCell : %d", fUpdateCell)); AliInfo(Form("DoUpdateOnly : %d", fDoUpdateOnly)); AliInfo(Form("Reclustering : %d", fReClusterize)); AliInfo(Form("ClusterBadChannelCheck : %d", fClusterBadChannelCheck)); AliInfo(Form("ClusterExoticChannelCheck : %d", fRejectExoticClusters)); AliInfo(Form("CellFiducialRegion : %d", fFiducial)); AliInfo(Form("ReCalibrateCluster : %d", fReCalibCluster)); AliInfo(Form("RecalculateClusPos : %d", fRecalClusPos)); AliInfo(Form("RecalShowerShape : %d", fRecalShowerShape)); AliInfo(Form("NonLinearityCorrection : %d", fDoNonLinearity)); AliInfo(Form("RecalDistBadChannel : %d", fRecalDistToBadChannels)); AliInfo(Form("TrackMatch : %d", fDoTrackMatch)); AliInfo("------------ Variables -------------------------"); AliInfo(Form("DebugLevel : %d", fDebugLevel)); AliInfo(Form("BasePath : %s", fBasePath.Data())); AliInfo(Form("CustomBCFile : %s", fCustomBC.Data())); AliInfo(Form("ConfigFileName : %s", fConfigName.Data())); AliInfo(Form("EMCALGeometryName : %s", fEMCALGeoName.Data())); AliInfo(Form("NonLinearityFunction : %d", fNonLinearFunc)); AliInfo(Form("NonLinearityThreshold : %d", fNonLinearThreshold)); AliInfo(Form("MisalignmentMatrixSurvey : %d", fMisalignSurvey)); AliInfo(Form("NumberOfCellsFromEMCALBorder : %d", fNCellsFromEMCALBorder)); AliInfo(Form("RCut : %f", fRcut)); AliInfo(Form("Mass : %f", fMass)); AliInfo(Form("Step : %f", fStep)); AliInfo(Form("EtaCut : %f", fEtacut)); AliInfo(Form("PhiCut : %f", fPhicut)); AliInfo(Form("ExoticCellFraction : %f", fExoticCellFraction)); AliInfo(Form("ExoticCellDiffTime : %f", fExoticCellDiffTime)); AliInfo(Form("ExoticCellMinAmplitude : %f", fExoticCellMinAmplitude)); AliInfo("============================================================="); } // init reco utils if (!fEMCALRecoUtils) fEMCALRecoUtils = new AliEMCALRecoUtils; // init geometry if requested if (fEMCALGeoName.Length()>0) fEMCALGeo = AliEMCALGeometry::GetInstance(fEMCALGeoName) ; // digits array fDigitsArr = new TClonesArray("AliEMCALDigit",1000); // initialising non-linearity parameters if (fNonLinearThreshold != -1) fEMCALRecoUtils->SetNonLinearityThreshold(fNonLinearThreshold); if (fNonLinearFunc != -1) fEMCALRecoUtils->SetNonLinearityFunction(fNonLinearFunc); // missalignment function fEMCALRecoUtils->SetPositionAlgorithm(AliEMCALRecoUtils::kPosTowerGlobal); // fiducial cut // do not do the eta0 fiducial cut if (fNCellsFromEMCALBorder != -1) fEMCALRecoUtils->SetNumberOfCellsFromEMCALBorder(fNCellsFromEMCALBorder); fEMCALRecoUtils->SwitchOnNoFiducialBorderInEMCALEta0(); // exotic cell rejection if (fExoticCellFraction != -1) fEMCALRecoUtils->SetExoticCellFractionCut(fExoticCellFraction); if (fExoticCellDiffTime != -1) fEMCALRecoUtils->SetExoticCellDiffTimeCut(fExoticCellDiffTime); if (fExoticCellMinAmplitude != -1) fEMCALRecoUtils->SetExoticCellMinAmplitudeCut(fExoticCellMinAmplitude); // setting track matching parameters ... mass, step size and residual cut if (fMass != -1) fEMCALRecoUtils->SetMass(fMass); if (fStep != -1) fEMCALRecoUtils->SetStep(fStep); // spatial cut based on separate eta/phi or common processing if (fCutEtaPhiSum) { fEMCALRecoUtils->SwitchOnCutEtaPhiSum(); if (fRcut != -1) fEMCALRecoUtils->SetCutR(fRcut); } else if (fCutEtaPhiSeparate) { fEMCALRecoUtils->SwitchOnCutEtaPhiSeparate(); if (fEtacut != -1) fEMCALRecoUtils->SetCutEta(fEtacut); if (fPhicut != -1) fEMCALRecoUtils->SetCutPhi(fPhicut); } } //_____________________________________________________ AliVEvent* AliEMCALTenderSupply::GetEvent() { // Return the event pointer. if (fTender) { return fTender->GetEvent(); } else if (fTask) { return fTask->InputEvent(); } return 0; } //_____________________________________________________ AliMCEvent* AliEMCALTenderSupply::GetMCEvent() { // Return the event pointer. if (fTender) { return fTender->MCEvent(); } else if (fTask) { return fTask->MCEvent(); } return 0; } //_____________________________________________________ void AliEMCALTenderSupply::ProcessEvent() { // Event loop. AliVEvent *event = GetEvent(); if (!event) { AliError("Event ptr = 0, returning"); return; } // Initialising parameters once per run number if (RunChanged()) { fRun = event->GetRunNumber(); AliWarning(Form("Run changed, initializing parameters for %d", fRun)); if (dynamic_cast<AliAODEvent*>(event)) { AliWarning("============================================================="); AliWarning("=== Running on AOD is not equivalent to running on ESD! ==="); AliWarning("============================================================="); } // init geometry if not already done if (fEMCALGeoName.Length()==0) { fEMCALGeo = AliEMCALGeometry::GetInstanceFromRunNumber(fRun); if (!fEMCALGeo) { AliFatal(Form("Can not create geometry: %s", fEMCALGeoName.Data())); return; } } // get pass if (fGetPassFromFileName) GetPass(); // define what recalib parameters are needed for various switches // this is based on implementation in AliEMCALRecoUtils Bool_t needRecoParam = fReClusterize; Bool_t needBadChannels = fBadCellRemove | fClusterBadChannelCheck | fRecalDistToBadChannels | fReClusterize; Bool_t needRecalib = fCalibrateEnergy | fReClusterize; Bool_t needTimecalib = fCalibrateTime | fReClusterize; Bool_t needMisalign = fRecalClusPos | fReClusterize; Bool_t needClusterizer = fReClusterize; if ( fRun > 209121 && fCalibrateTime ) fCalibrateTimeL1Phase = kTRUE; Bool_t needTimecalibL1Phase = (fCalibrateTime | fReClusterize) & fCalibrateTimeL1Phase; // init bad channels if (needBadChannels) { Int_t fInitBC = InitBadChannels(); if (fInitBC==0) AliError("InitBadChannels returned false, returning"); if (fInitBC==1) AliWarning("InitBadChannels OK"); if (fInitBC>1) AliWarning(Form("No external hot channel set: %d - %s", event->GetRunNumber(), fFilepass.Data())); } // init recalibration factors if (needRecalib) { if(fUseAutomaticRecalib) { Int_t fInitRecalib = InitRecalib(); if (fInitRecalib==0) AliError("InitRecalib returned false, returning"); if (fInitRecalib==1) AliWarning("InitRecalib OK"); if (fInitRecalib>1) AliWarning(Form("No recalibration available: %d - %s", event->GetRunNumber(), fFilepass.Data())); } if(fUseAutomaticRunDepRecalib) { Int_t fInitRunDepRecalib = InitRunDepRecalib(); if (fInitRunDepRecalib==0) AliError("InitrunDepRecalib returned false, returning"); if (fInitRunDepRecalib==1) AliWarning("InitRecalib OK"); if (fInitRunDepRecalib>1) AliWarning(Form("No Temperature recalibration available: %d - %s", event->GetRunNumber(), fFilepass.Data())); } } // init time calibration if (needTimecalib && fUseAutomaticTimeCalib) { Int_t initTC = InitTimeCalibration(); if (!initTC) AliError("InitTimeCalibration returned false, returning"); if (initTC==1) { fCalibrateTimeParamAvailable = kTRUE; AliWarning("InitTimeCalib OK"); } if (initTC > 1) AliWarning(Form("No external time calibration available: %d - %s", event->GetRunNumber(), fFilepass.Data())); } // init time calibration with L1 phase if (needTimecalibL1Phase && fUseAutomaticTimeCalib) { Int_t initTCL1Phase = InitTimeCalibrationL1Phase(); if (!initTCL1Phase) AliError("InitTimeCalibrationL1Phase returned false, returning"); if (initTCL1Phase==1) { fCalibrateTimeParamAvailable = kTRUE; AliWarning("InitTimeCalibL1Phase OK"); } if (initTCL1Phase > 1) AliWarning(Form("No external time calibration L1 phase available: %d - %s", event->GetRunNumber(), fFilepass.Data())); } // init misalignment matrix if (needMisalign) { if (!InitMisalignMatrix()) AliError("InitMisalignmentMatrix returned false, returning"); else AliWarning("InitMisalignMatrix OK"); } // initiate reco params with some defaults // will not overwrite, if those have been provided by user if (needRecoParam && fUseAutomaticRecParam) { Int_t initRC = InitRecParam(); if (initRC == 0) AliInfo("Defaults reco params loaded."); if (initRC > 1) AliWarning("User defined reco params."); } // init clusterizer if (needClusterizer) { if (!InitClusterization()) AliError("InitClusterization returned false, returning"); else AliWarning("InitClusterization OK"); } if (fDebugLevel>1) fEMCALRecoUtils->Print(""); } // disable implied switches ------------------------------------------------- // AliEMCALRecoUtils or clusterizer functions alredy include some // recalibration so based on those implied callibration te switches // here are disabled to avoid duplication // clusterizer does cluster energy recalibration, position recomputation // and shower shape if (fReClusterize) { fReCalibCluster = kFALSE; fRecalClusPos = kFALSE; fRecalShowerShape = kFALSE; } // CONFIGURE THE RECO UTILS ------------------------------------------------- // configure the reco utils // this option does energy recalibration if (fCalibrateEnergy) fEMCALRecoUtils->SwitchOnRecalibration(); else fEMCALRecoUtils->SwitchOffRecalibration(); // allows time calibration if (fCalibrateTime) fEMCALRecoUtils->SwitchOnTimeRecalibration(); else fEMCALRecoUtils->SwitchOffTimeRecalibration(); // allows time calibration with L1 phase if (fCalibrateTimeL1Phase) fEMCALRecoUtils->SwitchOnL1PhaseInTimeRecalibration(); else fEMCALRecoUtils->SwitchOffL1PhaseInTimeRecalibration(); // allows to zero bad cells if (fBadCellRemove) fEMCALRecoUtils->SwitchOnBadChannelsRemoval(); else fEMCALRecoUtils->SwitchOffBadChannelsRemoval(); // distance to bad channel recalibration if (fRecalDistToBadChannels) fEMCALRecoUtils->SwitchOnDistToBadChannelRecalculation(); else fEMCALRecoUtils->SwitchOffDistToBadChannelRecalculation(); // exclude exotic cells if (fRejectExoticCells) fEMCALRecoUtils->SwitchOnRejectExoticCell(); else fEMCALRecoUtils->SwitchOffRejectExoticCell(); // exclude clusters with exotic cells if (fRejectExoticClusters) fEMCALRecoUtils->SwitchOnRejectExoticCluster(); else fEMCALRecoUtils->SwitchOffRejectExoticCluster(); // TODO: not implemented switches // SwitchOnClusterEnergySmearing // SwitchOnRunDepCorrection // START PROCESSING --------------------------------------------------------- // Test if cells present AliVCaloCells *cells= event->GetEMCALCells(); if (cells->GetNumberOfCells()<=0) { if (fDebugLevel>1) AliWarning(Form("Number of EMCAL cells = %d, returning", cells->GetNumberOfCells())); return; } if (fDebugLevel>2) AliInfo(Form("Re-calibrate cluster %d\n",fReCalibCluster)); // mark the cells not recalibrated in case of selected // time, energy recalibration or bad channel removal if (fCalibrateEnergy || fCalibrateTime || fBadCellRemove || fCalibrateTimeL1Phase) fEMCALRecoUtils->ResetCellsCalibrated(); // CELL RECALIBRATION ------------------------------------------------------- // cell objects will be updated // the cell calibrations are also processed locally any time those are needed // in case that the cell objects are not to be updated here for later use if (fUpdateCell) { // do the update // includes exotic cell check in the UpdateCells function - is not provided // by the reco utils UpdateCells(); // switch off recalibrations so those are not done multiple times // this is just for safety, the recalibrated flag of cell object // should not allow for farther processing anyways fEMCALRecoUtils->SwitchOffRecalibration(); fEMCALRecoUtils->SwitchOffTimeRecalibration(); fEMCALRecoUtils->SwitchOffL1PhaseInTimeRecalibration(); if (fDoUpdateOnly) return; } // RECLUSTERIZATION --------------------------------------------------------- if (fReClusterize) { FillDigitsArray(); Clusterize(); UpdateClusters(); } // Store good clusters TClonesArray *clusArr = dynamic_cast<TClonesArray*>(event->FindListObject("caloClusters")); if (!clusArr) clusArr = dynamic_cast<TClonesArray*>(event->FindListObject("CaloClusters")); if (!clusArr) { AliWarning(Form("No cluster array, number of cells in event = %d, returning", cells->GetNumberOfCells())); return; } // PROCESS SINGLE CLUSTER RECALIBRATION ------------------------------------- // now go through clusters one by one and process separate correction // as those were defined or not Int_t nclusters = clusArr->GetEntriesFast(); for (Int_t icluster=0; icluster < nclusters; ++icluster) { AliVCluster *clust = static_cast<AliVCluster*>(clusArr->At(icluster)); if (!clust) continue; if (!clust->IsEMCAL()) continue; // REMOVE CLUSTERS WITH BAD CELLS ----------------------------- if (fClusterBadChannelCheck) { // careful, the the ClusterContainsBadChannel is dependent on // SwitchOnBadChannelsRemoval, switching it ON automatically // and returning to original value after processing Bool_t badRemoval = fEMCALRecoUtils->IsBadChannelsRemovalSwitchedOn(); fEMCALRecoUtils->SwitchOnBadChannelsRemoval(); Bool_t badResult = fEMCALRecoUtils->ClusterContainsBadChannel(fEMCALGeo, clust->GetCellsAbsId(), clust->GetNCells()); // switch the bad channels removal back if (!badRemoval) fEMCALRecoUtils->SwitchOffBadChannelsRemoval(); if (badResult) { delete clusArr->RemoveAt(icluster); continue; //TODO is it really needed to remove it? Or should we flag it? } } // REMOVE EXOTIC CLUSTERS ------------------------------------- // does process local cell recalibration energy and time without replacing // the global cell values, in case of no cell recalib done yet if (fRejectExoticClusters) { // careful, the IsExoticCluster is dependent on // SwitchOnRejectExoticCell, switching it ON automatically // and returning to original value after processing Bool_t exRemoval = fEMCALRecoUtils->IsRejectExoticCell(); fEMCALRecoUtils->SwitchOnRejectExoticCell(); // get bunch crossing Int_t bunchCrossNo = event->GetBunchCrossNumber(); Bool_t exResult = fEMCALRecoUtils->IsExoticCluster(clust, cells, bunchCrossNo); // switch the exotic channels removal back if (!exRemoval) fEMCALRecoUtils->SwitchOffRejectExoticCell(); if (exResult) { delete clusArr->RemoveAt(icluster); continue; //TODO is it really needed to remove it? Or should we flag it? } } // FIDUCIAL CUT ----------------------------------------------- if (fFiducial) { // depends on SetNumberOfCellsFromEMCALBorder // SwitchOnNoFiducialBorderInEMCALEta0 if (!fEMCALRecoUtils->CheckCellFiducialRegion(fEMCALGeo, clust, cells)){ delete clusArr->RemoveAt(icluster); continue; //TODO it would be nice to store the distance } } // CLUSTER ENERGY --------------------------------------------- // does process local cell recalibration energy and time without replacing // the global cell values, in case of no cell recalib done yet if (fReCalibCluster) { fEMCALRecoUtils->RecalibrateClusterEnergy(fEMCALGeo, clust, cells); if (clust->E() < 1e-9) { delete clusArr->RemoveAt(icluster); continue; } } // CLUSTER POSITION ------------------------------------------- // does process local cell energy recalibration, if enabled and cells // not calibrated yet if (fRecalClusPos) fEMCALRecoUtils->RecalculateClusterPosition(fEMCALGeo, cells, clust); // SHOWER SHAPE ----------------------------------------------- if (fRecalShowerShape) fEMCALRecoUtils->RecalculateClusterShowerShapeParameters(fEMCALGeo, cells, clust); // NONLINEARITY ----------------------------------------------- if (fDoNonLinearity) { Float_t correctedEnergy = fEMCALRecoUtils->CorrectClusterEnergyLinearity(clust); clust->SetE(correctedEnergy); } // DISTANCE TO BAD CHANNELS ----------------------------------- if (fRecalDistToBadChannels) fEMCALRecoUtils->RecalculateClusterDistanceToBadChannel(fEMCALGeo, cells, clust); } clusArr->Compress(); if (!fDoTrackMatch) return; // TRACK MATCHING ----------------------------------------------------------- if (!TGeoGlobalMagField::Instance()->GetField()) { event->InitMagneticField(); } fEMCALRecoUtils->FindMatches(event,0x0,fEMCALGeo,GetMCEvent()); fEMCALRecoUtils->SetClusterMatchedToTrack(event); fEMCALRecoUtils->SetTracksMatchedToCluster(event); } //_____________________________________________________ Bool_t AliEMCALTenderSupply::InitMisalignMatrix() { // Initialising misalignment matrices AliVEvent *event = GetEvent(); if (!event) return kFALSE; if (fGeomMatrixSet) { AliInfo("Misalignment matrix already set"); return kTRUE; } if (fDebugLevel>0) AliInfo("Initialising misalignment matrix"); if (fLoadGeomMatrices) { for(Int_t mod=0; mod < fEMCALGeo->GetNumberOfSuperModules(); ++mod) { if (fEMCALMatrix[mod]) { if (fDebugLevel > 2) fEMCALMatrix[mod]->Print(); fEMCALGeo->SetMisalMatrix(fEMCALMatrix[mod],mod); } else if(gGeoManager) { AliWarning(Form("Set matrix for SM %d from gGeoManager\n",mod)); fEMCALGeo->SetMisalMatrix(fEMCALGeo->GetMatrixForSuperModuleFromGeoManager(mod),mod) ; } else { AliError(Form("EMCal geometry matrix for SM %d is not available!",mod)); } } fGeomMatrixSet = kTRUE; return kTRUE; } Int_t runGM = event->GetRunNumber(); TObjArray *mobj = 0; if (fMisalignSurvey == kdefault) { //take default alignment corresponding to run no AliOADBContainer emcalgeoCont(Form("emcal")); emcalgeoCont.InitFromFile(AliDataFile::GetFileNameOADB("EMCAL/EMCALlocal2master.root").data(),Form("AliEMCALgeo")); mobj=(TObjArray*)emcalgeoCont.GetObject(runGM,"EmcalMatrices"); } if (fMisalignSurvey == kSurveybyS) { //take alignment at sector level if (runGM <= 140000) { //2010 data AliOADBContainer emcalgeoCont(Form("emcal2010")); emcalgeoCont.InitFromFile(AliDataFile::GetFileNameOADB("EMCAL/EMCALlocal2master.root").data(),Form("AliEMCALgeo")); mobj=(TObjArray*)emcalgeoCont.GetObject(100,"survey10"); } else if (runGM>140000) { // 2011 LHC11a pass1 data AliOADBContainer emcalgeoCont(Form("emcal2011")); emcalgeoCont.InitFromFile(AliDataFile::GetFileNameOADB("EMCAL/EMCALlocal2master.root").data(),Form("AliEMCALgeo")); mobj=(TObjArray*)emcalgeoCont.GetObject(100,"survey11byS"); } } if (fMisalignSurvey == kSurveybyM) { //take alignment at module level if (runGM <= 140000) { //2010 data AliOADBContainer emcalgeoCont(Form("emcal2010")); emcalgeoCont.InitFromFile(AliDataFile::GetFileNameOADB("EMCAL/EMCALlocal2master.root").data(),Form("AliEMCALgeo")); mobj=(TObjArray*)emcalgeoCont.GetObject(100,"survey10"); } else if (runGM>140000) { // 2011 LHC11a pass1 data AliOADBContainer emcalgeoCont(Form("emcal2011")); emcalgeoCont.InitFromFile(AliDataFile::GetFileNameOADB("EMCAL/EMCALlocal2master.root").data(),Form("AliEMCALgeo")); mobj=(TObjArray*)emcalgeoCont.GetObject(100,"survey11byM"); } } if (!mobj) { AliFatal("Geometry matrix array not found"); return kFALSE; } for(Int_t mod=0; mod < (fEMCALGeo->GetEMCGeometry())->GetNumberOfSuperModules(); mod++) { fEMCALMatrix[mod] = (TGeoHMatrix*) mobj->At(mod); if ( fEMCALMatrix[mod] ) { if (fDebugLevel > 2) fEMCALMatrix[mod]->Print(); fEMCALGeo->SetMisalMatrix(fEMCALMatrix[mod],mod); } else { AliWarning(Form("EMCal geometry matrix for SM %d is not available!",mod)); } } return kTRUE; } //_____________________________________________________ Int_t AliEMCALTenderSupply::InitBadChannels() { // Initialising bad channel maps AliVEvent *event = GetEvent(); if (!event) return 0; if (fDebugLevel>0) AliInfo("Initialising Bad channel map"); // init default maps first if (!fEMCALRecoUtils->GetEMCALBadChannelStatusMapArray()) fEMCALRecoUtils->InitEMCALBadChannelStatusMap() ; Int_t runBC = event->GetRunNumber(); AliOADBContainer *contBC = new AliOADBContainer(""); if (fBasePath!="") { //if fBasePath specified in the ->SetBasePath() if (fDebugLevel>0) AliInfo(Form("Loading Bad Channels OADB from given path %s",fBasePath.Data())); TFile *fbad=new TFile(Form("%s/EMCALBadChannels.root",fBasePath.Data()),"read"); if (!fbad || fbad->IsZombie()) { AliFatal(Form("EMCALBadChannels.root was not found in the path provided: %s",fBasePath.Data())); return 0; } if (fbad) delete fbad; contBC->InitFromFile(Form("%s/EMCALBadChannels.root",fBasePath.Data()),"AliEMCALBadChannels"); } else if (fCustomBC!="") { //if fCustomBC specified in the ->SetCustomBC() if (fDebugLevel>0) AliInfo(Form("Loading Bad Channels OADB from given path %s",fCustomBC.Data())); TFile *fbad=new TFile(Form("%s",fCustomBC.Data()),"read"); if (!fbad || fbad->IsZombie()) { AliFatal(Form("Input file was not found in the path provided: %s",fCustomBC.Data())); return 0; } if (fbad) delete fbad; contBC->InitFromFile(Form("%s",fCustomBC.Data()),"AliEMCALBadChannels"); } else { // Else choose the one in the $ALICE_PHYSICS directory if (fDebugLevel>0) AliInfo("Loading Bad Channels OADB from /OADB/EMCAL"); TFile *fbad=new TFile(AliDataFile::GetFileNameOADB("EMCAL/EMCALBadChannels.root").data(),"read"); if (!fbad || fbad->IsZombie()) { AliFatal("OADB/EMCAL/EMCALBadChannels.root was not found"); return 0; } if (fbad) delete fbad; contBC->InitFromFile(AliDataFile::GetFileNameOADB("EMCAL/EMCALBadChannels.root").data(),"AliEMCALBadChannels"); } TObjArray *arrayBC=(TObjArray*)contBC->GetObject(runBC); if (!arrayBC) { AliError(Form("No external hot channel set for run number: %d", runBC)); delete contBC; return 2; } Int_t sms = fEMCALGeo->GetEMCGeometry()->GetNumberOfSuperModules(); for (Int_t i=0; i<sms; ++i) { TH2I *h = fEMCALRecoUtils->GetEMCALChannelStatusMap(i); if (h) delete h; h=(TH2I*)arrayBC->FindObject(Form("EMCALBadChannelMap_Mod%d",i)); if (!h) { AliError(Form("Can not get EMCALBadChannelMap_Mod%d",i)); continue; } h->SetDirectory(0); fEMCALRecoUtils->SetEMCALChannelStatusMap(i,h); } delete contBC; return 1; } //_____________________________________________________ Int_t AliEMCALTenderSupply::InitRecalib() { // Initialising recalibration factors. AliVEvent *event = GetEvent(); if (!event) return 0; if (fDebugLevel>0) AliInfo("Initialising recalibration factors"); // init default maps first if (!fEMCALRecoUtils->GetEMCALRecalibrationFactorsArray()) fEMCALRecoUtils->InitEMCALRecalibrationFactors() ; Int_t runRC = event->GetRunNumber(); AliOADBContainer *contRF=new AliOADBContainer(""); if (fBasePath!="") { //if fBasePath specified in the ->SetBasePath() if (fDebugLevel>0) AliInfo(Form("Loading Recalib OADB from given path %s",fBasePath.Data())); TFile *fRecalib= new TFile(Form("%s/EMCALRecalib.root",fBasePath.Data()),"read"); if (!fRecalib || fRecalib->IsZombie()) { AliFatal(Form("EMCALRecalib.root not found in %s",fBasePath.Data())); return 0; } if (fRecalib) delete fRecalib; contRF->InitFromFile(Form("%s/EMCALRecalib.root",fBasePath.Data()),"AliEMCALRecalib"); } else { // Else choose the one in the $ALICE_PHYSICS directory if (fDebugLevel>0) AliInfo("Loading Recalib OADB from OADB/EMCAL"); TFile *fRecalib= new TFile(AliDataFile::GetFileNameOADB("EMCAL/EMCALRecalib.root").data(),"read"); if (!fRecalib || fRecalib->IsZombie()) { AliFatal("OADB/EMCAL/EMCALRecalib.root was not found"); return 0; } if (fRecalib) delete fRecalib; contRF->InitFromFile(AliDataFile::GetFileNameOADB("EMCAL/EMCALRecalib.root").data(),"AliEMCALRecalib"); } TObjArray *recal=(TObjArray*)contRF->GetObject(runRC); if (!recal) { AliError(Form("No Objects for run: %d",runRC)); delete contRF; return 2; } TObjArray *recalpass=(TObjArray*)recal->FindObject(fFilepass); if (!recalpass) { AliError(Form("No Objects for run: %d - %s",runRC,fFilepass.Data())); delete contRF; return 2; } TObjArray *recalib=(TObjArray*)recalpass->FindObject("Recalib"); if (!recalib) { AliError(Form("No Recalib histos found for %d - %s",runRC,fFilepass.Data())); delete contRF; return 2; } if (fDebugLevel>0) recalib->Print(); Int_t sms = fEMCALGeo->GetEMCGeometry()->GetNumberOfSuperModules(); for (Int_t i=0; i<sms; ++i) { TH2F *h = fEMCALRecoUtils->GetEMCALChannelRecalibrationFactors(i); if (h) delete h; h = (TH2F*)recalib->FindObject(Form("EMCALRecalFactors_SM%d",i)); if (!h) { AliError(Form("Could not load EMCALRecalFactors_SM%d",i)); continue; } h->SetDirectory(0); fEMCALRecoUtils->SetEMCALChannelRecalibrationFactors(i,h); } delete contRF; return 1; } //_____________________________________________________ Int_t AliEMCALTenderSupply::InitRunDepRecalib() { // Initialising recalibration factors. AliVEvent *event = GetEvent(); if (!event) return 0; if (fDebugLevel>0) AliInfo("Initialising recalibration factors"); // init default maps first if (!fEMCALRecoUtils->GetEMCALRecalibrationFactorsArray()) fEMCALRecoUtils->InitEMCALRecalibrationFactors() ; Int_t runRC = event->GetRunNumber(); AliOADBContainer *contRF=new AliOADBContainer(""); if (fBasePath!="") { //if fBasePath specified in the ->SetBasePath() if (fDebugLevel>0) AliInfo(Form("Loading Recalib OADB from given path %s",fBasePath.Data())); TFile *fRunDepRecalib= new TFile(Form("%s/EMCALTemperatureCorrCalib.root",fBasePath.Data()),"read"); if (!fRunDepRecalib || fRunDepRecalib->IsZombie()) { AliFatal(Form("EMCALTemperatureCorrCalib.root not found in %s",fBasePath.Data())); return 0; } if (fRunDepRecalib) delete fRunDepRecalib; contRF->InitFromFile(Form("%s/EMCALTemperatureCorrCalib.root",fBasePath.Data()),"AliEMCALRunDepTempCalibCorrections"); } else { // Else choose the one in the $ALICE_PHYSICS directory if (fDebugLevel>0) AliInfo("Loading Recalib OADB from OADB/EMCAL"); TFile *fRunDepRecalib= new TFile(AliDataFile::GetFileNameOADB("EMCAL/EMCALTemperatureCorrCalib.root").data(),"read"); if (!fRunDepRecalib || fRunDepRecalib->IsZombie()) { AliFatal("OADB/EMCAL/EMCALTemperatureCorrCalib.root was not found"); return 0; } if (fRunDepRecalib) delete fRunDepRecalib; contRF->InitFromFile(AliDataFile::GetFileNameOADB("EMCAL/EMCALTemperatureCorrCalib.root").data(),"AliEMCALRunDepTempCalibCorrections"); } TH1S *rundeprecal=(TH1S*)contRF->GetObject(runRC); if (!rundeprecal) { AliWarning(Form("No TemperatureCorrCalib Objects for run: %d",runRC)); // let's get the closest runnumber instead then.. Int_t lower = 0; Int_t ic = 0; Int_t maxEntry = contRF->GetNumberOfEntries(); while ((ic < maxEntry) && (contRF->UpperLimit(ic) < runRC)) { lower = ic; ic++; } Int_t closest = lower; if ((ic<maxEntry) && (contRF->LowerLimit(ic)-runRC) < (runRC - contRF->UpperLimit(lower))) { closest = ic; } AliWarning(Form("TemperatureCorrCalib Objects found closest id %d from run: %d", closest, contRF->LowerLimit(closest))); rundeprecal = (TH1S*) contRF->GetObjectByIndex(closest); } Int_t nSM = fEMCALGeo->GetEMCGeometry()->GetNumberOfSuperModules(); Int_t nbins = rundeprecal->GetNbinsX(); // Avoid use of Run1 param for Run2 if(nSM > 12 && nbins < 12288) { AliError(Form("Total SM is %d but T corrections available for %d channels, skip Init of T recalibration factors",nSM,nbins)); delete contRF; return 2; } if (fDebugLevel>0) rundeprecal->Print(); for (Int_t ism=0; ism<nSM; ++ism) { for (Int_t icol=0; icol<48; ++icol) { for (Int_t irow=0; irow<24; ++irow) { Float_t factor = fEMCALRecoUtils->GetEMCALChannelRecalibrationFactor(ism,icol,irow); Int_t absID = fEMCALGeo->GetAbsCellIdFromCellIndexes(ism, irow, icol); // original calibration factor factor *= rundeprecal->GetBinContent(absID) / 10000. ; // correction dependent on T fEMCALRecoUtils->SetEMCALChannelRecalibrationFactor(ism,icol,irow,factor); } // columns } // rows } // SM loop delete contRF; return 1; } //_____________________________________________________ Int_t AliEMCALTenderSupply::InitTimeCalibration() { // Initialising bad channel maps AliVEvent *event = GetEvent(); if (!event) return 0; if (fDebugLevel>0) AliInfo("Initialising time calibration map"); // init default maps first if (!fEMCALRecoUtils->GetEMCALTimeRecalibrationFactorsArray()) fEMCALRecoUtils->InitEMCALTimeRecalibrationFactors() ; Int_t runBC = event->GetRunNumber(); AliOADBContainer *contBC = new AliOADBContainer(""); if (fBasePath!="") { //if fBasePath specified in the ->SetBasePath() if (fDebugLevel>0) AliInfo(Form("Loading time calibration OADB from given path %s",fBasePath.Data())); TFile *fbad=new TFile(Form("%s/EMCALTimeCalib.root",fBasePath.Data()),"read"); if (!fbad || fbad->IsZombie()) { AliFatal(Form("EMCALTimeCalib.root was not found in the path provided: %s",fBasePath.Data())); return 0; } if (fbad) delete fbad; contBC->InitFromFile(Form("%s/EMCALTimeCalib.root",fBasePath.Data()),"AliEMCALTimeCalib"); } else { // Else choose the one in the $ALICE_PHYSICS directory if (fDebugLevel>0) AliInfo("Loading time calibration OADB from OADB/EMCAL"); TFile *fbad=new TFile(AliDataFile::GetFileNameOADB("EMCAL/EMCALTimeCalib.root").data(),"read"); if (!fbad || fbad->IsZombie()) { AliFatal("OADB/EMCAL/EMCALTimeCalib.root was not found"); return 0; } if (fbad) delete fbad; contBC->InitFromFile(AliDataFile::GetFileNameOADB("EMCAL/EMCALTimeCalib.root").data(),"AliEMCALTimeCalib"); } TObjArray *arrayBC=(TObjArray*)contBC->GetObject(runBC); if (!arrayBC) { AliError(Form("No external time calibration set for run number: %d", runBC)); delete contBC; return 2; } // Here, it looks for a specific pass TString pass = fFilepass; if (fFilepass=="calo_spc") pass ="pass1"; TObjArray *arrayBCpass=(TObjArray*)arrayBC->FindObject(pass); if (!arrayBCpass) { AliError(Form("No external time calibration set for: %d -%s", runBC,pass.Data())); delete contBC; return 2; } if (fDebugLevel>0) arrayBCpass->Print(); for(Int_t i = 0; i < 4; i++) { TH1F *h = fEMCALRecoUtils->GetEMCALChannelTimeRecalibrationFactors(i); if (h) delete h; h = (TH1F*)arrayBCpass->FindObject(Form("hAllTimeAvBC%d",i)); if (!h) { AliError(Form("Can not get hAllTimeAvBC%d",i)); continue; } h->SetDirectory(0); fEMCALRecoUtils->SetEMCALChannelTimeRecalibrationFactors(i,h); } delete contBC; return 1; } //_____________________________________________________ Int_t AliEMCALTenderSupply::InitTimeCalibrationL1Phase() { // Initialising run-by-run L1 phase in time calibration maps AliVEvent *event = GetEvent(); if (!event) return 0; if (fDebugLevel>0) AliInfo("Initialising run-by-run L1 phase in time calibration map"); // init default maps first if (!fEMCALRecoUtils->GetEMCALL1PhaseInTimeRecalibrationArray()) fEMCALRecoUtils->InitEMCALL1PhaseInTimeRecalibration() ; Int_t runBC = event->GetRunNumber(); AliOADBContainer *contBC = new AliOADBContainer(""); if (fBasePath!="") { //if fBasePath specified in the ->SetBasePath() if (fDebugLevel>0) AliInfo(Form("Loading time calibration OADB from given path %s",fBasePath.Data())); TFile *timeFile=new TFile(Form("%s/EMCALTimeL1PhaseCalib.root",fBasePath.Data()),"read"); if (!timeFile || timeFile->IsZombie()) { AliFatal(Form("EMCALTimeL1PhaseCalib.root was not found in the path provided: %s",fBasePath.Data())); return 0; } if (timeFile) delete timeFile; contBC->InitFromFile(Form("%s/EMCALTimeL1PhaseCalib.root",fBasePath.Data()),"AliEMCALTimeL1PhaseCalib"); } else { // Else choose the one in the $ALICE_PHYSICS directory if (fDebugLevel>0) AliInfo("Loading L1 phase in time calibration OADB from OADB/EMCAL"); TFile *timeFile=new TFile(AliDataFile::GetFileNameOADB("EMCAL/EMCALTimeL1PhaseCalib.root").data(),"read"); if (!timeFile || timeFile->IsZombie()) { AliFatal("OADB/EMCAL/EMCALTimeL1PhaseCalib.root was not found"); return 0; } if (timeFile) delete timeFile; contBC->InitFromFile(AliDataFile::GetFileNameOADB("EMCAL/EMCALTimeL1PhaseCalib.root").data(),"AliEMCALTimeL1PhaseCalib"); } TObjArray *arrayBC=(TObjArray*)contBC->GetObject(runBC); if (!arrayBC) { AliError(Form("No external L1 phase in time calibration set for run number: %d", runBC)); delete contBC; return 2; } // Only 1 L1 phase correction possible, except special cases TString pass = "pass1"; if ( fFilepass=="muon_calo_pass1" && fRun > 209121 && fRun < 244284 ) pass = "pass0";//period LHC15a-m TObjArray *arrayBCpass=(TObjArray*)arrayBC->FindObject(pass); if (!arrayBCpass) { AliError(Form("No external L1 phase in time calibration set for: %d -%s", runBC,pass.Data())); delete contBC; return 2; } if (fDebugLevel>0) arrayBCpass->Print(); TH1C *h = fEMCALRecoUtils->GetEMCALL1PhaseInTimeRecalibrationForAllSM(); if (h) delete h; h = (TH1C*)arrayBCpass->FindObject(Form("h%d",runBC)); if (!h) { AliFatal(Form("There is no calibration histogram h%d for this run",runBC)); } h->SetDirectory(0); fEMCALRecoUtils->SetEMCALL1PhaseInTimeRecalibrationForAllSM(h); delete contBC; return 1; } //_____________________________________________________ void AliEMCALTenderSupply::UpdateCells() { //Remove bad cells from the cell list //Recalibrate energy and time cells //This is required for later reclusterization AliVEvent *event = GetEvent(); if (!event) return ; AliVCaloCells *cells = event->GetEMCALCells(); Int_t bunchCrossNo = event->GetBunchCrossNumber(); fEMCALRecoUtils->RecalibrateCells(cells, bunchCrossNo); // remove exotic cells - loop through cells and zero the exotic ones // just like with bad cell rejection in reco utils (inside RecalibrateCells) if (fRejectExoticCells) { Short_t absId =-1; Double_t ecell = 0; Double_t tcell = 0; Double_t efrac = 0; Int_t mclabel = -1; Bool_t isExot = kFALSE; // loop through cells Int_t nEMcell = cells->GetNumberOfCells() ; for (Int_t iCell = 0; iCell < nEMcell; iCell++) { cells->GetCell(iCell, absId, ecell, tcell, mclabel, efrac); isExot = fEMCALRecoUtils->IsExoticCell(absId, cells, bunchCrossNo); // zero if exotic if (isExot) cells->SetCell(iCell, absId, 0.0, -1.0, mclabel, efrac); } // cell loop } // reject exotic cells cells->Sort(); } //_____________________________________________________ TString AliEMCALTenderSupply::GetBeamType() { // Get beam type : pp-AA-pA // ESDs have it directly, AODs get it from hardcoded run number ranges AliVEvent *event = GetEvent(); if (!event) { AliError("Couldn't retrieve event!"); return ""; } TString beamType; AliESDEvent *esd = dynamic_cast<AliESDEvent*>(event); if (esd) { const AliESDRun *run = esd->GetESDRun(); beamType = run->GetBeamType(); } else { Int_t runNumber = event->GetRunNumber(); if ((runNumber >= 136851 && runNumber <= 139517) // LHC10h || (runNumber >= 166529 && runNumber <= 170593)) // LHC11h { beamType = "A-A"; } else { beamType = "p-p"; } } return beamType; } //_____________________________________________________ Int_t AliEMCALTenderSupply::InitRecParam() { // Init reco params if not yet exist (probably shipped by the user already) if (fRecParam != 0) return 2; TString beamType = GetBeamType(); // set some default reco params fRecParam = new AliEMCALRecParam(); fRecParam->SetClusteringThreshold(0.100); fRecParam->SetMinECut(0.050); if (!fCalibrateTimeParamAvailable) { fRecParam->SetTimeCut(250*1.e-9); fRecParam->SetTimeMin(425*1.e-9); fRecParam->SetTimeMax(825*1.e-9); } else { fRecParam->SetTimeCut(100*1.e-9); fRecParam->SetTimeMin(-50*1.e-9); fRecParam->SetTimeMax(50*1.e-9); } if (beamType == "A-A") { fRecParam->SetClusterizerFlag(AliEMCALRecParam::kClusterizerv2); } else { fRecParam->SetClusterizerFlag(AliEMCALRecParam::kClusterizerv1); } return 0; } //_____________________________________________________ Bool_t AliEMCALTenderSupply::InitClusterization() { // Initialing clusterization/unfolding algorithm and set all the needed parameters. AliVEvent *event = GetEvent(); if (!event) return kFALSE; if (fDebugLevel>0) AliInfo(Form("Initialising reclustering parameters: Clusterizer type: %d",fRecParam->GetClusterizerFlag())); //---setup clusterizer if (fClusterizer) { // avoid deleting fDigitsArr fClusterizer->SetDigitsArr(0); delete fClusterizer; fClusterizer = 0; } if (fRecParam->GetClusterizerFlag() == AliEMCALRecParam::kClusterizerv1) fClusterizer = new AliEMCALClusterizerv1 (fEMCALGeo); else if (fRecParam->GetClusterizerFlag() == AliEMCALRecParam::kClusterizerv2) fClusterizer = new AliEMCALClusterizerv2(fEMCALGeo); else if (fRecParam->GetClusterizerFlag() == AliEMCALRecParam::kClusterizerNxN) { AliEMCALClusterizerNxN *clusterizer = new AliEMCALClusterizerNxN(fEMCALGeo); clusterizer->SetNRowDiff(fRecParam->GetNRowDiff()); clusterizer->SetNColDiff(fRecParam->GetNColDiff()); fClusterizer = clusterizer; } else { AliFatal(Form("Clusterizer < %d > not available", fRecParam->GetClusterizerFlag())); return kFALSE; } // Set the clustering parameters fClusterizer->SetECAClusteringThreshold(fRecParam->GetClusteringThreshold()); fClusterizer->SetECALogWeight (fRecParam->GetW0() ); fClusterizer->SetMinECut (fRecParam->GetMinECut() ); fClusterizer->SetUnfolding (fRecParam->GetUnfold() ); fClusterizer->SetECALocalMaxCut (fRecParam->GetLocMaxCut() ); fClusterizer->SetTimeCut (fRecParam->GetTimeCut() ); fClusterizer->SetTimeMin (fRecParam->GetTimeMin() ); fClusterizer->SetTimeMax (fRecParam->GetTimeMax() ); fClusterizer->SetInputCalibrated (kTRUE ); fClusterizer->SetJustClusters (kTRUE ); // In case of unfolding after clusterization is requested, set the corresponding parameters if (fRecParam->GetUnfold()) { for (Int_t i = 0; i < 8; ++i) { fClusterizer->SetSSPars(i, fRecParam->GetSSPars(i)); } for (Int_t i = 0; i < 3; ++i) { fClusterizer->SetPar5 (i, fRecParam->GetPar5(i)); fClusterizer->SetPar6 (i, fRecParam->GetPar6(i)); } fClusterizer->InitClusterUnfolding(); } fClusterizer->SetDigitsArr(fDigitsArr); fClusterizer->SetOutput(0); fClusterArr = const_cast<TObjArray *>(fClusterizer->GetRecPoints()); return kTRUE; } //_____________________________________________________ void AliEMCALTenderSupply::FillDigitsArray() { // Fill digits from cells to a TClonesArray. AliVEvent *event = GetEvent(); if (!event) return; // In case of MC productions done before aliroot tag v5-02-Rev09 // assing the cluster label to all the cells belonging to this cluster // very rough if (fSetCellMCLabelFromCluster || fSetCellMCLabelFromEdepFrac) { for (Int_t i = 0; i < fgkTotalCellNumber; i++) { fCellLabels [i] =-1 ; fOrgClusterCellId[i] =-1 ; } Int_t nClusters = event->GetNumberOfCaloClusters(); for (Int_t i = 0; i < nClusters; i++) { AliVCluster *clus = event->GetCaloCluster(i); if (!clus) continue; if (!clus->IsEMCAL()) continue ; Int_t label = clus->GetLabel(); UShort_t * index = clus->GetCellsAbsId() ; for(Int_t icell=0; icell < clus->GetNCells(); icell++) { if(!fSetCellMCLabelFromEdepFrac) fCellLabels[index[icell]] = label; fOrgClusterCellId[index[icell]] = i ; // index of the original cluster } // cell in cluster loop }// cluster loop } fDigitsArr->Clear("C"); AliVCaloCells *cells = event->GetEMCALCells(); Int_t ncells = cells->GetNumberOfCells(); for (Int_t icell = 0, idigit = 0; icell < ncells; ++icell) { Double_t amp=0, cellTime=0, efrac = 0; Float_t cellAmplitude=0; Short_t cellNumber=0; Int_t mcLabel=-1; if (cells->GetCell(icell, cellNumber, amp, cellTime, mcLabel, efrac) != kTRUE) break; cellAmplitude = amp; // compilation problem // Do not add if energy already too low (some cells set to 0 if bad channels) if (cellAmplitude < fRecParam->GetMinECut()) continue; // If requested, do not include exotic cells if (fEMCALRecoUtils->IsExoticCell(cellNumber,cells,event->GetBunchCrossNumber())) continue; if(!fSetCellMCLabelFromEdepFrac) { if (fSetCellMCLabelFromCluster) mcLabel = fCellLabels[cellNumber]; else if (fRemapMCLabelForAODs ) RemapMCLabelForAODs(mcLabel); } // // New way to set the cell MC labels, // valid only for MC productions with aliroot > v5-07-21 // TArrayI labeArr(0); TArrayF eDepArr(0); Int_t nLabels = 0; if(fSetCellMCLabelFromEdepFrac && fOrgClusterCellId[cellNumber] >= 0) // index can be negative if noisy cell that did not form cluster { mcLabel = -1; fCellLabels[cellNumber] = idigit; Int_t iclus = fOrgClusterCellId[cellNumber]; if(iclus < 0) { AliInfo("Negative original cluster index, skip \n"); continue; } AliVCluster *clus = event->GetCaloCluster(iclus); for(Int_t icluscell=0; icluscell < clus->GetNCells(); icluscell++ ) { if(cellNumber != clus->GetCellAbsId(icluscell)) continue ; // Select the MC label contributing, only if enough energy deposition fEMCALRecoUtils->RecalculateCellLabelsRemoveAddedGenerator(cellNumber, clus, GetMCEvent(), cellAmplitude, labeArr, eDepArr); nLabels = labeArr.GetSize(); } if(cellAmplitude <= 0.01) continue ; // accept if > 10 MeV } // recalculate MC labels if (mcLabel > 0 && efrac < 1e-6) efrac = 1; AliEMCALDigit* digit = new((*fDigitsArr)[idigit]) AliEMCALDigit(mcLabel, mcLabel, cellNumber, cellAmplitude, (Float_t)cellTime, AliEMCALDigit::kHG,idigit, 0, 0, efrac*cellAmplitude); if(nLabels > 0) { digit->SetListOfParents(nLabels,labeArr.GetArray(),eDepArr.GetArray()); } idigit++; } } //_____________________________________________________ void AliEMCALTenderSupply::Clusterize() { // Clusterize. fClusterizer->Digits2Clusters(""); } //_____________________________________________________ void AliEMCALTenderSupply::UpdateClusters() { // Update ESD cluster list. AliVEvent *event = GetEvent(); if (!event) return; TClonesArray *clus = dynamic_cast<TClonesArray*>(event->FindListObject("caloClusters")); if (!clus) clus = dynamic_cast<TClonesArray*>(event->FindListObject("CaloClusters")); if (!clus) { AliError(" Null pointer to calo clusters array, returning"); return; } // Before destroying the orignal list, assign to the rec points the MC labels // of the original clusters, if requested if (fSetCellMCLabelFromCluster == 2) SetClustersMCLabelFromOriginalClusters() ; Int_t nents = clus->GetEntriesFast(); for (Int_t i=0; i < nents; ++i) { AliVCluster *c = dynamic_cast<AliVCluster*>(clus->At(i)); if (!c) continue; if (c->IsEMCAL()) { delete clus->RemoveAt(i); } } clus->Compress(); RecPoints2Clusters(clus); } //_____________________________________________________ void AliEMCALTenderSupply::RecPoints2Clusters(TClonesArray *clus) { // Convert AliEMCALRecoPoints to AliESDCaloClusters/AliAODCaloClusters. // Cluster energy, global position, cells and their amplitude fractions are restored. AliVEvent *event = GetEvent(); if (!event) return; Int_t ncls = fClusterArr->GetEntriesFast(); for(Int_t i=0, nout=clus->GetEntriesFast(); i < ncls; ++i) { AliEMCALRecPoint *recpoint = static_cast<AliEMCALRecPoint*>(fClusterArr->At(i)); Int_t ncellsTrue = 0; const Int_t ncells = recpoint->GetMultiplicity(); UShort_t absIds[ncells]; Double32_t ratios[ncells]; Int_t *dlist = recpoint->GetDigitsList(); Float_t *elist = recpoint->GetEnergiesList(); for (Int_t c = 0; c < ncells; ++c) { AliEMCALDigit *digit = static_cast<AliEMCALDigit*>(fDigitsArr->At(dlist[c])); absIds[ncellsTrue] = digit->GetId(); ratios[ncellsTrue] = elist[c]/digit->GetAmplitude(); if (ratios[ncellsTrue] < 0.001) continue; ++ncellsTrue; } if (ncellsTrue < 1) { AliWarning("Skipping cluster with no cells"); continue; } // calculate new cluster position TVector3 gpos; recpoint->GetGlobalPosition(gpos); Float_t g[3]; gpos.GetXYZ(g); AliVCluster *c = static_cast<AliVCluster*>(clus->New(nout++)); c->SetID(nout-1); c->SetType(AliVCluster::kEMCALClusterv1); c->SetE(recpoint->GetEnergy()); c->SetPosition(g); c->SetNCells(ncellsTrue); c->SetDispersion(recpoint->GetDispersion()); c->SetEmcCpvDistance(-1); //not yet implemented c->SetChi2(-1); //not yet implemented c->SetTOF(recpoint->GetTime()) ; //time-of-flight c->SetNExMax(recpoint->GetNExMax()); //number of local maxima Float_t elipAxis[2]; recpoint->GetElipsAxis(elipAxis); c->SetM02(elipAxis[0]*elipAxis[0]) ; c->SetM20(elipAxis[1]*elipAxis[1]) ; c->SetCellsAbsId(absIds); c->SetCellsAmplitudeFraction(ratios); // // MC labels // Int_t parentMult = 0; Int_t *parentList = recpoint->GetParents(parentMult); Float_t *parentListDE = recpoint->GetParentsDE(); // deposited energy if (parentMult > 0) { c->SetLabel(parentList, parentMult); if(fSetCellMCLabelFromEdepFrac) c->SetClusterMCEdepFractionFromEdepArray(parentListDE); } // // Set the cell energy deposition fraction map: // if( parentMult > 0 && fSetCellMCLabelFromEdepFrac ) { UInt_t * mcEdepFracPerCell = new UInt_t[ncellsTrue]; // Get the digit that originated this cell cluster for(Int_t icell = 0; icell < ncellsTrue ; icell++) { Int_t idigit = fCellLabels[absIds[icell]]; const AliEMCALDigit * dig = (const AliEMCALDigit*)fDigitsArr->At(idigit); // Find the 4 MC labels that contributed to the cluster and their // deposited energy in the current digit mcEdepFracPerCell[icell] = 0; // init Int_t nparents = dig->GetNiparent(); if ( nparents > 0 ) { Int_t digLabel =-1 ; Float_t edep = 0 ; Float_t edepTot = 0 ; Float_t mcEDepFrac[4] = {0,0,0,0}; // all parents in digit for ( Int_t jndex = 0 ; jndex < nparents ; jndex++ ) { digLabel = dig->GetIparent (jndex+1); edep = dig->GetDEParent(jndex+1); edepTot += edep; if ( digLabel == parentList[0] ) mcEDepFrac[0] = edep; else if ( digLabel == parentList[1] ) mcEDepFrac[1] = edep; else if ( digLabel == parentList[2] ) mcEDepFrac[2] = edep; else if ( digLabel == parentList[3] ) mcEDepFrac[3] = edep; } // all prarents in digit // Divide energy deposit by total deposited energy // Do this only when deposited energy is significant, use 10 MeV although 50 MeV should be expected if(edepTot > 0.01) { mcEdepFracPerCell[icell] = c->PackMCEdepFraction(mcEDepFrac); } } // at least one parent label in digit } // cell in cluster loop c->SetCellsMCEdepFractionMap(mcEdepFracPerCell); delete [] mcEdepFracPerCell; } // at least one parent in cluster, do the cell primary packing } } //___________________________________________________________ void AliEMCALTenderSupply::RemapMCLabelForAODs(Int_t & label) { // MC label for Cells not remapped after ESD filtering, do it here. if (label < 0) return; AliAODEvent * evt = dynamic_cast<AliAODEvent*> (GetEvent()) ; if (!evt) return ; TClonesArray * arr = dynamic_cast<TClonesArray*>(evt->FindListObject("mcparticles")) ; if (!arr) return ; if (label < arr->GetEntriesFast()) { AliAODMCParticle * particle = dynamic_cast<AliAODMCParticle *>(arr->At(label)); if (!particle) return ; if (label == particle->Label()) return ; // label already OK } // loop on the particles list and check if there is one with the same label for (Int_t ind = 0; ind < arr->GetEntriesFast(); ind++) { AliAODMCParticle * particle = dynamic_cast<AliAODMCParticle *>(arr->At(ind)); if (!particle) continue ; if (label == particle->Label()) { label = ind; return; } } label = -1; } //_____________________________________________________________________________________________ void AliEMCALTenderSupply::SetClustersMCLabelFromOriginalClusters() { // Get the original clusters that contribute to the new rec point cluster, // assign the labels of such clusters to the new rec point cluster. // Only approximatedly valid when output are V1 clusters, or input/output clusterizer // are the same handle with care // Copy from same method in AliAnalysisTaskEMCALClusterize, but here modify the recpoint and // not the output calocluster Int_t ncls = fClusterArr->GetEntriesFast(); for(Int_t irp=0; irp < ncls; ++irp) { TArrayI clArray(300) ; //Weird if more than a few clusters are in the origin ... clArray.Reset(); Int_t nClu = 0; Int_t nLabTotOrg = 0; Float_t emax = -1; Int_t idMax = -1; AliEMCALRecPoint *clus = static_cast<AliEMCALRecPoint*>(fClusterArr->At(irp)); //Find the clusters that originally had the cells const Int_t ncells = clus->GetMultiplicity(); Int_t *digList = clus->GetDigitsList(); for (Int_t iLoopCell = 0 ; iLoopCell < ncells ; iLoopCell++) { AliEMCALDigit *digit = static_cast<AliEMCALDigit*>(fDigitsArr->At(digList[iLoopCell])); Int_t idCell = digit->GetId(); if (idCell>=0) { Int_t idCluster = fOrgClusterCellId[idCell]; Bool_t set = kTRUE; for (Int_t icl =0; icl < nClu; icl++) { if (((Int_t)clArray.GetAt(icl))==-1) continue; if (idCluster == ((Int_t)clArray.GetAt(icl))) set = kFALSE; } if (set && idCluster >= 0) { clArray.SetAt(idCluster,nClu++); nLabTotOrg+=(GetEvent()->GetCaloCluster(idCluster))->GetNLabels(); //Search highest E cluster AliVCluster * clOrg = GetEvent()->GetCaloCluster(idCluster); if (emax < clOrg->E()) { emax = clOrg->E(); idMax = idCluster; } } } }// cell loop // Put the first in the list the cluster with highest energy if (idMax != ((Int_t)clArray.GetAt(0))) // Max not at first position { Int_t maxIndex = -1; Int_t firstCluster = ((Int_t)clArray.GetAt(0)); for (Int_t iLoopCluster = 0 ; iLoopCluster < nClu ; iLoopCluster++) { if (idMax == ((Int_t)clArray.GetAt(iLoopCluster))) maxIndex = iLoopCluster; } if (firstCluster >=0 && idMax >=0) { clArray.SetAt(idMax,0); clArray.SetAt(firstCluster,maxIndex); } } // Get the labels list in the original clusters, assign all to the new cluster TArrayI clMCArray(nLabTotOrg) ; clMCArray.Reset(); Int_t nLabTot = 0; for (Int_t iLoopCluster = 0 ; iLoopCluster < nClu ; iLoopCluster++) { Int_t idCluster = (Int_t) clArray.GetAt(iLoopCluster); AliVCluster * clOrg = GetEvent()->GetCaloCluster(idCluster); Int_t nLab = clOrg->GetNLabels(); for (Int_t iLab = 0 ; iLab < nLab ; iLab++) { Int_t lab = clOrg->GetLabelAt(iLab) ; if (lab>=0) { Bool_t set = kTRUE; for(Int_t iLabTot =0; iLabTot < nLabTot; iLabTot++) { if (lab == ((Int_t)clMCArray.GetAt(iLabTot))) set = kFALSE; } if (set) clMCArray.SetAt(lab,nLabTot++); } } }// cluster loop // Set the final list of labels to rec point Int_t *labels = new Int_t[nLabTot]; for(Int_t il = 0; il < nLabTot; il++) labels[il] = clMCArray.GetArray()[il]; clus->SetParents(nLabTot,labels); } // rec point array } //_____________________________________________________ void AliEMCALTenderSupply::GetPass() { // Get passx from filename AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); fInputTree = mgr->GetTree(); if (!fInputTree) { AliError("Pointer to tree = 0, returning"); return; } fInputFile = fInputTree->GetCurrentFile(); if (!fInputFile) { AliError("Null pointer input file, returning"); return; } TString fname(fInputFile->GetName()); if (fname.Contains("pass1")) fFilepass = TString("pass1"); else if (fname.Contains("pass2")) fFilepass = TString("pass2"); else if (fname.Contains("pass3")) fFilepass = TString("pass3"); else if (fname.Contains("pass4")) fFilepass = TString("pass4"); else if (fname.Contains("pass5")) fFilepass = TString("pass5"); else if (fname.Contains("LHC11c") && fname.Contains("spc_calo")) fFilepass = TString("spc_calo"); else if (fname.Contains("calo") || fname.Contains("high_lumi")) { //printf("AliEMCALTenderSupply::GetPass() - Path contains <calo> or <high-lumi>, set as <pass1>\n"); fFilepass = TString("pass1"); } else if (fname.Contains("LHC14a1a")) { fCalibrateEnergy = kTRUE; fUseAutomaticRecalib = kTRUE; AliInfo("Energy calibration activated for this MC production!"); fFilepass = TString("LHC14a1a"); } else { AliError(Form("Pass number string not found: %s", fname.Data())); return; } }
32.158017
139
0.650172
aknospe
4f693392a5ae36989618897b08f67bc7b7a73e3a
4,586
cpp
C++
src/Implement/RequestHandler.cpp
Jazz86/Group4
d48f610b57cbd01f8b072416036c1e64acbdc88d
[ "BSD-3-Clause" ]
null
null
null
src/Implement/RequestHandler.cpp
Jazz86/Group4
d48f610b57cbd01f8b072416036c1e64acbdc88d
[ "BSD-3-Clause" ]
19
2021-04-13T07:23:39.000Z
2021-06-29T04:43:15.000Z
src/Implement/RequestHandler.cpp
Jazz86/Group4
d48f610b57cbd01f8b072416036c1e64acbdc88d
[ "BSD-3-Clause" ]
3
2021-04-06T09:05:56.000Z
2021-04-13T10:08:15.000Z
// Copyright (c) 2021, 鍾淯丞, 周杰仕, 林仁鴻. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "RequestHandler.h" #include <netinet/in.h> #include <sys/socket.h> #include <sys/types.h> #include <unistd.h> #include <string> #include "FileOperator.h" std::unordered_map<std::string, APIHandler *> RequestHandler::apis = { {"POST_explorer_file", new FileOperator()}, {"GET_explorer_file", new FileOperator()}}; RequestHandler::RequestHandler() { this->read_size = 4096; } void RequestHandler::SetFd(const int &file_descriptor) { this->client_fd = file_descriptor; } int RequestHandler::ReadHeader(std::string *header, std::string *msg_over_header) { char input_buffer[this->read_size]; const std::string find_key = "Content-Length:"; const std::string end_of_header = "\r\n\r\n"; // keep read buffer until no request message while (true) { int msg_read = recv(this->client_fd, input_buffer, sizeof(input_buffer), 0); // means end of request if (msg_read <= 0) { return -1; } // add read buffer to header *header += std::string(input_buffer, msg_read); // find \r\n\r\n to get end of header size_t start_cut_pos = header->find(find_key, 0) + find_key.length() + 1; size_t end_cut_pos = header->find(end_of_header, 0); if (end_cut_pos != std::string::npos) { size_t header_size = end_cut_pos + end_of_header.length(); try { // no content_length means body size = 0 if (start_cut_pos == std::string::npos) { *msg_over_header = ""; *header = header->substr(0, header_size); return 0; } // convert content-length string to int int client_content_length = std::stoi( header->substr(start_cut_pos, end_cut_pos - start_cut_pos)); // it may occur that reading too many info from buffer, need to move the // body part out of header message *msg_over_header = header->substr(header_size, header->length() - header_size); *header = header->substr(0, header_size); return client_content_length; } catch (...) { // TODO: call error } } } } std::string RequestHandler::ReadBody(const int &content_length, const std::string &body, std::string *next_request_part) { std::string result = ""; std::string buffer_result = ""; int string_length_needed = content_length - body.length(); // will keep reading until complete message received while (string_length_needed > 0) { // buffer size is decided by content-length and length header has read char input_buffer[string_length_needed]; int msg_read = recv(this->client_fd, input_buffer, sizeof(input_buffer), 0); buffer_result += std::string(input_buffer, msg_read); string_length_needed -= msg_read; if (msg_read < 0) { // TODO: error handle } } // maybe first request is too short that already get info from second header, // need to be removed result = body.substr(0, content_length) + buffer_result; if (body.length() > content_length) { *next_request_part = body.substr(content_length, body.length() - content_length); } return result; } void RequestHandler::WaitForMessage() { // a final complete request message which will be parsed to OperateData std::string complete_request = ""; std::string msg_over_header = ""; int client_content_length = 0; char *input_buffer; // parts of message belongs to next request std::string next_request = ""; while (true) { complete_request = next_request; client_content_length = ReadHeader(&complete_request, &msg_over_header); if (client_content_length < 0) { break; } complete_request += ReadBody(client_content_length, msg_over_header, &next_request); // parse message to OperateData RequestParser *tmp_parser = RequestParser::GetInstance(); this->data = tmp_parser->ParseData(complete_request); this->data->header["client_file_descriptor"] = std::to_string(this->client_fd); const std::string api_name = this->data->header["method"] + "_" + this->data->header["url"]; APIHandler *api_handler = RequestHandler::apis[api_name]; if (api_handler == nullptr) { // should call error, wrong api calling will terminate receiving break; } else { api_handler->CallingAPI(std::move(this->data)); } } }
36.110236
80
0.657436
Jazz86
4f6b6094454a9da7a3d6e3df839cf7a1e71ccae1
1,173
hpp
C++
common/include/cleantype/details/cleantype_fp/fp_interact.hpp
ChronoCube/AM225
6e0789095f59eeb426c9e4ae9b600be0c04eca61
[ "MIT" ]
81
2018-12-21T22:44:48.000Z
2022-01-01T22:14:59.000Z
common/include/cleantype/details/cleantype_fp/fp_interact.hpp
ChronoCube/AM225
6e0789095f59eeb426c9e4ae9b600be0c04eca61
[ "MIT" ]
null
null
null
common/include/cleantype/details/cleantype_fp/fp_interact.hpp
ChronoCube/AM225
6e0789095f59eeb426c9e4ae9b600be0c04eca61
[ "MIT" ]
8
2018-12-24T12:15:44.000Z
2021-06-16T19:19:51.000Z
// This file is part of cleantype: Clean Types for C++ // Copyright Pascal Thomet - 2018 // Distributed under the Boost Software License, Version 1.0. (see LICENSE.md) #pragma once #include <functional> #include <iostream> #include <iterator> namespace cleantype_fp_interact { template <typename F> std::function<void()> interact(F f) { return [f]() -> void { std::cout << f(std::string(std::istreambuf_iterator<char>(std::cin.rdbuf()), std::istreambuf_iterator<char>())); }; } template <typename F, typename InputStream, typename OutputStream> std::function<void()> interact_by_line(F f, InputStream & is, OutputStream & os) { return [f, &is, &os]() -> void { std::string line; while (!is.eof()) { std::getline(is, line); std::string out = f(line); os << out << "\n"; } }; } template <typename F> std::function<void()> interact_by_line(F f) { return interact_by_line(f, std::cin, std::cout); } } // namespace cleantype_fp_interact
27.928571
88
0.556692
ChronoCube
4f6c6cacb3a43bb61bc4dd168dea64f8f9968a95
347
cpp
C++
start_point/hiker.tests.cpp
cyber-dojo-start-points/gplusplus-assert
4389a864871bde913d9bbbbd404f03aa54409f7f
[ "BSD-2-Clause" ]
null
null
null
start_point/hiker.tests.cpp
cyber-dojo-start-points/gplusplus-assert
4389a864871bde913d9bbbbd404f03aa54409f7f
[ "BSD-2-Clause" ]
null
null
null
start_point/hiker.tests.cpp
cyber-dojo-start-points/gplusplus-assert
4389a864871bde913d9bbbbd404f03aa54409f7f
[ "BSD-2-Clause" ]
null
null
null
#include "hiker.hpp" #include <cassert> #include <iostream> namespace { void test_global_function() { assert(answer() == 42); } void test_instance_method() { assert(hiker().answer() == 42); } } int main() { test_global_function(); test_instance_method(); std::cout << "All tests passed\n"; }
14.458333
39
0.585014
cyber-dojo-start-points
4f6c702697b5852adefb8f08819a5e69936771e5
81,959
cpp
C++
ghost/src/stats/statsdota.cpp
m-unkel/OHSystem
4aa16eddf3a446ac6a1e7897adc2e6d8e69a8976
[ "Apache-2.0" ]
2
2016-06-15T09:16:49.000Z
2017-07-25T11:05:16.000Z
ghost/src/stats/statsdota.cpp
m-unkel/OHSystem
4aa16eddf3a446ac6a1e7897adc2e6d8e69a8976
[ "Apache-2.0" ]
2
2016-06-21T10:23:37.000Z
2016-06-21T11:04:39.000Z
ghost/src/stats/statsdota.cpp
m-unkel/OHSystem
4aa16eddf3a446ac6a1e7897adc2e6d8e69a8976
[ "Apache-2.0" ]
2
2016-06-16T17:21:18.000Z
2018-07-01T13:12:19.000Z
/** * Copyright [2013-2014] [OHsystem] * * We spent a lot of time writing this code, so show some respect: * - Do not remove this copyright notice anywhere (bot, website etc.) * - We do not provide support to those who removed copyright notice * * OHSystem is free software: You can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * You can contact the developers on: admin@ohsystem.net * or join us directly here: http://forum.ohsystem.net/ * * Visit us also on http://ohsystem.net/ and keep track always of the latest * features and changes. * * * This is modified from GHOST++: http://ohbotplusplus.googlecode.com/ */ #include "../ohbot.h" #include "../utils/util.h" #include "../database/ghostdb.h" #include "../game/gameplayer.h" #include "../game/gameprotocol.h" #include "../game/game_base.h" #include "stats.h" #include "statsdota.h" #include "../language.h" // // CStatsDOTA // CStatsDOTA :: CStatsDOTA( CBaseGame *nGame ) : CStats( nGame ), m_Winner( 0 ), m_Min( 0 ), m_Sec( 0 ), m_TowerLimit( false ), m_KillLimit( 0 ), m_TimeLimit( 0 ), m_SentinelTowers( 0 ), m_ScourgeTowers( 0 ), m_SentinelKills( 0 ), m_ScourgeKills( 0 ), m_LastCreepTime( 0 ) { TypePrefix=m_Game->m_OHBot->GetAliasName(m_Game->m_GameAlias); transform( TypePrefix.begin( ), TypePrefix.end( ), TypePrefix.begin( ), (int(*)(int))toupper ); Log->Info( "[STATS"+TypePrefix+"] using "+TypePrefix+" stats" ); for( unsigned int i = 0; i < 12; ++i ) { m_Players[i] = NULL; m_LeaverKills[i] = 0; m_LeaverDeaths[i] = 0; m_AssistsOnLeaverKills[i] = 0; m_DeathsByLeaver[i] = 0; m_LatestKill[i] = 0; m_KillCounter[i] = 0; //The killcounter for checking as double kill etc (not the general kills of a player.) m_FFKills[i] = 0; m_KillStreakCounter[i] = 0; m_BufferedItemOne[i] = ""; m_BufferedItemTwo[i] = ""; m_BufferedItemThree[i] = ""; m_BufferedItemFour[i] = ""; m_BufferedItemFive[i] = ""; m_BufferedItemSix[i] = ""; m_BufferedItemCount[i] = 0; m_MaphackClickCounter[i] = 0; } m_FirstBlood = false; } CStatsDOTA :: ~CStatsDOTA( ) { for( unsigned int i = 0; i < 12; ++i ) { if( m_Players[i] ) delete m_Players[i]; } } bool CStatsDOTA :: ProcessAction( CIncomingAction *Action ) { if( m_Locked ) return m_Winner != 0; unsigned int i = 0; BYTEARRAY *ActionData = Action->GetAction( ); BYTEARRAY Data; BYTEARRAY Key; BYTEARRAY Value; // dota actions with real time replay data start with 0x6b then the null terminated string "dr.x" // unfortunately more than one action can be sent in a single packet and the length of each action isn't explicitly represented in the packet // so we have to either parse all the actions and calculate the length based on the type or we can search for an identifying sequence // parsing the actions would be more correct but would be a lot more difficult to write for relatively little gain // so we take the easy route (which isn't always guaranteed to work) and search the data for the sequence "6b 64 72 2e 78 00" and hope it identifies an action while( ActionData->size( ) >= i + 6 ) { string MinString = UTIL_ToString( ( m_Game->m_GameTicks / 1000 ) / 60 ); string SecString = UTIL_ToString( ( m_Game->m_GameTicks / 1000 ) % 60 ); if( MinString.size( ) == 1 ) MinString.insert( 0, "0" ); if( SecString.size( ) == 1 ) SecString.insert( 0, "0" ); if( (*ActionData)[i] == 0x6b && (*ActionData)[i + 1] == 0x64 && (*ActionData)[i + 2] == 0x72 && (*ActionData)[i + 3] == 0x2e && (*ActionData)[i + 4] == 0x78 && (*ActionData)[i + 5] == 0x00 ) { // we think we've found an action with real time replay data (but we can't be 100% sure) // next we parse out two null terminated strings and a 4 byte integer if( ActionData->size( ) >= i + 7 ) { // the first null terminated string should either be the strings "Data" or "Global" or a player id in ASCII representation, e.g. "1" or "2" Data = UTIL_ExtractCString( *ActionData, i + 6 ); if( ActionData->size( ) >= i + 8 + Data.size( ) ) { // the second null terminated string should be the key Key = UTIL_ExtractCString( *ActionData, i + 7 + Data.size( ) ); if( ActionData->size( ) >= i + 12 + Data.size( ) + Key.size( ) ) { // the 4 byte integer should be the value Value = BYTEARRAY( ActionData->begin( ) + i + 8 + Data.size( ) + Key.size( ), ActionData->begin( ) + i + 12 + Data.size( ) + Key.size( ) ); string DataString = string( Data.begin( ), Data.end( ) ); string KeyString = string( Key.begin( ), Key.end( ) ); uint32_t ValueInt = UTIL_ByteArrayToUInt32( Value, false ); // m_Game->SendAllChat( "[STATS] " + DataString + ", " + KeyString + ", " + UTIL_ToString( ValueInt ) ); if( DataString == "Data" ) { // these are received during the game // you could use these to calculate killing sprees and double or triple kills (you'd have to make up your own time restrictions though) // you could also build a table of "who killed who" data if( KeyString.size( ) >= 5 && KeyString.substr( 0, 4 ) == "Hero" ) { // a hero died string VictimColourString = KeyString.substr( 4 ); uint32_t VictimColour = UTIL_ToUInt32( VictimColourString ); CGamePlayer *Killer = m_Game->GetPlayerFromColour( ValueInt ); CGamePlayer *Victim = m_Game->GetPlayerFromColour( VictimColour ); if( Killer ) { m_KillStreakCounter[ValueInt]++; if( ( m_KillCounter[ValueInt] == 0 && m_LatestKill[ValueInt] == 0 ) || GetTime() - m_LatestKill[ValueInt] >= 18) { m_KillCounter[ValueInt] = 1; m_LatestKill[ValueInt] = GetTime(); } else if( m_KillCounter[ValueInt] != 0 && GetTime() - m_LatestKill[ValueInt] < 18 ) { m_KillCounter[ValueInt]++; m_LatestKill[ValueInt] = GetTime(); if(m_KillCounter[ValueInt] == 2 ) { m_Game->GAME_Print( 131, MinString, SecString, Killer->GetName(), "", "" ); Log->Debug("[STATS"+TypePrefix+"] "+Killer->GetName()+" got a double kill."); m_Game->AppendLogData("4\tk\t" + Killer->GetName( ) + "\t-\t" + m_Players[ValueInt]->GetHero( ) + "\t-\t" + MinString + ":" + SecString + "\tdk\n"); } if(m_KillCounter[ValueInt] == 3 ) { m_Game->GAME_Print( 132, MinString, SecString, Killer->GetName(), "", "" ); Log->Debug("[STATS"+TypePrefix+"] "+Killer->GetName()+" got a tripple kill."); m_Game->AppendLogData("4\tk\t" + Killer->GetName( ) + "\t-\t" + m_Players[ValueInt]->GetHero( ) + "\t-\t" + MinString + ":" + SecString + "\ttk\n"); } if(m_KillCounter[ValueInt] == 4 ) { m_Game->GAME_Print( 133, MinString, SecString, Killer->GetName(), "", "" ); Log->Debug("[STATS"+TypePrefix+"] "+Killer->GetName()+" got an ultra kill."); m_Game->AppendLogData("4\tk\t" + Killer->GetName( ) + "\t-\t" + m_Players[ValueInt]->GetHero( ) + "\t-\t" + MinString + ":" + SecString + "\tuk\n"); } if(m_KillCounter[ValueInt] >= 5 ) { m_Game->GAME_Print( 134, MinString, SecString, Killer->GetName(), "", "" ); Log->Debug("[STATS"+TypePrefix+"] "+Killer->GetName()+" got a rampage."); m_Game->AppendLogData("4\tk\t" + Killer->GetName( ) + "\t-\t" + m_Players[ValueInt]->GetHero( ) + "\t-\t" + MinString + ":" + SecString + "\trk\n"); } } switch(m_KillStreakCounter[ValueInt]) { case 3: Log->Debug("[STATS"+TypePrefix+"] "+Killer->GetName()+" is on a killing spree."); break; case 4: Log->Debug("[STATS"+TypePrefix+"] "+Killer->GetName()+" is dominating."); break; case 5: Log->Debug("[STATS"+TypePrefix+"] "+Killer->GetName()+" has a mega kill."); break; case 6: Log->Debug("[STATS"+TypePrefix+"] "+Killer->GetName()+" is unstoppable."); break; case 7: Log->Debug("[STATS"+TypePrefix+"] "+Killer->GetName()+" is wicked sick."); break; case 8: Log->Debug("[STATS"+TypePrefix+"] "+Killer->GetName()+" has a monster kill."); break; case 9: Log->Debug("[STATS"+TypePrefix+"] "+Killer->GetName()+" is godlike."); break; case 10: Log->Debug("[STATS"+TypePrefix+"] "+Killer->GetName()+" is beyond godlike."); break; } } if( Killer && Victim ) { if( ( ValueInt >= 1 && ValueInt <= 5 ) || ( ValueInt >= 7 && ValueInt <= 11 ) ) { if ((ValueInt <= 5 && VictimColour <= 5) || (ValueInt >= 7 && VictimColour >= 7)) { m_Game->GAME_Print( 12, MinString, SecString, Killer->GetName(), Victim->GetName(), "" ); // He denied a team-mate, don't count that. } else { // A legit kill, lets count that. if (!m_Players[ValueInt]) m_Players[ValueInt] = new CDBDotAPlayer( ); if (ValueInt != VictimColour) m_Players[ValueInt]->SetKills( m_Players[ValueInt]->GetKills() + 1 ); if( ValueInt >= 1 && ValueInt <= 5 ) m_SentinelKills++; else m_ScourgeKills++; } } if( ( VictimColour >= 1 && VictimColour <= 5 ) || ( VictimColour >= 7 && VictimColour <= 11 ) ) { if (!m_Players[VictimColour]) m_Players[VictimColour] = new CDBDotAPlayer( ); m_Players[VictimColour]->SetDeaths( m_Players[VictimColour]->GetDeaths() + 1 ); m_KillStreakCounter[VictimColour] = 0; } if( !m_FirstBlood ) { m_Game->GAME_Print( 13, MinString, SecString, Killer->GetName(), Victim->GetName(), "" ); Log->Debug( "[STATS"+TypePrefix+": " + m_Game->GetGameName( ) + "] player [" + Killer->GetName( ) + "] slained player [" + Victim->GetName( ) + "] as first blood." ); m_Game->AppendLogData("4\tfb\t" + Killer->GetName( ) + "\t" + Victim->GetName( ) + "[" + Victim->GetName( ) + "]"); m_FirstBlood = true; } else { m_Game->GAME_Print( 14, MinString, SecString, Killer->GetName(), Victim->GetName(), "" ); Log->Debug( "[STATS"+TypePrefix+": " + m_Game->GetGameName( ) + "] player [" + Killer->GetName( ) + "] killed player [" + Victim->GetName( ) + "]" ); m_Game->AppendLogData("4\tk\t" + Killer->GetName( ) + "\t" + Victim->GetName( ) + "\t" + m_Players[ValueInt]->GetHero( ) + "\t" + m_Players[VictimColour]->GetHero( ) + "\t" + MinString + ":" + SecString + "\t-\n"); } if( GetTime() - Killer->GetLastAttackTimeToFountain() <=5 && m_Game->m_OHBot->m_FountainFarmDetection) { m_Game->SendChat(Killer->GetPID(), m_Game->m_OHBot->m_Language->YouHaveBeenDetectedAsFountainFarmer()); m_FFKills[ValueInt]++; Killer->SetFFLevel(); if(Killer->GetFFLevel() == 3 ) { m_Game->BanPlayerByPenality( Killer->GetName(), Killer->GetExternalIPString(), m_Game->m_OHBot->m_BotManagerName, Killer->GetPenalityLevel(), "FountainFarm" ); } } } else if( Victim ) { if( ( VictimColour >= 1 && VictimColour <= 5 ) || ( VictimColour >= 7 && VictimColour <= 11 ) ) { if (!m_Players[VictimColour]) m_Players[VictimColour] = new CDBDotAPlayer( ); m_Game->GAME_Print( 15, MinString, SecString, Victim->GetName(), "", "" ); m_Players[VictimColour]->SetDeaths( m_Players[VictimColour]->GetDeaths() + 1 ); m_Game->AppendLogData("4\ts\t-\t" + Victim->GetName( ) + "\t-\t" + m_Players[VictimColour]->GetHero( ) + "\t" + MinString + ":" + SecString + "\t-\n"); } if( ValueInt == 0 ) { m_Game->GAME_Print( 16, MinString, SecString, Victim->GetName(), "", "" ); m_SentinelKills++; Log->Debug( "[STATS"+TypePrefix+": " + m_Game->GetGameName( ) + "] the Sentinel killed player [" + Victim->GetName( ) + "]" ); m_Game->AppendLogData("4\tsek\tSentinel\t" + Victim->GetName( ) + "\t-\t" + m_Players[VictimColour]->GetHero( ) + "\t" + MinString + ":" + SecString + "\t-\n"); m_KillStreakCounter[VictimColour] = 0; } else if( ValueInt == 6 ) { m_Game->GAME_Print( 17, MinString, SecString, Victim->GetName(), "", "" ); m_ScourgeKills++; Log->Debug( "[STATS"+TypePrefix+": " + m_Game->GetGameName( ) + "] the Scourge killed player [" + Victim->GetName( ) + "]" ); m_Game->AppendLogData("4\tsck\tScourge\t" + Victim->GetName( ) + "\t-\t" + m_Players[VictimColour]->GetHero( ) + "\t" + MinString + ":" + SecString + "\t-\n"); m_KillStreakCounter[VictimColour] = 0; } else { // removing this, occur probably on neutral kills /* Log->Debug( "[ANTIFARM] player [" + Victim->GetName() + "] got killed by a leaver." ); if( m_LeaverKills[VictimColour] == 0 && m_AssistsOnLeaverKills[VictimColour] == 0 ) m_DeathsByLeaver[VictimColour]++; else m_Game->SendAllChat( "[ANTIFARM] Player ["+Victim->GetName()+"] killed already ["+UTIL_ToString(m_DeathsByLeaver[VictimColour])+"] leavers and assisted on ["+UTIL_ToString(m_AssistsOnLeaverKills[VictimColour])+"] kills. Justice has been done!" ); */ } } if( Killer && !Victim ) { Log->Debug( "[ANTIFARM] player [" + Killer->GetName() + "] killed a leaver." ); m_LeaverKills[ValueInt]++; if( m_LeaverKills[ValueInt] >= m_Game->m_OHBot->m_MinimumLeaverKills ) m_Game->SendAllChat( "[ANTIFARM] Player ["+Killer->GetName()+"] killed already ["+UTIL_ToString(m_LeaverKills[ValueInt])+"] leavers, the stats wont be recorded anymore." ); m_LeaverDeaths[VictimColour]++; if( m_LeaverDeaths[ValueInt] >= m_Game->m_OHBot->m_MinimumLeaverDeaths ) m_Game->SendAllChat( "[ANTIFARM] A leaver ["+UTIL_ToString(VictimColour)+"] was already ["+UTIL_ToString(m_LeaverDeaths[ValueInt])+"] times killed while he left. All remaining deaths wont be recorded." ); if( GetTime() - Killer->GetLastAttackTimeToFountain() <=5 && m_Game->m_OHBot->m_FountainFarmDetection) { m_Game->SendChat(Killer->GetPID(), m_Game->m_OHBot->m_Language->YouHaveBeenDetectedAsFountainFarmer() ); m_FFKills[ValueInt]++; Killer->SetFFLevel(); if(Killer->GetFFLevel() == 3 ) { m_Game->BanPlayerByPenality( Killer->GetName(), Killer->GetExternalIPString(), m_Game->m_OHBot->m_BotManagerName, Killer->GetPenalityLevel(), "FountainFarm" ); } } } if( Victim != NULL ) { int32_t kills = m_Players[VictimColour]->GetKills( );; int32_t deaths = m_Players[VictimColour]->GetDeaths( ); int32_t assists = m_Players[VictimColour]->GetAssists( ); if( ( deaths - kills - ( assists * 0.5 ) ) >= 8 ) { if( Victim->GetFeedLevel( ) != 2 ) m_Game->SendAllChat( "[INFO] Player ["+Victim->GetName( )+"] got marked as feeder, you may votekick him." ); Victim->SetFeedLevel( 2 ); } else if( ( deaths - kills - ( assists * 0.5 ) ) > 5 ) { m_Game->SendChat( Victim, "[INFO] Feed Detection triggered. Please stop dying to avoid a potential kick for feeding." ); m_Game->SendChat( Victim, "[INFO] Feeding on purpose is bannable, for more information check out '!rule feeding'." ); Victim->SetFeedLevel( 1 ); } } } else if( KeyString.size( ) >= 4 && KeyString.substr( 0, 6 ) == "Assist" ) { // assist string AssistentColourString = KeyString.substr( 6 ); uint32_t AssistentColour = UTIL_ToUInt32( AssistentColourString ); CGamePlayer *Assistent = m_Game->GetPlayerFromColour( AssistentColour ); CGamePlayer *Victim = m_Game->GetPlayerFromColour( ValueInt ); if( !m_Players[AssistentColour] ) m_Players[AssistentColour] = new CDBDotAPlayer( ); if ( Assistent && Victim ) { m_Game->GAME_Print( 18, MinString, SecString, Assistent->GetName(), Victim->GetName( ), "" ); m_Players[AssistentColour]->SetAssists(m_Players[AssistentColour]->GetAssists() + 1); Log->Debug( "[STATS"+TypePrefix+": " + m_Game->GetGameName( ) + "] player [" + Assistent->GetName( ) + "] assist to kill player [" + Victim->GetName( ) + "]" ); m_Game->AppendLogData("4\ta\t" + Assistent->GetName( ) + "\t" + Victim->GetName( ) + "\t" + m_Players[AssistentColour]->GetHero( ) + "\t" + m_Players[ValueInt]->GetHero( ) + "\t" + MinString + ":" + SecString + "\t-\n"); } if( Assistent && !Victim ) { Log->Debug( "[ANTIFARM] Player ["+Assistent->GetName( )+"] assisted to kill a leaver." ); m_AssistsOnLeaverKills[AssistentColour]++; if( m_AssistsOnLeaverKills[AssistentColour] >= m_Game->m_OHBot->m_MinimumLeaverKills ) m_Game->SendAllChat( "[ANTIFARM] Player ["+Assistent->GetName()+"] assisted to kill ["+UTIL_ToString(m_AssistsOnLeaverKills[AssistentColour])+"] leavers, all assists for leavers will be removed." ); } } else if( KeyString.size( ) >= 8 && KeyString.substr( 0, 7 ) == "Courier" ) { // a courier died if( ( ValueInt >= 1 && ValueInt <= 5 ) || ( ValueInt >= 7 && ValueInt <= 11 ) ) { if( !m_Players[ValueInt] ) m_Players[ValueInt] = new CDBDotAPlayer( ); m_Players[ValueInt]->SetCourierKills( m_Players[ValueInt]->GetCourierKills( ) + 1 ); } string VictimColourString = KeyString.substr( 7 ); uint32_t VictimColour = UTIL_ToUInt32( VictimColourString ); CGamePlayer *Killer = m_Game->GetPlayerFromColour( ValueInt ); CGamePlayer *Victim = m_Game->GetPlayerFromColour( VictimColour ); /* if( Killer && Victim ) Log->Debug( "[STATS"+TypePrefix+": " + m_Game->GetGameName( ) + "] player [" + Killer->GetName( ) + "] killed a courier owned by player [" + Victim->GetName( ) + "]" ); else if( Victim ) { if( ValueInt == 0 ) Log->Debug( "[STATS"+TypePrefix+": " + m_Game->GetGameName( ) + "] the Sentinel killed a courier owned by player [" + Victim->GetName( ) + "]" ); else if( ValueInt == 6 ) Log->Debug( "[STATS"+TypePrefix+": " + m_Game->GetGameName( ) + "] the Scourge killed a courier owned by player [" + Victim->GetName( ) + "]" ); } */ } else if( KeyString.size( ) >= 8 && KeyString.substr( 0, 5 ) == "Tower" ) { // a tower died if( ( ValueInt >= 1 && ValueInt <= 5 ) || ( ValueInt >= 7 && ValueInt <= 11 ) ) { if( !m_Players[ValueInt] ) m_Players[ValueInt] = new CDBDotAPlayer( ); m_Players[ValueInt]->SetTowerKills( m_Players[ValueInt]->GetTowerKills( ) + 1 ); } string Alliance = KeyString.substr( 5, 1 ); string Level = KeyString.substr( 6, 1 ); string Side = KeyString.substr( 7, 1 ); CGamePlayer *Killer = m_Game->GetPlayerFromColour( ValueInt ); string AllianceString; string SideString; if( Alliance == "0" ) { m_ScourgeTowers++; AllianceString = "Sentinel"; } else if( Alliance == "1" ) { m_SentinelTowers++; AllianceString = "Scourge"; } else AllianceString = "unknown"; if( Side == "0" ) SideString = "top"; else if( Side == "1" ) SideString = "mid"; else if( Side == "2" ) SideString = "bottom"; else SideString = "unknown"; if( Level == "3" && m_Game->m_OHBot->m_FountainFarmWarning ) { m_Game->SendAllChat( "["+m_Game->m_OHBot->m_BotManagerName+"] "+m_Game->m_OHBot->m_FountainFarmMessage ); } if( Killer ) { m_Game->GAME_Print( 19, MinString, SecString, Killer->GetName( ), AllianceString, SideString+" "+Level ); Log->Debug( "[STATS"+TypePrefix+": " + m_Game->GetGameName( ) + "] player [" + Killer->GetName( ) + "] destroyed a level [" + Level + "] " + AllianceString + " tower (" + SideString + ")" ); m_Game->AppendLogData("4\ttok\t" + Killer->GetName( ) + "\t" + AllianceString + "\t" + m_Players[ValueInt]->GetHero( ) + "\t-\t" + MinString + ":" + SecString + "\t" + SideString + ":" + Level + "\n"); } else { if( ValueInt == 0 ) { m_Game->GAME_Print( 20, MinString, SecString, "", "", SideString+" "+Level ); Log->Debug( "[STATS"+TypePrefix+": " + m_Game->GetGameName( ) + "] the Sentinel destroyed a level [" + Level + "] " + AllianceString + " tower (" + SideString + ")" ); m_Game->AppendLogData("4\tsetk\tSentinel\tScourge\t-\t-\t" + MinString + ":" + SecString + "\t" + SideString + ":" + Level + "\n"); } else if( ValueInt == 6 ) { m_Game->GAME_Print( 21, MinString, SecString, "", "", SideString+" "+Level ); Log->Debug( "[STATS"+TypePrefix+": " + m_Game->GetGameName( ) + "] the Scourge destroyed a level [" + Level + "] " + AllianceString + " tower (" + SideString + ")" ); m_Game->AppendLogData("4\tsctk\tScourge\tSentinel\t-\t-\t" +MinString + ":" + SecString + "\t" + SideString + ":" + Level + "\n"); } } } else if( KeyString.size( ) >= 6 && KeyString.substr( 0, 3 ) == "Rax" ) { // a rax died if( ( ValueInt >= 1 && ValueInt <= 5 ) || ( ValueInt >= 7 && ValueInt <= 11 ) ) { if( !m_Players[ValueInt] ) m_Players[ValueInt] = new CDBDotAPlayer( ); m_Players[ValueInt]->SetRaxKills( m_Players[ValueInt]->GetRaxKills( ) + 1 ); } string Alliance = KeyString.substr( 3, 1 ); string Side = KeyString.substr( 4, 1 ); string Type = KeyString.substr( 5, 1 ); CGamePlayer *Killer = m_Game->GetPlayerFromColour( ValueInt ); string AllianceString; string SideString; string TypeString; if( Alliance == "0" ) AllianceString = "Sentinel"; else if( Alliance == "1" ) AllianceString = "Scourge"; else AllianceString = "unknown"; if( Side == "0" ) SideString = "top"; else if( Side == "1" ) SideString = "mid"; else if( Side == "2" ) SideString = "bottom"; else SideString = "unknown"; if( Type == "0" ) TypeString = "melee"; else if( Type == "1" ) TypeString = "ranged"; else TypeString = "unknown"; if( Killer ) { m_Game->GAME_Print( 22, MinString, SecString, Killer->GetName(), AllianceString, SideString+" "+TypeString ); Log->Debug( "[STATS"+TypePrefix+": " + m_Game->GetGameName( ) + "] player [" + Killer->GetName( ) + "] destroyed a " + TypeString + " " + AllianceString + " rax (" + SideString + ")" ); m_Game->AppendLogData("4\trk\t" + Killer->GetName( ) + "\t" + AllianceString + "\t" + m_Players[ValueInt]->GetHero( ) + "\t-\t" + MinString + ":" + SecString + "\t" + SideString + ":" + TypeString + "\n"); } else { if( ValueInt == 0 ) { m_Game->GAME_Print( 23, MinString, SecString, "", "", SideString+" "+TypeString ); Log->Debug( "[STATS"+TypePrefix+": " + m_Game->GetGameName( ) + "] the Sentinel destroyed a " + TypeString + " " + AllianceString + " rax (" + SideString + ")" ); m_Game->AppendLogData("4\tserk\tSentinel\t" + AllianceString + "\t-\t-\t" + MinString + ":" + SecString + "\t" + SideString + ":" + TypeString + "\n"); } else if( ValueInt == 6 ) { m_Game->GAME_Print( 24, MinString, SecString, "", "", SideString+" "+TypeString ); Log->Debug( "[STATS"+TypePrefix+": " + m_Game->GetGameName( ) + "] the Scourge destroyed a " + TypeString + " " + AllianceString + " rax (" + SideString + ")" ); m_Game->AppendLogData("4\tscrk\tScourge\t" + AllianceString + "\t-\t-\t" + MinString + ":" + SecString + "\t" + SideString + ":" + TypeString + "\n"); } } } else if( KeyString.size( ) >= 6 && KeyString.substr( 0, 5 ) == "Level" ) { string LevelString = KeyString.substr( 5 ); uint32_t Level = UTIL_ToUInt32( LevelString ); CGamePlayer *Player = m_Game->GetPlayerFromColour( ValueInt ); if (Player) { if (!m_Players[ValueInt]) m_Players[ValueInt] = new CDBDotAPlayer( ); m_Players[ValueInt]->SetLevel(Level); Log->Debug( "[STATS"+TypePrefix+": " + m_Game->GetGameName( ) + "] "+ Player->GetName() + " is now level " + UTIL_ToString(m_Players[ValueInt]->GetLevel()) ); m_Game->AppendLogData("4\tlu\t" + Player->GetName( ) + "\t-\t" + m_Players[ValueInt]->GetHero( ) + "\t-\t" + MinString + ":" + SecString + "\t" + UTIL_ToString(m_Players[ValueInt]->GetLevel()) + "\n"); } } else if( KeyString.size( ) >= 8 && KeyString.substr( 0, 4 ) == "SWAP" ) { // swap players int i = KeyString.find( "_") + 1; int y = KeyString.find( "_", i ); string FromString = KeyString.substr( i, y-i ); uint32_t FromColour = UTIL_ToUInt32( FromString ); CGamePlayer *FromPlayer = m_Game->GetPlayerFromColour( FromColour ); string ToString = KeyString.substr( y + 1 ); uint32_t ToColour = UTIL_ToUInt32( ToString ); CGamePlayer *ToPlayer = m_Game->GetPlayerFromColour( ToColour ); m_Game->GAME_Print( 25, MinString, SecString, FromPlayer->GetName( ), ToPlayer->GetName( ), "req" ); if ((FromColour >= 1 && FromColour <= 5 ) || ( FromColour >= 7 && FromColour <= 11 )) if ((ToColour >= 1 && ToColour <= 5 ) || ( ToColour >= 7 && ToColour <= 11 )) { m_Players[ToColour]->SetNewColour( FromColour ); m_Players[FromColour]->SetNewColour( ToColour ); // Log->Debug( m_Players[ToColour] +" / "+ m_Players[FromColour] ); CDBDotAPlayer* bufferPlayer = m_Players[ToColour]; m_Players[ToColour] = m_Players[FromColour]; m_Players[FromColour] = bufferPlayer; if ( FromPlayer ) FromString = FromPlayer->GetName( ); if ( ToPlayer ) ToString = ToPlayer->GetName( ); Log->Debug( "SWITCH " + FromPlayer->GetName( ) + " with " + ToPlayer->GetName( ) ); m_Game->GAME_Print( 25, MinString, SecString, FromPlayer->GetName( ), ToPlayer->GetName( ), "succ" ); Log->Debug( "[STATS"+TypePrefix+": " + m_Game->GetGameName( ) + "] swap players from ["+FromString+"] to ["+ToString+"]." ); m_Game->AppendLogData("4\tsw\t" + FromPlayer->GetName() + "\t" + ToPlayer->GetName() + "\t" + m_Players[FromColour]->GetHero() + "\t" + m_Players[ToColour]->GetHero() + "\t" + MinString + ":" + SecString + "\t-\n"); } } else if( KeyString.size( ) >= 6 && KeyString.substr( 0, 6 ) == "Throne" ) { // the frozen throne got hurt m_Game->GAME_Print( 26, MinString, SecString, "", "", UTIL_ToString( ValueInt ) ); Log->Debug( "[STATS"+TypePrefix+": " + m_Game->GetGameName( ) + "] the Frozen Throne is now at " + UTIL_ToString( ValueInt ) + "% HP" ); m_Game->AppendLogData("4\tftk\t-\tFrozen Throne\t-\t-\t" + MinString + ":" + SecString + "\t" + UTIL_ToString( ValueInt ) + "\n"); } else if ( KeyString.size( ) >= 6 && KeyString.substr( 0, 6 ) == "Roshan" ) { if( ValueInt == 0 ) { m_Game->GAME_Print( 28, MinString, SecString, "Sentinel", "", "" ); Log->Debug( "[STATS"+TypePrefix+": " + m_Game->GetGameName( ) + "] Roshan killed by the Sentinel" ); m_Game->AppendLogData("4\trosh\tSentinel\t-\t-\t-\t" + MinString + ":" + SecString + "\t-\n"); } else if( ValueInt == 6 ) { m_Game->GAME_Print( 28, MinString, SecString, "Scourge", "", ""); Log->Debug( "[STATS"+TypePrefix+": " + m_Game->GetGameName( ) + "] Roshan killed by the Scourge" ); m_Game->AppendLogData("4\trosh\tScourge\t-\t-\t-\t" + MinString + ":" + SecString + "\t-\n"); } } else if ( KeyString.size( ) >= 7 && KeyString.substr( 0, 7 ) == "AegisOn") { CGamePlayer *Player = m_Game->GetPlayerFromColour( ValueInt ); if (Player) { Log->Debug( "[STATS"+TypePrefix+": " + m_Game->GetGameName( ) + "] "+Player->GetName( ) + " picked up AEGIS." ); m_Game->GAME_Print( 29, MinString, SecString, Player->GetName( ), "", "pick" ); m_Game->AppendLogData("4\tap\t" + Player->GetName( ) + "\t-\t-\t-\t" + MinString + ":" + SecString + "\t-\n"); } } else if ( KeyString.size( ) >= 8 && KeyString.substr( 0, 8 ) == "AegisOff") { CGamePlayer *Player = m_Game->GetPlayerFromColour( ValueInt ); if (Player) { Log->Debug( "[STATS"+TypePrefix+": " + m_Game->GetGameName( ) + "] "+Player->GetName( ) + " dropped AEGIS." ); m_Game->GAME_Print( 29, MinString, SecString, Player->GetName( ), "", "drop" ); m_Game->AppendLogData("4\tad\t" + Player->GetName( ) + "\t-\t-\t-\t" + MinString + ":" + SecString + "\t-\n"); } } else if( KeyString.size( ) >= 4 && KeyString.substr( 0, 4 ) == "Tree" ) { // the world tree got hurt m_Game->GAME_Print( 27, MinString, SecString, "", "", UTIL_ToString( ValueInt ) ); Log->Debug( "[STATS"+TypePrefix+": " + m_Game->GetGameName( ) + "] the World Tree is now at " + UTIL_ToString( ValueInt ) + "% HP" ); m_Game->AppendLogData("4\twtk\t-\tWorld Tree\t-\t-\t" + MinString + ":" + SecString + "\t" + UTIL_ToString( ValueInt ) + "\n"); } else if( KeyString.size( ) >= 2 && KeyString.substr( 0, 2 ) == "CK" ) { // a player disconnected } else if( KeyString.size( ) >= 3 && KeyString.substr( 0, 3 ) == "CSK" ) { /* if( ( ValueInt >= 1 && ValueInt <= 5 ) || ( ValueInt >= 7 && ValueInt <= 11 ) ) { if( !m_Players[ValueInt] ) m_Players[ValueInt] = new CDBDotAPlayer( ); m_Players[ValueInt]->SetCreepKills( m_Players[ValueInt]->GetCreepKills( ) + 1 ); } */ // creep kill value recieved (aprox every 3 - 4) string PlayerID = KeyString.substr( 3 ); uint32_t ID = UTIL_ToUInt32( PlayerID ); if( ( ID >= 1 && ID <= 5 ) || ( ID >= 7 && ID <= 11 ) ) { if (!m_Players[ID]) m_Players[ID] = new CDBDotAPlayer( ); m_Players[ID]->SetCreepKills(ValueInt); } } else if( KeyString.size( ) >= 3 && KeyString.substr( 0, 3 ) == "CSD" ) { // creep denie value recieved (aprox every 3 - 4) string PlayerID = KeyString.substr( 3 ); uint32_t ID = UTIL_ToUInt32( PlayerID ); if( ( ID >= 1 && ID <= 5 ) || ( ID >= 7 && ID <= 11 ) ) { if (!m_Players[ID]) m_Players[ID] = new CDBDotAPlayer( ); m_Players[ID]->SetCreepDenies(ValueInt); } } else if( KeyString.size( ) >= 2 && KeyString.substr( 0, 2 ) == "NK" ) { // creep denie value recieved (aprox every 3 - 4) string PlayerID = KeyString.substr( 2 ); uint32_t ID = UTIL_ToUInt32( PlayerID ); if( ( ID >= 1 && ID <= 5 ) || ( ID >= 7 && ID <= 11 ) ) { if (!m_Players[ID]) m_Players[ID] = new CDBDotAPlayer( ); m_Players[ID]->SetNeutralKills(ValueInt); } } else if (KeyString.size( ) >= 10 && KeyString.substr( 0, 9 ) == "RuneStore") { string RuneType = KeyString.substr( 9, 1 ); /* RuneType: 1. Haste 2. Regeneration 3. Double Damage 4. Illusion 5. Illusion */ string Rune = "unknown"; if( RuneType == "1" ) { Rune = "Haste"; } else if( RuneType == "2" ) { Rune = "Regeneration"; } else if( RuneType == "3" ) { Rune = "Double Damage"; } else if( RuneType == "4" ) { Rune = "Illusion"; } else if( RuneType == "5" ) { Rune = "Invisible"; } else if( RuneType == "6" ) { Rune = "Bounty"; } CGamePlayer *Player = m_Game->GetPlayerFromColour( ValueInt ); if (Player) { m_Game->GAME_Print( 30, MinString, SecString, Player->GetName(), "", RuneType ); Log->Debug( "[STATS"+TypePrefix+": " + m_Game->GetGameName( ) + "] Player " + Player->GetName() + " bottled a " + Rune + " Rune." ); m_Game->AppendLogData("4\trs\t" + Player->GetName( ) + "\t-\t-\t-\t" + MinString + ":" + SecString + "\t" + Rune + "\n"); } } else if (KeyString.size( ) >= 8 && KeyString.substr( 0, 7 ) == "RuneUse") { string RuneType = KeyString.substr( 7, 1 ); /* RuneType: 1. Haste 2. Regeneration 3. Double Damage 4. Illusion 5: Invis */ string Rune = "unknown"; if( RuneType == "1" ) { Rune = "Haste"; } else if( RuneType == "2" ) { Rune = "Regeneration"; } else if( RuneType == "3" ) { Rune = "Double Damage"; } else if( RuneType == "4" ) { Rune = "Illusion"; } else if( RuneType == "5" ) { Rune = "Invisible"; } else if( RuneType == "6" ) { Rune = "Bounty"; } CGamePlayer *Player = m_Game->GetPlayerFromColour( ValueInt ); if (Player) { m_Game->GAME_Print( 31, MinString, SecString, Player->GetName(), "", RuneType ); Log->Debug( "[STATS"+TypePrefix+": " + m_Game->GetGameName( ) + "] Player " + Player->GetName() + " used a " + Rune + " Rune." ); m_Game->AppendLogData("4\tru\t" + Player->GetName( ) + "\t-\t-\t-\t" + MinString + ":" + SecString + "\t" + Rune + "\n"); } } else if(KeyString.size( ) >= 5 && KeyString.substr( 0, 4 ) == "PUI_") { string Item = string( Value.rbegin( ), Value.rend( ) ); string PlayerID = KeyString.substr( 4 ); uint32_t ID = UTIL_ToUInt32( PlayerID ); m_BufferedItemCount[ID]++; if(m_BufferedItemCount[ID]==1) m_BufferedItemOne[ID] = Item; if(m_BufferedItemCount[ID]==2) m_BufferedItemTwo[ID] = Item; if(m_BufferedItemCount[ID]==3) m_BufferedItemThree[ID] = Item; if(m_BufferedItemCount[ID]==4) m_BufferedItemFour[ID] = Item; if(m_BufferedItemCount[ID]==5) m_BufferedItemFive[ID] = Item; if(m_BufferedItemCount[ID]==6) { m_BufferedItemSix[ID] = Item; m_BufferedItemCount[ID]=0; } CGamePlayer *Player = m_Game->GetPlayerFromColour( ID ); if (Player) { m_Game->AppendLogData("4\tinv\t" + Player->GetName( ) + "\t-\t-\t-\t" + MinString + ":" + SecString + "\t" + Item + "\n"); } } else if(KeyString.size( ) >= 5 && KeyString.substr( 0, 4 ) == "DRI_") { string Item = string( Value.rbegin( ), Value.rend( ) ); string PlayerID = KeyString.substr( 4 ); uint32_t ID = UTIL_ToUInt32( PlayerID ); CGamePlayer *Player = m_Game->GetPlayerFromColour( ID ); if (Player) m_Game->AppendLogData("4\tinv\t" + Player->GetName( ) + "\t-\t-\t-\t" + MinString + ":" + SecString + "\t" + Item + "\n"); } else if(KeyString.size( ) >= 11 && KeyString.substr( 0, 11 ) == "GameStarted") { m_Game->GAME_Print( 1, MinString, SecString, "System", "", "Game started, Creeps spawned" ); Log->Debug( "[STATS"+TypePrefix+": " + m_Game->GetGameName( ) + "] Game Started, creeps spawned" ); m_Game->AppendLogData("4\tcreep_spawn\t\t-\t-\t-\t" + MinString + ":" + SecString + "\t\n"); } else if(KeyString.size( ) >= 4 && KeyString.substr( 0, 4 ) == "Mode") { string ModeString = KeyString.substr( 4 ); Log->Debug( "[STATS"+TypePrefix+": " + m_Game->GetGameName( ) + "] Mode Set: " + ModeString ); m_Game->GAME_Print( 1, MinString, SecString, "System", "", ModeString ); m_Game->AppendLogData("4\tmode\t-\t-\t-\t-\t" + MinString + ":" + SecString + "\t" + ModeString + "\n"); } else if( KeyString.size( ) >= 2 && KeyString.substr( 0, 2 ) == "SP" ) { string Spell = string( Value.rbegin( ), Value.rend( ) ); string PlayerID = KeyString.substr( 4 ); string SpellID = KeyString.substr( 2, 1 ); uint32_t ID = UTIL_ToUInt32( PlayerID ); CGamePlayer *Player = m_Game->GetPlayerFromColour( ID ); Log->Debug( "[DEBUG: Found Spell: "+Spell+ " | PlayerID: "+PlayerID+" | SpellID: "+SpellID ); if( ( ID >= 1 && ID <= 5 ) || ( ID >= 7 && ID <= 11 ) ) { if( !m_Players[ID] ) m_Players[ID] = new CDBDotAPlayer( ); m_Players[ID]->SetSpell( UTIL_ToUInt32( SpellID ) - 1, Spell ); m_Game->AppendLogData("4\tspell\t" + Player->GetName( ) + "\t" + SpellID + "\t" + Spell + "\t-\t" + MinString + ":" + SecString + "\t\n"); } } else if( KeyString.size( ) >= 2 && KeyString.substr( 0, 2 ) == "MH" ) { string Spell = string( Value.rbegin( ), Value.rend( ) ); string PlayerID = KeyString.substr( 2 ); uint32_t ID = UTIL_ToUInt32( PlayerID ); uint32_t Time = ValueInt; CGamePlayer *Player = m_Game->GetPlayerFromColour( ID ); if( Player ) { m_MaphackClickCounter[ID]++; Log->Info("[STATS"+TypePrefix+": " + m_Game->GetGameName( ) + "] Increased MaphackClickCounter for ["+Player->GetName()+"] to ["+UTIL_ToString(m_MaphackClickCounter[ID])+"]"); if(m_MaphackClickCounter[ID] >= 2) { m_Game->m_PairedSSs.push_back(PairedSS( string(), m_Game->m_OHBot->m_DB->ThreadedStatsSystem( Player->GetName(), m_Game->m_GameName, ValueInt, "mh_detection" ) ) ); m_Game->m_PairedBanAdds.push_back( PairedBanAdd( string(), m_Game->m_OHBot->m_DB->ThreadedBanAdd( Player->GetSpoofedRealm( ), Player->GetName( ), Player->GetExternalIPString( ), m_Game->m_GameName, m_Game->m_OHBot->m_BotManagerName, "Maphack", 0, "" ) ) ); Player->SetDeleteMe( true ); Player->SetLeftReason( m_Game->m_OHBot->m_Language->WasKickedByPlayer( Player->GetName() ) ); Player->SetLeftCode( PLAYERLEAVE_LOST ); m_Game->SendAllChat("Player ["+Player->GetName()+"] got removed from the game for using unallowed 3rd party tools."); } } } else if( KeyString.size( ) >= 12 && KeyString.substr( 0, 12 ) == "LoD_HeroResp" ) { string ID = KeyString.substr(13); uint32_t PlayerID = UTIL_ToUInt32(ID); string type = string( Value.rbegin( ), Value.rend( ) ); uint32_t bb = UTIL_ToUInt32( type ); CGamePlayer *Player = m_Game->GetPlayerFromColour( PlayerID ); if(Player) { Log->Info("[STATS"+TypePrefix+": " + m_Game->GetGameName( ) + "] Player ["+Player->GetName( )+"] respawned." + (bb==1?"(buyback)":"(typical)")); } } else if(KeyString.size() >= 11 && KeyString.substr(0, 11) == "LoD_DeadFor" ) { string ID = KeyString.substr(12); uint32_t PlayerID = UTIL_ToUInt32(ID); string time = string( Value.rbegin( ), Value.rend( ) ); CGamePlayer *Player = m_Game->GetPlayerFromColour( PlayerID ); if(Player) { Log->Info("[STATS"+TypePrefix+": " + m_Game->GetGameName( ) + "] Player ["+Player->GetName( )+"] is dead for the next ["+time+"] seconds."); } } else if(KeyString.size() >= 7 && KeyString.substr(0, 7) == "LoD_INV" ) { string ID = KeyString.substr(8); uint32_t PlayerID = UTIL_ToUInt32(ID); string item = string( Value.rbegin( ), Value.rend( ) ); CGamePlayer *Player = m_Game->GetPlayerFromColour( PlayerID ); if(Player) { Log->Info("[STATS"+TypePrefix+": " + m_Game->GetGameName( ) + "] Player ["+Player->GetName( )+"] got item in inventory ["+item+"]"); } } else if(KeyString.size() >= 9 && KeyString.substr(0, 9) == "LoD_HeroX" ) { string val = KeyString.substr(10); CGamePlayer *Player = m_Game->GetPlayerFromColour( ValueInt ); if(Player) { Log->Info("[STATS"+TypePrefix+": " + m_Game->GetGameName( ) + "] Player ["+Player->GetName( )+"] has a noted X-Position ["+val+"]"); } } else if(KeyString.size() >= 9 && KeyString.substr(0, 9) == "LoD_HeroY" ) { string val = KeyString.substr(10); CGamePlayer *Player = m_Game->GetPlayerFromColour( ValueInt ); if(Player) { Log->Info("[STATS"+TypePrefix+": " + m_Game->GetGameName( ) + "] Player ["+Player->GetName( )+"] has a noted Y-Position ["+val+"]"); } } } else if( DataString == "Global" ) { // these are only received at the end of the game if( KeyString == "Winner" && m_Winner != 1 && m_Winner != 2 ) { // Value 1 -> sentinel // Value 2 -> scourge m_Winner = ValueInt; if( m_Winner == 1 ) Log->Debug( "[STATS"+TypePrefix+": " + m_Game->GetGameName( ) + "] detected winner: Sentinel" ); else if( m_Winner == 2 ) Log->Debug( "[STATS"+TypePrefix+": " + m_Game->GetGameName( ) + "] detected winner: Scourge" ); else Log->Debug( "[STATS"+TypePrefix+": " + m_Game->GetGameName( ) + "] detected winner: " + UTIL_ToString( ValueInt ) ); } else if( KeyString == "m" ) m_Min = ValueInt; else if( KeyString == "s" ) m_Sec = ValueInt; if( m_Winner == 1 ) m_Game->GAME_Print( 1, MinString, SecString, "", "", "Winner detected: [Sentinel]" ); else if( m_Winner == 2 ) m_Game->GAME_Print( 1, MinString, SecString, "", "", "Winner detected: [Scourge]" ); else m_Game->GAME_Print( 1, MinString, SecString, "", "", "No winner detected, game ended in a draw" ); } else if( DataString.size( ) <= 2 && DataString.find_first_not_of( "1234567890" ) == string :: npos ) { // these are only received at the end of the game uint32_t ID = UTIL_ToUInt32( DataString ); if( ( ID >= 1 && ID <= 5 ) || ( ID >= 7 && ID <= 11 ) ) { if( !m_Players[ID] ) { m_Players[ID] = new CDBDotAPlayer( ); m_Players[ID]->SetColour( ID ); } // Key "1" -> Kills // Key "2" -> Deaths // Key "3" -> Creep Kills // Key "4" -> Creep Denies // Key "5" -> Assists // Key "6" -> Current Gold // Key "7" -> Neutral Kills // Key "8_0" -> Item 1 // Key "8_1" -> Item 2 // Key "8_2" -> Item 3 // Key "8_3" -> Item 4 // Key "8_4" -> Item 5 // Key "8_5" -> Item 6 // Key "id" -> ID (1-5 for sentinel, 6-10 for scourge, accurate after using -sp and/or -switch) if( KeyString == "1" ) { if ( m_LeaverKills[ID] >= m_Game->m_OHBot->m_MinimumLeaverKills ) { Log->Debug( "[ANTIFARM] Player with colour [" + UTIL_ToString(ID) + "] got [" + UTIL_ToString(ValueInt) + "] kills, removing [" + UTIL_ToString(m_LeaverKills[ID]) + "] leaver kills." ); m_Players[ID]->SetKills( ValueInt - m_LeaverKills[ID] ); } else m_Players[ID]->SetKills( ValueInt - m_FFKills[ID] ); if( ValueInt > 500 ) { m_Players[ID]->SetKills( 0 ); Log->Debug("[INFO] Noted an invalid statsrecord on playercolour ["+UTIL_ToString(ID)+"]. Set the kills to [0]" ); } } else if( KeyString == "2" ) { if( m_LeaverDeaths[ID] >= m_Game->m_OHBot->m_MinimumLeaverDeaths ) { if( m_DeathsByLeaver[ID] != 0 && m_Game->m_OHBot->m_DeathsByLeaverReduction ) { Log->Debug( "[ANTIFARM] Player with colour [" + UTIL_ToString(ID) + "] got [" + UTIL_ToString(ValueInt) + "] deaths, removing [" + UTIL_ToString(m_LeaverDeaths[ID]) + "] leaver deaths and ["+UTIL_ToString(m_LeaverDeaths[ID])+"] kills from leavers." ); m_Players[ID]->SetDeaths( ValueInt - m_LeaverDeaths[ID] - m_LeaverDeaths[ID]); } else { Log->Debug( "[ANTIFARM] Player with colour [" + UTIL_ToString(ID) + "] got [" + UTIL_ToString(ValueInt) + "] deaths, removing [" + UTIL_ToString(m_LeaverDeaths[ID]) + "] leaver deaths." ); m_Players[ID]->SetDeaths( ValueInt - m_LeaverDeaths[ID] ); } } else if( m_DeathsByLeaver[ID] != 0 && m_Game->m_OHBot->m_DeathsByLeaverReduction && m_LeaverDeaths[ID] < m_Game->m_OHBot->m_MinimumLeaverDeaths ) { Log->Debug( "[ANTIFARM] Player with colour [" + UTIL_ToString(ID) + "] got [" + UTIL_ToString(ValueInt) + "] deaths, removing ["+UTIL_ToString(m_DeathsByLeaver[ID])+"] kills from leavers." ); m_Players[ID]->SetDeaths( ValueInt - m_LeaverDeaths[ID] - m_LeaverDeaths[ID]); } else m_Players[ID]->SetDeaths( ValueInt ); if( ValueInt > 500 ) { m_Players[ID]->SetDeaths( 0 ); Log->Debug("[INFO] Noted an invalid statsrecord on playercolour ["+UTIL_ToString(ID)+"]. Set the deaths to [0]" ); } } else if( KeyString == "3" ) { m_Players[ID]->SetCreepKills( ValueInt ); if( ValueInt > 5000 ) { m_Players[ID]->SetCreepKills( 0 ); Log->Debug("[INFO] Noted an invalid statsrecord on playercolour ["+UTIL_ToString(ID)+"]. Set the creepkills to [0]" ); } } else if( KeyString == "4" ) { m_Players[ID]->SetCreepDenies( ValueInt ); if( ValueInt > 5000 ) { m_Players[ID]->SetCreepDenies( 0 ); Log->Debug("[INFO] Noted an invalid statsrecord on playercolour ["+UTIL_ToString(ID)+"]. Set the creepdenies to [0]" ); } } else if( KeyString == "5" ) { if( m_AssistsOnLeaverKills[ID] >= m_Game->m_OHBot->m_MinimumLeaverAssists ) { Log->Debug( "[ANTIFARM] Player with colour [" + UTIL_ToString(ID) + "] got [" + UTIL_ToString(ValueInt) + "] assists, removing [" + UTIL_ToString( m_AssistsOnLeaverKills[ID] ) + "] assist kills." ); m_Players[ID]->SetAssists( ValueInt - m_AssistsOnLeaverKills[ID] ); } else m_Players[ID]->SetAssists( ValueInt ); if( ValueInt > 500 ) { m_Players[ID]->SetAssists( 0 ); Log->Debug("[INFO] Noted an invalid statsrecord on playercolour ["+UTIL_ToString(ID)+"]. Set the assists to [0]" ); } } else if( KeyString == "6" ) m_Players[ID]->SetGold( ValueInt ); else if( KeyString == "7" ) { m_Players[ID]->SetNeutralKills( ValueInt ); if( ValueInt > 5000 ) { m_Players[ID]->SetNeutralKills( 0 ); Log->Debug("[INFO] Noted an invalid statsrecord on playercolour ["+UTIL_ToString(ID)+"]. Set the neutralkills to [0]" ); } } else if( KeyString == "8_0" ) m_Players[ID]->SetItem( 0, string( Value.rbegin( ), Value.rend( ) ) ); else if( KeyString == "8_1" ) m_Players[ID]->SetItem( 1, string( Value.rbegin( ), Value.rend( ) ) ); else if( KeyString == "8_2" ) m_Players[ID]->SetItem( 2, string( Value.rbegin( ), Value.rend( ) ) ); else if( KeyString == "8_3" ) m_Players[ID]->SetItem( 3, string( Value.rbegin( ), Value.rend( ) ) ); else if( KeyString == "8_4" ) m_Players[ID]->SetItem( 4, string( Value.rbegin( ), Value.rend( ) ) ); else if( KeyString == "8_5" ) m_Players[ID]->SetItem( 5, string( Value.rbegin( ), Value.rend( ) ) ); else if( KeyString == "9" ) { m_Players[ID]->SetHero( string( Value.rbegin( ), Value.rend( ) ) ); CGamePlayer *Player = m_Game->GetPlayerFromColour( ID ); if( Player ) m_Game->AppendLogData("4\thp\t" + Player->GetName( ) + "\t-\t" + string( Value.rbegin( ), Value.rend( ) ) + "\t-\t" + MinString + ":" + SecString + "\t-\n"); } else if( KeyString == "id" ) { // DotA sends id values from 1-10 with 1-5 being sentinel players and 6-10 being scourge players // unfortunately the actual player colours are from 1-5 and from 7-11 so we need to deal with this case here if( ValueInt >= 6 ) m_Players[ID]->SetNewColour( ValueInt + 1 ); else m_Players[ID]->SetNewColour( ValueInt ); } } } if( !m_Game->m_PlayerUpdate && m_Game->m_LogData != "" && m_Game->m_OHBot->m_LiveGames ) { unsigned int Players = 0; for( unsigned int i = 0; i < 12; ++i ) { if( m_Players[i] ) { CGamePlayer *Player = m_Game->GetPlayerFromColour( m_Players[i]->GetNewColour( ) ); if( Player) m_Game->AppendLogData("6\t" + UTIL_ToString( m_Players[i]->GetNewColour( ) ) + "\t" + m_Players[i]->GetHero( ) + "\t" + Player->GetName( ) + "\t" + UTIL_ToString( m_Players[i]->GetLevel( ) ) + "\t" + UTIL_ToString( m_Players[i]->GetKills( ) ) + "/" + UTIL_ToString( m_Players[i]->GetDeaths( ) ) + "/" + UTIL_ToString( m_Players[i]->GetAssists( ) ) + "\t" + UTIL_ToString( m_Players[i]->GetTowerKills( ) ) + "/" + UTIL_ToString( m_Players[i]->GetRaxKills( ) ) + "\n"); else m_Game->AppendLogData("6\t-\n"); ++Players; } } m_Game->m_PlayerUpdate = true; } i += 12 + Data.size( ) + Key.size( ); } else ++i; } else ++i; } else ++i; } else ++i; } // set winner if any win conditions have been met // that is actually from ENT bot sources and not complete binded into this bot // Todo: Add conditions option into the header if( m_Winner == 0 ) { if( m_KillLimit != 0 ) { if( m_SentinelKills >= m_KillLimit ) { m_Winner = 1; return true; } else if( m_ScourgeKills >= m_KillLimit ) { m_Winner = 2; return true; } } if( m_TowerLimit != 0) { if( m_SentinelTowers >= m_TowerLimit ) { m_Winner = 1; return true; } else if( m_ScourgeTowers >= m_TowerLimit ) { m_Winner = 2; return true; } } if( m_TimeLimit != 0 && m_Game->GetGameTicks( ) > m_TimeLimit * 1000 ) { // we must determine a winner at this point // or at least we must try...! if( m_SentinelKills > m_ScourgeKills ) { m_Winner = 1; return true; } else if( m_SentinelKills < m_ScourgeKills ) { m_Winner = 2; return true; } // ok, base on creep kills then? uint32_t SentinelTotal = 0; uint32_t ScourgeTotal = 0; for( unsigned int i = 0; i < 12; ++i ) { if( m_Players[i] ) { uint32_t Colour = i; if( m_Players[i]->GetNewColour( ) != 0 ) Colour = m_Players[i]->GetNewColour( ); if( Colour >= 1 && Colour <= 5 ) SentinelTotal += m_Players[i]->GetCreepKills( ) + m_Players[i]->GetCreepDenies( ); if( Colour >= 7 && Colour <= 11 ) ScourgeTotal += m_Players[i]->GetCreepKills( ) + m_Players[i]->GetCreepDenies( ); } } if( SentinelTotal > ScourgeTotal ) { m_Winner = 1; return true; } else if( SentinelTotal < ScourgeTotal ) { m_Winner = 2; return true; } } } return m_Winner != 0; } void CStatsDOTA :: Save( COHBot *GHost, COHBotDB *DB, uint32_t GameID ) { if( DB->Begin( ) ) { // since we only record the end game information it's possible we haven't recorded anything yet if the game didn't end with a tree/throne death // this will happen if all the players leave before properly finishing the game // the dotagame stats are always saved (with winner = 0 if the game didn't properly finish) // the dotaplayer stats are only saved if the game is properly finished unsigned int Players = 0; // save the dotagame GHost->m_Callables.push_back( DB->ThreadedDotAGameAdd( GameID, m_Winner, m_Min, m_Sec ) ); // check for invalid colours and duplicates // this can only happen if DotA sends us garbage in the "id" value but we should check anyway for( unsigned int i = 0; i < 12; ++i ) { if( m_Players[i] ) { uint32_t Colour = m_Players[i]->GetNewColour( ); if( !( ( Colour >= 1 && Colour <= 5 ) || ( Colour >= 7 && Colour <= 11 ) ) ) { //Log->Debug( "[STATS"+TypePrefix+": " + m_Game->GetGameName( ) + "] discarding player data, invalid colour found" ); DB->Commit( ); return; } for( unsigned int j = i + 1; j < 12; ++j ) { if( m_Players[j] && Colour == m_Players[j]->GetNewColour( ) ) { //Log->Debug( "[STATS"+TypePrefix+": " + m_Game->GetGameName( ) + "] discarding player data, duplicate colour found" ); DB->Commit( ); return; } } } } string data = ""; for( unsigned int i = 0; i < 12; ++i ) { if( m_Players[i] ) { if(m_Players[i]->GetItem( 0 ) != "" || m_Players[i]->GetItem( 1 ) != "" || m_Players[i]->GetItem( 2 ) != "" || m_Players[i]->GetItem( 3 ) != "" || m_Players[i]->GetItem( 4 ) != "" || m_Players[i]->GetItem( 5 ) != "") data += "( " + UTIL_ToString( m_Game->m_OHBot->m_BotID ) + ", " + UTIL_ToString( GameID ) + ", " + UTIL_ToString( m_Players[i]->GetColour( ) ) + ", " + UTIL_ToString( m_Players[i]->GetKills( ) ) + ", " + UTIL_ToString( m_Players[i]->GetDeaths( ) ) + ", " + UTIL_ToString( m_Players[i]->GetCreepKills( ) ) + ", " + UTIL_ToString( m_Players[i]->GetCreepDenies( ) ) + ", " + UTIL_ToString( m_Players[i]->GetAssists( ) ) + ", " + UTIL_ToString( m_Players[i]->GetGold( ) ) + ", " + UTIL_ToString( m_Players[i]->GetNeutralKills( ) ) + ", '" + m_Players[i]->GetItem( 0 ) + "', '" + m_Players[i]->GetItem( 1 ) + "', '" + m_Players[i]->GetItem( 2 ) + "', '" + m_Players[i]->GetItem( 3 ) + "', '" + m_Players[i]->GetItem( 4 ) + "', '" + m_Players[i]->GetItem( 5 ) + "', '" + m_Players[i]->GetSpell( 0 ) + "', '" + m_Players[i]->GetSpell( 1 ) + "', '" + m_Players[i]->GetSpell( 2 ) + "', '" + m_Players[i]->GetSpell( 3 ) + "', '" + m_Players[i]->GetSpell( 4 ) + "', '" + m_Players[i]->GetSpell( 5 ) + "', '" + m_Players[i]->GetHero( ) + "', " + UTIL_ToString( m_Players[i]->GetNewColour( ) ) + ", " + UTIL_ToString( m_Players[i]->GetTowerKills( ) ) + ", " + UTIL_ToString( m_Players[i]->GetRaxKills( ) ) + ", " + UTIL_ToString( m_Players[i]->GetCourierKills( ) ) + ", " + UTIL_ToString( m_Players[i]->GetLevel( ) ) + " )"; else data += "( " + UTIL_ToString( m_Game->m_OHBot->m_BotID ) + ", " + UTIL_ToString( GameID ) + ", " + UTIL_ToString( m_Players[i]->GetColour( ) ) + ", " + UTIL_ToString( m_Players[i]->GetKills( ) ) + ", " + UTIL_ToString( m_Players[i]->GetDeaths( ) ) + ", " + UTIL_ToString( m_Players[i]->GetCreepKills( ) ) + ", " + UTIL_ToString( m_Players[i]->GetCreepDenies( ) ) + ", " + UTIL_ToString( m_Players[i]->GetAssists( ) ) + ", " + UTIL_ToString( m_Players[i]->GetGold( ) ) + ", " + UTIL_ToString( m_Players[i]->GetNeutralKills( ) ) + ", '" + m_BufferedItemOne[i] + "', '" + m_BufferedItemTwo[i] + "', '" + m_BufferedItemThree[i] + "', '" + m_BufferedItemFour[i] + "', '" + m_BufferedItemFive[i] + "', '" + m_BufferedItemSix[i] + "', '" + m_Players[i]->GetSpell( 0 ) + "', '" + m_Players[i]->GetSpell( 1 ) + "', '" + m_Players[i]->GetSpell( 2 ) + "', '" + m_Players[i]->GetSpell( 3 ) + "', '" + m_Players[i]->GetSpell( 4 ) + "', '" + m_Players[i]->GetSpell( 5 ) + "', '" + m_Players[i]->GetHero( ) + "', " + UTIL_ToString( m_Players[i]->GetNewColour( ) ) + ", " + UTIL_ToString( m_Players[i]->GetTowerKills( ) ) + ", " + UTIL_ToString( m_Players[i]->GetRaxKills( ) ) + ", " + UTIL_ToString( m_Players[i]->GetCourierKills( ) ) + ", " + UTIL_ToString( m_Players[i]->GetLevel( ) ) + " )"; if(i!=11) data += ", "; ++Players; } } GHost->m_Callables.push_back( DB->ThreadedDotAPlayerAdd( GameID, data ) ); if( DB->Commit( ) ) Log->Debug( "[STATS"+TypePrefix+": " + m_Game->GetGameName( ) + "] saving " + UTIL_ToString( Players ) + " players" ); else Log->Debug( "[STATS"+TypePrefix+": " + m_Game->GetGameName( ) + "] unable to commit database transaction, data not saved" ); } else Log->Debug( "[STATS"+TypePrefix+": " + m_Game->GetGameName( ) + "] unable to begin database transaction, data not saved" ); }
65.253981
1,330
0.38989
m-unkel
4f6e330884ab0ae26b1a29d792da3fc5a9aff545
194
cpp
C++
c++/lec1_jan27/counter.cpp
vyomshm/rust-programming
2942f1684b961e15d8ab92227ba83361828e1e4d
[ "Unlicense" ]
null
null
null
c++/lec1_jan27/counter.cpp
vyomshm/rust-programming
2942f1684b961e15d8ab92227ba83361828e1e4d
[ "Unlicense" ]
null
null
null
c++/lec1_jan27/counter.cpp
vyomshm/rust-programming
2942f1684b961e15d8ab92227ba83361828e1e4d
[ "Unlicense" ]
null
null
null
#include <iostream> using namespace std; int main(int argc, char** argv) { int n = 10; cout << "Number daal : \n"; cin >> n; int i = 0; while(i <= n) { cout << i << endl; i++; } }
12.125
33
0.520619
vyomshm
4f6f00859496f3c26048d787615729a386b36663
3,777
hpp
C++
SuperReads_RNA/global-1/SuperReadsR/include/skip_list_map.hpp
wrf/stringtie
2e99dccd9a2e2ce51cfddcb3896984fa773697f7
[ "MIT" ]
255
2015-02-18T20:27:23.000Z
2022-03-18T18:55:35.000Z
SuperReads_RNA/global-1/SuperReadsR/include/skip_list_map.hpp
wrf/stringtie
2e99dccd9a2e2ce51cfddcb3896984fa773697f7
[ "MIT" ]
350
2015-03-11T14:24:06.000Z
2022-03-29T03:54:10.000Z
SuperReads_RNA/global-1/SuperReadsR/include/skip_list_map.hpp
wrf/stringtie
2e99dccd9a2e2ce51cfddcb3896984fa773697f7
[ "MIT" ]
66
2015-02-19T00:21:38.000Z
2022-03-30T09:52:23.000Z
/* SuperRead pipeline * Copyright (C) 2012 Genome group at University of Maryland. * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef __SKIP_LIST_MAP_HPP__ #define __SKIP_LIST_MAP_HPP__ #include <skip_list_set.hpp> #include <utility> template<typename Key, typename T, class Compare = std::less<Key>, int p_ = 4, typename Random = xor_random> class skip_list_map : public skip_list_set<std::pair<const Key,T>,first_comp<std::pair<const Key,T>,Compare>,p_,Random> { public: typedef Key key_type; typedef T mapped_type; typedef std::pair<const Key,T> value_type; private: typedef skip_list_set<value_type,first_comp<value_type,Compare>,p_,Random> super; public: typedef Compare key_compare; typedef first_comp<value_type,Compare> value_compare; typedef value_type& reference; typedef const value_type& const_reference; typedef typename super::iterator iterator; typedef typename super::const_iterator const_iterator; typedef typename super::size_type size_type; typedef typename super::difference_type difference_type; typedef typename super::pointer pointer; typedef typename super::const_pointer const_pointer; explicit skip_list_map(const Compare& comp = Compare(), const Random& rand = Random()) : super(value_compare(comp), rand) { } explicit skip_list_map(int max_height, const Compare& comp = Compare(), const Random& rand = Random()) : super(max_height, value_compare(comp), rand) { } template<typename InputIterator> skip_list_map(int max_height, InputIterator first, InputIterator last, const Compare& comp = Compare(), const Random& rand = Random()) : super(max_height, first, last, comp, rand) { } virtual ~skip_list_map() { } // Some methods have different interface between the map and set // data structure, in particular with respect to const-ness. Deal // with those here. std::pair<iterator, iterator> equal_range(const key_type& x) { return super::equal_range(x); } std::pair<const_iterator, const_iterator> equal_range(const key_type& x) const { return super::equal_range(x); } iterator find(const key_type& x) { return super::find(x); } const_iterator find(const key_type& x) const { return super::find(x); } iterator lower_bound(const key_type& x) { return super::lower_bound(x); } const_iterator lower_bound(const key_type& x) const { return super::lower_bound(x); } iterator upper_bound(const key_type& x) { return super::upper_bound(x); } const_iterator upper_bound(const key_type& x) const { return super::upper_bound(x); } // Extra subscript operator mapped_type& operator[](const key_type& x) { return (*((this->insert(std::make_pair(x,T()))).first)).second; } // Differences in the comparators key_compare key_comp() const { return super::value_comp.comp; } value_compare value_comp() const { return super::value_comp; } }; #endif // __SKIP_LIST_MAP_HPP__
38.540816
99
0.692348
wrf
4f703c8d19beffeacbe6d5f3a2da15a4d55eb5b5
4,371
cpp
C++
bt-maxsat/mcs.cpp
Laakeri/phylogeny-aaai
4b97a6da97fc2be0e466c2197fbd4b51c036cb5f
[ "MIT" ]
null
null
null
bt-maxsat/mcs.cpp
Laakeri/phylogeny-aaai
4b97a6da97fc2be0e466c2197fbd4b51c036cb5f
[ "MIT" ]
null
null
null
bt-maxsat/mcs.cpp
Laakeri/phylogeny-aaai
4b97a6da97fc2be0e466c2197fbd4b51c036cb5f
[ "MIT" ]
null
null
null
#include "mcs.hpp" #include <vector> #include <cassert> #include "utils.hpp" #include "graph.hpp" namespace triangulator { namespace mcs { std::vector<int> Mcs(const Graph& graph) { std::vector<int> order(graph.n()); static std::vector<int> label; static std::vector<char> rm; static std::vector<std::vector<int> > labels; utils::InitZero(label, graph.n()); utils::InitZero(rm, graph.n()); if (labels.size() < graph.n()) labels.resize(graph.n()); for (int i = 0; i < graph.n(); i++) labels[i].clear(); for (int i = 0; i < graph.n(); i++) labels[0].push_back(i); int max_label = 0; for (int it = graph.n() - 1; it >= 0; it--) { if (labels[max_label].size() == 0) { max_label--; it++; continue; } int x = labels[max_label].back(); labels[max_label].pop_back(); if (rm[x]) { it++; continue; } order[it] = x; for (int nx : graph.Neighbors(x)) { if (!rm[nx]) { label[nx]++; labels[label[nx]].push_back(nx); max_label = std::max(max_label, label[nx]); } } rm[x] = true; } return order; } McsMOutput McsM(const Graph& graph) { // these vectors are static to prevent reallocating memory every time this function is called static std::vector<int> label; static std::vector<char> rm, rc; static std::vector<std::vector<int> > reach; utils::InitZero(label, graph.n()); utils::InitZero(rm, graph.n()); utils::InitZero(rc, graph.n()); if (reach.size() < graph.n()) reach.resize(graph.n()); for (int i = 0; i < graph.n(); i++) reach[i].clear(); std::vector<Edge> fill; std::vector<int> order(graph.n()); std::vector<char> is_maximal_point(graph.n()); // TODO: maybe better variable names? int prev_label = -1; for (int it = graph.n() - 1; it >= 0; it--) { int x = 0; int max_label = 0; for (int i = 0; i < graph.n(); i++) { if (!rm[i] && label[i] >= max_label) { x = i; max_label = label[x]; } } assert(rm[x] == 0 && label[x] < graph.n()); order[it] = x; is_maximal_point[it] = (label[x] <= prev_label); prev_label = label[x]; for (int i = 0; i < graph.n(); i++) { rc[i] = false; } rc[x] = true; rm[x] = true; for (int y : graph.Neighbors(x)) { if (!rm[y]) { rc[y] = true; reach[label[y]].push_back(y); } } for (int i = 0; i < graph.n(); i++) { while (!reach[i].empty()) { int y = reach[i].back(); reach[i].pop_back(); for (int z : graph.Neighbors(y)) { if (!rm[z] && !rc[z]) { rc[z] = true; if (label[z] > i) { reach[label[z]].push_back(z); label[z]++; fill.push_back({x, z}); } else { reach[i].push_back(z); } } } } } for (int y : graph.Neighbors(x)) { if (!rm[y]) label[y]++; } } return McsMOutput({fill, order, is_maximal_point}); } std::vector<Graph> Atoms(const Graph& graph, const McsMOutput& mcs_m_output) { Graph filled_graph(graph); filled_graph.AddEdges(mcs_m_output.fill_edges); // Use static to not allocate memory every time this is called static std::vector<char> rm, block; utils::InitZero(rm, graph.n()); utils::InitZero(block, graph.n()); std::vector<Graph> atoms; for (int it = 0; it < graph.n(); it++) { int x = mcs_m_output.elimination_order[it]; if (mcs_m_output.is_maximal_clique_point[it]) { std::vector<int> cand_clique; for (int nx : filled_graph.Neighbors(x)) { if (!rm[nx]) cand_clique.push_back(nx); } if (graph.IsClique(cand_clique)) { for (int y : cand_clique) block[y] = 1; std::vector<int> component = graph.FindComponentAndMark(x, block); for (int y : cand_clique) block[y] = 0; component.insert(component.end(), cand_clique.begin(), cand_clique.end()); atoms.push_back(Graph(graph.EdgesIn(component))); } } rm[x] = true; } int found = 0; // TODO for (int x = 0; x < graph.n(); x++) { if (!block[x]) { std::vector<int> component = graph.FindComponentAndMark(x, block); atoms.push_back(Graph(graph.EdgesIn(component))); found++; } } assert(found == 1); // TODO return atoms; } } // namespace mcs } // namespace triangulator
29.14
95
0.554793
Laakeri
4f71dae7f6dd5b08d7a0290cee6a62620cf7145c
693
cpp
C++
spoj/SMPSEQ6.cpp
cosmicray001/Online_judge_Solutions-
5dc6f90d3848eb192e6edea8e8c731f41a1761dd
[ "MIT" ]
3
2018-01-08T02:52:51.000Z
2021-03-03T01:08:44.000Z
spoj/SMPSEQ6.cpp
cosmicray001/Online_judge_Solutions-
5dc6f90d3848eb192e6edea8e8c731f41a1761dd
[ "MIT" ]
null
null
null
spoj/SMPSEQ6.cpp
cosmicray001/Online_judge_Solutions-
5dc6f90d3848eb192e6edea8e8c731f41a1761dd
[ "MIT" ]
1
2020-08-13T18:07:35.000Z
2020-08-13T18:07:35.000Z
#include <bits/stdc++.h> #define le 105 using namespace std; int n[le]; int m[le]; bool fnc(int key, int ct, int len, int x){ int i = ct - x, f = ct + x; if(i < 0) i = 0; if(f >= len) f = len - 1; for(int c = i; c <= f; c++){ if(key == m[c]) return 1; } return 0; } int main(){ int len, x; scanf("%d %d", &len, &x); for(int i = 0; i < len; scanf("%d", &n[i]), i++); for(int i = 0; i < len; scanf("%d", &m[i]), i++); bool f = false; for(int i = 0; i < len; i++){ if(fnc(n[i], i, len, x)){ if(f) printf(" "); f = true; printf("%d ", i + 1); } } printf("\n"); return 0; }
21
53
0.408369
cosmicray001
4f72bd378c6ba8febc3482cee9f6fca0f28ebc22
3,177
hpp
C++
ngraph/core/include/openvino/op/roi_align.hpp
lsc31/openvino
c00b0b6ae402c781a19cacf966fd4ac379ec5370
[ "Apache-2.0" ]
1
2021-07-14T07:20:24.000Z
2021-07-14T07:20:24.000Z
ngraph/core/include/openvino/op/roi_align.hpp
lsc31/openvino
c00b0b6ae402c781a19cacf966fd4ac379ec5370
[ "Apache-2.0" ]
35
2020-11-13T16:32:58.000Z
2022-03-12T15:05:16.000Z
ngraph/core/include/openvino/op/roi_align.hpp
sungeunk/openvino
c55291d62fced468570d15594738a7db6ef31c9d
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #pragma once #include "openvino/op/op.hpp" namespace ov { namespace op { namespace v3 { class OPENVINO_API ROIAlign : public Op { public: OPENVINO_OP("ROIAlign", "opset3", op::Op, 3); BWDCMP_RTTI_DECLARATION; enum class PoolingMode { AVG, MAX }; ROIAlign() = default; /// \brief Constructs a ROIAlign node matching the ONNX ROIAlign specification /// /// \param input Input feature map {N, C, H, W} /// \param rois Regions of interest to pool over /// \param batch_indices Indices of images in the batch matching /// the number or ROIs /// \param pooled_h Height of the ROI output features /// \param pooled_w Width of the ROI output features /// \param sampling_ratio Number of sampling points used to compute /// an output element /// \param spatial_scale Spatial scale factor used to translate ROI coordinates /// \param mode Method of pooling - 'avg' or 'max' ROIAlign(const Output<Node>& input, const Output<Node>& rois, const Output<Node>& batch_indices, const int pooled_h, const int pooled_w, const int sampling_ratio, const float spatial_scale, const std::string& mode); ROIAlign(const Output<Node>& input, const Output<Node>& rois, const Output<Node>& batch_indices, const int pooled_h, const int pooled_w, const int sampling_ratio, const float spatial_scale, const PoolingMode mode); void validate_and_infer_types() override; bool visit_attributes(AttributeVisitor& visitor) override; std::shared_ptr<Node> clone_with_new_inputs(const OutputVector& new_args) const override; int get_pooled_h() const { return m_pooled_h; } int get_pooled_w() const { return m_pooled_w; } int get_sampling_ratio() const { return m_sampling_ratio; } float get_spatial_scale() const { return m_spatial_scale; } PoolingMode get_mode() const { return m_mode; } bool evaluate(const HostTensorVector& outputs, const HostTensorVector& inputs) const override; bool has_evaluate() const override; private: PoolingMode mode_from_string(const std::string& mode) const; private: int m_pooled_h; int m_pooled_w; int m_sampling_ratio; float m_spatial_scale; PoolingMode m_mode; }; } // namespace v3 } // namespace op std::ostream& operator<<(std::ostream& s, const op::v3::ROIAlign::PoolingMode& mode); template <> class OPENVINO_API AttributeAdapter<op::v3::ROIAlign::PoolingMode> : public EnumAttributeAdapterBase<op::v3::ROIAlign::PoolingMode> { public: AttributeAdapter(op::v3::ROIAlign::PoolingMode& value) : EnumAttributeAdapterBase<op::v3::ROIAlign::PoolingMode>(value) {} OPENVINO_RTTI("AttributeAdapter<ov::op::v3::ROIAlign::PoolingMode>"); BWDCMP_RTTI_DECLARATION; }; } // namespace ov
32.418367
98
0.647466
lsc31
4f7342d0f47f28890fe3f1f7d842b32032c21894
9,005
hpp
C++
src/lua_api.hpp
Dmitry450/sfml-lua-game
43b5c355440e913a4405fa3f44d50c4968ebe9c9
[ "Unlicense" ]
null
null
null
src/lua_api.hpp
Dmitry450/sfml-lua-game
43b5c355440e913a4405fa3f44d50c4968ebe9c9
[ "Unlicense" ]
null
null
null
src/lua_api.hpp
Dmitry450/sfml-lua-game
43b5c355440e913a4405fa3f44d50c4968ebe9c9
[ "Unlicense" ]
null
null
null
#ifndef LUA_API_HPP #define LUA_API_HPP #include <lua.hpp> #include <iostream> #include <SFML/Graphics/Rect.hpp> #include <SFML/System/Vector2.hpp> #include <vector> #include "entitymgr.hpp" #include "entity.hpp" #include "world.hpp" #include "resource_holder.hpp" #include "animation.hpp" #include "player.hpp" // Resources required for API // There should be better way to access them... extern World *world; extern EntityManager *entmgr; extern TextureHolder *textures; extern Player *player; // TODO - more players? // Utility functions // Checks argument count and raises error if rargc != lua_gettop() inline void check_lua_argc(lua_State *L, int rargc) { if (lua_gettop(L) != rargc) { luaL_error(L, "expected %I arguments", rargc); } } // Same as above but there can be rargc1 or rargc2 arguments. // If arguments count == rargc2, returns true, otherwise false inline bool check_lua_argc2(lua_State *L, int rargc1, int rargc2) { int argc = lua_gettop(L); if (argc != rargc1 && argc != rargc2) { luaL_error(L, "expected %I or %I arguments", rargc1, rargc2); } return argc == rargc2; } // Gets entity from manager, raises error if unable to inline Entity *get_entity(lua_State *L, int id) { Entity *entity = entmgr->getByID((entityid)id); if (entity == nullptr) { luaL_error(L, "no entity with id %I found", id); } return entity; } // Checks is resources for api aviable, raises error if not inline void check_resources(lua_State *L) { if (world == nullptr || entmgr == nullptr || textures == nullptr || player == nullptr) { luaL_error(L, "resources required for API are unaviable"); } } // Print error occured in pcall inline void printerr(lua_State *L) { const char *msg = lua_tostring(L, -1); std::cout<<msg<<'\n'; lua_pop(L, 1); } // Construct animation from table on top of stack inline void construct_animation(lua_State *L, std::string &name, AnimationManager &dst) { float time_per_frame; int x, y, width, height, frames; lua_pushstring(L, "time_per_frame"); // Push key lua_gettable(L, -2); // Pop key, push value[key] time_per_frame = luaL_checknumber(L, -1); lua_pop(L, 1); // Pop value[key] lua_pushstring(L, "x"); // Push key lua_gettable(L, -2); // Pop key, push value[key] x = luaL_checkinteger(L, -1); lua_pop(L, 1); // Pop value[key] lua_pushstring(L, "y"); // Push key lua_gettable(L, -2); // Pop key, push value[key] y = luaL_checkinteger(L, -1); lua_pop(L, 1); // Pop value[key] lua_pushstring(L, "width"); // Push key lua_gettable(L, -2); // Pop key, push value[key] width = luaL_checkinteger(L, -1); lua_pop(L, 1); // Pop value[key] lua_pushstring(L, "height"); // Push key lua_gettable(L, -2); // Pop key, push value[key] height = luaL_checkinteger(L, -1); lua_pop(L, 1); // Pop value[key] lua_pushstring(L, "frames"); // Push key lua_gettable(L, -2); // Pop key, push value[key] frames = luaL_checkinteger(L, -1); lua_pop(L, 1); // Pop value[key] sf::IntRect frame(x, y, width, height); Animation *anim = nullptr; std::vector<sf::IntRect> frames_list; for (int i = 0; i < frames; i++) { frames_list.push_back(sf::IntRect(frame)); frame.left += width; } anim = new Animation(time_per_frame, frames_list); dst.addAnimation(name, anim); } // API void api_init(lua_State *L); // Returns is script was loaded without errors bool run_script(lua_State *L, const char *filename); void run_update_hooks(lua_State *L, float dtime); // World interaction interface // int world_getAt(int, int) // Returns block at given position int world_getAt(lua_State *L); // void world_setAt(int, int, int) // Sets block at given position. First two arguments are x and y coords, last one // is block id FROM 0 TO 255 int world_setAt(lua_State *L); // void world_setTilemap(string) // Sets tilemap for world blocks. Be sure you called resources_loadTexture first int world_setTilemap(lua_State *L); // void world_setBlockFrame(int, int, int) // Sets tilemap position for block. Note that you dont need to multiply it by BLOCK_SIZE. // First argument is block id, FROM 2 TO 255 (excluding air and OOB, since they are not drawn) // last two are x and y position. int world_setBlockFrame(lua_State *L); // Entities interface // int entity_newEntity() // Tries to create new entity. Returns entity id. 0 means fail int entity_newEntity(lua_State *L); // bool entity_exists(int) // Returns is entity in EntityManager. First argument is entity id int entity_exists(lua_State *L); // void entity_setTexture(int, string) // Sets texture of an entity. First argument is entity id, second // is texture name. Texture taken from TextureHolder, so be sure to preload it int entity_setTexture(lua_State *L); // void entity_setAnimationsManager(int, AnimationsMap) // Sets entity's animation manager. First argument is entity id // second is a table where key is animation name and value is // Animation. // Animation is a table with keys: // time_per_frame - float number // x, y, width, height - int params of the first frame // frames - int count of HORYZONTAL frames // mirror - boolean, means would be created mirrored copy of the animation or not int entity_setAnimationsManager(lua_State *L); // void entity_addAnimation(int, string, Animation) // Adds animation to entity. First argument is entity id, second is animation name, // third is Animation (see entity_setAnimationsManager for Animation specification) int entity_addAnimation(lua_State *L); // void entity_mirror(int[, bool]) // Mirrors entity's sprite. First argument is entity id. // If second argument given, set mirror state instead of toggle int entity_mirror(lua_State *L); // void entity_setAnimation(int, string[, bool]) // Select entity's animation. First argument is an entity id, second is animation name. // Do nothing if there is no such animation. // Optional third argument means would be used mirrored animation or not. If there is no // mirrored animation, this argument ignored int entity_setAnimation(lua_State *L); // void entity_setPosition(int, float, float) // Set entity's position. First argument is entity id, other two are x and y coords int entity_setPosition(lua_State *L); // Vector2f entity_getPosition(int) // Returns entity's x and y position in table Vector2f. First argument is entity id int entity_getPosition(lua_State *L); // void entity_setSize(int, float, float) // Set entity's size. First argument is entity id, other two are width and height int entity_setSize(lua_State *L); // Size entity_getSize(int) // Returns entitys width and height in table Size. First argument is entity id int entity_getSize(lua_State *L); // void entity_setVelocity(int, float, float) // Set entity's velocity. First argument is entity id, other two are x and y velocity int entity_setVelocity(lua_State *L); // Vector2f entity_getVelocity(int) // Returns entity's x and y velocity in table Vector2f. First argument is entity id int entity_getVelocity(lua_State *L); // CollisionInfo entity_getCollisionInfo(int) // Returns world collision info for entity. First argument is entity id. // CollisionInfo is a table with keys: // blockl, blockr, blocku, blockd - booleans, for left, right, up and down blocks // that collide with entity int entity_getCollisionInfo(lua_State *L); // intlist entity_findCollisions(int) // Returns list of entity ids that collide with specified entity int entity_findCollisions(lua_State *L); // intlist entity_findCollisionsWith(int, intlist) // Same as above, but finds collisions only with entities specified in second argument int entity_findCollisionsWith(lua_State *L); // bool entity_isCollide(int, int) // Returns is two entity collide. int entity_isCollide(lua_State *L); // void entity_delEntity(int) // Removes entity. First argument is entity id int entity_delEntity(lua_State *L); // Player interface // int player_getPlayerEntity() // Returns entity id of players entity. If player has no entity, 0 returned int player_getEntity(lua_State *L); // KeyPresses player_getPlayerKeys() // Returns key presses of player. // KeyPresses is a table with keys: // left, right, up, down, jump - booleans, meaning is player presses that keys or not int player_getKeys(lua_State *L); // Mouse player_getPlayerMouse() // Returns players mouse state. // Mouse is a table with keys: // lmb, rmb - booleans, meaning is player presses left or right mouse buttons // x, y - floats, mouse position in world (mouse position in window + camera position) int player_getMouse(lua_State *L); // Resources interface // void resources_loadTexture(string) // Loads a texture from given path int resources_loadTexture(lua_State *L); #endif
30.117057
94
0.708828
Dmitry450
4f740d2dea703267eb20f1a1586544eafacac4f6
46,492
cc
C++
src/kudu/consensus/raft_consensus_quorum-test.cc
SuckShit/kudu
ec5d1e29e019d4e5274231ae57cc14e7a4d52a72
[ "Apache-2.0" ]
6
2020-05-12T02:18:48.000Z
2021-04-15T20:39:21.000Z
src/kudu/consensus/raft_consensus_quorum-test.cc
toddlipcon/kudu
e5ee5e08c68c9c661ce676ad629b4ad3abf57def
[ "Apache-2.0" ]
null
null
null
src/kudu/consensus/raft_consensus_quorum-test.cc
toddlipcon/kudu
e5ee5e08c68c9c661ce676ad629b4ad3abf57def
[ "Apache-2.0" ]
null
null
null
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include <algorithm> #include <cstdint> #include <functional> #include <memory> #include <ostream> #include <string> #include <unordered_map> #include <unordered_set> #include <vector> #include <boost/optional/optional.hpp> #include <gflags/gflags_declare.h> #include <glog/logging.h> #include <gtest/gtest.h> #include "kudu/clock/logical_clock.h" #include "kudu/common/common.pb.h" #include "kudu/common/schema.h" #include "kudu/common/timestamp.h" #include "kudu/common/wire_protocol-test-util.h" #include "kudu/common/wire_protocol.pb.h" #include "kudu/consensus/consensus-test-util.h" #include "kudu/consensus/consensus.pb.h" #include "kudu/consensus/consensus_meta.h" #include "kudu/consensus/consensus_meta_manager.h" #include "kudu/consensus/consensus_peers.h" #include "kudu/consensus/consensus_queue.h" #include "kudu/consensus/log.h" #include "kudu/consensus/log.pb.h" #include "kudu/consensus/log_index.h" #include "kudu/consensus/log_reader.h" #include "kudu/consensus/log_util.h" #include "kudu/consensus/metadata.pb.h" #include "kudu/consensus/opid.pb.h" #include "kudu/consensus/opid_util.h" #include "kudu/consensus/quorum_util.h" #include "kudu/consensus/raft_consensus.h" #include "kudu/consensus/time_manager.h" #include "kudu/fs/fs_manager.h" #include "kudu/gutil/casts.h" #include "kudu/gutil/map-util.h" #include "kudu/gutil/ref_counted.h" #include "kudu/gutil/strings/strcat.h" #include "kudu/gutil/strings/substitute.h" #include "kudu/tablet/metadata.pb.h" #include "kudu/util/async_util.h" #include "kudu/util/mem_tracker.h" #include "kudu/util/metrics.h" #include "kudu/util/monotime.h" #include "kudu/util/pb_util.h" #include "kudu/util/status.h" #include "kudu/util/status_callback.h" #include "kudu/util/test_macros.h" #include "kudu/util/test_util.h" #include "kudu/util/threadpool.h" DECLARE_int32(raft_heartbeat_interval_ms); DECLARE_bool(enable_leader_failure_detection); METRIC_DECLARE_entity(tablet); using kudu::log::Log; using kudu::log::LogEntryPB; using kudu::log::LogOptions; using kudu::log::LogReader; using kudu::pb_util::SecureShortDebugString; using std::shared_ptr; using std::string; using std::unique_ptr; using std::vector; using strings::Substitute; using strings::SubstituteAndAppend; namespace kudu { namespace consensus { const char* kTestTablet = "TestTablet"; void DoNothing(const string& s) { } Status WaitUntilLeaderForTests(RaftConsensus* raft) { MonoTime deadline = MonoTime::Now() + MonoDelta::FromSeconds(15); while (MonoTime::Now() < deadline) { if (raft->role() == RaftPeerPB::LEADER) { return Status::OK(); } SleepFor(MonoDelta::FromMilliseconds(10)); } return Status::TimedOut("Timed out waiting to become leader"); } // Test suite for tests that focus on multiple peer interaction, but // without integrating with other components, such as transactions. class RaftConsensusQuorumTest : public KuduTest { public: typedef vector<unique_ptr<LogEntryPB>> LogEntries; RaftConsensusQuorumTest() : clock_(Timestamp(1)), metric_entity_(METRIC_ENTITY_tablet.Instantiate(&metric_registry_, "raft-test")), schema_(GetSimpleTestSchema()) { options_.tablet_id = kTestTablet; FLAGS_enable_leader_failure_detection = false; CHECK_OK(ThreadPoolBuilder("raft").Build(&raft_pool_)); } // Builds an initial configuration of 'num' elements. // All of the peers start as followers. void BuildInitialRaftConfigPB(int num) { config_ = BuildRaftConfigPB(num); config_.set_opid_index(kInvalidOpIdIndex); peers_.reset(new TestPeerMapManager(config_)); } Status BuildFsManagersAndLogs(int num) { // Build the fsmanagers and logs for (int i = 0; i < num; i++) { shared_ptr<MemTracker> parent_mem_tracker = MemTracker::CreateTracker(-1, Substitute("peer-$0", i)); parent_mem_trackers_.push_back(parent_mem_tracker); string test_path = GetTestPath(Substitute("peer-$0-root", i)); FsManagerOpts opts; opts.parent_mem_tracker = parent_mem_tracker; opts.wal_root = test_path; opts.data_roots = { test_path }; unique_ptr<FsManager> fs_manager(new FsManager(env_, opts)); RETURN_NOT_OK(fs_manager->CreateInitialFileSystemLayout()); RETURN_NOT_OK(fs_manager->Open()); scoped_refptr<Log> log; RETURN_NOT_OK(Log::Open(LogOptions(), fs_manager.get(), /*file_cache*/nullptr, kTestTablet, schema_, 0, // schema_version /*metric_entity*/nullptr, &log)); logs_.emplace_back(std::move(log)); fs_managers_.push_back(std::move(fs_manager)); } return Status::OK(); } // Builds a configuration of 'num' voters. RaftConfigPB BuildRaftConfigPB(int num) { RaftConfigPB raft_config; for (int i = 0; i < num; i++) { RaftPeerPB* peer_pb = raft_config.add_peers(); peer_pb->set_member_type(RaftPeerPB::VOTER); peer_pb->set_permanent_uuid(fs_managers_[i]->uuid()); HostPortPB* hp = peer_pb->mutable_last_known_addr(); hp->set_host(Substitute("peer-$0.fake-domain-for-tests", i)); hp->set_port(0); } return raft_config; } Status BuildPeers() { CHECK_EQ(config_.peers_size(), fs_managers_.size()); for (int i = 0; i < config_.peers_size(); i++) { FsManager* fs = fs_managers_[i].get(); scoped_refptr<ConsensusMetadataManager> cmeta_manager( new ConsensusMetadataManager(fs)); RETURN_NOT_OK(cmeta_manager->Create(kTestTablet, config_, kMinimumTerm)); RaftPeerPB* local_peer_pb; RETURN_NOT_OK(GetRaftConfigMember(&config_, fs->uuid(), &local_peer_pb)); shared_ptr<RaftConsensus> peer; ServerContext ctx({ /*quiescing*/nullptr, /*num_leaders*/nullptr, raft_pool_.get() }); RETURN_NOT_OK(RaftConsensus::Create(options_, config_.peers(i), std::move(cmeta_manager), std::move(ctx), &peer)); peers_->AddPeer(config_.peers(i).permanent_uuid(), peer); } return Status::OK(); } Status StartPeers() { ConsensusBootstrapInfo boot_info; TestPeerMap all_peers = peers_->GetPeerMapCopy(); for (int i = 0; i < config_.peers_size(); i++) { shared_ptr<RaftConsensus> peer; RETURN_NOT_OK(peers_->GetPeerByIdx(i, &peer)); unique_ptr<PeerProxyFactory> proxy_factory( new LocalTestPeerProxyFactory(peers_.get())); unique_ptr<TimeManager> time_manager( new TimeManager(&clock_, Timestamp::kMin)); unique_ptr<TestTransactionFactory> txn_factory( new TestTransactionFactory(logs_[i].get())); txn_factory->SetConsensus(peer.get()); txn_factories_.emplace_back(std::move(txn_factory)); RETURN_NOT_OK(peer->Start( boot_info, std::move(proxy_factory), logs_[i], std::move(time_manager), txn_factories_.back().get(), metric_entity_, &DoNothing)); } return Status::OK(); } Status BuildConfig(int num) { RETURN_NOT_OK(BuildFsManagersAndLogs(num)); BuildInitialRaftConfigPB(num); RETURN_NOT_OK(BuildPeers()); return Status::OK(); } Status BuildAndStartConfig(int num) { RETURN_NOT_OK(BuildConfig(num)); RETURN_NOT_OK(StartPeers()); // Automatically elect the last node in the list. const int kLeaderIdx = num - 1; shared_ptr<RaftConsensus> leader; RETURN_NOT_OK(peers_->GetPeerByIdx(kLeaderIdx, &leader)); RETURN_NOT_OK(leader->EmulateElectionForTests()); return Status::OK(); } LocalTestPeerProxy* GetLeaderProxyToPeer(int peer_idx, int leader_idx) { shared_ptr<RaftConsensus> follower; CHECK_OK(peers_->GetPeerByIdx(peer_idx, &follower)); shared_ptr<RaftConsensus> leader; CHECK_OK(peers_->GetPeerByIdx(leader_idx, &leader)); for (LocalTestPeerProxy* proxy : down_cast<LocalTestPeerProxyFactory*>( leader->peer_proxy_factory_.get())->GetProxies()) { if (proxy->GetTarget() == follower->peer_uuid()) { return proxy; } } CHECK(false) << "Proxy not found"; return nullptr; } Status AppendDummyMessage(int peer_idx, scoped_refptr<ConsensusRound>* round) { unique_ptr<ReplicateMsg> msg(new ReplicateMsg()); msg->set_op_type(NO_OP); msg->mutable_noop_request(); msg->set_timestamp(clock_.Now().ToUint64()); shared_ptr<RaftConsensus> peer; CHECK_OK(peers_->GetPeerByIdx(peer_idx, &peer)); // Use a latch in place of a Transaction callback. unique_ptr<Synchronizer> sync(new Synchronizer()); *round = peer->NewRound(std::move(msg), sync->AsStatusCallback()); EmplaceOrDie(&syncs_, round->get(), std::move(sync)); RETURN_NOT_OK_PREPEND(peer->Replicate(round->get()), Substitute("Unable to replicate to peer $0", peer_idx)); return Status::OK(); } static void FireSharedSynchronizer(const shared_ptr<Synchronizer>& sync, const Status& s) { sync->StatusCB(s); } Status CommitDummyMessage(int peer_idx, ConsensusRound* round, shared_ptr<Synchronizer>* commit_sync = nullptr) { StatusCallback commit_callback; if (commit_sync != nullptr) { shared_ptr<Synchronizer> sync(std::make_shared<Synchronizer>()); commit_callback = [sync](const Status& s) { FireSharedSynchronizer(sync, s); }; *commit_sync = std::move(sync); } else { commit_callback = &DoNothingStatusCB; } unique_ptr<CommitMsg> msg(new CommitMsg()); msg->set_op_type(NO_OP); msg->mutable_commited_op_id()->CopyFrom(round->id()); CHECK_OK(logs_[peer_idx]->AsyncAppendCommit(std::move(msg), commit_callback)); return Status::OK(); } Status WaitForReplicate(ConsensusRound* round) { return FindOrDie(syncs_, round)->Wait(); } Status TimedWaitForReplicate(ConsensusRound* round, const MonoDelta& delta) { return FindOrDie(syncs_, round)->WaitFor(delta); } void WaitForReplicateIfNotAlreadyPresent(const OpId& to_wait_for, int peer_idx) { shared_ptr<RaftConsensus> peer; CHECK_OK(peers_->GetPeerByIdx(peer_idx, &peer)); while (true) { if (OpIdCompare(peer->queue_->GetLastOpIdInLog(), to_wait_for) >= 0) { return; } SleepFor(MonoDelta::FromMilliseconds(1)); } } // Waits for an operation to be (database) committed in the replica at index // 'peer_idx'. If the operation was already committed this returns immediately. void WaitForCommitIfNotAlreadyPresent(int64_t to_wait_for, int peer_idx, int leader_idx) { MonoDelta timeout(MonoDelta::FromSeconds(10)); MonoTime start(MonoTime::Now()); shared_ptr<RaftConsensus> peer; CHECK_OK(peers_->GetPeerByIdx(peer_idx, &peer)); int backoff_exp = 0; const int kMaxBackoffExp = 8; OpId committed = MinimumOpId(); while (true) { boost::optional<OpId> opt_committed = peer->GetLastOpId(COMMITTED_OPID); if (opt_committed) { committed = *opt_committed; if (committed.index() >= to_wait_for) { return; } } if (MonoTime::Now() > (start + timeout)) { break; } SleepFor(MonoDelta::FromMilliseconds(1LL << backoff_exp)); backoff_exp = std::min(backoff_exp + 1, kMaxBackoffExp); } LOG(ERROR) << "Max timeout reached (" << timeout.ToString() << ") while waiting for commit of " << "op " << to_wait_for << " on replica. Last committed op on replica: " << committed.index() << ". Dumping state and quitting."; vector<string> lines; shared_ptr<RaftConsensus> leader; CHECK_OK(peers_->GetPeerByIdx(leader_idx, &leader)); for (const string& line : lines) { LOG(ERROR) << line; } // Gather the replica and leader operations for printing LogEntries replica_ops; GatherLogEntries(peer_idx, logs_[peer_idx], &replica_ops); LogEntries leader_ops; GatherLogEntries(leader_idx, logs_[leader_idx], &leader_ops); SCOPED_TRACE(PrintOnError(replica_ops, Substitute("local peer ($0)", peer->peer_uuid()))); SCOPED_TRACE(PrintOnError(leader_ops, Substitute("leader (peer-$0)", leader_idx))); FAIL() << "Replica did not commit."; } // Used in ReplicateSequenceOfMessages() to specify whether // we should wait for all replicas to have replicated the // sequence or just a majority. enum ReplicateWaitMode { WAIT_FOR_ALL_REPLICAS, WAIT_FOR_MAJORITY }; // Used in ReplicateSequenceOfMessages() to specify whether // we should also commit the messages in the sequence enum CommitMode { DONT_COMMIT, COMMIT_ONE_BY_ONE }; // Replicates a sequence of messages to the peer passed as leader. // Optionally waits for the messages to be replicated to followers. // 'last_op_id' is set to the id of the last replicated operation. // The operations are only committed if 'commit_one_by_one' is true. void ReplicateSequenceOfMessages(int seq_size, int leader_idx, ReplicateWaitMode wait_mode, CommitMode commit_mode, OpId* last_op_id, vector<scoped_refptr<ConsensusRound>>* rounds, shared_ptr<Synchronizer>* commit_sync = nullptr) { for (int i = 0; i < seq_size; i++) { scoped_refptr<ConsensusRound> round; ASSERT_OK(AppendDummyMessage(leader_idx, &round)); ASSERT_OK(WaitForReplicate(round.get())); last_op_id->CopyFrom(round->id()); if (commit_mode == COMMIT_ONE_BY_ONE) { CommitDummyMessage(leader_idx, round.get(), commit_sync); } rounds->push_back(round); } if (wait_mode == WAIT_FOR_ALL_REPLICAS) { shared_ptr<RaftConsensus> leader; CHECK_OK(peers_->GetPeerByIdx(leader_idx, &leader)); TestPeerMap all_peers = peers_->GetPeerMapCopy(); int i = 0; for (const TestPeerMap::value_type& entry : all_peers) { if (entry.second->peer_uuid() != leader->peer_uuid()) { WaitForReplicateIfNotAlreadyPresent(*last_op_id, i); } i++; } } } void GatherLogEntries(int idx, const scoped_refptr<Log>& log, LogEntries* entries) { ASSERT_OK(log->WaitUntilAllFlushed()); log->Close(); shared_ptr<LogReader> log_reader; ASSERT_OK(log::LogReader::Open(fs_managers_[idx].get(), /*index*/nullptr, kTestTablet, metric_entity_.get(), /*file_cache*/nullptr, &log_reader)); log::SegmentSequence segments; log_reader->GetSegmentsSnapshot(&segments); LogEntries ret; for (const log::SegmentSequence::value_type& entry : segments) { ASSERT_OK(entry->ReadEntries(&ret)); } *entries = std::move(ret); } // Verifies that the replica's log match the leader's. This deletes the // peers (so we're sure that no further writes occur) and closes the logs // so it must be the very last thing to run, in a test. void VerifyLogs(int leader_idx, int first_replica_idx, int last_replica_idx) { // Wait for in-flight transactions to be done. We're destroying the // peers next and leader transactions won't be able to commit anymore. for (const auto& factory : txn_factories_) { factory->WaitDone(); } // Shut down all the peers. TestPeerMap all_peers = peers_->GetPeerMapCopy(); for (const TestPeerMap::value_type& entry : all_peers) { entry.second->Shutdown(); } LogEntries leader_entries; GatherLogEntries(leader_idx, logs_[leader_idx], &leader_entries); shared_ptr<RaftConsensus> leader; CHECK_OK(peers_->GetPeerByIdx(leader_idx, &leader)); for (int replica_idx = first_replica_idx; replica_idx < last_replica_idx; replica_idx++) { LogEntries replica_entries; GatherLogEntries(replica_idx, logs_[replica_idx], &replica_entries); shared_ptr<RaftConsensus> replica; CHECK_OK(peers_->GetPeerByIdx(replica_idx, &replica)); VerifyReplica(leader_entries, replica_entries, leader->peer_uuid(), replica->peer_uuid()); } } void ExtractReplicateIds(const LogEntries& entries, vector<OpId>* ids) { ids->reserve(entries.size() / 2); for (const auto& entry : entries) { if (entry->has_replicate()) { ids->push_back(entry->replicate().id()); } } } void VerifyReplicateOrderMatches(const LogEntries& leader_entries, const LogEntries& replica_entries) { vector<OpId> leader_ids, replica_ids; ExtractReplicateIds(leader_entries, &leader_ids); ExtractReplicateIds(replica_entries, &replica_ids); ASSERT_EQ(leader_ids.size(), replica_ids.size()); for (int i = 0; i < leader_ids.size(); i++) { ASSERT_EQ(SecureShortDebugString(leader_ids[i]), SecureShortDebugString(replica_ids[i])); } } void VerifyNoCommitsBeforeReplicates(const LogEntries& entries) { std::unordered_set<OpId, OpIdHashFunctor, OpIdEqualsFunctor> replication_ops; for (const auto& entry : entries) { if (entry->has_replicate()) { ASSERT_TRUE(InsertIfNotPresent(&replication_ops, entry->replicate().id())) << "REPLICATE op id showed up twice: " << SecureShortDebugString(*entry); } else if (entry->has_commit()) { ASSERT_EQ(1, replication_ops.erase(entry->commit().commited_op_id())) << "COMMIT came before associated REPLICATE: " << SecureShortDebugString(*entry); } } } void VerifyReplica(const LogEntries& leader_entries, const LogEntries& replica_entries, const string& leader_name, const string& replica_name) { SCOPED_TRACE(PrintOnError(leader_entries, Substitute("Leader: $0", leader_name))); SCOPED_TRACE(PrintOnError(replica_entries, Substitute("Replica: $0", replica_name))); // Check that the REPLICATE messages come in the same order on both nodes. VerifyReplicateOrderMatches(leader_entries, replica_entries); // Check that no COMMIT precedes its related REPLICATE on both the replica // and leader. VerifyNoCommitsBeforeReplicates(replica_entries); VerifyNoCommitsBeforeReplicates(leader_entries); } string PrintOnError(const LogEntries& replica_entries, const string& replica_id) { string ret = ""; SubstituteAndAppend(&ret, "$1 log entries for replica $0:\n", replica_id, replica_entries.size()); for (const auto& replica_entry : replica_entries) { StrAppend(&ret, "Replica log entry: ", SecureShortDebugString(*replica_entry), "\n"); } return ret; } // Read the ConsensusMetadata for the given peer from disk. scoped_refptr<ConsensusMetadata> ReadConsensusMetadataFromDisk(int peer_index) { FsManager* fs = fs_managers_[peer_index].get(); scoped_refptr<ConsensusMetadata> cmeta; CHECK_OK(ConsensusMetadata::Load(fs, kTestTablet, fs->uuid(), &cmeta)); return cmeta; } // Assert that the durable term == term and that the peer that got the vote == voted_for. void AssertDurableTermAndVote(int peer_index, int64_t term, const std::string& voted_for) { scoped_refptr<ConsensusMetadata> cmeta = ReadConsensusMetadataFromDisk(peer_index); ASSERT_EQ(term, cmeta->current_term()); ASSERT_EQ(voted_for, cmeta->voted_for()); } // Assert that the durable term == term and that the peer has not yet voted. void AssertDurableTermWithoutVote(int peer_index, int64_t term) { scoped_refptr<ConsensusMetadata> cmeta = ReadConsensusMetadataFromDisk(peer_index); ASSERT_EQ(term, cmeta->current_term()); ASSERT_FALSE(cmeta->has_voted_for()); } ~RaftConsensusQuorumTest() { peers_->Clear(); } protected: ConsensusOptions options_; RaftConfigPB config_; OpId initial_id_; vector<shared_ptr<MemTracker>> parent_mem_trackers_; vector<unique_ptr<FsManager>> fs_managers_; vector<scoped_refptr<Log> > logs_; unique_ptr<ThreadPool> raft_pool_; unique_ptr<TestPeerMapManager> peers_; vector<unique_ptr<TestTransactionFactory>> txn_factories_; clock::LogicalClock clock_; MetricRegistry metric_registry_; scoped_refptr<MetricEntity> metric_entity_; const Schema schema_; std::unordered_map<ConsensusRound*, unique_ptr<Synchronizer>> syncs_; }; // Tests Replicate/Commit a single message through the leader. TEST_F(RaftConsensusQuorumTest, TestFollowersReplicateAndCommitMessage) { // Constants with the indexes of peers with certain roles, // since peers don't change roles in this test. const int kFollower0Idx = 0; const int kFollower1Idx = 1; const int kLeaderIdx = 2; ASSERT_OK(BuildAndStartConfig(3)); OpId last_op_id; vector<scoped_refptr<ConsensusRound>> rounds; shared_ptr<Synchronizer> commit_sync; NO_FATALS(ReplicateSequenceOfMessages( 1, kLeaderIdx, WAIT_FOR_ALL_REPLICAS, DONT_COMMIT, &last_op_id, &rounds, &commit_sync)); // Commit the operation ASSERT_OK(CommitDummyMessage(kLeaderIdx, rounds[0].get(), &commit_sync)); // Wait for everyone to commit the operations. // We need to make sure the CommitMsg lands on the leaders log or the // verification will fail. Since CommitMsgs are appended to the replication // queue there is a scenario where they land in the followers log before // landing on the leader's log. However we know that they are durable // on the leader when the commit callback is triggered. // We thus wait for the commit callback to trigger, ensuring durability // on the leader and then for the commits to be present on the replicas. ASSERT_OK(commit_sync->Wait()); WaitForCommitIfNotAlreadyPresent(last_op_id.index(), kFollower0Idx, kLeaderIdx); WaitForCommitIfNotAlreadyPresent(last_op_id.index(), kFollower1Idx, kLeaderIdx); VerifyLogs(2, 0, 1); } // Tests Replicate/Commit a sequence of messages through the leader. // First a sequence of replicates and then a sequence of commits. TEST_F(RaftConsensusQuorumTest, TestFollowersReplicateAndCommitSequence) { // Constants with the indexes of peers with certain roles, // since peers don't change roles in this test. const int kFollower0Idx = 0; const int kFollower1Idx = 1; const int kLeaderIdx = 2; int seq_size = AllowSlowTests() ? 1000 : 100; ASSERT_OK(BuildAndStartConfig(3)); OpId last_op_id; vector<scoped_refptr<ConsensusRound>> rounds; shared_ptr<Synchronizer> commit_sync; NO_FATALS(ReplicateSequenceOfMessages( seq_size, kLeaderIdx, WAIT_FOR_ALL_REPLICAS, DONT_COMMIT, &last_op_id, &rounds, &commit_sync)); // Commit the operations, but wait for the replicates to finish first for (const scoped_refptr<ConsensusRound>& round : rounds) { ASSERT_OK(CommitDummyMessage(kLeaderIdx, round.get(), &commit_sync)); } // See comment at the end of TestFollowersReplicateAndCommitMessage // for an explanation on this waiting sequence. ASSERT_OK(commit_sync->Wait()); WaitForCommitIfNotAlreadyPresent(last_op_id.index(), kFollower0Idx, kLeaderIdx); WaitForCommitIfNotAlreadyPresent(last_op_id.index(), kFollower1Idx, kLeaderIdx); VerifyLogs(2, 0, 1); } TEST_F(RaftConsensusQuorumTest, TestConsensusContinuesIfAMinorityFallsBehind) { // Constants with the indexes of peers with certain roles, // since peers don't change roles in this test. const int kFollower0Idx = 0; const int kFollower1Idx = 1; const int kLeaderIdx = 2; ASSERT_OK(BuildAndStartConfig(3)); OpId last_replicate; vector<scoped_refptr<ConsensusRound>> rounds; { // lock one of the replicas down by obtaining the state lock // and never letting it go. shared_ptr<RaftConsensus> follower0; CHECK_OK(peers_->GetPeerByIdx(kFollower0Idx, &follower0)); RaftConsensus::LockGuard l(follower0->lock_); // If the locked replica would stop consensus we would hang here // as we wait for operations to be replicated to a majority. NO_FATALS(ReplicateSequenceOfMessages( 10, kLeaderIdx, WAIT_FOR_MAJORITY, COMMIT_ONE_BY_ONE, &last_replicate, &rounds)); // Follower 1 should be fine (Were we to wait for follower0's replicate // this would hang here). We know he must have replicated but make sure // by calling Wait(). WaitForReplicateIfNotAlreadyPresent(last_replicate, kFollower1Idx); WaitForCommitIfNotAlreadyPresent(last_replicate.index(), kFollower1Idx, kLeaderIdx); } // After we let the lock go the remaining follower should get up-to-date WaitForReplicateIfNotAlreadyPresent(last_replicate, kFollower0Idx); WaitForCommitIfNotAlreadyPresent(last_replicate.index(), kFollower0Idx, kLeaderIdx); VerifyLogs(2, 0, 1); } TEST_F(RaftConsensusQuorumTest, TestConsensusStopsIfAMajorityFallsBehind) { // Constants with the indexes of peers with certain roles, // since peers don't change roles in this test. const int kFollower0Idx = 0; const int kFollower1Idx = 1; const int kLeaderIdx = 2; ASSERT_OK(BuildAndStartConfig(3)); OpId last_op_id; scoped_refptr<ConsensusRound> round; { // lock two of the replicas down by obtaining the state locks // and never letting them go. shared_ptr<RaftConsensus> follower0; CHECK_OK(peers_->GetPeerByIdx(kFollower0Idx, &follower0)); RaftConsensus::LockGuard l_0(follower0->lock_); shared_ptr<RaftConsensus> follower1; CHECK_OK(peers_->GetPeerByIdx(kFollower1Idx, &follower1)); RaftConsensus::LockGuard l_1(follower1->lock_); // Append a single message to the queue ASSERT_OK(AppendDummyMessage(kLeaderIdx, &round)); last_op_id.CopyFrom(round->id()); // This should timeout. Status status = TimedWaitForReplicate(round.get(), MonoDelta::FromMilliseconds(500)); ASSERT_TRUE(status.IsTimedOut()); } // After we release the locks the operation should replicate to all replicas // and we commit. ASSERT_OK(WaitForReplicate(round.get())); CommitDummyMessage(kLeaderIdx, round.get()); // Assert that everything was ok WaitForReplicateIfNotAlreadyPresent(last_op_id, kFollower0Idx); WaitForReplicateIfNotAlreadyPresent(last_op_id, kFollower1Idx); WaitForCommitIfNotAlreadyPresent(last_op_id.index(), kFollower0Idx, kLeaderIdx); WaitForCommitIfNotAlreadyPresent(last_op_id.index(), kFollower1Idx, kLeaderIdx); VerifyLogs(2, 0, 1); } // If some communication error happens the leader will resend the request to the // peers. This tests that the peers handle repeated requests. TEST_F(RaftConsensusQuorumTest, TestReplicasHandleCommunicationErrors) { // Constants with the indexes of peers with certain roles, // since peers don't change roles in this test. const int kFollower0Idx = 0; const int kFollower1Idx = 1; const int kLeaderIdx = 2; ASSERT_OK(BuildAndStartConfig(3)); OpId last_op_id; // Append a dummy message, with faults injected on the first attempt // to send the message. scoped_refptr<ConsensusRound> round; GetLeaderProxyToPeer(kFollower0Idx, kLeaderIdx)->InjectCommFaultLeaderSide(); GetLeaderProxyToPeer(kFollower1Idx, kLeaderIdx)->InjectCommFaultLeaderSide(); ASSERT_OK(AppendDummyMessage(kLeaderIdx, &round)); // We should successfully replicate it due to retries. ASSERT_OK(WaitForReplicate(round.get())); GetLeaderProxyToPeer(kFollower0Idx, kLeaderIdx)->InjectCommFaultLeaderSide(); GetLeaderProxyToPeer(kFollower1Idx, kLeaderIdx)->InjectCommFaultLeaderSide(); ASSERT_OK(CommitDummyMessage(kLeaderIdx, round.get())); // The commit should eventually reach both followers as well. last_op_id = round->id(); WaitForCommitIfNotAlreadyPresent(last_op_id.index(), kFollower0Idx, kLeaderIdx); WaitForCommitIfNotAlreadyPresent(last_op_id.index(), kFollower1Idx, kLeaderIdx); // Append a sequence of messages, and keep injecting errors into the // replica proxies. vector<scoped_refptr<ConsensusRound>> rounds; shared_ptr<Synchronizer> commit_sync; for (int i = 0; i < 100; i++) { scoped_refptr<ConsensusRound> round; ASSERT_OK(AppendDummyMessage(kLeaderIdx, &round)); ConsensusRound* round_ptr = round.get(); last_op_id.CopyFrom(round->id()); rounds.push_back(round); // inject comm faults if (i % 2 == 0) { GetLeaderProxyToPeer(kFollower0Idx, kLeaderIdx)->InjectCommFaultLeaderSide(); } else { GetLeaderProxyToPeer(kFollower1Idx, kLeaderIdx)->InjectCommFaultLeaderSide(); } ASSERT_OK(WaitForReplicate(round_ptr)); ASSERT_OK(CommitDummyMessage(kLeaderIdx, round_ptr, &commit_sync)); } // Assert last operation was correctly replicated and committed. WaitForReplicateIfNotAlreadyPresent(last_op_id, kFollower0Idx); WaitForReplicateIfNotAlreadyPresent(last_op_id, kFollower1Idx); // See comment at the end of TestFollowersReplicateAndCommitMessage // for an explanation on this waiting sequence. ASSERT_OK(commit_sync->Wait()); WaitForCommitIfNotAlreadyPresent(last_op_id.index(), kFollower0Idx, kLeaderIdx); WaitForCommitIfNotAlreadyPresent(last_op_id.index(), kFollower1Idx, kLeaderIdx); VerifyLogs(2, 0, 1); } // In this test we test the ability of the leader to send heartbeats // to replicas by simply pushing nothing after the configuration round // and still expecting for the replicas' Update() method to be called. TEST_F(RaftConsensusQuorumTest, TestLeaderHeartbeats) { // Constants with the indexes of peers with certain roles, // since peers don't change roles in this test. const int kFollower0Idx = 0; const int kFollower1Idx = 1; const int kLeaderIdx = 2; ASSERT_OK(BuildConfig(3)); shared_ptr<RaftConsensus> follower0; CHECK_OK(peers_->GetPeerByIdx(kFollower0Idx, &follower0)); shared_ptr<RaftConsensus> follower1; CHECK_OK(peers_->GetPeerByIdx(kFollower1Idx, &follower1)); ASSERT_OK(StartPeers()); shared_ptr<RaftConsensus> leader; CHECK_OK(peers_->GetPeerByIdx(kLeaderIdx, &leader)); ASSERT_OK(leader->EmulateElectionForTests()); // Wait for the config round to get committed and count the number // of update calls, calls after that will be heartbeats. OpId config_round; config_round.set_term(1); config_round.set_index(1); WaitForCommitIfNotAlreadyPresent(config_round.index(), kFollower0Idx, kLeaderIdx); WaitForCommitIfNotAlreadyPresent(config_round.index(), kFollower1Idx, kLeaderIdx); int repl0_init_count = follower0->update_calls_for_tests(); int repl1_init_count = follower1->update_calls_for_tests(); // Now wait for about 4 times the heartbeat period; the counters // should have increased between 3 to 8 times. // // Why the variance? Heartbeat timing is jittered such that the period // between heartbeats can be anywhere from 3/4 to 5/4 the interval. SleepFor(MonoDelta::FromMilliseconds(FLAGS_raft_heartbeat_interval_ms * 4LL)); int repl0_final_count = follower0->update_calls_for_tests(); int repl1_final_count = follower1->update_calls_for_tests(); ASSERT_GE(repl0_final_count - repl0_init_count, 3); ASSERT_LE(repl0_final_count - repl0_init_count, 8); ASSERT_GE(repl1_final_count - repl1_init_count, 3); ASSERT_LE(repl1_final_count - repl1_init_count, 8); VerifyLogs(2, 0, 1); } // After creating the initial configuration, this test writes a small sequence // of messages to the initial leader. It then shuts down the current // leader, makes another peer become leader and writes a sequence of // messages to it. The new leader and the follower should agree on the // sequence of messages. TEST_F(RaftConsensusQuorumTest, TestLeaderElectionWithQuiescedQuorum) { const int kInitialNumPeers = 5; ASSERT_OK(BuildAndStartConfig(kInitialNumPeers)); OpId last_op_id; shared_ptr<Synchronizer> last_commit_sync; vector<scoped_refptr<ConsensusRound>> rounds; // Loop twice, successively shutting down the previous leader. for (int current_config_size = kInitialNumPeers; current_config_size >= kInitialNumPeers - 1; current_config_size--) { NO_FATALS(ReplicateSequenceOfMessages( 10, current_config_size - 1, WAIT_FOR_ALL_REPLICAS, COMMIT_ONE_BY_ONE, &last_op_id, &rounds, &last_commit_sync)); // Make sure the last operation is committed everywhere ASSERT_OK(last_commit_sync->Wait()); for (int i = 0; i < current_config_size - 1; i++) { WaitForCommitIfNotAlreadyPresent(last_op_id.index(), i, current_config_size - 1); } // Now shutdown the current leader. LOG(INFO) << "Shutting down current leader with index " << (current_config_size - 1); shared_ptr<RaftConsensus> current_leader; CHECK_OK(peers_->GetPeerByIdx(current_config_size - 1, &current_leader)); current_leader->Shutdown(); peers_->RemovePeer(current_leader->peer_uuid()); // ... and make the peer before it become leader. shared_ptr<RaftConsensus> new_leader; CHECK_OK(peers_->GetPeerByIdx(current_config_size - 2, &new_leader)); // This will force an election in which we expect to make the last // non-shutdown peer in the list become leader. int64_t flush_count_before = new_leader->consensus_metadata_for_tests()->flush_count_for_tests(); LOG(INFO) << "Running election for future leader with index " << (current_config_size - 1); ASSERT_OK(new_leader->StartElection(RaftConsensus::ELECT_EVEN_IF_LEADER_IS_ALIVE, RaftConsensus::EXTERNAL_REQUEST)); WaitUntilLeaderForTests(new_leader.get()); LOG(INFO) << "Election won"; int64_t flush_count_after = new_leader->consensus_metadata_for_tests()->flush_count_for_tests(); ASSERT_EQ(flush_count_after, flush_count_before + 1) << "Expected only one consensus metadata flush for a leader election"; // ... replicating a set of messages to the new leader should now be possible. NO_FATALS(ReplicateSequenceOfMessages( 10, current_config_size - 2, WAIT_FOR_MAJORITY, COMMIT_ONE_BY_ONE, &last_op_id, &rounds, &last_commit_sync)); // Make sure the last operation is committed everywhere ASSERT_OK(last_commit_sync->Wait()); for (int i = 0; i < current_config_size - 2; i++) { WaitForCommitIfNotAlreadyPresent(last_op_id.index(), i, current_config_size - 2); } } // We can only verify the logs of the peers that were not killed, due to the // old leaders being out-of-date now. VerifyLogs(2, 0, 1); } TEST_F(RaftConsensusQuorumTest, TestReplicasEnforceTheLogMatchingProperty) { ASSERT_OK(BuildAndStartConfig(3)); OpId last_op_id; shared_ptr<Synchronizer> last_commit_sync; vector<scoped_refptr<ConsensusRound>> rounds; NO_FATALS(ReplicateSequenceOfMessages( 10, 2, WAIT_FOR_ALL_REPLICAS, COMMIT_ONE_BY_ONE, &last_op_id, &rounds, &last_commit_sync)); // Make sure the last operation is committed everywhere ASSERT_OK(last_commit_sync->Wait()); WaitForCommitIfNotAlreadyPresent(last_op_id.index(), 0, 2); WaitForCommitIfNotAlreadyPresent(last_op_id.index(), 1, 2); // Now replicas should only accept operations with // 'last_id' as the preceding id. ConsensusRequestPB req; ConsensusResponsePB resp; shared_ptr<RaftConsensus> leader; CHECK_OK(peers_->GetPeerByIdx(2, &leader)); shared_ptr<RaftConsensus> follower; CHECK_OK(peers_->GetPeerByIdx(0, &follower)); req.set_caller_uuid(leader->peer_uuid()); req.set_caller_term(last_op_id.term()); req.mutable_preceding_id()->CopyFrom(last_op_id); req.set_committed_index(last_op_id.index()); req.set_all_replicated_index(0); // Send a request with the next index. ReplicateMsg* replicate = req.add_ops(); replicate->set_timestamp(clock_.Now().ToUint64()); OpId* id = replicate->mutable_id(); id->set_term(last_op_id.term()); id->set_index(last_op_id.index() + 1); replicate->set_op_type(NO_OP); // Since the req adds the next op, the leader must have also appended it. req.set_last_idx_appended_to_leader(id->index()); // Appending this message to peer0 should work and update // its 'last_received' to 'id'. ASSERT_OK(follower->Update(&req, &resp)); ASSERT_TRUE(OpIdEquals(resp.status().last_received(), *id)); ASSERT_EQ(0, follower->queue_->metrics_.num_ops_behind_leader->value()); // Now skip one message in the same term. The replica should // complain with the right error message. req.mutable_preceding_id()->set_index(id->index() + 1); id->set_index(id->index() + 2); // Appending this message to peer0 should return a Status::OK // but should contain an error referring to the log matching property. ASSERT_OK(follower->Update(&req, &resp)); ASSERT_TRUE(resp.has_status()); ASSERT_TRUE(resp.status().has_error()); ASSERT_EQ(ConsensusErrorPB::PRECEDING_ENTRY_DIDNT_MATCH, resp.status().error().code()); ASSERT_STR_CONTAINS(resp.status().error().status().message(), "Log matching property violated"); } // Test that RequestVote performs according to "spec". TEST_F(RaftConsensusQuorumTest, TestRequestVote) { ASSERT_OK(BuildAndStartConfig(3)); OpId last_op_id; shared_ptr<Synchronizer> last_commit_sync; vector<scoped_refptr<ConsensusRound>> rounds; NO_FATALS(ReplicateSequenceOfMessages( 10, 2, WAIT_FOR_ALL_REPLICAS, COMMIT_ONE_BY_ONE, &last_op_id, &rounds, &last_commit_sync)); // Make sure the last operation is committed everywhere ASSERT_OK(last_commit_sync->Wait()); WaitForCommitIfNotAlreadyPresent(last_op_id.index(), 0, 2); WaitForCommitIfNotAlreadyPresent(last_op_id.index(), 1, 2); // Ensure last-logged OpId is > (0,0). ASSERT_TRUE(OpIdLessThan(MinimumOpId(), last_op_id)); const int kPeerIndex = 1; shared_ptr<RaftConsensus> peer; CHECK_OK(peers_->GetPeerByIdx(kPeerIndex, &peer)); auto flush_count = [&]() { return peer->consensus_metadata_for_tests()->flush_count_for_tests(); }; VoteRequestPB request; request.set_tablet_id(kTestTablet); request.mutable_candidate_status()->mutable_last_received()->CopyFrom(last_op_id); // Test that the replica won't vote since it has recently heard from // a valid leader. int flush_count_before = flush_count(); VoteResponsePB response; request.set_candidate_uuid(fs_managers_[0]->uuid()); request.set_candidate_term(last_op_id.term() + 1); ASSERT_OK(peer->RequestVote(&request, TabletVotingState(boost::none, tablet::TABLET_DATA_READY), &response)); ASSERT_FALSE(response.vote_granted()); ASSERT_EQ(ConsensusErrorPB::LEADER_IS_ALIVE, response.consensus_error().code()); ASSERT_EQ(0, flush_count() - flush_count_before) << "A rejected vote should not flush metadata"; // Test that replicas only vote yes for a single peer per term. // Indicate that replicas should vote even if they think another leader is alive. // This will allow the rest of the requests in the test to go through. flush_count_before = flush_count(); request.set_ignore_live_leader(true); ASSERT_OK(peer->RequestVote(&request, TabletVotingState(boost::none, tablet::TABLET_DATA_READY), &response)); ASSERT_TRUE(response.vote_granted()); ASSERT_EQ(last_op_id.term() + 1, response.responder_term()); NO_FATALS(AssertDurableTermAndVote(kPeerIndex, last_op_id.term() + 1, fs_managers_[0]->uuid())); ASSERT_EQ(1, flush_count() - flush_count_before) << "A granted vote should flush only once"; // Ensure we get same response for same term and same UUID. response.Clear(); flush_count_before = flush_count(); ASSERT_OK(peer->RequestVote(&request, TabletVotingState(boost::none, tablet::TABLET_DATA_READY), &response)); ASSERT_TRUE(response.vote_granted()); ASSERT_EQ(0, flush_count() - flush_count_before) << "Confirming a previous vote should not flush"; // Ensure we get a "no" for a different candidate UUID for that term. flush_count_before = flush_count(); response.Clear(); request.set_candidate_uuid(fs_managers_[2]->uuid()); ASSERT_OK(peer->RequestVote(&request, TabletVotingState(boost::none, tablet::TABLET_DATA_READY), &response)); ASSERT_FALSE(response.vote_granted()); ASSERT_TRUE(response.has_consensus_error()); ASSERT_EQ(ConsensusErrorPB::ALREADY_VOTED, response.consensus_error().code()); ASSERT_EQ(last_op_id.term() + 1, response.responder_term()); NO_FATALS(AssertDurableTermAndVote(kPeerIndex, last_op_id.term() + 1, fs_managers_[0]->uuid())); ASSERT_EQ(0, flush_count() - flush_count_before) << "Rejected votes for same term should not flush"; // // Test that replicas refuse votes for an old term. // // Increase the term of our candidate, which will cause the voter replica to // increase its own term to match. flush_count_before = flush_count(); request.set_candidate_uuid(fs_managers_[0]->uuid()); request.set_candidate_term(last_op_id.term() + 2); response.Clear(); ASSERT_OK(peer->RequestVote(&request, TabletVotingState(boost::none, tablet::TABLET_DATA_READY), &response)); ASSERT_TRUE(response.vote_granted()); ASSERT_EQ(last_op_id.term() + 2, response.responder_term()); NO_FATALS(AssertDurableTermAndVote(kPeerIndex, last_op_id.term() + 2, fs_managers_[0]->uuid())); ASSERT_EQ(1, flush_count() - flush_count_before) << "Accepted votes with increased term should flush once"; // Now try the old term. // Note: Use the peer who "won" the election on the previous term (peer 0), // although in practice the impl does not store historical vote data. flush_count_before = flush_count(); request.set_candidate_term(last_op_id.term() + 1); response.Clear(); ASSERT_OK(peer->RequestVote(&request, TabletVotingState(boost::none, tablet::TABLET_DATA_READY), &response)); ASSERT_FALSE(response.vote_granted()); ASSERT_TRUE(response.has_consensus_error()); ASSERT_EQ(ConsensusErrorPB::INVALID_TERM, response.consensus_error().code()); ASSERT_EQ(last_op_id.term() + 2, response.responder_term()); NO_FATALS(AssertDurableTermAndVote(kPeerIndex, last_op_id.term() + 2, fs_managers_[0]->uuid())); ASSERT_EQ(0, flush_count() - flush_count_before) << "Rejected votes for old terms should not flush"; // Ensure that replicas don't change term or flush any metadata for a pre-election // request, even when they vote "yes". flush_count_before = flush_count(); request.set_candidate_term(last_op_id.term() + 3); request.set_is_pre_election(true); response.Clear(); ASSERT_OK(peer->RequestVote(&request, TabletVotingState(boost::none, tablet::TABLET_DATA_READY), &response)); ASSERT_TRUE(response.vote_granted()); ASSERT_FALSE(response.has_consensus_error()); ASSERT_EQ(last_op_id.term() + 2, response.responder_term()); NO_FATALS(AssertDurableTermAndVote(kPeerIndex, last_op_id.term() + 2, fs_managers_[0]->uuid())); ASSERT_EQ(0, flush_count() - flush_count_before) << "Pre-elections should not flush"; request.set_is_pre_election(false); // // Ensure replicas vote no for an old op index. // flush_count_before = flush_count(); request.set_candidate_uuid(fs_managers_[0]->uuid()); request.set_candidate_term(last_op_id.term() + 3); request.mutable_candidate_status()->mutable_last_received()->CopyFrom(MinimumOpId()); response.Clear(); ASSERT_OK(peer->RequestVote(&request, TabletVotingState(boost::none, tablet::TABLET_DATA_READY), &response)); ASSERT_FALSE(response.vote_granted()); ASSERT_TRUE(response.has_consensus_error()); ASSERT_EQ(ConsensusErrorPB::LAST_OPID_TOO_OLD, response.consensus_error().code()); ASSERT_EQ(last_op_id.term() + 3, response.responder_term()); NO_FATALS(AssertDurableTermWithoutVote(kPeerIndex, last_op_id.term() + 3)); ASSERT_EQ(1, flush_count() - flush_count_before) << "Rejected votes for old op index but new term should flush once."; // Send a "heartbeat" to the peer. It should be rejected. ConsensusRequestPB req; req.set_caller_term(last_op_id.term()); req.set_caller_uuid(fs_managers_[0]->uuid()); req.set_committed_index(last_op_id.index()); req.set_all_replicated_index(0); ConsensusResponsePB res; Status s = peer->Update(&req, &res); ASSERT_EQ(last_op_id.term() + 3, res.responder_term()); ASSERT_TRUE(res.status().has_error()); ASSERT_EQ(ConsensusErrorPB::INVALID_TERM, res.status().error().code()); LOG(INFO) << "Follower rejected old heartbeat, as expected: " << SecureShortDebugString(res); } } // namespace consensus } // namespace kudu
39.736752
99
0.701691
SuckShit
4f78d7537f9a917aa50ebcd6fcd56688262b3b96
355
hpp
C++
src/utils/IIterrator.hpp
Vict0rynox/ft_retro
fe3ab75fb86406367837ba393e1c221133590bf4
[ "MIT" ]
null
null
null
src/utils/IIterrator.hpp
Vict0rynox/ft_retro
fe3ab75fb86406367837ba393e1c221133590bf4
[ "MIT" ]
null
null
null
src/utils/IIterrator.hpp
Vict0rynox/ft_retro
fe3ab75fb86406367837ba393e1c221133590bf4
[ "MIT" ]
null
null
null
// // Created by Victor Vasiliev on 11/4/17. // #ifndef FT_RETRO_IITERRATOR_HPP #define FT_RETRO_IITERRATOR_HPP namespace Utils { template <class T> class IIterrator { public: virtual T curr() = 0; virtual bool isEnd() = 0; virtual void next() = 0; virtual void prev() = 0; virtual void reset() = 0; }; } #endif //FT_RETRO_IITERRATOR_HPP
16.136364
41
0.687324
Vict0rynox
4f7983eaa644cea5fa78e69e1ad66e2bc75d0fc2
27,397
cpp
C++
libgpos/server/src/unittest/gpos/memory/CCacheTest.cpp
soumyadeep2007/gporca
f255dea5a93a9e1fdd1b3303779866799fd13cb5
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
libgpos/server/src/unittest/gpos/memory/CCacheTest.cpp
soumyadeep2007/gporca
f255dea5a93a9e1fdd1b3303779866799fd13cb5
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
libgpos/server/src/unittest/gpos/memory/CCacheTest.cpp
soumyadeep2007/gporca
f255dea5a93a9e1fdd1b3303779866799fd13cb5
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
//--------------------------------------------------------------------------- // Greenplum Database // Copyright (C) 2011 EMC CORP. // // @filename: // CCacheTest.cpp // // @doc: // Tests for CCache //--------------------------------------------------------------------------- #include "gpos/error/CAutoTrace.h" #include "gpos/common/CAutoP.h" #include "gpos/common/CRandom.h" #include "gpos/memory/CAutoMemoryPool.h" #include "gpos/memory/CCacheFactory.h" #include "gpos/task/CAutoTaskProxy.h" #include "gpos/test/CUnittest.h" #include "unittest/gpos/memory/CCacheTest.h" using namespace gpos; #define GPOS_CACHE_THREADS 10 #define GPOS_CACHE_ELEMENTS 20 #define GPOS_CACHE_DUPLICATES 5 #define GPOS_CACHE_DUPLICATES_TO_DELETE 3 // static variable static BOOL fUnique = true; //--------------------------------------------------------------------------- // @function: // CCacheTest::EresUnittest // // @doc: // Driver of cache unittests // //--------------------------------------------------------------------------- GPOS_RESULT CCacheTest::EresUnittest() { CUnittest rgut[] = { GPOS_UNITTEST_FUNC(CCacheTest::EresUnittest_Basic), GPOS_UNITTEST_FUNC(CCacheTest::EresUnittest_Refcount), GPOS_UNITTEST_FUNC(CCacheTest::EresUnittest_Eviction), GPOS_UNITTEST_FUNC(CCacheTest::EresUnittest_Iteration), GPOS_UNITTEST_FUNC(CCacheTest::EresUnittest_DeepObject), GPOS_UNITTEST_FUNC(CCacheTest::EresUnittest_IterativeDeletion)}; fUnique = true; GPOS_RESULT eres = CUnittest::EresExecute(rgut, GPOS_ARRAY_SIZE(rgut)); if (GPOS_OK == eres) { fUnique = false; eres = CUnittest::EresExecute(rgut, GPOS_ARRAY_SIZE(rgut)); } return eres; } //--------------------------------------------------------------------------- // @function: // CCacheTest::SSimpleObject::FMyEqual // // @doc: // Key equality function // //--------------------------------------------------------------------------- BOOL CCacheTest::SSimpleObject::FMyEqual(ULONG *const &pvKey, ULONG *const &pvKeySecond) { BOOL fReturn = false; if (NULL == pvKey && NULL == pvKeySecond) { fReturn = true; } else if (NULL == pvKey || NULL == pvKeySecond) { fReturn = false; } else { fReturn = (*pvKey) == (*pvKeySecond); } return fReturn; } //--------------------------------------------------------------------------- // @function: // CCacheTest::CDeepObject::UlMyHash // // @doc: // The hash code of linked list is the summation of entries' keys // //--------------------------------------------------------------------------- ULONG CCacheTest::CDeepObject::UlMyHash(CDeepObject::CDeepObjectList *const &plist) { ULONG ulKey = 0; SDeepObjectEntry *pdoe = plist->First(); while (pdoe != NULL) { ulKey += pdoe->m_ulKey; pdoe = plist->Next(pdoe); } return ulKey; } //--------------------------------------------------------------------------- // @function: // CCacheTest::CDeepObject::FMyEqual // // @doc: // Two objects are equal if the keys in their corresponding list // entries are equal // //--------------------------------------------------------------------------- BOOL CCacheTest::CDeepObject::FMyEqual( CDeepObject::CDeepObjectList *const &plist, CDeepObject::CDeepObjectList *const &plistSecond) { BOOL fReturn = false; if (NULL == plist && NULL == plistSecond) { fReturn = true; } else if (NULL == plist || NULL == plistSecond) { fReturn = false; } else { if (plist->Size() != plistSecond->Size()) { fReturn = false; } else { fReturn = true; SDeepObjectEntry *pdoe = plist->First(); SDeepObjectEntry *pdoeSecond = plistSecond->First(); while (NULL != pdoe) { GPOS_ASSERT(NULL != pdoeSecond && "Reached a NULL entry in the second list"); if (pdoe->m_ulKey != pdoeSecond->m_ulKey) { fReturn = false; break; } pdoe = plist->Next(pdoe); pdoeSecond = plistSecond->Next(pdoeSecond); } } } return fReturn; } //--------------------------------------------------------------------------- // @function: // CCacheTest::CDeepObject::AddEntry // // @doc: // Adds a new entry to the linked list // //--------------------------------------------------------------------------- void CCacheTest::CDeepObject::AddEntry(CMemoryPool *mp, ULONG ulKey, ULONG ulVal) { m_list.Prepend(GPOS_NEW(mp) SDeepObjectEntry(ulKey, ulVal)); } //--------------------------------------------------------------------------- // @function: // CCacheTest::EresUnittest_Basic // // @doc: // Basic cache test (insert, lookup, delete, lookup again) // //--------------------------------------------------------------------------- GPOS_RESULT CCacheTest::EresUnittest_Basic() { CAutoP<CCache<SSimpleObject *, ULONG *> > apcache; apcache = CCacheFactory::CreateCache<SSimpleObject *, ULONG *>( fUnique, UNLIMITED_CACHE_QUOTA, SSimpleObject::UlMyHash, SSimpleObject::FMyEqual); CCache<SSimpleObject *, ULONG *> *pcache = apcache.Value(); //insertion - scope for accessor { CSimpleObjectCacheAccessor ca(pcache); SSimpleObject *pso = GPOS_NEW(ca.Pmp()) SSimpleObject(1, 2); #ifdef GPOS_DEBUG SSimpleObject *psoReturned = #endif // GPOS_DEBUG ca.Insert(&(pso->m_ulKey), pso); //release the ownership from pso, but ccacheentry still has the ownership pso->Release(); GPOS_ASSERT(psoReturned == pso && "Incorrect cache entry was inserted"); GPOS_ASSERT(1 == pcache->Size()); // insert duplicate while not allowed if (pcache->AllowsDuplicateKeys()) { CSimpleObjectCacheAccessor ca(pcache); SSimpleObject *psoDuplicate = GPOS_NEW(ca.Pmp()) SSimpleObject(1, 5); #ifdef GPOS_DEBUG SSimpleObject *psoReturned = #endif // GPOS_DEBUG ca.Insert(&(psoDuplicate->m_ulKey), psoDuplicate); GPOS_ASSERT(psoReturned == pso && "Duplicate insertion must fail"); GPOS_ASSERT(1 == pcache->Size()); // delete original cache object ca.MarkForDeletion(); } // lookup - scope for accessor { CSimpleObjectCacheAccessor ca(pcache); ULONG ulkey = 1; ca.Lookup(&ulkey); pso = ca.Val(); if (NULL != pso) { // release object since there is no customer to release it after lookup and before CCache's cleanup pso->Release(); } GPOS_ASSERT_IMP(!pcache->AllowsDuplicateKeys(), NULL != pso && 2 == pso->m_ulValue); GPOS_ASSERT_IMP(pcache->AllowsDuplicateKeys(), NULL == pso); } // delete - scope for accessor { CSimpleObjectCacheAccessor ca(pcache); ULONG ulkey = 1; ca.Lookup(&ulkey); pso = ca.Val(); GPOS_ASSERT_IMP(!pcache->AllowsDuplicateKeys(), NULL != pso); if (NULL != pso) { // release object since there is no customer to release it after lookup and before CCache's cleanup pso->Release(); ca.MarkForDeletion(); } } // lookup again - scope for accessor { CSimpleObjectCacheAccessor ca(pcache); ULONG ulkey = 1; ca.Lookup(&ulkey); pso = ca.Val(); GPOS_ASSERT(NULL == pso); } // at this point, we still maintain a valid cached object held by the // outmost accessor GPOS_ASSERT(NULL != psoReturned && 2 == psoReturned->m_ulValue); } GPOS_ASSERT(0 == pcache->Size()); return GPOS_OK; } //--------------------------------------------------------------------------- // @function: // CCacheTest::EresUnittest_Refcount // // @doc: // Basic Ref count test: // Insert Ref Count object, dec ref count of the object, and get the object from cache // //--------------------------------------------------------------------------- GPOS_RESULT CCacheTest::EresUnittest_Refcount() { CAutoP<CCache<SSimpleObject *, ULONG *> > apcache; apcache = CCacheFactory::CreateCache<SSimpleObject *, ULONG *>( fUnique, UNLIMITED_CACHE_QUOTA, SSimpleObject::UlMyHash, SSimpleObject::FMyEqual); CCache<SSimpleObject *, ULONG *> *pcache = apcache.Value(); SSimpleObject *pso = NULL; //Scope of the accessor when we insert { CSimpleObjectCacheAccessor ca(pcache); CMemoryPool *mp = ca.Pmp(); pso = GPOS_NEW(mp) SSimpleObject(1, 2); GPOS_ASSERT(1 == pso->RefCount()); #ifdef GPOS_DEBUG SSimpleObject *psoReturned = #endif // GPOS_DEBUG ca.Insert(&(pso->m_ulKey), pso); // 1 by CRefCount, 2 by CCacheEntry constructor and 3 by CCache Accessor GPOS_ASSERT(3 == pso->RefCount() && "Expected refcount to be 3"); GPOS_ASSERT(psoReturned == pso && "Incorrect cache entry was inserted"); } GPOS_ASSERT( 2 == pso->RefCount() && "Expected refcount to be 2 because CCacheAccessor goes out of scope"); { //Create new access for lookup CSimpleObjectCacheAccessor ca(pcache); GPOS_ASSERT(2 == pso->RefCount() && "Expected pso and CCacheEntry to have ownership"); //Ideally Lookup should return valid object. Until CCache evict and no one has reference to it, this object can't be deleted ca.Lookup(&(pso->m_ulKey)); // 1 by CRefCount, 2 by CCacheEntry constructor, 3 by CCache Accessor, 4 by Lookup GPOS_ASSERT( 4 == pso->RefCount() && "Expected pso, CCacheEntry CCacheAccessor, and customer to have ownership"); // Ideally it shouldn't delete itself because CCache is still holding this object pso->Release(); GPOS_ASSERT( 3 == pso->RefCount() && "Expected CCacheEntry, CCacheAccessor and customer to have ownership"); } GPOS_ASSERT( 2 == pso->RefCount() && "Expected refcount to be 1. CCacheEntry and customer have the ownership"); // release object since there is no customer to release it after lookup and before CCache's cleanup pso->Release(); return GPOS_OK; } //--------------------------------------------------------------------------- // @function: // CCacheTest::InsertOneElement // // @doc: // Inserts one SSimpleObject with both key and value set to ulKey. // Returns the size of a single instance of SSimpleObject // //--------------------------------------------------------------------------- ULLONG CCacheTest::InsertOneElement(CCache<SSimpleObject *, ULONG *> *pCache, ULONG ulKey) { ULLONG ulTotalAllocatedSize = 0; SSimpleObject *pso = NULL; { CSimpleObjectCacheAccessor ca(pCache); CMemoryPool *mp = ca.Pmp(); pso = GPOS_NEW(mp) SSimpleObject(ulKey, ulKey); ca.Insert(&(pso->m_ulKey), pso); GPOS_ASSERT( 3 == pso->RefCount() && "Expected pso, cacheentry and cacheaccessor to have ownership"); //Remove the ownership of pso. Still CCacheEntry has the ownership pso->Release(); GPOS_ASSERT(2 == pso->RefCount() && "Expected pso and cacheentry to have ownership"); ulTotalAllocatedSize = mp->TotalAllocatedSize(); } GPOS_ASSERT(1 == pso->RefCount() && "Expected only cacheentry to have ownership"); return ulTotalAllocatedSize; } //--------------------------------------------------------------------------- // @function: // CCacheTest::ULFillCacheWithoutEviction // // @doc: // Inserts as many SSimpleObjects as needed (starting with the key ulKeyStart and // sequentially generating the successive keys) to consume cache quota. // Returns the key of the last inserted element //--------------------------------------------------------------------------- ULONG CCacheTest::ULFillCacheWithoutEviction(CCache<SSimpleObject *, ULONG *> *pCache, ULONG ulKeyStart) { #ifdef GPOS_DEBUG // initial size of the cache ULLONG ullInitialCacheSize = pCache->TotalAllocatedSize(); ULLONG ullOldEvictionCounter = pCache->GetEvictionCounter(); #endif ULLONG ullOneElemSize = InsertOneElement(pCache, ulKeyStart); #ifdef GPOS_DEBUG ULLONG ullOneElemCacheSize = pCache->TotalAllocatedSize(); ULLONG ullNewEvictionCounter = pCache->GetEvictionCounter(); #endif GPOS_ASSERT((ullOneElemCacheSize > ullInitialCacheSize || ullOldEvictionCounter < ullNewEvictionCounter) && "Cache size didn't change upon insertion"); ULLONG ullCacheCapacity = pCache->GetCacheQuota() / ullOneElemSize; // We already have an element in the cache and the eviction happens after we violate. // So, we should not trigger eviction inserting cacheCapacity + 1 for (ULONG ulElemCount = 1; ulElemCount <= ullCacheCapacity; ulElemCount++) { InsertOneElement(pCache, ulKeyStart + ulElemCount); GPOS_CHECK_ABORT; } #ifdef GPOS_DEBUG ULLONG ullSizeBeforeEviction = #endif // GPOS_DEBUG pCache->TotalAllocatedSize(); // Check the size of the cache. Nothing should be evicted if the cache was initially empty #ifdef GPOS_DEBUG ULLONG ullExpectedCacheSize = (ullCacheCapacity + 1) * ullOneElemSize; #endif // GPOS_DEBUG GPOS_ASSERT_IMP( 0 == ullInitialCacheSize, ullSizeBeforeEviction == ullExpectedCacheSize && ullSizeBeforeEviction + ullOneElemSize > ullInitialCacheSize); return (ULONG)(ullCacheCapacity + ulKeyStart); } //--------------------------------------------------------------------------- // @function: // CCacheTest::CheckGenerationSanityAfterEviction // // @doc: // Checks if after eviction we have more entries from newer generation than the older generation //--------------------------------------------------------------------------- void CCacheTest::CheckGenerationSanityAfterEviction( CCache<SSimpleObject *, ULONG *> *pCache, ULLONG #ifdef GPOS_DEBUG ullOneElemSize #endif , ULONG ulOldGenBeginKey, ULONG ulOldGenEndKey, ULONG ulNewGenEndKey) { ULONG uloldGenEntryCount = 0; ULONG ulNewGenEntryCount = 0; for (ULONG ulKey = ulOldGenBeginKey; ulKey <= ulNewGenEndKey; ulKey++) { CSimpleObjectCacheAccessor ca(pCache); ca.Lookup(&ulKey); SSimpleObject *pso = ca.Val(); if (NULL != pso) { // release object since there is no customer to release it after lookup and before CCache's cleanup pso->Release(); if (ulKey <= ulOldGenEndKey) { uloldGenEntryCount++; } else { ulNewGenEntryCount++; } } } #ifdef GPOS_DEBUG ULLONG ullCacheCapacity = pCache->GetCacheQuota() / ullOneElemSize; #endif // total in-cache entries must be at least as many as the minimum number of in-cache entries after an eviction GPOS_ASSERT( uloldGenEntryCount + ulNewGenEntryCount >= (ULONG)((double) ullCacheCapacity * (1 - pCache->GetEvictionFactor()))); // there should be at least as many new gen entries as the old gen entries as they get to live longer GPOS_ASSERT(ulNewGenEntryCount >= uloldGenEntryCount); } //--------------------------------------------------------------------------- // @function: // CCacheTest::TestEvictionForOneCacheSize // // @doc: // Tests if cache eviction works for a single cache size //--------------------------------------------------------------------------- void CCacheTest::TestEvictionForOneCacheSize(ULLONG ullCacheQuota) { CAutoP<CCache<SSimpleObject *, ULONG *> > apCache; apCache = CCacheFactory::CreateCache<SSimpleObject *, ULONG *>( false, /* not an unique cache */ ullCacheQuota, SSimpleObject::UlMyHash, SSimpleObject::FMyEqual); CCache<SSimpleObject *, ULONG *> *pCache = apCache.Value(); ULONG ulLastKeyFirstGen = ULFillCacheWithoutEviction(pCache, 0); #ifdef GPOS_DEBUG ULLONG ullSizeBeforeEviction = pCache->TotalAllocatedSize(); #endif ULLONG ullOneElemSize = InsertOneElement(pCache, ulLastKeyFirstGen + 1); #ifdef GPOS_DEBUG ULLONG ullPostEvictionSize = pCache->TotalAllocatedSize(); #endif // Make sure cache is now smaller, due to eviction GPOS_ASSERT(ullPostEvictionSize < ullSizeBeforeEviction); // Now insert another batch of elements to fill the cache ULONG ulLastKeySecondGen = ULFillCacheWithoutEviction(pCache, ulLastKeyFirstGen + 2); // Another batch of insert to the cache's filling should evict all the second generation keys ULONG ulLastKeyThirdGen = ULFillCacheWithoutEviction(pCache, ulLastKeySecondGen + 1); CSimpleObjectCacheAccessor caBeforeEviction(pCache); // this is now pinned as the accessor is not going out of scope; pinned entry is used later for checking non-eviction caBeforeEviction.Lookup(&ulLastKeyThirdGen); SSimpleObject *psoBeforeEviction = caBeforeEviction.Val(); if (NULL != psoBeforeEviction) { // release object since there is no customer to release it after lookup and before CCache's cleanup psoBeforeEviction->Release(); } // Now verify everything from the first generation insertion is evicted for (ULONG ulKey = 0; ulKey <= ulLastKeyFirstGen; ulKey++) { CSimpleObjectCacheAccessor ca(pCache); ca.Lookup(&ulKey); SSimpleObject *pso = ca.Val(); if (NULL != pso) { // release object since there is no customer to release it after lookup and before CCache's cleanup pso->Release(); } GPOS_ASSERT(NULL == pso); } // now ensure that newer gen items are outliving older gen during cache eviction CheckGenerationSanityAfterEviction(pCache, ullOneElemSize, ulLastKeyFirstGen + 2, ulLastKeySecondGen, ulLastKeyThirdGen); ULLONG ullNewQuota = static_cast<ULLONG>(static_cast<double>(ullCacheQuota) * 0.5); // drastically reduce the size of the cache pCache->SetCacheQuota(ullNewQuota); GPOS_ASSERT(pCache->GetCacheQuota() == ullNewQuota); // now ensure that newer gen items are outliving older gen during cache eviction CheckGenerationSanityAfterEviction(pCache, ullOneElemSize, ulLastKeyFirstGen + 2, ulLastKeySecondGen, ulLastKeyThirdGen); // now check pinning would retain the entry, no matter how many eviction is triggered // Another batch of insert to the cache's filling should evict all the third generation keys ULONG ulLastKeyFourthGen = ULFillCacheWithoutEviction(pCache, ulLastKeyThirdGen + 1); // Another batch of insert to the cache's filling should evict all the forth generation keys ULONG ulLastKeyFifthGen = ULFillCacheWithoutEviction(pCache, ulLastKeyFourthGen + 1); // Another batch of insert to the cache's filling should evict all the fifth generation keys ULFillCacheWithoutEviction(pCache, ulLastKeyFifthGen + 1); for (ULONG ulKey = ulLastKeySecondGen + 1; ulKey <= ulLastKeyFourthGen; ulKey++) { CSimpleObjectCacheAccessor ca(pCache); ca.Lookup(&ulKey); SSimpleObject *pso = ca.Val(); if (NULL != pso) { // release object since there is no customer to release it after lookup and before CCache's cleanup pso->Release(); } // everything is evicted from third and fourth gen, except the pinned entry GPOS_ASSERT_IMP(ulKey != ulLastKeyThirdGen, NULL == pso); GPOS_ASSERT_IMP(ulKey == ulLastKeyThirdGen, NULL != pso); } } //--------------------------------------------------------------------------- // @function: // CCacheTest::EresUnittest_Eviction // // @doc: // Test if cache eviction works // //--------------------------------------------------------------------------- GPOS_RESULT CCacheTest::EresUnittest_Eviction() { TestEvictionForOneCacheSize(10240); TestEvictionForOneCacheSize(20480); return GPOS_OK; } //--------------------------------------------------------------------------- // @function: // CCacheTest::EresInsertDuplicates // // @doc: // Helper function: insert multiple elements with duplicate keys // //--------------------------------------------------------------------------- GPOS_RESULT CCacheTest::EresInsertDuplicates(CCache<SSimpleObject *, ULONG *> *pcache) { ULONG ulDuplicates = 1; if (!pcache->AllowsDuplicateKeys()) { ulDuplicates = GPOS_CACHE_DUPLICATES; } for (ULONG i = 0; i < GPOS_CACHE_ELEMENTS; i++) { for (ULONG j = 0; j < ulDuplicates; j++) { CSimpleObjectCacheAccessor ca(pcache); SSimpleObject *pso = GPOS_NEW(ca.Pmp()) SSimpleObject(i, j); #ifdef GPOS_DEBUG SSimpleObject *psoReturned = #endif // GPOS_DEBUG ca.Insert(&(pso->m_ulKey), pso); GPOS_ASSERT(NULL != psoReturned); pso->Release(); } GPOS_CHECK_ABORT; } { CAutoMemoryPool amp; CMemoryPool *mp = amp.Pmp(); CAutoTrace at(mp); at.Os() << std::endl << "Total memory consumption by cache: " << pcache->TotalAllocatedSize() << " bytes"; at.Os() << std::endl << "Total memory consumption by memory manager: " << CMemoryPoolManager::GetMemoryPoolMgr()->TotalAllocatedSize() << " bytes"; } return GPOS_OK; } //--------------------------------------------------------------------------- // @function: // CCacheTest::EresRemoveDuplicates // // @doc: // Helper function: remove multiple elements with the same key // //--------------------------------------------------------------------------- GPOS_RESULT CCacheTest::EresRemoveDuplicates(CCache<SSimpleObject *, ULONG *> *pcache) { for (ULONG i = 0; i < GPOS_CACHE_ELEMENTS; i++) { GPOS_CHECK_ABORT; CSimpleObjectCacheAccessor ca(pcache); ca.Lookup(&i); ULONG count = 0; SSimpleObject *pso = ca.Val(); GPOS_ASSERT(NULL != pso); if (NULL != pso) { // release object since there is no customer to release it after lookup and before CCache's cleanup pso->Release(); } while (NULL != pso) { GPOS_CHECK_ABORT; GPOS_ASSERT(pso->m_ulValue < GPOS_CACHE_DUPLICATES && "Incorrect entry was found"); if (pso->m_ulValue < GPOS_CACHE_DUPLICATES_TO_DELETE) { ca.MarkForDeletion(); count++; } pso = ca.Next(); } GPOS_ASSERT(count == GPOS_CACHE_DUPLICATES_TO_DELETE && "Incorrect number of deleted entries"); } return GPOS_OK; } //--------------------------------------------------------------------------- // @function: // CCacheTest::EresUnittest_DeepObject // // @doc: // Cache test with deep objects // //--------------------------------------------------------------------------- GPOS_RESULT CCacheTest::EresUnittest_DeepObject() { CAutoMemoryPool amp(CAutoMemoryPool::ElcNone); // construct a key CDeepObject *pdoDummy = GPOS_NEW(amp.Pmp()) CDeepObject(); pdoDummy->AddEntry(amp.Pmp(), 1, 1); pdoDummy->AddEntry(amp.Pmp(), 2, 2); CAutoP<CCache<CDeepObject *, CDeepObject::CDeepObjectList *> > apcache; apcache = CCacheFactory::CreateCache<CDeepObject *, CDeepObject::CDeepObjectList *>( fUnique, UNLIMITED_CACHE_QUOTA, &CDeepObject::UlMyHash, &CDeepObject::FMyEqual); CCache<CDeepObject *, CDeepObject::CDeepObjectList *> *pcache = apcache.Value(); // insertion - scope for accessor { CDeepObjectCacheAccessor ca(pcache); CMemoryPool *mp = ca.Pmp(); CDeepObject *pdo = GPOS_NEW(mp) CDeepObject(); pdo->AddEntry(mp, 1, 1); pdo->AddEntry(mp, 2, 2); #ifdef GPOS_DEBUG CDeepObject *pdoReturned = #endif // GPOS_DEBUG ca.Insert(pdo->Key(), pdo); pdo->Release(); GPOS_ASSERT(NULL != pdoReturned && "Incorrect cache entry was inserted"); // insert duplicate while not allowed if (pcache->AllowsDuplicateKeys()) { CDeepObjectCacheAccessor ca(pcache); CMemoryPool *mp = ca.Pmp(); CDeepObject *pdoDuplicate = GPOS_NEW(mp) CDeepObject(); pdoDuplicate->AddEntry(mp, 1, 5); pdoDuplicate->AddEntry(mp, 2, 5); #ifdef GPOS_DEBUG CDeepObject *pdoReturned = #endif // GPOS_DEBUG ca.Insert(pdoDuplicate->Key(), pdoDuplicate); GPOS_ASSERT(pdoReturned == pdo && "Duplicate insertion must fail"); // delete original cache object ca.MarkForDeletion(); } // lookup - scope for accessor { CDeepObjectCacheAccessor ca(pcache); ca.Lookup(pdoDummy->Key()); pdo = ca.Val(); if (NULL != pdo) { // release object since there is no customer to release it after lookup and before CCache's cleanup pdo->Release(); } GPOS_ASSERT_IMP(pcache->AllowsDuplicateKeys(), NULL == pdo); GPOS_ASSERT_IMP(!pcache->AllowsDuplicateKeys(), NULL != pdo); GPOS_ASSERT_IMP(!pcache->AllowsDuplicateKeys(), 3 == CDeepObject::UlMyHash(pdo->Key()) && "Incorrect cache entry"); } // delete - scope for accessor { CDeepObjectCacheAccessor ca(pcache); ca.Lookup(pdoDummy->Key()); pdo = ca.Val(); GPOS_ASSERT_IMP(!pcache->AllowsDuplicateKeys(), NULL != pdo); if (NULL != pdo) { // release object since there is no customer to release it after lookup and before CCache's cleanup pdo->Release(); ca.MarkForDeletion(); } } // lookup again - scope for accessor { CDeepObjectCacheAccessor ca(pcache); ca.Lookup(pdoDummy->Key()); pdo = ca.Val(); GPOS_ASSERT(NULL == pdo); } // at this point, we still maintain a valid cached object held by the // outmost accessor GPOS_ASSERT(NULL != pdoReturned && 3 == CDeepObject::UlMyHash(pdoReturned->Key())); } return GPOS_OK; } //--------------------------------------------------------------------------- // @function: // CCacheTest::EresUnittest_Iteration // // @doc: // Cache iteration test // //--------------------------------------------------------------------------- GPOS_RESULT CCacheTest::EresUnittest_Iteration() { CAutoP<CCache<SSimpleObject *, ULONG *> > apcache; apcache = CCacheFactory::CreateCache<SSimpleObject *, ULONG *>( fUnique, UNLIMITED_CACHE_QUOTA, SSimpleObject::UlMyHash, SSimpleObject::FMyEqual); CCache<SSimpleObject *, ULONG *> *pcache = apcache.Value(); CCacheTest::EresInsertDuplicates(pcache); #ifdef GPOS_DEBUG ULONG ulDuplicates = 1; if (!pcache->AllowsDuplicateKeys()) { ulDuplicates = GPOS_CACHE_DUPLICATES; } #endif // GPOS_DEBUG for (ULONG i = 0; i < GPOS_CACHE_ELEMENTS; i++) { GPOS_CHECK_ABORT; CSimpleObjectCacheAccessor ca(pcache); ca.Lookup(&i); ULONG count = 0; SSimpleObject *pso = ca.Val(); GPOS_ASSERT(NULL != pso); // release object since there is no customer to release it after lookup and before CCache's cleanup pso->Release(); while (NULL != pso) { GPOS_CHECK_ABORT; GPOS_ASSERT(ulDuplicates > pso->m_ulValue && "Incorrect entry was found"); count++; pso = ca.Next(); } GPOS_ASSERT(count == ulDuplicates && "Incorrect number of duplicates"); } return GPOS_OK; } //--------------------------------------------------------------------------- // @function: // CCacheTest::EresUnittest_IterativeDeletion // // @doc: // Cache iterative deletion test // //--------------------------------------------------------------------------- GPOS_RESULT CCacheTest::EresUnittest_IterativeDeletion() { GPOS_ASSERT(GPOS_CACHE_DUPLICATES >= GPOS_CACHE_DUPLICATES_TO_DELETE); CAutoP<CCache<SSimpleObject *, ULONG *> > apcache; apcache = CCacheFactory::CreateCache<SSimpleObject *, ULONG *>( fUnique, UNLIMITED_CACHE_QUOTA, SSimpleObject::UlMyHash, SSimpleObject::FMyEqual); CCache<SSimpleObject *, ULONG *> *pcache = apcache.Value(); CCacheTest::EresInsertDuplicates(pcache); if (!pcache->AllowsDuplicateKeys()) { CCacheTest::EresRemoveDuplicates(pcache); } #ifdef GPOS_DEBUG ULONG ulDuplicates = 1; ULONG ulDuplicatesToDelete = 0; if (!pcache->AllowsDuplicateKeys()) { ulDuplicates = GPOS_CACHE_DUPLICATES; ulDuplicatesToDelete = GPOS_CACHE_DUPLICATES_TO_DELETE; } ULONG ulRemaining = ulDuplicates - ulDuplicatesToDelete; #endif // GPOS_DEBUG // count remaining duplicate entries for (ULONG i = 0; i < GPOS_CACHE_ELEMENTS; i++) { GPOS_CHECK_ABORT; CSimpleObjectCacheAccessor ca(pcache); ca.Lookup(&i); ULONG count = 0; SSimpleObject *pso = ca.Val(); GPOS_ASSERT_IMP(0 < ulRemaining, NULL != pso); if (NULL != pso) { // release object since there is no customer to release it after lookup and before CCache's cleanup pso->Release(); } while (NULL != pso) { GPOS_CHECK_ABORT; GPOS_ASSERT(pso->m_ulValue >= ulDuplicatesToDelete && "Incorrect entry value was found"); count++; pso = ca.Next(); } GPOS_ASSERT(count == ulRemaining && "Incorrect number of remaining duplicates"); } return GPOS_OK; } // EOF
27.260697
126
0.638245
soumyadeep2007
4f7a47f47f5c2936a021bdd471bcef92905fc271
40,660
cpp
C++
src/pal/src/thread/threadsusp.cpp
CyberSys/coreclr-mono
83b2cb83b32faa45b4f790237b5c5e259692294a
[ "MIT" ]
1
2015-05-22T14:11:51.000Z
2015-05-22T14:11:51.000Z
src/pal/src/thread/threadsusp.cpp
CyberSys/coreclr-mono
83b2cb83b32faa45b4f790237b5c5e259692294a
[ "MIT" ]
null
null
null
src/pal/src/thread/threadsusp.cpp
CyberSys/coreclr-mono
83b2cb83b32faa45b4f790237b5c5e259692294a
[ "MIT" ]
null
null
null
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // /*++ Module Name: threadsusp.cpp Abstract: Implementation of functions related to threads. Revision History: --*/ #include "pal/corunix.hpp" #include "pal/thread.hpp" #include "pal/mutex.hpp" #include "pal/seh.hpp" #include "pal/init.h" #include "pal/dbgmsg.h" #include <pthread.h> #include <unistd.h> #include <errno.h> #include <stddef.h> #include <sys/stat.h> #include <limits.h> #include <debugmacrosext.h> #if defined(_AIX) // AIX requires explicit definition of the union semun (see semctl man page) union semun { int val; struct semid_ds * buf; unsigned short * array; }; #endif using namespace CorUnix; /* ------------------- Definitions ------------------------------*/ SET_DEFAULT_DEBUG_CHANNEL(THREAD); /* This code is written to the blocking pipe of a thread that was created in suspended state in order to resume it. */ CONST BYTE WAKEUPCODE=0x2A; // #define USE_GLOBAL_LOCK_FOR_SUSPENSION // Uncomment this define to use the global suspension lock. /* The global suspension lock can be used in place of each thread having its own suspension mutex or spinlock. The downside is that it restricts us to only performing one suspension or resumption in the PAL at a time. */ #ifdef USE_GLOBAL_LOCK_FOR_SUSPENSION static LONG g_ssSuspensionLock = 0; #endif #if !HAVE_MACH_EXCEPTIONS static sigset_t smDefaultmask; // masks signals that the PAL handles as exceptions. #endif // !HAVE_MACH_EXCEPTIONS #if USE_SIGNALS_FOR_THREAD_SUSPENSION static sigset_t smWaitmask; // used so a thread does not receive a SIGUSR1 or SIGUSR2, during a suspension retry, until it enters sigsuspend static sigset_t smSuspmask; // used when a thread is suspended via signals; blocks all signals except SIGUSR2 static sigset_t smContmask; // used when a thread is in sigsuspend on a suspension retry, waiting to receive a SIGUSR1 #endif // USE_SIGNALS_FOR_THREAD_SUSPENSION /*++ Function: InternalSuspendNewThreadFromData On platforms where we use pipes for starting threads suspended, this function sets the blocking pipe for the thread and blocks until the wakeup code is written to the pipe by ResumeThread. --*/ PAL_ERROR CThreadSuspensionInfo::InternalSuspendNewThreadFromData( CPalThread *pThread ) { PAL_ERROR palError = NO_ERROR; AcquireSuspensionLock(pThread); pThread->suspensionInfo.SetSelfSusp(TRUE); ReleaseSuspensionLock(pThread); int pipe_descs[2]; if (pipe(pipe_descs) == -1) { ERROR("pipe() failed! error is %d (%s)\n", errno, strerror(errno)); return ERROR_NOT_ENOUGH_MEMORY; } // [0] is the read end of the pipe, and [1] is the write end. pThread->suspensionInfo.SetBlockingPipe(pipe_descs[1]); pThread->SetStartStatus(TRUE); BYTE resume_code = 0; ssize_t read_ret; // Block until ResumeThread writes something to the pipe while ((read_ret = read(pipe_descs[0], &resume_code, sizeof(resume_code))) != sizeof(resume_code)) { if (read_ret != -1 || EINTR != errno) { // read might return 0 (with EAGAIN) if the other end of the pipe gets closed palError = ERROR_INTERNAL_ERROR; break; } } if (palError == NO_ERROR && resume_code != WAKEUPCODE) { // If we did read successfully but the byte didn't match WAKEUPCODE, we treat it as a failure. palError = ERROR_INTERNAL_ERROR; } if (palError == NO_ERROR) { AcquireSuspensionLock(pThread); pThread->suspensionInfo.SetSelfSusp(FALSE); ReleaseSuspensionLock(pThread); } // Close the pipes regardless of whether we were successful. close(pipe_descs[0]); close(pipe_descs[1]); return palError; } /*++ Function: ResumeThread See MSDN doc. --*/ DWORD PALAPI ResumeThread( IN HANDLE hThread ) { PAL_ERROR palError; CPalThread *pthrResumer; DWORD dwSuspendCount = (DWORD)-1; PERF_ENTRY(ResumeThread); ENTRY("ResumeThread(hThread=%p)\n", hThread); pthrResumer = InternalGetCurrentThread(); palError = InternalResumeThread( pthrResumer, hThread, &dwSuspendCount ); if (NO_ERROR != palError) { pthrResumer->SetLastError(palError); dwSuspendCount = (DWORD) -1; } else { _ASSERT_MSG(dwSuspendCount != static_cast<DWORD>(-1), "InternalResumeThread returned success but dwSuspendCount did not change.\n"); } LOGEXIT("ResumeThread returns DWORD %u\n", dwSuspendCount); PERF_EXIT(ResumeThread); return dwSuspendCount; } /*++ Function: InternalResumeThread InternalResumeThread converts the handle of the target thread to a CPalThread, and passes both the resumer and target thread references to InternalResumeThreadFromData. A reference to the suspend count from the resumption attempt is passed back to the caller of this function. --*/ PAL_ERROR CorUnix::InternalResumeThread( CPalThread *pthrResumer, HANDLE hTargetThread, DWORD *pdwSuspendCount ) { PAL_ERROR palError = NO_ERROR; CPalThread *pthrTarget = NULL; IPalObject *pobjThread = NULL; palError = InternalGetThreadDataFromHandle( pthrResumer, hTargetThread, 0, // THREAD_SUSPEND_RESUME &pthrTarget, &pobjThread ); if (NO_ERROR == palError) { palError = pthrResumer->suspensionInfo.InternalResumeThreadFromData( pthrResumer, pthrTarget, pdwSuspendCount ); } if (NULL != pobjThread) { pobjThread->ReleaseReference(pthrResumer); } return palError; } /*++ Function: InternalResumeThreadFromData InternalResumeThreadFromData resumes the target thread. First, the suspension mutexes of the threads are acquired. Next, there's a check to ensure that the target thread was actually suspended. Finally, the resume attempt is made and the suspension mutexes are released. The suspend count of the target thread is passed back to the caller of this function. Note that ReleaseSuspensionLock(s) is called before hitting ASSERTs in error paths. Currently, this seems unnecessary since asserting within InternalResumeThreadFromData will not cause cleanup to occur. However, this may change since it would be preferable to perform cleanup. Thus, calls to release suspension locks remain in the error paths. --*/ PAL_ERROR CThreadSuspensionInfo::InternalResumeThreadFromData( CPalThread *pthrResumer, CPalThread *pthrTarget, DWORD *pdwSuspendCount ) { PAL_ERROR palError = NO_ERROR; int nWrittenBytes = -1; if (SignalHandlerThread == pthrTarget->GetThreadType()) { ASSERT("Attempting to resume the signal handling thread, which can never be suspended.\n"); palError = ERROR_INVALID_HANDLE; goto InternalResumeThreadFromDataExit; } // Acquire suspension mutex AcquireSuspensionLocks(pthrResumer, pthrTarget); // Check target thread's state to ensure it hasn't died. // Setting a thread's state to TS_DONE is protected by the // target's suspension mutex. if (pthrTarget->synchronizationInfo.GetThreadState() == TS_DONE) { palError = ERROR_INVALID_HANDLE; ReleaseSuspensionLocks(pthrResumer, pthrTarget); goto InternalResumeThreadFromDataExit; } // If this is a dummy thread, then it represents a process that was created with CREATE_SUSPENDED // and it should have a blocking pipe set. If GetBlockingPipe returns -1 for a dummy thread, then // something is wrong - either CREATE_SUSPENDED wasn't used or the process was already resumed. if (pthrTarget->IsDummy() && -1 == pthrTarget->suspensionInfo.GetBlockingPipe()) { palError = ERROR_INVALID_HANDLE; ERROR("Tried to wake up dummy thread without a blocking pipe.\n"); ReleaseSuspensionLocks(pthrResumer, pthrTarget); goto InternalResumeThreadFromDataExit; } // If there is a blocking pipe on this thread, resume it by writing the wake up code to that pipe. if (-1 != pthrTarget->suspensionInfo.GetBlockingPipe()) { // If write() is interrupted by a signal before writing data, // it returns -1 and sets errno to EINTR. In this case, we // attempt the write() again. writeAgain: nWrittenBytes = write(pthrTarget->suspensionInfo.GetBlockingPipe(), &WAKEUPCODE, sizeof(WAKEUPCODE)); // The size of WAKEUPCODE is 1 byte. If write returns 0, we'll treat it as an error. if (sizeof(WAKEUPCODE) != nWrittenBytes) { // If we are here during process creation, this is most likely caused by the target // process dying before reaching this point and thus breaking the pipe. if (nWrittenBytes == -1 && EPIPE == errno) { palError = ERROR_INVALID_HANDLE; ReleaseSuspensionLocks(pthrResumer, pthrTarget); ERROR("Write failed with EPIPE\n"); goto InternalResumeThreadFromDataExit; } else if (nWrittenBytes == 0 || (nWrittenBytes == -1 && EINTR == errno)) { TRACE("write() failed with EINTR; re-attempting write\n"); goto writeAgain; } else { // Some other error occurred; need to release suspension mutexes before leaving ResumeThread. palError = ERROR_INTERNAL_ERROR; ReleaseSuspensionLocks(pthrResumer, pthrTarget); ASSERT("Write() failed; error is %d (%s)\n", errno, strerror(errno)); goto InternalResumeThreadFromDataExit; } } // Reset blocking pipe to -1 since we're done using it. pthrTarget->suspensionInfo.SetBlockingPipe(-1); ReleaseSuspensionLocks(pthrResumer, pthrTarget); goto InternalResumeThreadFromDataExit; } else { *pdwSuspendCount = 0; palError = ERROR_BAD_COMMAND; } InternalResumeThreadFromDataExit: if (NO_ERROR == palError) { *pdwSuspendCount = 1; } return palError; } /*++ Function: TryAcquireSuspensionLock TryAcquireSuspensionLock is a utility function that tries to acquire a thread's suspension mutex or spinlock. If it succeeds, the function returns TRUE. Otherwise, it returns FALSE. This function is used in AcquireSuspensionLocks. Note that the global lock cannot be acquired in this function since it makes no sense to do so. A thread holding the global lock is the only thread that can perform suspend or resume operations so it doesn't need to acquire a second lock. --*/ BOOL CThreadSuspensionInfo::TryAcquireSuspensionLock( CPalThread* pthrTarget ) { int iPthreadRet = 0; #if DEADLOCK_WHEN_THREAD_IS_SUSPENDED_WHILE_BLOCKED_ON_MUTEX { iPthreadRet = SPINLOCKTryAcquire(pthrTarget->suspensionInfo.GetSuspensionSpinlock()); } #else // DEADLOCK_WHEN_THREAD_IS_SUSPENDED_WHILE_BLOCKED_ON_MUTEX { iPthreadRet = pthread_mutex_trylock(pthrTarget->suspensionInfo.GetSuspensionMutex()); _ASSERT_MSG(iPthreadRet == 0 || iPthreadRet == EBUSY, "pthread_mutex_trylock returned %d\n", iPthreadRet); } #endif // DEADLOCK_WHEN_THREAD_IS_SUSPENDED_WHILE_BLOCKED_ON_MUTEX // If iPthreadRet is 0, lock acquisition was successful. Otherwise, it failed. return (iPthreadRet == 0); } /*++ Function: AcquireSuspensionLock AcquireSuspensionLock acquires a thread's suspension mutex or spinlock. If USE_GLOBAL_LOCK_FOR_SUSPENSION is defined, it will acquire the global lock. A thread in this function blocks until it acquires its lock, unlike in TryAcquireSuspensionLock. --*/ void CThreadSuspensionInfo::AcquireSuspensionLock( CPalThread* pthrCurrent ) { #ifdef USE_GLOBAL_LOCK_FOR_SUSPENSION { SPINLOCKAcquire(&g_ssSuspensionLock, 0); } #else // USE_GLOBAL_LOCK_FOR_SUSPENSION { #if DEADLOCK_WHEN_THREAD_IS_SUSPENDED_WHILE_BLOCKED_ON_MUTEX { SPINLOCKAcquire(&pthrCurrent->suspensionInfo.m_nSpinlock, 0); } #else // DEADLOCK_WHEN_THREAD_IS_SUSPENDED_WHILE_BLOCKED_ON_MUTEX { INDEBUG(int iPthreadError = ) pthread_mutex_lock(&pthrCurrent->suspensionInfo.m_ptmSuspmutex); _ASSERT_MSG(iPthreadError == 0, "pthread_mutex_lock returned %d\n", iPthreadError); } #endif // DEADLOCK_WHEN_THREAD_IS_SUSPENDED_WHILE_BLOCKED_ON_MUTEX } #endif // USE_GLOBAL_LOCK_FOR_SUSPENSION } /*++ Function: ReleaseSuspensionLock ReleaseSuspensionLock is a function that releases a thread's suspension mutex or spinlock. If USE_GLOBAL_LOCK_FOR_SUSPENSION is defined, it will release the global lock. --*/ void CThreadSuspensionInfo::ReleaseSuspensionLock( CPalThread* pthrCurrent ) { #ifdef USE_GLOBAL_LOCK_FOR_SUSPENSION { SPINLOCKRelease(&g_ssSuspensionLock); } #else // USE_GLOBAL_LOCK_FOR_SUSPENSION { #if DEADLOCK_WHEN_THREAD_IS_SUSPENDED_WHILE_BLOCKED_ON_MUTEX { SPINLOCKRelease(&pthrCurrent->suspensionInfo.m_nSpinlock); } #else // DEADLOCK_WHEN_THREAD_IS_SUSPENDED_WHILE_BLOCKED_ON_MUTEX { INDEBUG(int iPthreadError = ) pthread_mutex_unlock(&pthrCurrent->suspensionInfo.m_ptmSuspmutex); _ASSERT_MSG(iPthreadError == 0, "pthread_mutex_unlock returned %d\n", iPthreadError); } #endif // DEADLOCK_WHEN_THREAD_IS_SUSPENDED_WHILE_BLOCKED_ON_MUTEX } #endif // USE_GLOBAL_LOCK_FOR_SUSPENSION } /*++ Function: AcquireSuspensionLocks AcquireSuspensionLocks is used to acquire the suspension locks of a suspender (or resumer) and target thread. The thread will perform a blocking call to acquire its own suspension lock and will then try to acquire the target thread's lock without blocking. If it fails to acquire the target's lock, it releases its own lock and the thread will try to acquire both locks again. The key is that both locks must be acquired together. Originally, only blocking calls were used to acquire the suspender and the target lock. However, this was problematic since a thread could acquire its own lock and then block on acquiring the target lock. In the meantime, the target could have already acquired its own lock and be attempting to suspend the suspender thread. This clearly causes deadlock. A second approach used locking hierarchies, where locks were acquired use thread id ordering. This was better but suffered from the scenario where thread A acquires thread B's suspension mutex first. In the meantime, thread C acquires thread A's suspension mutex and its own. Thus, thread A is suspended while holding thread B's mutex. This is problematic if thread C now wants to suspend thread B. The issue here is that a thread can be suspended while holding someone else's mutex but not holding its own. In the end, the correct approach is to always acquire your suspension mutex first. This prevents you from being suspended while holding the target's mutex. Then, attempt to acquire the target's mutex. If the mutex cannot be acquired, release your own and try again. This all or nothing approach is the safest and avoids nasty race conditions. If USE_GLOBAL_LOCK_FOR_SUSPENSION is defined, the calling thread will acquire the global lock when possible. --*/ VOID CThreadSuspensionInfo::AcquireSuspensionLocks( CPalThread *pthrSuspender, CPalThread *pthrTarget ) { BOOL fReacquire = FALSE; #ifdef USE_GLOBAL_LOCK_FOR_SUSPENSION AcquireSuspensionLock(pthrSuspender); #else // USE_GLOBAL_LOCK_FOR_SUSPENSION do { fReacquire = FALSE; AcquireSuspensionLock(pthrSuspender); if (!TryAcquireSuspensionLock(pthrTarget)) { // pthread_mutex_trylock returned EBUSY so release the first lock and try again. ReleaseSuspensionLock(pthrSuspender); fReacquire = TRUE; sched_yield(); } } while (fReacquire); #endif // USE_GLOBAL_LOCK_FOR_SUSPENSION // Whenever the native implementation for the wait subsystem's thread // blocking requires a lock as protection (as pthread conditions do with // the associated mutex), we need to grab that lock to prevent the target // thread from being suspended while holding the lock. // Failing to do so can lead to a multiple threads deadlocking such as the // one described in VSW 363793. // In general, in similar scenarios, we need to grab the protecting lock // every time suspension safety/unsafety is unbalanced on the two sides // using the same condition (or any other native blocking support which // needs an associated native lock), i.e. when either the signaling // thread(s) is(are) signaling from an unsafe area and the waiting // thread(s) is(are) waiting from a safe one, or vice versa (the scenario // described in VSW 363793 is a good example of the first type of // unbalanced suspension safety/unsafety). // Instead, whenever signaling and waiting sides are both marked safe or // unsafe, the deadlock cannot take place since either the suspending // thread will suspend them anyway (regardless of the native lock), or it // won't suspend any of them, since they are both marked unsafe. // Such a balanced scenario applies, for instance, to critical sections // where depending on whether the target CS is internal or not, both the // signaling and the waiting side will access the mutex/condition from // respectively an unsafe or safe region. pthrTarget->AcquireNativeWaitLock(); } /*++ Function: ReleaseSuspensionLocks ReleaseSuspensionLocks releases both thread's suspension mutexes. Note that the locks are released in the opposite order they're acquired. This prevents a suspending or resuming thread from being suspended while holding the target's lock. If USE_GLOBAL_LOCK_FOR_SUSPENSION is defined, it simply releases the global lock. --*/ VOID CThreadSuspensionInfo::ReleaseSuspensionLocks( CPalThread *pthrSuspender, CPalThread *pthrTarget ) { // See comment in AcquireSuspensionLocks pthrTarget->ReleaseNativeWaitLock(); #ifdef USE_GLOBAL_LOCK_FOR_SUSPENSION ReleaseSuspensionLock(pthrSuspender); #else // USE_GLOBAL_LOCK_FOR_SUSPENSION ReleaseSuspensionLock(pthrTarget); ReleaseSuspensionLock(pthrSuspender); #endif // USE_GLOBAL_LOCK_FOR_SUSPENSION } /*++ Function: PostOnSuspendSemaphore PostOnSuspendSemaphore is a utility function for a thread to post on its POSIX or SysV suspension semaphore. --*/ void CThreadSuspensionInfo::PostOnSuspendSemaphore() { #if USE_POSIX_SEMAPHORES if (sem_post(&m_semSusp) == -1) { ASSERT("sem_post returned -1 and set errno to %d (%s)\n", errno, strerror(errno)); } #elif USE_SYSV_SEMAPHORES if (semop(m_nSemsuspid, &m_sbSempost, 1) == -1) { ASSERT("semop - post returned -1 and set errno to %d (%s)\n", errno, strerror(errno)); } #elif USE_PTHREAD_CONDVARS int status; // The suspending thread may not have entered the wait yet, in which case the cond var // signal below will be a no-op. To prevent the race condition we set m_fSuspended to // TRUE first (which the suspender will take as an indication that no wait is required). // But the setting of the flag and the signal must appear atomic to the suspender (as // reading the flag and potentially waiting must appear to us) to avoid the race // condition where the suspender reads the flag as FALSE, we set it and signal and the // suspender then waits. // Acquire the suspend mutex. Once we enter the critical section the suspender has // either gotten there before us (and is waiting for our signal) or is yet to even // check the flag (so we can set it here to stop them attempting a wait). status = pthread_mutex_lock(&m_mutexSusp); if (status != 0) { ASSERT("pthread_mutex_lock returned %d (%s)\n", status, strerror(status)); } m_fSuspended = TRUE; status = pthread_cond_signal(&m_condSusp); if (status != 0) { ASSERT("pthread_cond_signal returned %d (%s)\n", status, strerror(status)); } status = pthread_mutex_unlock(&m_mutexSusp); if (status != 0) { ASSERT("pthread_mutex_unlock returned %d (%s)\n", status, strerror(status)); } #endif // USE_POSIX_SEMAPHORES } /*++ Function: WaitOnSuspendSemaphore WaitOnSuspendSemaphore is a utility function for a thread to wait on its POSIX or SysV suspension semaphore. --*/ void CThreadSuspensionInfo::WaitOnSuspendSemaphore() { #if USE_POSIX_SEMAPHORES while (sem_wait(&m_semSusp) == -1) { ASSERT("sem_wait returned -1 and set errno to %d (%s)\n", errno, strerror(errno)); } #elif USE_SYSV_SEMAPHORES while (semop(m_nSemsuspid, &m_sbSemwait, 1) == -1) { ASSERT("semop wait returned -1 and set errno to %d (%s)\n", errno, strerror(errno)); } #elif USE_PTHREAD_CONDVARS int status; // By the time we wait the target thread may have already signalled its suspension (in // which case m_fSuspended will be TRUE and we shouldn't wait on the cond var). But we // must check the flag and potentially wait atomically to avoid the race where we read // the flag and the target thread sets it and signals before we have a chance to wait. status = pthread_mutex_lock(&m_mutexSusp); if (status != 0) { ASSERT("pthread_mutex_lock returned %d (%s)\n", status, strerror(status)); } // If the target has already acknowledged the suspend we shouldn't wait. while (!m_fSuspended) { // We got here before the target could signal. Wait on them (which atomically releases // the mutex during the wait). status = pthread_cond_wait(&m_condSusp, &m_mutexSusp); if (status != 0) { ASSERT("pthread_cond_wait returned %d (%s)\n", status, strerror(status)); } } status = pthread_mutex_unlock(&m_mutexSusp); if (status != 0) { ASSERT("pthread_mutex_unlock returned %d (%s)\n", status, strerror(status)); } #endif // USE_POSIX_SEMAPHORES } /*++ Function: PostOnResumeSemaphore PostOnResumeSemaphore is a utility function for a thread to post on its POSIX or SysV resume semaphore. --*/ void CThreadSuspensionInfo::PostOnResumeSemaphore() { #if USE_POSIX_SEMAPHORES if (sem_post(&m_semResume) == -1) { ASSERT("sem_post returned -1 and set errno to %d (%s)\n", errno, strerror(errno)); } #elif USE_SYSV_SEMAPHORES if (semop(m_nSemrespid, &m_sbSempost, 1) == -1) { ASSERT("semop - post returned -1 and set errno to %d (%s)\n", errno, strerror(errno)); } #elif USE_PTHREAD_CONDVARS int status; // The resuming thread may not have entered the wait yet, in which case the cond var // signal below will be a no-op. To prevent the race condition we set m_fResumed to // TRUE first (which the resumer will take as an indication that no wait is required). // But the setting of the flag and the signal must appear atomic to the resumer (as // reading the flag and potentially waiting must appear to us) to avoid the race // condition where the resumer reads the flag as FALSE, we set it and signal and the // resumer then waits. // Acquire the resume mutex. Once we enter the critical section the resumer has // either gotten there before us (and is waiting for our signal) or is yet to even // check the flag (so we can set it here to stop them attempting a wait). status = pthread_mutex_lock(&m_mutexResume); if (status != 0) { ASSERT("pthread_mutex_lock returned %d (%s)\n", status, strerror(status)); } m_fResumed = TRUE; status = pthread_cond_signal(&m_condResume); if (status != 0) { ASSERT("pthread_cond_signal returned %d (%s)\n", status, strerror(status)); } status = pthread_mutex_unlock(&m_mutexResume); if (status != 0) { ASSERT("pthread_mutex_unlock returned %d (%s)\n", status, strerror(status)); } #endif // USE_POSIX_SEMAPHORES } /*++ Function: WaitOnResumeSemaphore WaitOnResumeSemaphore is a utility function for a thread to wait on its POSIX or SysV resume semaphore. --*/ void CThreadSuspensionInfo::WaitOnResumeSemaphore() { #if USE_POSIX_SEMAPHORES while (sem_wait(&m_semResume) == -1) { ASSERT("sem_wait returned -1 and set errno to %d (%s)\n", errno, strerror(errno)); } #elif USE_SYSV_SEMAPHORES while (semop(m_nSemrespid, &m_sbSemwait, 1) == -1) { ASSERT("semop wait returned -1 and set errno to %d (%s)\n", errno, strerror(errno)); } #elif USE_PTHREAD_CONDVARS int status; // By the time we wait the target thread may have already signalled its resumption (in // which case m_fResumed will be TRUE and we shouldn't wait on the cond var). But we // must check the flag and potentially wait atomically to avoid the race where we read // the flag and the target thread sets it and signals before we have a chance to wait. status = pthread_mutex_lock(&m_mutexResume); if (status != 0) { ASSERT("pthread_mutex_lock returned %d (%s)\n", status, strerror(status)); } // If the target has already acknowledged the resume we shouldn't wait. while (!m_fResumed) { // We got here before the target could signal. Wait on them (which atomically releases // the mutex during the wait). status = pthread_cond_wait(&m_condResume, &m_mutexResume); if (status != 0) { ASSERT("pthread_cond_wait returned %d (%s)\n", status, strerror(status)); } } status = pthread_mutex_unlock(&m_mutexResume); if (status != 0) { ASSERT("pthread_mutex_unlock returned %d (%s)\n", status, strerror(status)); } #endif // USE_POSIX_SEMAPHORES } #if !HAVE_MACH_EXCEPTIONS || USE_SIGNALS_FOR_THREAD_SUSPENSION /*++ Function: InitializeSignalSets InitializeSignalSets initializes the signal masks used for thread suspension operations. Each thread's signal mask is initially set to smDefaultMask in InitializePreCreate. This mask blocks SIGUSR2, and SIGUSR1 if suspension using signals is off. This mask also blocks common signals so they will be handled by the PAL's signal handling thread. --*/ VOID CThreadSuspensionInfo::InitializeSignalSets() { #if !HAVE_MACH_EXCEPTIONS sigemptyset(&smDefaultmask); #ifndef DO_NOT_USE_SIGNAL_HANDLING_THREAD // The default signal mask masks all common signals except those that represent // synchronous exceptions in the PAL or are used by the system (e.g. SIGPROF on BSD). // Note that SIGPROF is used by the BSD thread scheduler and masking it caused a // significant reduction in performance. sigaddset(&smDefaultmask, SIGHUP); sigaddset(&smDefaultmask, SIGABRT); #ifdef SIGEMT sigaddset(&smDefaultmask, SIGEMT); #endif sigaddset(&smDefaultmask, SIGSYS); sigaddset(&smDefaultmask, SIGALRM); sigaddset(&smDefaultmask, SIGURG); sigaddset(&smDefaultmask, SIGTSTP); sigaddset(&smDefaultmask, SIGCONT); sigaddset(&smDefaultmask, SIGCHLD); sigaddset(&smDefaultmask, SIGTTIN); sigaddset(&smDefaultmask, SIGTTOU); sigaddset(&smDefaultmask, SIGIO); sigaddset(&smDefaultmask, SIGXCPU); sigaddset(&smDefaultmask, SIGXFSZ); sigaddset(&smDefaultmask, SIGVTALRM); sigaddset(&smDefaultmask, SIGWINCH); #ifdef SIGINFO sigaddset(&smDefaultmask, SIGINFO); #endif sigaddset(&smDefaultmask, SIGPIPE); sigaddset(&smDefaultmask, SIGUSR2); #if !USE_SIGNALS_FOR_THREAD_SUSPENSION { // Don't mask SIGUSR1 if using signal suspension since SIGUSR1 is needed // to suspend threads. sigaddset(&smDefaultmask, SIGUSR1); } #endif // !USE_SIGNALS_FOR_THREAD_SUSPENSION #endif // DO_NOT_USE_SIGNAL_HANDLING_THREAD #endif // !HAVE_MACH_EXCEPTIONS #if USE_SIGNALS_FOR_THREAD_SUSPENSION #if !HAVE_MACH_EXCEPTIONS #ifdef DO_NOT_USE_SIGNAL_HANDLING_THREAD { // If the SWT is turned on, SIGUSR2 was already added to the mask. // Otherwise, add it to the mask now. sigaddset(&smDefaultmask, SIGUSR2); } #endif #endif // !HAVE_MACH_EXCEPTIONS // smContmask is used to allow a thread to accept a SIGUSR1 when in sigsuspend, // after a pending suspension sigfillset(&smContmask); sigdelset(&smContmask, SIGUSR1); // smSuspmask is used in sigsuspend during a safe suspension attempt. sigfillset(&smSuspmask); sigdelset(&smSuspmask, SIGUSR2); // smWaitmask forces a thread to wait for a SIGUSR1 during a suspension retry sigemptyset(&smWaitmask); sigaddset(&smWaitmask, SIGUSR1); sigaddset(&smWaitmask, SIGUSR2); #endif // USE_SIGNALS_FOR_THREAD_SUSPENSION } #endif // !HAVE_MACH_EXCEPTIONS || USE_SIGNALS_FOR_THREAD_SUSPENSION /*++ Function: InitializeSuspensionLock InitializeSuspensionLock initializes a thread's suspension spinlock or suspension mutex. It is called from the CThreadSuspensionInfo constructor. --*/ VOID CThreadSuspensionInfo::InitializeSuspensionLock() { #if DEADLOCK_WHEN_THREAD_IS_SUSPENDED_WHILE_BLOCKED_ON_MUTEX SPINLOCKInit(&m_nSpinlock); #else int iError = pthread_mutex_init(&m_ptmSuspmutex, NULL); if (0 != iError ) { ASSERT("pthread_mutex_init(&suspmutex) returned %d\n", iError); return; } m_fSuspmutexInitialized = TRUE; #endif // DEADLOCK_WHEN_THREAD_IS_SUSPENDED_WHILE_BLOCKED_ON_MUTEX } /*++ Function: InitializePreCreate InitializePreCreate initializes the semaphores and signal masks used for thread suspension. At the end, it sets the calling thread's signal mask to the default signal mask. --*/ PAL_ERROR CThreadSuspensionInfo::InitializePreCreate() { PAL_ERROR palError = ERROR_INTERNAL_ERROR; int iError = 0; #if SEM_INIT_MODIFIES_ERRNO int nStoredErrno; #endif // SEM_INIT_MODIFIES_ERRNO #if USE_POSIX_SEMAPHORES #if SEM_INIT_MODIFIES_ERRNO nStoredErrno = errno; #endif // SEM_INIT_MODIFIES_ERRNO // initialize suspension semaphore iError = sem_init(&m_semSusp, 0, 0); #if SEM_INIT_MODIFIES_ERRNO if (iError == 0) { // Restore errno if sem_init succeeded. errno = nStoredErrno; } #endif // SEM_INIT_MODIFIES_ERRNO if (0 != iError ) { ASSERT("sem_init(&suspsem) returned %d\n", iError); goto InitializePreCreateExit; } #if SEM_INIT_MODIFIES_ERRNO nStoredErrno = errno; #endif // SEM_INIT_MODIFIES_ERRNO // initialize resume semaphore iError = sem_init(&m_semResume, 0, 0); #if SEM_INIT_MODIFIES_ERRNO if (iError == 0) { // Restore errno if sem_init succeeded. errno = nStoredErrno; } #endif // SEM_INIT_MODIFIES_ERRNO if (0 != iError ) { ASSERT("sem_init(&suspsem) returned %d\n", iError); sem_destroy(&m_semSusp); goto InitializePreCreateExit; } m_fSemaphoresInitialized = TRUE; #elif USE_SYSV_SEMAPHORES // preparing to initialize the SysV semaphores. union semun semunData; m_nSemsuspid = semget(IPC_PRIVATE, 1, IPC_CREAT | 0666); if (m_nSemsuspid == -1) { ASSERT("semget for suspension sem id returned -1 and set errno to %d (%s)\n", errno, strerror(errno)); goto InitializePreCreateExit; } m_nSemrespid = semget(IPC_PRIVATE, 1, IPC_CREAT | 0666); if (m_nSemrespid == -1) { ASSERT("semget for resumption sem id returned -1 and set errno to %d (%s)\n", errno, strerror(errno)); goto InitializePreCreateExit; } if (m_nSemsuspid == m_nSemrespid) { ASSERT("Suspension and Resumption Semaphores have the same id\n"); goto InitializePreCreateExit; } semunData.val = 0; iError = semctl(m_nSemsuspid, 0, SETVAL, semunData); if (iError == -1) { ASSERT("semctl for suspension sem id returned -1 and set errno to %d (%s)\n", errno, strerror(errno)); goto InitializePreCreateExit; } semunData.val = 0; iError = semctl(m_nSemrespid, 0, SETVAL, semunData); if (iError == -1) { ASSERT("semctl for resumption sem id returned -1 and set errno to %d (%s)\n", errno, strerror(errno)); goto InitializePreCreateExit; } // initialize suspend semaphore m_sbSemwait.sem_num = 0; m_sbSemwait.sem_op = -1; m_sbSemwait.sem_flg = 0; // initialize resume semaphore m_sbSempost.sem_num = 0; m_sbSempost.sem_op = 1; m_sbSempost.sem_flg = 0; #elif USE_PTHREAD_CONDVARS iError = pthread_cond_init(&m_condSusp, NULL); if (iError != 0) { ASSERT("pthread_cond_init for suspension returned %d (%s)\n", iError, strerror(iError)); goto InitializePreCreateExit; } iError = pthread_mutex_init(&m_mutexSusp, NULL); if (iError != 0) { ASSERT("pthread_mutex_init for suspension returned %d (%s)\n", iError, strerror(iError)); goto InitializePreCreateExit; } iError = pthread_cond_init(&m_condResume, NULL); if (iError != 0) { ASSERT("pthread_cond_init for resume returned %d (%s)\n", iError, strerror(iError)); goto InitializePreCreateExit; } iError = pthread_mutex_init(&m_mutexResume, NULL); if (iError != 0) { ASSERT("pthread_mutex_init for resume returned %d (%s)\n", iError, strerror(iError)); goto InitializePreCreateExit; } m_fSemaphoresInitialized = TRUE; #endif // USE_POSIX_SEMAPHORES #if USE_SIGNALS_FOR_THREAD_SUSPENSION // m_smOrigmask is used to restore a thread's signal mask. // This is not needed for sigsuspend operations since sigsuspend // automatically restores the original mask sigemptyset(&m_smOrigmask); #endif #if !HAVE_MACH_EXCEPTIONS // This signal mask blocks SIGUSR2 when signal suspension is turned on // (SIGUSR2 must be blocked for signal suspension), and masks other signals // when the signal waiting thread is turned on. We must use SIG_SETMASK // so all threads start with the same signal mask. Otherwise, issues can arise. // For example, on BSD using suspension with signals, the control handler // routine thread, spawned from the signal handling thread, inherits the // signal handling thread's mask which blocks SIGUSR1. Thus, the // control handler routine thread cannot be suspended. Using SETMASK // ensures that SIGUSR1 is not blocked. iError = pthread_sigmask(SIG_SETMASK, &smDefaultmask, NULL); if (iError != 0) { ASSERT("pthread sigmask(SIG_SETMASK, &smDefaultmask) returned %d\n", iError); goto InitializePreCreateExit; } #endif // !HAVE_MACH_EXCEPTIONS // Initialization was successful. palError = NO_ERROR; InitializePreCreateExit: if (NO_ERROR == palError && 0 != iError) { switch (iError) { case ENOMEM: case EAGAIN: { palError = ERROR_OUTOFMEMORY; break; } default: { ASSERT("A pthrSuspender init call returned %d (%s)\n", iError, strerror(iError)); palError = ERROR_INTERNAL_ERROR; } } } return palError; } CThreadSuspensionInfo::~CThreadSuspensionInfo() { #if !DEADLOCK_WHEN_THREAD_IS_SUSPENDED_WHILE_BLOCKED_ON_MUTEX if (m_fSuspmutexInitialized) { INDEBUG(int iError = ) pthread_mutex_destroy(&m_ptmSuspmutex); _ASSERT_MSG(0 == iError, "pthread_mutex_destroy returned %d (%s)\n", iError, strerror(iError)); } #endif #if USE_POSIX_SEMAPHORES if (m_fSemaphoresInitialized) { int iError; iError = sem_destroy(&m_semSusp); _ASSERT_MSG(0 == iError, "sem_destroy failed and set errno to %d (%s)\n", errno, strerror(errno)); iError = sem_destroy(&m_semResume); _ASSERT_MSG(0 == iError, "sem_destroy failed and set errno to %d (%s)\n", errno, strerror(errno)); } #elif USE_SYSV_SEMAPHORES DestroySemaphoreIds(); #elif USE_PTHREAD_CONDVARS if (m_fSemaphoresInitialized) { int iError; iError = pthread_cond_destroy(&m_condSusp); _ASSERT_MSG(0 == iError, "pthread_cond_destroy failed with %d (%s)\n", iError, strerror(iError)); iError = pthread_mutex_destroy(&m_mutexSusp); _ASSERT_MSG(0 == iError, "pthread_mutex_destroy failed with %d (%s)\n", iError, strerror(iError)); iError = pthread_cond_destroy(&m_condResume); _ASSERT_MSG(0 == iError, "pthread_cond_destroy failed with %d (%s)\n", iError, strerror(iError)); iError = pthread_mutex_destroy(&m_mutexResume); _ASSERT_MSG(0 == iError, "pthread_mutex_destroy failed with %d (%s)\n", iError, strerror(iError)); } #endif // USE_POSIX_SEMAPHORES } #if USE_SYSV_SEMAPHORES /*++ Function: DestroySemaphoreIds DestroySemaphoreIds is called from the CThreadSuspensionInfo destructor and from PROCCleanupThreadSemIds. If a thread exits before shutdown or is suspended during shutdown, its destructor will be invoked and the semaphore ids destroyed. In assert or exceptions situations that are suspension unsafe, PROCCleanupThreadSemIds is called, which uses DestroySemaphoreIds. --*/ void CThreadSuspensionInfo::DestroySemaphoreIds() { union semun semunData; if (m_nSemsuspid != 0) { semunData.val = 0; if (0 != semctl(m_nSemsuspid, 0, IPC_RMID, semunData)) { ERROR("semctl(Semsuspid) failed and set errno to %d (%s)\n", errno, strerror(errno)); } else { m_nSemsuspid = 0; } } if (this->m_nSemrespid) { semunData.val = 0; if (0 != semctl(m_nSemrespid, 0, IPC_RMID, semunData)) { ERROR("semctl(Semrespid) failed and set errno to %d (%s)\n", errno, strerror(errno)); } else { m_nSemrespid = 0; } } } #endif // USE_SYSV_SEMAPHORES #if USE_SIGNALS_FOR_THREAD_SUSPENSION /*++ Function: HandleSuspendSignal Returns: true if the signal is expected by this PAL instance; false should be chained to the next signal handler. HandleSuspendSignal is called from within the SIGUSR1 handler. The thread that invokes this function will suspend itself if it's suspension safe or set its pending flag to TRUE and continue executing until it becomes suspension safe. --*/ bool CThreadSuspensionInfo::HandleSuspendSignal( CPalThread *pthrTarget ) { if (!GetSuspendSignalSent()) { return false; } SetSuspendSignalSent(FALSE); if (IsSuspensionStateSafe()) { SetSuspPending(FALSE); if (!pthrTarget->GetCreateSuspended()) { /* Note that we don't call sem_post when CreateSuspended is true. This is to handle the scenario where a thread suspends itself and another thread then attempts to suspend that thread. It won't wait on the semaphore if the self suspending thread already posted but didn't reach the matching wait. */ PostOnSuspendSemaphore(); } else { pthrTarget->SetStartStatus(TRUE); } sigsuspend(&smSuspmask); } else { SetSuspPending(TRUE); } return true; } /*++ Function: HandleResumeSignal Returns: true if the signal is expected by this PAL instance; false should be chained to the next signal handler. HandleResumeSignal is called from within the SIGUSR2 handler. A thread suspended by sigsuspend will enter the SUGUSR2 handler and reach this function, which checks that SIGUSR2 was sent by InternalResumeThreadFromData and that the resumed thread still has a positive suspend count. After these checks, the resumed thread posts on its resume semaphore so the resuming thread can continue execution. --*/ bool CThreadSuspensionInfo::HandleResumeSignal() { if (!GetResumeSignalSent()) { return false; } SetResumeSignalSent(FALSE); // This thread is no longer suspended - if it self suspended, // then its self suspension field should now be set to FALSE. if (GetSelfSusp()) { SetSelfSusp(FALSE); } PostOnResumeSemaphore(); return true; } #endif // USE_SIGNALS_FOR_THREAD_SUSPENSION
32.269841
143
0.697049
CyberSys
4f7b0b54b537ceb2d02a0147f50c33123ddfc8ef
1,914
cpp
C++
assignment07/assignment7-2.cpp
qpakzk/SSU-CSE-Problem-Solving
44cc6b913d86008c2f23536ed0c395115b6ccef6
[ "MIT" ]
null
null
null
assignment07/assignment7-2.cpp
qpakzk/SSU-CSE-Problem-Solving
44cc6b913d86008c2f23536ed0c395115b6ccef6
[ "MIT" ]
null
null
null
assignment07/assignment7-2.cpp
qpakzk/SSU-CSE-Problem-Solving
44cc6b913d86008c2f23536ed0c395115b6ccef6
[ "MIT" ]
null
null
null
/* * Problem Solving Assignment7-2 : 여행 계획 세우기 * https://www.acmicpc.net/problem/2152 */ #include <cstdio> #include <vector> #include <stack> #include <cstring> #define MAXLEN 10001 using namespace std; int N, M, S, T; vector<vector<int> > G, GI, GG; bool visited[MAXLEN]; int g_num, group[MAXLEN], g_cnt[MAXLEN], result[MAXLEN]; stack<int> s; int max(int a, int b) { return a > b ? a : b; } void DFS(int v) { visited[v] = true; for(int i = 0; i < G[v].size(); i++) if(!visited[G[v][i]]) DFS(G[v][i]); s.push(v); } void SCC(int v) { visited[v] = true; group[v] = g_num; g_cnt[g_num]++; for(int i = 0; i < GI[v].size(); i++) if(!visited[GI[v][i]]) SCC(GI[v][i]); } void DFS2(int v, int weight) { result[v] = max(result[v], weight); for(int i = 0; i < GG[v].size(); i++) { if(result[v] + g_cnt[GG[v][i]] > result[GG[v][i]]) DFS2(GG[v][i], g_cnt[GG[v][i]] + result[v]); } visited[v] = false; } int main(void) { scanf("%d %d %d %d", &N, &M, &S, &T); G.resize(N + 1); GI.resize(N + 1); for(int m = 1; m <= M; m++) { int A, B; scanf("%d %d", &A, &B); G[A].push_back(B); GI[B].push_back(A); } memset(visited, 0, sizeof(visited)); for(int n = 1; n <= N; n++) { if (!visited[n]) DFS(n); } memset(visited, 0, sizeof(visited)); while(!s.empty()) { int v = s.top(); s.pop(); if(!visited[v]) { g_num++; SCC(v); } } GG.resize(g_num + 1); for (int i = 1; i <= N; i++) for(int j = 0; j < G[i].size(); j++) if (group[i] != group[G[i][j]]) GG[group[i]].push_back(group[G[i][j]]); memset(visited, 0, sizeof(visited)); DFS2(group[S], g_cnt[group[S]]); printf("%d\n", result[group[T]]); return 0; }
21.505618
58
0.474399
qpakzk
4f7c5b63f1b16711787957c7c62659cdfd576be3
1,656
cpp
C++
host/display/balance_layer.cpp
wmax351/airball-embedded
204189922415b0f3cbef5dda14fa137e3c806a7d
[ "MIT" ]
null
null
null
host/display/balance_layer.cpp
wmax351/airball-embedded
204189922415b0f3cbef5dda14fa137e3c806a7d
[ "MIT" ]
null
null
null
host/display/balance_layer.cpp
wmax351/airball-embedded
204189922415b0f3cbef5dda14fa137e3c806a7d
[ "MIT" ]
null
null
null
#include "balance_layer.h" #include <algorithm> #include <mutex> namespace airball { double valid_gain(double x) { return std::max(0.0, std::min(1.0, x)); } balance_layer::balance_layer( double left_gain, double right_gain, snd_pcm_uframes_t ramp_period) { goal_ = { valid_gain(left_gain), valid_gain(right_gain), }; current_ = goal_; set_ramp_period(ramp_period); } void balance_layer::set_gains(double left_gain, double right_gain) { std::lock_guard<std::mutex> lock(mu_); goal_ = { valid_gain(left_gain), valid_gain(right_gain), }; } void balance_layer::set_ramp_period(snd_pcm_uframes_t ramp_period) { std::lock_guard<std::mutex> lock(mu_); ramp_period_ = ramp_period; gain_step_per_sample_ = 1.0 / (double) ramp_period_; } void balance_layer::step_gains_to_goal() { current_ = { step_gain_to_goal(current_.left, goal_.left), step_gain_to_goal(current_.right, goal_.right), }; } double sign(double x) { return x < 0 ? -1.0 : 1.0; } double balance_layer::step_gain_to_goal(double current, double goal) { if (abs(goal - current) < gain_step_per_sample_) { return goal; } return current + gain_step_per_sample_ * sign(goal - current); } int16_t scale_value(int16_t value, double scaling) { return (int16_t) ((double) value * scaling); } void balance_layer::apply(int16_t* buf, snd_pcm_uframes_t frames) { std::lock_guard<std::mutex> lock(mu_); for (size_t i = 0; i < frames; i++) { step_gains_to_goal(); *buf = scale_value(*buf, current_.left); buf++; *buf = scale_value(*buf, current_.right); buf++; } } } // namespace airball
22.684932
70
0.688406
wmax351
4f7ca119e6142e3d538b5b0114dd6849cbacc1a6
9,291
cc
C++
tests/unittests/stream_unittest.cc
curasystems/cef
75bf737f56659bdc8e441b2e4e0cb8b343936dc4
[ "BSD-3-Clause" ]
1
2015-11-23T12:12:08.000Z
2015-11-23T12:12:08.000Z
tests/unittests/stream_unittest.cc
curasystems/cef
75bf737f56659bdc8e441b2e4e0cb8b343936dc4
[ "BSD-3-Clause" ]
null
null
null
tests/unittests/stream_unittest.cc
curasystems/cef
75bf737f56659bdc8e441b2e4e0cb8b343936dc4
[ "BSD-3-Clause" ]
1
2020-02-13T08:12:07.000Z
2020-02-13T08:12:07.000Z
// Copyright (c) 2009 The Chromium Embedded Framework 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 "include/cef_stream.h" #include "testing/gtest/include/gtest/gtest.h" static void VerifyStreamReadBehavior(CefRefPtr<CefStreamReader> stream, const std::string& contents) { int contentSize = static_cast<int>(contents.size()); const char* contentStr = contents.c_str(); // Move to the beginning of the stream ASSERT_EQ(0, stream->Seek(0, SEEK_SET)); ASSERT_EQ(0, stream->Tell()); // Move to the end of the stream ASSERT_EQ(0, stream->Seek(0, SEEK_END)); ASSERT_EQ(contentSize, stream->Tell()); // Move to the beginning of the stream ASSERT_EQ(0, stream->Seek(-contentSize, SEEK_CUR)); ASSERT_EQ(0, stream->Tell()); // Read 10 characters at a time and verify the result char buff[10]; int res, read, offset = 0; do { read = std::min((int)sizeof(buff), contentSize-offset); res = stream->Read(buff, 1, read); ASSERT_EQ(read, res); ASSERT_TRUE(!memcmp(contentStr+offset, buff, res)); offset += res; } while(offset < contentSize); // Read past the end of the file stream->Read(buff, 1, 1); ASSERT_TRUE(stream->Eof()); } static void VerifyStreamWriteBehavior(CefRefPtr<CefStreamWriter> stream, const std::string& contents) { int contentSize = static_cast<int>(contents.size()); const char* contentStr = contents.c_str(); // Write 10 characters at a time and verify the result int res, write, offset = 0; do { write = std::min(10, contentSize-offset); res = stream->Write(contentStr+offset, 1, write); ASSERT_EQ(write, res); offset += res; ASSERT_EQ(offset, stream->Tell()); } while(offset < contentSize); // Move to the beginning of the stream ASSERT_EQ(0, stream->Seek(-contentSize, SEEK_CUR)); ASSERT_EQ(0, stream->Tell()); // Move to the end of the stream ASSERT_EQ(0, stream->Seek(0, SEEK_END)); ASSERT_EQ(contentSize, stream->Tell()); // Move to the beginning of the stream ASSERT_EQ(0, stream->Seek(0, SEEK_SET)); ASSERT_EQ(0, stream->Tell()); } TEST(StreamTest, ReadFile) { const char* fileName = "StreamTest.VerifyReadFile.txt"; CefString fileNameStr = "StreamTest.VerifyReadFile.txt"; std::string contents = "This is my test\ncontents for the file"; // Create the file FILE* f = NULL; #ifdef _WIN32 fopen_s(&f, fileName, "wb"); #else f = fopen(fileName, "wb"); #endif ASSERT_TRUE(f != NULL); ASSERT_EQ((size_t)1, fwrite(contents.c_str(), contents.size(), 1, f)); fclose(f); // Test the stream CefRefPtr<CefStreamReader> stream( CefStreamReader::CreateForFile(fileNameStr)); ASSERT_TRUE(stream.get() != NULL); VerifyStreamReadBehavior(stream, contents); // Release the file pointer stream = NULL; // Delete the file #ifdef _WIN32 ASSERT_EQ(0, _unlink(fileName)); #else ASSERT_EQ(0, unlink(fileName)); #endif } TEST(StreamTest, ReadData) { std::string contents = "This is my test\ncontents for the file"; // Test the stream CefRefPtr<CefStreamReader> stream( CefStreamReader::CreateForData((void*)contents.c_str(), contents.size())); ASSERT_TRUE(stream.get() != NULL); VerifyStreamReadBehavior(stream, contents); } TEST(StreamTest, WriteFile) { const char* fileName = "StreamTest.VerifyWriteFile.txt"; CefString fileNameStr = "StreamTest.VerifyWriteFile.txt"; std::string contents = "This is my test\ncontents for the file"; // Test the stream CefRefPtr<CefStreamWriter> stream( CefStreamWriter::CreateForFile(fileNameStr)); ASSERT_TRUE(stream.get() != NULL); VerifyStreamWriteBehavior(stream, contents); // Release the file pointer stream = NULL; // Read the file that was written FILE* f = NULL; char* buff = new char[contents.size()]; #ifdef _WIN32 fopen_s(&f, fileName, "rb"); #else f = fopen(fileName, "rb"); #endif ASSERT_TRUE(f != NULL); ASSERT_EQ((size_t)1, fread(buff, contents.size(), 1, f)); // Read past the end of the file fgetc(f); ASSERT_TRUE(feof(f)); fclose(f); // Verify the file contents ASSERT_TRUE(!memcmp(contents.c_str(), buff, contents.size())); delete [] buff; // Delete the file #ifdef _WIN32 ASSERT_EQ(0, _unlink(fileName)); #else ASSERT_EQ(0, unlink(fileName)); #endif } bool g_ReadHandlerTesterDeleted = false; class ReadHandlerTester : public CefReadHandler { public: ReadHandlerTester() : read_called_(false), read_ptr_(NULL), read_size_(0), read_n_(0), seek_called_(false), seek_offset_(0), seek_whence_(0), tell_called_(false), eof_called_(false) { } virtual ~ReadHandlerTester() { g_ReadHandlerTesterDeleted = true; } virtual size_t Read(void* ptr, size_t size, size_t n) { read_called_ = true; read_ptr_ = ptr; read_size_ = size; read_n_ = n; return 10; } virtual int Seek(long offset, int whence) { seek_called_ = true; seek_offset_ = offset; seek_whence_ = whence; return 10; } virtual long Tell() { tell_called_ = true; return 10; } virtual int Eof() { eof_called_ = true; return 10; } bool read_called_; const void* read_ptr_; size_t read_size_; size_t read_n_; bool seek_called_; long seek_offset_; int seek_whence_; bool tell_called_; bool eof_called_; IMPLEMENT_REFCOUNTING(ReadHandlerTester); }; TEST(StreamTest, ReadHandler) { ReadHandlerTester* handler = new ReadHandlerTester(); ASSERT_TRUE(handler != NULL); CefRefPtr<CefStreamReader> stream(CefStreamReader::CreateForHandler(handler)); ASSERT_TRUE(stream.get() != NULL); // CefReadHandler Read const char* read_ptr = "My data"; size_t read_size = sizeof(read_ptr); size_t read_n = 1; size_t read_res = stream->Read((void*)read_ptr, read_size, read_n); ASSERT_TRUE(handler->read_called_); ASSERT_EQ((size_t)10, read_res); ASSERT_EQ(read_ptr, handler->read_ptr_); ASSERT_EQ(read_size, handler->read_size_); ASSERT_EQ(read_n, handler->read_n_); // CefReadHandler Seek long seek_offset = 10; int seek_whence = SEEK_CUR; int seek_res = stream->Seek(seek_offset, seek_whence); ASSERT_TRUE(handler->seek_called_); ASSERT_EQ(10, seek_res); ASSERT_EQ(seek_offset, handler->seek_offset_); ASSERT_EQ(seek_whence, handler->seek_whence_); // CefReadHandler Tell long tell_res = stream->Tell(); ASSERT_TRUE(handler->tell_called_); ASSERT_EQ(10, tell_res); // CefReadHandler Eof int eof_res = stream->Eof(); ASSERT_TRUE(handler->eof_called_); ASSERT_EQ(10, eof_res); // Delete the stream stream = NULL; // Verify that the handler object was deleted ASSERT_TRUE(g_ReadHandlerTesterDeleted); } bool g_WriteHandlerTesterDeleted = false; class WriteHandlerTester : public CefWriteHandler { public: WriteHandlerTester() : write_called_(false), write_ptr_(NULL), write_size_(0), write_n_(0), seek_called_(false), seek_offset_(0), seek_whence_(0), tell_called_(false), flush_called_(false) { } virtual ~WriteHandlerTester() { g_WriteHandlerTesterDeleted = true; } virtual size_t Write(const void* ptr, size_t size, size_t n) { write_called_ = true; write_ptr_ = ptr; write_size_ = size; write_n_ = n; return 10; } virtual int Seek(long offset, int whence) { seek_called_ = true; seek_offset_ = offset; seek_whence_ = whence; return 10; } virtual long Tell() { tell_called_ = true; return 10; } virtual int Flush() { flush_called_ = true; return 10; } bool write_called_; const void* write_ptr_; size_t write_size_; size_t write_n_; bool seek_called_; long seek_offset_; int seek_whence_; bool tell_called_; bool flush_called_; IMPLEMENT_REFCOUNTING(WriteHandlerTester); }; TEST(StreamTest, WriteHandler) { WriteHandlerTester* handler = new WriteHandlerTester(); ASSERT_TRUE(handler != NULL); CefRefPtr<CefStreamWriter> stream(CefStreamWriter::CreateForHandler(handler)); ASSERT_TRUE(stream.get() != NULL); // CefWriteHandler Write const char* write_ptr = "My data"; size_t write_size = sizeof(write_ptr); size_t write_n = 1; size_t write_res = stream->Write(write_ptr, write_size, write_n); ASSERT_TRUE(handler->write_called_); ASSERT_EQ((size_t)10, write_res); ASSERT_EQ(write_ptr, handler->write_ptr_); ASSERT_EQ(write_size, handler->write_size_); ASSERT_EQ(write_n, handler->write_n_); // CefWriteHandler Seek long seek_offset = 10; int seek_whence = SEEK_CUR; int seek_res = stream->Seek(seek_offset, seek_whence); ASSERT_TRUE(handler->seek_called_); ASSERT_EQ(10, seek_res); ASSERT_EQ(seek_offset, handler->seek_offset_); ASSERT_EQ(seek_whence, handler->seek_whence_); // CefWriteHandler Tell long tell_res = stream->Tell(); ASSERT_TRUE(handler->tell_called_); ASSERT_EQ(10, tell_res); // CefWriteHandler Flush int flush_res = stream->Flush(); ASSERT_TRUE(handler->flush_called_); ASSERT_EQ(10, flush_res); // Delete the stream stream = NULL; // Verify that the handler object was deleted ASSERT_TRUE(g_WriteHandlerTesterDeleted); }
25.110811
80
0.695619
curasystems
4f80f069bca4f2900e7e1a112f4e2836fc3506a2
5,954
cpp
C++
ClientMigration/TRedirectServer/ServerMain.cpp
Fiskmans/ClientMigration
ab863986fb580b790c5918819878f86e8c5b4d6b
[ "MIT" ]
1
2020-03-16T12:19:42.000Z
2020-03-16T12:19:42.000Z
ClientMigration/TRedirectServer/ServerMain.cpp
Fiskmans/ClientMigration
ab863986fb580b790c5918819878f86e8c5b4d6b
[ "MIT" ]
null
null
null
ClientMigration/TRedirectServer/ServerMain.cpp
Fiskmans/ClientMigration
ab863986fb580b790c5918819878f86e8c5b4d6b
[ "MIT" ]
null
null
null
#include <pch.h> #include "ServerMain.h" #include <string> #include <SetupMessage.h> #include <StatusMessage.h> #include <thread> #include <TimeHelper.h> #include <Random.h> RedirectServer::RedirectServer() { } RedirectServer::~RedirectServer() { } #define PORT 5763 #define CLIENTPORT 5764 int CalculateBroadcastIP(std::string aIP, std::string aSubNet, std::string& aBroadcast) { struct in_addr host, mask, broadcast; char broadcast_address[INET_ADDRSTRLEN]; if (inet_pton(AF_INET, aIP.c_str(), &host) == 1 && inet_pton(AF_INET, aSubNet.c_str(), &mask) == 1) { broadcast.S_un.S_addr = host.S_un.S_addr | ~mask.S_un.S_addr; } else { return 1; } if (inet_ntop(AF_INET,&broadcast,broadcast_address,INET_ADDRSTRLEN) != NULL) { std::cout << "Broadcast address of " + aIP + " with netmask " + aSubNet + " is " + broadcast_address + "\n"; } else { return 1; } aBroadcast = broadcast_address; return S_OK; } void RedirectServer::StartServer() { struct sockaddr_in si_other; int slen, recv_len; char buf[BUFLEN]; WSADATA wsa; slen = sizeof(si_other); //Initialise winsock std::cout << "Initialising Winsock...\n"; if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) { std::cout << "Failed.Error Code: " + std::to_string(WSAGetLastError()) + "\n"; return; } std::cout << "Initialised.\n"; //Create a socket mySocket = socket(AF_INET, SOCK_DGRAM, 0); if (mySocket == INVALID_SOCKET) { std::cout << "Could not create socket: " + std::to_string(WSAGetLastError()) + "\n"; return; } std::cout << "Socket created.\n"; struct addrinfo* result = NULL, * ptr = NULL, hints; ZeroMemory(&hints, sizeof(hints)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_DGRAM; hints.ai_protocol = IPPROTO_UDP; hints.ai_flags = AI_PASSIVE; // Resolve the local address and port to be used by the server int iResult = getaddrinfo(NULL, STRINGVALUE(PORT), &hints, &result); if (iResult != 0) { printf("getaddrinfo failed: %d\n", iResult); WSACleanup(); return; } std::cout << "Got address info!\n"; int broadcast = 1; setsockopt(mySocket, SOL_SOCKET, SO_BROADCAST, (const char*)&broadcast, sizeof broadcast); //Bind if (bind(mySocket, result->ai_addr, (int)result->ai_addrlen)) { std::cout << "Bind failed with error code : " + std::to_string(WSAGetLastError()) + "\n"; return; } std::cout << "Bind Successfull\n"; u_long mode = 1; // 1 to enable non-blocking socket ioctlsocket(mySocket, FIONBIO, &mode); Connect(); Listen(); closesocket(mySocket); WSACleanup(); return; } void RedirectServer::HandShake() { } void RedirectServer::Connect() { } void RedirectServer::Listen() { sockaddr_in si_other; int slen, recv_len; char buf[BUFLEN]; slen = sizeof(si_other); while (true) { for (auto& cli : myClients) { if (!cli.second.IsAlive()) { StatusMessage message; message.myStatus = StatusMessage::Status::UserDisconnected; message.myAssignedID = cli.second.GetID(); TransmitMessage(message); myClients.erase(cli.first); break; } else { cli.second.Flush(); } } recv_len = recvfrom(mySocket, buf, BUFLEN, 0, reinterpret_cast<sockaddr*>(&si_other), &slen); char addressBuffer[512]; InetNtopA(AF_INET, &si_other, addressBuffer, 512); std::string key = addressBuffer; if (recv_len == SOCKET_ERROR) { int error = WSAGetLastError(); if (error == WSAEWOULDBLOCK) { std::this_thread::yield(); continue; } std::cout << "Could not recvieve data from client(s): " + std::to_string(WSAGetLastError()) + " ip: " + key + "\n"; myClients[key].Invalidate(); continue; } NetMessage* message = reinterpret_cast<NetMessage*>(buf); if (message->myType == NetMessage::Type::Ping) { std::cout << "I Was pinged\n"; } auto it = myClients.find(key); if (it == myClients.end()) { static unsigned short IDCOUNTER = 3; myClients[key] = Connection(si_other, slen, mySocket, ++IDCOUNTER, std::bind(&RedirectServer::TransmitMessage, this, std::placeholders::_1),std::bind(&RedirectServer::RequestList,this,std::placeholders::_1)); it = myClients.find(key); } if (it->second.PreProcessReceive(buf, recv_len)) { it->second.Receive(buf, recv_len); } } } void RedirectServer::TransmitMessage(const NetMessage& aMessage) { switch (aMessage.myType) { case NetMessage::Type::Status: { const StatusMessage& status = *reinterpret_cast<const StatusMessage*>(&aMessage); switch (status.myStatus) { case StatusMessage::Status::UserConnected: { std::cout << "Telling all clients that [" << status.myUsername << "] has connected on id [" + std::to_string(status.myAssignedID) + "]\n"; for (auto& it : myClients) { if (it.second.GetID() == status.myAssignedID) { for (auto& cli : myClients) { if (cli.second.GetID() != it.second.GetID()) { StatusMessage userStatus; userStatus.SetName(cli.second.GetName()); userStatus.myStatus = StatusMessage::Status::UserOnline; userStatus.myAssignedID = cli.second.GetID(); it.second.Send(userStatus); } } } else { it.second.Send(status); } } } break; case StatusMessage::Status::UserDisconnected: { std::cout << "Telling all clients that ["; for (auto& i : myClients) { if (i.second.GetID() == status.myAssignedID) { std::cout << i.second.GetName(); } } std::cout << "] has disconnected.\n"; for (auto& it : myClients) { if (it.second.GetID() != status.myAssignedID) { it.second.Send(status); } } } break; case StatusMessage::Status::UserOnline: default: std::cout << "This should never happen\n"; break; } } break; default: break; } } std::vector<Connection*> RedirectServer::RequestList(const Connection& aRequester) { std::vector<Connection*> out; for (auto& i : myClients) { out.push_back(&i.second); } return out; }
21.97048
211
0.656533
Fiskmans
4f818a437a8353c1bc88390138b08219d790c8d8
3,623
cpp
C++
Source/VlcMedia/Private/Player/VlcMediaSource.cpp
jeirix/UnrealEngine5VLC
f74f5dde001631b2856cece61d5f5b907ae35c3c
[ "BSD-3-Clause" ]
1
2022-03-23T04:35:54.000Z
2022-03-23T04:35:54.000Z
Source/VlcMedia/Private/Player/VlcMediaSource.cpp
jeirix/UnrealEngine5VLC
f74f5dde001631b2856cece61d5f5b907ae35c3c
[ "BSD-3-Clause" ]
null
null
null
Source/VlcMedia/Private/Player/VlcMediaSource.cpp
jeirix/UnrealEngine5VLC
f74f5dde001631b2856cece61d5f5b907ae35c3c
[ "BSD-3-Clause" ]
null
null
null
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #include "VlcMediaSource.h" #include "VlcMediaPrivate.h" #include "Vlc.h" /* FVlcMediaReader structors *****************************************************************************/ FVlcMediaSource::FVlcMediaSource(FLibvlcInstance* InVlcInstance) : Media(nullptr) , VlcInstance(InVlcInstance) { } /* FVlcMediaReader interface *****************************************************************************/ FTimespan FVlcMediaSource::GetDuration() const { if (Media == nullptr) { return FTimespan::Zero(); } int64 Duration = FVlc::MediaGetDuration(Media); if (Duration < 0) { return FTimespan::Zero(); } return FTimespan(Duration * ETimespan::TicksPerMillisecond); } FLibvlcMedia* FVlcMediaSource::OpenArchive(const TSharedRef<FArchive, ESPMode::ThreadSafe>& Archive, const FString& OriginalUrl) { check(Media == nullptr); if (Archive->TotalSize() > 0) { Data = Archive; Media = FVlc::MediaNewCallbacks( VlcInstance, nullptr, &FVlcMediaSource::HandleMediaRead, &FVlcMediaSource::HandleMediaSeek, &FVlcMediaSource::HandleMediaClose, this ); if (Media == nullptr) { UE_LOG(LogVlcMedia, Warning, TEXT("Failed to open media from archive: %s (%s)"), *OriginalUrl, ANSI_TO_TCHAR(FVlc::Errmsg())); Data.Reset(); } else { CurrentUrl = OriginalUrl; } } return Media; } FLibvlcMedia* FVlcMediaSource::OpenUrl(const FString& Url) { check(Media == nullptr); Media = FVlc::MediaNewLocation(VlcInstance, TCHAR_TO_ANSI(*Url)); if (Media == nullptr) { UE_LOG(LogVlcMedia, Warning, TEXT("Failed to open media from URL: %s (%s)"), *Url, ANSI_TO_TCHAR(FVlc::Errmsg())); } else { CurrentUrl = Url; } return Media; } void FVlcMediaSource::Close() { if (Media != nullptr) { FVlc::MediaRelease(Media); Media = nullptr; } Data.Reset(); CurrentUrl.Reset(); } /* FVlcMediaReader static functions *****************************************************************************/ int FVlcMediaSource::HandleMediaOpen(void* Opaque, void** OutData, uint64* OutSize) { auto Reader = (FVlcMediaSource*)Opaque; if ((Reader == nullptr) || !Reader->Data.IsValid()) { return 0; } *OutSize = Reader->Data->TotalSize(); return 0; } SSIZE_T FVlcMediaSource::HandleMediaRead(void* Opaque, void* Buffer, SIZE_T Length) { auto Reader = (FVlcMediaSource*)Opaque; if (Reader == nullptr) { return -1; } TSharedPtr<FArchive, ESPMode::ThreadSafe> Data = Reader->Data; if (!Reader->Data.IsValid()) { return -1; } SIZE_T DataSize = (SIZE_T)Data->TotalSize(); SIZE_T BytesToRead = FMath::Min(Length, DataSize); SIZE_T DataPosition = Reader->Data->Tell(); if ((DataSize - BytesToRead) < DataPosition) { BytesToRead = DataSize - DataPosition; } if (BytesToRead > 0) { Data->Serialize(Buffer, BytesToRead); } return (SSIZE_T)BytesToRead; } int FVlcMediaSource::HandleMediaSeek(void* Opaque, uint64 Offset) { auto Reader = (FVlcMediaSource*)Opaque; if (Reader == nullptr) { return -1; } TSharedPtr<FArchive, ESPMode::ThreadSafe> Data = Reader->Data; if (!Reader->Data.IsValid()) { return -1; } if ((uint64)Data->TotalSize() <= Offset) { return -1; } Reader->Data->Seek(Offset); return 0; } void FVlcMediaSource::HandleMediaClose(void* Opaque) { auto Reader = (FVlcMediaSource*)Opaque; if (Reader != nullptr) { Reader->Data->Seek(0); } }
19.068421
130
0.606956
jeirix
4f8275c4bb3f7d34dc743838782eb60aee8c8ccc
8,993
cpp
C++
unittests/ADT/ArrayRefTest.cpp
AlexVlx/llvm
08ba61dfeeac3e1eccff413870340197935e28bc
[ "Apache-2.0" ]
938
2015-12-03T16:45:43.000Z
2022-03-17T20:28:02.000Z
unittests/ADT/ArrayRefTest.cpp
AlexVlx/llvm
08ba61dfeeac3e1eccff413870340197935e28bc
[ "Apache-2.0" ]
127
2015-12-03T21:42:53.000Z
2019-11-21T14:34:20.000Z
unittests/ADT/ArrayRefTest.cpp
AlexVlx/llvm
08ba61dfeeac3e1eccff413870340197935e28bc
[ "Apache-2.0" ]
280
2015-12-03T16:51:35.000Z
2022-01-24T00:01:54.000Z
//===- llvm/unittest/ADT/ArrayRefTest.cpp - ArrayRef unit tests -----------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "llvm/ADT/ArrayRef.h" #include "llvm/Support/Allocator.h" #include "llvm/Support/raw_ostream.h" #include "gtest/gtest.h" #include <limits> #include <vector> using namespace llvm; // Check that the ArrayRef-of-pointer converting constructor only allows adding // cv qualifiers (not removing them, or otherwise changing the type) static_assert( std::is_convertible<ArrayRef<int *>, ArrayRef<const int *>>::value, "Adding const"); static_assert( std::is_convertible<ArrayRef<int *>, ArrayRef<volatile int *>>::value, "Adding volatile"); static_assert(!std::is_convertible<ArrayRef<int *>, ArrayRef<float *>>::value, "Changing pointer of one type to a pointer of another"); static_assert( !std::is_convertible<ArrayRef<const int *>, ArrayRef<int *>>::value, "Removing const"); static_assert( !std::is_convertible<ArrayRef<volatile int *>, ArrayRef<int *>>::value, "Removing volatile"); // Check that we can't accidentally assign a temporary location to an ArrayRef. // (Unfortunately we can't make use of the same thing with constructors.) // // Disable this check under MSVC; even MSVC 2015 isn't inconsistent between // std::is_assignable and actually writing such an assignment. #if !defined(_MSC_VER) static_assert( !std::is_assignable<ArrayRef<int *>&, int *>::value, "Assigning from single prvalue element"); static_assert( !std::is_assignable<ArrayRef<int *>&, int * &&>::value, "Assigning from single xvalue element"); static_assert( std::is_assignable<ArrayRef<int *>&, int * &>::value, "Assigning from single lvalue element"); static_assert( !std::is_assignable<ArrayRef<int *>&, std::initializer_list<int *>>::value, "Assigning from an initializer list"); #endif namespace { TEST(ArrayRefTest, AllocatorCopy) { BumpPtrAllocator Alloc; static const uint16_t Words1[] = { 1, 4, 200, 37 }; ArrayRef<uint16_t> Array1 = makeArrayRef(Words1, 4); static const uint16_t Words2[] = { 11, 4003, 67, 64000, 13 }; ArrayRef<uint16_t> Array2 = makeArrayRef(Words2, 5); ArrayRef<uint16_t> Array1c = Array1.copy(Alloc); ArrayRef<uint16_t> Array2c = Array2.copy(Alloc); EXPECT_TRUE(Array1.equals(Array1c)); EXPECT_NE(Array1.data(), Array1c.data()); EXPECT_TRUE(Array2.equals(Array2c)); EXPECT_NE(Array2.data(), Array2c.data()); // Check that copy can cope with uninitialized memory. struct NonAssignable { const char *Ptr; NonAssignable(const char *Ptr) : Ptr(Ptr) {} NonAssignable(const NonAssignable &RHS) = default; void operator=(const NonAssignable &RHS) { assert(RHS.Ptr != nullptr); } bool operator==(const NonAssignable &RHS) const { return Ptr == RHS.Ptr; } } Array3Src[] = {"hello", "world"}; ArrayRef<NonAssignable> Array3Copy = makeArrayRef(Array3Src).copy(Alloc); EXPECT_EQ(makeArrayRef(Array3Src), Array3Copy); EXPECT_NE(makeArrayRef(Array3Src).data(), Array3Copy.data()); } TEST(ArrayRefTest, SizeTSizedOperations) { ArrayRef<char> AR(nullptr, std::numeric_limits<ptrdiff_t>::max()); // Check that drop_back accepts size_t-sized numbers. EXPECT_EQ(1U, AR.drop_back(AR.size() - 1).size()); // Check that drop_front accepts size_t-sized numbers. EXPECT_EQ(1U, AR.drop_front(AR.size() - 1).size()); // Check that slice accepts size_t-sized numbers. EXPECT_EQ(1U, AR.slice(AR.size() - 1).size()); EXPECT_EQ(AR.size() - 1, AR.slice(1, AR.size() - 1).size()); } TEST(ArrayRefTest, DropBack) { static const int TheNumbers[] = {4, 8, 15, 16, 23, 42}; ArrayRef<int> AR1(TheNumbers); ArrayRef<int> AR2(TheNumbers, AR1.size() - 1); EXPECT_TRUE(AR1.drop_back().equals(AR2)); } TEST(ArrayRefTest, DropFront) { static const int TheNumbers[] = {4, 8, 15, 16, 23, 42}; ArrayRef<int> AR1(TheNumbers); ArrayRef<int> AR2(&TheNumbers[2], AR1.size() - 2); EXPECT_TRUE(AR1.drop_front(2).equals(AR2)); } TEST(ArrayRefTest, DropWhile) { static const int TheNumbers[] = {1, 3, 5, 8, 10, 11}; ArrayRef<int> AR1(TheNumbers); ArrayRef<int> Expected = AR1.drop_front(3); EXPECT_EQ(Expected, AR1.drop_while([](const int &N) { return N % 2 == 1; })); EXPECT_EQ(AR1, AR1.drop_while([](const int &N) { return N < 0; })); EXPECT_EQ(ArrayRef<int>(), AR1.drop_while([](const int &N) { return N > 0; })); } TEST(ArrayRefTest, DropUntil) { static const int TheNumbers[] = {1, 3, 5, 8, 10, 11}; ArrayRef<int> AR1(TheNumbers); ArrayRef<int> Expected = AR1.drop_front(3); EXPECT_EQ(Expected, AR1.drop_until([](const int &N) { return N % 2 == 0; })); EXPECT_EQ(ArrayRef<int>(), AR1.drop_until([](const int &N) { return N < 0; })); EXPECT_EQ(AR1, AR1.drop_until([](const int &N) { return N > 0; })); } TEST(ArrayRefTest, TakeBack) { static const int TheNumbers[] = {4, 8, 15, 16, 23, 42}; ArrayRef<int> AR1(TheNumbers); ArrayRef<int> AR2(AR1.end() - 1, 1); EXPECT_TRUE(AR1.take_back().equals(AR2)); } TEST(ArrayRefTest, TakeFront) { static const int TheNumbers[] = {4, 8, 15, 16, 23, 42}; ArrayRef<int> AR1(TheNumbers); ArrayRef<int> AR2(AR1.data(), 2); EXPECT_TRUE(AR1.take_front(2).equals(AR2)); } TEST(ArrayRefTest, TakeWhile) { static const int TheNumbers[] = {1, 3, 5, 8, 10, 11}; ArrayRef<int> AR1(TheNumbers); ArrayRef<int> Expected = AR1.take_front(3); EXPECT_EQ(Expected, AR1.take_while([](const int &N) { return N % 2 == 1; })); EXPECT_EQ(ArrayRef<int>(), AR1.take_while([](const int &N) { return N < 0; })); EXPECT_EQ(AR1, AR1.take_while([](const int &N) { return N > 0; })); } TEST(ArrayRefTest, TakeUntil) { static const int TheNumbers[] = {1, 3, 5, 8, 10, 11}; ArrayRef<int> AR1(TheNumbers); ArrayRef<int> Expected = AR1.take_front(3); EXPECT_EQ(Expected, AR1.take_until([](const int &N) { return N % 2 == 0; })); EXPECT_EQ(AR1, AR1.take_until([](const int &N) { return N < 0; })); EXPECT_EQ(ArrayRef<int>(), AR1.take_until([](const int &N) { return N > 0; })); } TEST(ArrayRefTest, Equals) { static const int A1[] = {1, 2, 3, 4, 5, 6, 7, 8}; ArrayRef<int> AR1(A1); EXPECT_TRUE(AR1.equals({1, 2, 3, 4, 5, 6, 7, 8})); EXPECT_FALSE(AR1.equals({8, 1, 2, 4, 5, 6, 6, 7})); EXPECT_FALSE(AR1.equals({2, 4, 5, 6, 6, 7, 8, 1})); EXPECT_FALSE(AR1.equals({0, 1, 2, 4, 5, 6, 6, 7})); EXPECT_FALSE(AR1.equals({1, 2, 42, 4, 5, 6, 7, 8})); EXPECT_FALSE(AR1.equals({42, 2, 3, 4, 5, 6, 7, 8})); EXPECT_FALSE(AR1.equals({1, 2, 3, 4, 5, 6, 7, 42})); EXPECT_FALSE(AR1.equals({1, 2, 3, 4, 5, 6, 7})); EXPECT_FALSE(AR1.equals({1, 2, 3, 4, 5, 6, 7, 8, 9})); ArrayRef<int> AR1a = AR1.drop_back(); EXPECT_TRUE(AR1a.equals({1, 2, 3, 4, 5, 6, 7})); EXPECT_FALSE(AR1a.equals({1, 2, 3, 4, 5, 6, 7, 8})); ArrayRef<int> AR1b = AR1a.slice(2, 4); EXPECT_TRUE(AR1b.equals({3, 4, 5, 6})); EXPECT_FALSE(AR1b.equals({2, 3, 4, 5, 6})); EXPECT_FALSE(AR1b.equals({3, 4, 5, 6, 7})); } TEST(ArrayRefTest, EmptyEquals) { EXPECT_TRUE(ArrayRef<unsigned>() == ArrayRef<unsigned>()); } TEST(ArrayRefTest, ConstConvert) { int buf[4]; for (int i = 0; i < 4; ++i) buf[i] = i; static int *A[] = {&buf[0], &buf[1], &buf[2], &buf[3]}; ArrayRef<const int *> a((ArrayRef<int *>(A))); a = ArrayRef<int *>(A); } static std::vector<int> ReturnTest12() { return {1, 2}; } static void ArgTest12(ArrayRef<int> A) { EXPECT_EQ(2U, A.size()); EXPECT_EQ(1, A[0]); EXPECT_EQ(2, A[1]); } TEST(ArrayRefTest, InitializerList) { std::initializer_list<int> init_list = { 0, 1, 2, 3, 4 }; ArrayRef<int> A = init_list; for (int i = 0; i < 5; ++i) EXPECT_EQ(i, A[i]); std::vector<int> B = ReturnTest12(); A = B; EXPECT_EQ(1, A[0]); EXPECT_EQ(2, A[1]); ArgTest12({1, 2}); } TEST(ArrayRefTest, EmptyInitializerList) { ArrayRef<int> A = {}; EXPECT_TRUE(A.empty()); A = {}; EXPECT_TRUE(A.empty()); } // Test that makeArrayRef works on ArrayRef (no-op) TEST(ArrayRefTest, makeArrayRef) { static const int A1[] = {1, 2, 3, 4, 5, 6, 7, 8}; // No copy expected for non-const ArrayRef (true no-op) ArrayRef<int> AR1(A1); ArrayRef<int> &AR1Ref = makeArrayRef(AR1); EXPECT_EQ(&AR1, &AR1Ref); // A copy is expected for non-const ArrayRef (thin copy) const ArrayRef<int> AR2(A1); const ArrayRef<int> &AR2Ref = makeArrayRef(AR2); EXPECT_NE(&AR2Ref, &AR2); EXPECT_TRUE(AR2.equals(AR2Ref)); } TEST(ArrayRefTest, OwningArrayRef) { static const int A1[] = {0, 1}; OwningArrayRef<int> A(makeArrayRef(A1)); OwningArrayRef<int> B(std::move(A)); EXPECT_EQ(A.data(), nullptr); } static_assert(is_trivially_copyable<ArrayRef<int>>::value, "trivially copyable"); } // end anonymous namespace
34.324427
80
0.650061
AlexVlx
4f82c566d5621dc806c3e47d3c1b0a7805c266fb
544
hpp
C++
game_server/src/crank.hpp
CellWarsOfficial/CellWars
40b1e956c871ee686062eba1251a9f9a43d86c2c
[ "Apache-2.0" ]
5
2017-07-20T10:36:23.000Z
2018-01-30T16:18:31.000Z
game_server/src/crank.hpp
CellWarsOfficial/CellWars
40b1e956c871ee686062eba1251a9f9a43d86c2c
[ "Apache-2.0" ]
null
null
null
game_server/src/crank.hpp
CellWarsOfficial/CellWars
40b1e956c871ee686062eba1251a9f9a43d86c2c
[ "Apache-2.0" ]
null
null
null
#ifndef CRANK_HPP #define CRANK_HPP #include <block.hpp> #include <action.hpp> #include <constants.hpp> #include <bitset> class Crank: public Action { public: virtual ~Crank() = default; virtual void crank(Block *block); virtual void crank_for(Block *block, int generations); virtual CELL_TYPE crank_cell(Block *block, int x, int y); virtual CELL_TYPE revive_cell(Block *block, int x, int y); virtual int count_cell_neighbours(Block *block, int x, int y); void init_bitmap(Block *block); int prune_area(Block *block, int x, int y); }; #endif
24.727273
62
0.751838
CellWarsOfficial
4f82d48f28516e55c1ff7c492df0fdbd4804f3fa
1,113
hpp
C++
Engine/Terrain/TRMisc.hpp
openlastchaos/lastchaos-source-client
3d88594dba7347b1bb45378136605e31f73a8555
[ "Apache-2.0" ]
1
2022-02-14T15:46:44.000Z
2022-02-14T15:46:44.000Z
Engine/Terrain/TRMisc.hpp
openlastchaos/lastchaos-source-client
3d88594dba7347b1bb45378136605e31f73a8555
[ "Apache-2.0" ]
null
null
null
Engine/Terrain/TRMisc.hpp
openlastchaos/lastchaos-source-client
3d88594dba7347b1bb45378136605e31f73a8555
[ "Apache-2.0" ]
2
2022-01-10T22:17:06.000Z
2022-01-17T09:34:08.000Z
#ifndef SE_INCL_TERRAIN_MISC_HPP #define SE_INCL_TERRAIN_MISC_HPP #ifdef PRAGMA_ONCE #pragma once #endif struct SimpleTerrainTriangle { SimpleTerrainTriangle(void) {}; SimpleTerrainTriangle(FLOAT3D v0, FLOAT3D v1, FLOAT3D v2) { stt_avx[0] = v0; stt_avx[1] = v1; stt_avx[2] = v2; } FLOAT3D stt_avx[3]; }; ENGINE_API extern FLOAT TR_GetHeight( CTerrainImp *ptr, FLOAT fX, FLOAT fZ ); // yjpark // Extract vertices and triangles from specified rectange on height map extern void TR_ExtractVertices(CTerrainImp *ptr, CTRect rcSource, CStaticArray<FLOAT3D> &avxVertices); extern void TR_ExtractAttrPoligonsInRect( CTerrainImp *ptrTerrain, CTRect &rcExtract, FLOAT3D **pavRetVtx, INDEX &ctRetVertices, GFXColor **pacolRetCol, UWORD **puwRetInd, INDEX &ctRetIndices, UWORD ubAttr ); // [070705: Su-won] ATTRIBUTEMAP_BLOCK extern void TR_ExtractAttrBlockPolygonsInRect( CTerrainImp *ptr, CTRect &rcExtract, FLOAT3D **pavRetVtx, INDEX &ctRetVertices, UWORD **puwRetInd, INDEX &ctRetIndices, float fHeight ); #endif
32.735294
88
0.718778
openlastchaos
4f848efdca12eb576e319aeca0a344c29bf2519a
15,329
hpp
C++
ad_physics/generated/include/ad/physics/DurationSquared.hpp
hulk-mk/map
261e7329afdc56d6f8cfb63285039764b2dc6361
[ "MIT" ]
null
null
null
ad_physics/generated/include/ad/physics/DurationSquared.hpp
hulk-mk/map
261e7329afdc56d6f8cfb63285039764b2dc6361
[ "MIT" ]
null
null
null
ad_physics/generated/include/ad/physics/DurationSquared.hpp
hulk-mk/map
261e7329afdc56d6f8cfb63285039764b2dc6361
[ "MIT" ]
1
2020-10-27T11:09:30.000Z
2020-10-27T11:09:30.000Z
/* * ----------------- BEGIN LICENSE BLOCK --------------------------------- * * Copyright (C) 2018-2020 Intel Corporation * * SPDX-License-Identifier: MIT * * ----------------- END LICENSE BLOCK ----------------------------------- */ /** * Generated file * @file * * Generator Version : 11.0.0-1997 */ #pragma once #include <cmath> #include <iostream> #include <limits> #include <sstream> #include <stdexcept> #include "spdlog/fmt/ostr.h" #include "spdlog/spdlog.h" /*! * @brief namespace ad */ namespace ad { /*! * @brief namespace physics */ namespace physics { /*! * \brief Define to indicate whether throwing exceptions is enabled */ #define AD_PHYSICS_DURATIONSQUARED_THROWS_EXCEPTION 1 #if SAFE_DATATYPES_EXPLICIT_CONVERSION /*! * \brief Enable/Disable explicit conversion. Currently set to "only explicit conversion". */ #define _AD_PHYSICS_DURATIONSQUARED_EXPLICIT_CONVERSION_ explicit #else /*! * \brief Enable/Disable explicit conversion. Currently set to "implicit conversion allowed". */ #define _AD_PHYSICS_DURATIONSQUARED_EXPLICIT_CONVERSION_ #endif /*! * \brief Forward declaration of Duration * * Since DurationSquared is defined explicitly as a physical type we have to consider this * within operations. Therefore this square-rooted type is defined. */ class Duration; /*! * \brief DataType DurationSquared * * DurationSquared represents a squared Duration * The unit is: SecondSquared */ class DurationSquared { public: /*! * \brief constant defining the minimum valid DurationSquared value (used in isValid()) */ static const double cMinValue; /*! * \brief constant defining the maximum valid DurationSquared value (used in isValid()) */ static const double cMaxValue; /*! * \brief constant defining the assumed DurationSquared value accuracy * (used in comparison operator==(), operator!=()) */ static const double cPrecisionValue; /*! * \brief default constructor * * The default value of DurationSquared is: * std::numeric_limits<double>::quiet_NaN() */ DurationSquared() : mDurationSquared(std::numeric_limits<double>::quiet_NaN()) { } /*! * \brief standard constructor * * \note \ref \_AD_PHYSICS_DURATIONSQUARED_EXPLICIT_CONVERSION\_ defines, if only an explicit conversion is allowed. */ _AD_PHYSICS_DURATIONSQUARED_EXPLICIT_CONVERSION_ DurationSquared(double const iDurationSquared) : mDurationSquared(iDurationSquared) { } /*! * \brief standard copy constructor */ DurationSquared(const DurationSquared &other) = default; /*! * \brief standard move constructor */ DurationSquared(DurationSquared &&other) = default; /** * \brief standard assignment operator * * \param[in] other Other DurationSquared * * \returns Reference to this DurationSquared. */ DurationSquared &operator=(const DurationSquared &other) = default; /** * \brief standard move operator * * \param[in] other Other DurationSquared * * \returns Reference to this DurationSquared. */ DurationSquared &operator=(DurationSquared &&other) = default; /** * \brief standard comparison operator * * \param[in] other Other DurationSquared * * \returns \c true if both DurationSquared are valid and can be taken as numerically equal */ bool operator==(const DurationSquared &other) const { ensureValid(); other.ensureValid(); return std::fabs(mDurationSquared - other.mDurationSquared) < cPrecisionValue; } /** * \brief standard comparison operator * * \param[in] other Other DurationSquared. * * \returns \c true if one of the DurationSquared is not valid or they can be taken as numerically different */ bool operator!=(const DurationSquared &other) const { return !operator==(other); } /** * \brief standard comparison operator * * \param[in] other Other DurationSquared. * * \returns \c true if both DurationSquared are valid and * this DurationSquared is strictly numerically greater than other. * \note the precision of DurationSquared is considered */ bool operator>(const DurationSquared &other) const { ensureValid(); other.ensureValid(); return (mDurationSquared > other.mDurationSquared) && operator!=(other); } /** * \brief standard comparison operator * * \param[in] other Other DurationSquared. * * \returns \c true if both DurationSquared are valid and * this DurationSquared is strictly numerically smaller than other. * \note the precision of DurationSquared is considered */ bool operator<(const DurationSquared &other) const { ensureValid(); other.ensureValid(); return (mDurationSquared < other.mDurationSquared) && operator!=(other); } /** * \brief standard comparison operator * * \param[in] other Other DurationSquared. * * \returns \c true if both DurationSquared are valid and * this DurationSquared is numerically greater than other. * \note the precision of DurationSquared is considered */ bool operator>=(const DurationSquared &other) const { ensureValid(); other.ensureValid(); return ((mDurationSquared > other.mDurationSquared) || operator==(other)); } /** * \brief standard comparison operator * * \param[in] other Other DurationSquared * * \returns \c true if both DurationSquared are valid and * this DurationSquared is numerically smaller than other. * \note the precision of DurationSquared is considered */ bool operator<=(const DurationSquared &other) const { ensureValid(); other.ensureValid(); return ((mDurationSquared < other.mDurationSquared) || operator==(other)); } /** * \brief standard arithmetic operator * * \param[in] other Other DurationSquared * * \returns Result of arithmetic operation. * * \note throws a std::out_of_range exception if one of the two operands or the result of * the operation is not valid */ DurationSquared operator+(const DurationSquared &other) const { ensureValid(); other.ensureValid(); DurationSquared const result(mDurationSquared + other.mDurationSquared); result.ensureValid(); return result; } /** * \brief standard arithmetic operator * * \param[in] other Other DurationSquared * * \returns Result of arithmetic operation. * * \note throws a std::out_of_range exception if one of the two operands or the result of * the operation is not valid */ DurationSquared &operator+=(const DurationSquared &other) { ensureValid(); other.ensureValid(); mDurationSquared += other.mDurationSquared; ensureValid(); return *this; } /** * \brief standard arithmetic operator * * \param[in] other Other DurationSquared * * \returns Result of arithmetic operation. * * \note throws a std::out_of_range exception if one of the two operands or the result of * the operation is not valid */ DurationSquared operator-(const DurationSquared &other) const { ensureValid(); other.ensureValid(); DurationSquared const result(mDurationSquared - other.mDurationSquared); result.ensureValid(); return result; } /** * \brief standard arithmetic operator * * \param[in] other Other DurationSquared * * \returns Result of arithmetic operation. * * \note throws a std::out_of_range exception if one of the two operands or the result of * the operation is not valid */ DurationSquared operator-=(const DurationSquared &other) { ensureValid(); other.ensureValid(); mDurationSquared -= other.mDurationSquared; ensureValid(); return *this; } /** * \brief standard arithmetic operator * * \param[in] scalar Scalar double value * * \returns Result of arithmetic operation. * * \note throws a std::out_of_range exception if \c value or the result of * the operation is not valid */ DurationSquared operator*(const double &scalar) const { ensureValid(); DurationSquared const result(mDurationSquared * scalar); result.ensureValid(); return result; } /** * \brief standard arithmetic operator * * \param[in] scalar Scalar double value * * \returns Result of arithmetic operation. * * \note throws a std::out_of_range exception if this or the result of * the operation is not valid or other is zero */ DurationSquared operator/(const double &scalar) const { DurationSquared const scalarDurationSquared(scalar); DurationSquared const result(operator/(scalarDurationSquared)); result.ensureValid(); return result; } /** * \brief standard arithmetic operator * * \param[in] other Other DurationSquared * * \returns Result of arithmetic operation. * * \note throws a std::out_of_range exception if one of the two operands or the result of * the operation is not valid or other is zero * \note since DurationSquared is a type with physical unit, the division results in the dimensionless type. */ double operator/(const DurationSquared &other) const { ensureValid(); other.ensureValidNonZero(); double const result = mDurationSquared / other.mDurationSquared; return result; } /** * \brief standard arithmetic operator * * \returns Result of arithmetic operation. * * \note throws a std::out_of_range exception if this or the result of * the operation is not valid */ DurationSquared operator-() const { ensureValid(); DurationSquared const result(-mDurationSquared); result.ensureValid(); // LCOV_EXCL_BR_LINE Some types do not throw an exception return result; } /*! * \brief conversion to base type: double * * \note the conversion to the base type removes the physical unit. * \ref \_AD_PHYSICS_DURATIONSQUARED_EXPLICIT_CONVERSION\_ defines, if only explicit calls are allowed. */ _AD_PHYSICS_DURATIONSQUARED_EXPLICIT_CONVERSION_ operator double() const { return mDurationSquared; } /*! * \returns \c true if the DurationSquared in a valid range * * An DurationSquared value is defined to be valid if: * - It is normal or zero (see std::fpclassify()) * - \ref cMinValue <= value <= \ref cMaxValue */ bool isValid() const { auto const valueClass = std::fpclassify(mDurationSquared); return ((valueClass == FP_NORMAL) || (valueClass == FP_ZERO)) && (cMinValue <= mDurationSquared) && (mDurationSquared <= cMaxValue); } /*! * \brief ensure that the DurationSquared is valid * * Throws an std::out_of_range() exception if the DurationSquared * in not valid (i.e. isValid() returns false) */ void ensureValid() const { if (!isValid()) { spdlog::info("ensureValid(::ad::physics::DurationSquared)>> {} value out of range", *this); // LCOV_EXCL_BR_LINE #if (AD_PHYSICS_DURATIONSQUARED_THROWS_EXCEPTION == 1) throw std::out_of_range("DurationSquared value out of range"); // LCOV_EXCL_BR_LINE #endif } } /*! * \brief ensure that the DurationSquared is valid and non zero * * Throws an std::out_of_range() exception if the DurationSquared * in not valid or zero (i.e. isValid() returns false) */ void ensureValidNonZero() const { ensureValid(); if (operator==(DurationSquared(0.))) // LCOV_EXCL_BR_LINE { spdlog::info("ensureValid(::ad::physics::DurationSquared)>> {} value is zero", *this); // LCOV_EXCL_BR_LINE #if (AD_PHYSICS_DURATIONSQUARED_THROWS_EXCEPTION == 1) throw std::out_of_range("DurationSquared value is zero"); // LCOV_EXCL_BR_LINE #endif } } /*! * \brief get minimum valid DurationSquared (i.e. \ref cMinValue) */ static DurationSquared getMin() { return DurationSquared(cMinValue); } /*! * \brief get maximum valid DurationSquared (i.e. \ref cMaxValue) */ static DurationSquared getMax() { return DurationSquared(cMaxValue); } /*! * \brief get assumed accuracy of DurationSquared (i.e. \ref cPrecisionValue) */ static DurationSquared getPrecision() { return DurationSquared(cPrecisionValue); } private: /*! * \brief the actual value of the type */ double mDurationSquared; }; } // namespace physics } // namespace ad /** * \brief standard arithmetic operator * * \param[in] other Other DurationSquared as double value * \param[in] value DurationSquared value * * \returns Result of arithmetic operation. * * \note throws a std::out_of_range exception if \c value or the result of * the operation is not valid */ inline ::ad::physics::DurationSquared operator*(const double &other, ::ad::physics::DurationSquared const &value) { return value.operator*(other); } /*! * \brief namespace std */ namespace std { /*! * \brief overload of the std::fabs for DurationSquared */ inline ::ad::physics::DurationSquared fabs(const ::ad::physics::DurationSquared other) { ::ad::physics::DurationSquared const result(std::fabs(static_cast<double>(other))); return result; } /*! * \brief specialization of the std::numeric_limits for DurationSquared * * Derived from std::numeric_limits<double> with overloaded functions: * std::numeric_limits<DurationSquared>::lowest() (\see DurationSquared::getMin()) * std::numeric_limits<DurationSquared>::max() (\see DurationSquared::getMax()) * std::numeric_limits<DurationSquared>::epsilon() (\see DurationSquared::getPrecision()) */ template <> class numeric_limits<::ad::physics::DurationSquared> : public numeric_limits<double> { public: /*! * \see std::numeric_limits::lowest() */ static inline ::ad::physics::DurationSquared lowest() { return ::ad::physics::DurationSquared::getMin(); } /*! * \see std::numeric_limits::max() */ static inline ::ad::physics::DurationSquared max() { return ::ad::physics::DurationSquared::getMax(); } /*! * \see std::numeric_limits::epsilon() */ static inline ::ad::physics::DurationSquared epsilon() { return ::ad::physics::DurationSquared::getPrecision(); } }; /*! * \brief overload of the std::sqrt for DurationSquared * * The square root of a squared type is basic type: Duration. */ ::ad::physics::Duration sqrt(::ad::physics::DurationSquared const other); } // namespace std /*! * \brief protect the definition of functions from duplicates by typedef usage within other data types */ #ifndef GEN_GUARD_AD_PHYSICS_DURATIONSQUARED #define GEN_GUARD_AD_PHYSICS_DURATIONSQUARED /*! * @brief namespace ad */ namespace ad { /*! * @brief namespace physics */ namespace physics { /** * \brief standard ostream operator * * \param[in] os The output stream to write to * \param[in] _value DurationSquared value * * \returns The stream object. * */ inline std::ostream &operator<<(std::ostream &os, DurationSquared const &_value) { return os << double(_value); } } // namespace physics } // namespace ad namespace std { /*! * \brief overload of the std::to_string for DurationSquared */ inline std::string to_string(::ad::physics::DurationSquared const &value) { return to_string(static_cast<double>(value)); } } // namespace std #endif // GEN_GUARD_AD_PHYSICS_DURATIONSQUARED
26.42931
118
0.687977
hulk-mk
4f84ff2b6c6528f1c18a73ceb21af11c6fabb053
28,189
cpp
C++
src/coreclr/src/vm/inlinetracking.cpp
patricksadowski/runtime
aa5b2041471d7687dbddb1d275ea8a93943c43bf
[ "MIT" ]
2
2020-05-27T10:46:24.000Z
2020-05-27T10:46:27.000Z
src/coreclr/src/vm/inlinetracking.cpp
patricksadowski/runtime
aa5b2041471d7687dbddb1d275ea8a93943c43bf
[ "MIT" ]
1
2020-04-24T10:03:11.000Z
2020-04-24T10:03:11.000Z
src/coreclr/src/vm/inlinetracking.cpp
patricksadowski/runtime
aa5b2041471d7687dbddb1d275ea8a93943c43bf
[ "MIT" ]
1
2020-08-04T14:01:38.000Z
2020-08-04T14:01:38.000Z
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // ============================================================================================= // Code for tracking method inlinings in NGen and R2R images. // The only information stored is "who" got inlined "where", no offsets or inlining depth tracking. // (No good for debugger yet.) // This information is later exposed to profilers and can be useful for ReJIT. // Runtime inlining is not being tracked because profilers can deduce it via callbacks anyway. // ============================================================================================= #include "common.h" #include "inlinetracking.h" #include "ceeload.h" #include "versionresilienthashcode.h" using namespace NativeFormat; #ifndef DACCESS_COMPILE bool MethodInModule::operator <(const MethodInModule& other) const { STANDARD_VM_CONTRACT; if (m_module == other.m_module) { return m_methodDef < other.m_methodDef; } else { // Since NGen images are supposed to be determenistic, // we need stable sort order that isn't changing between different runs // That's why we use names and GUIDs instead of just doing m_module < other.m_module // First we try to compare simple names (should be fast enough) LPCUTF8 simpleName = m_module ? m_module->GetSimpleName() : ""; LPCUTF8 otherSimpleName = other.m_module ? other.m_module->GetSimpleName() : ""; int nameCmpResult = strcmp(simpleName, otherSimpleName); if (nameCmpResult == 0) { // Names are equal but module addresses aren't, it's suspicious // falling back to module GUIDs GUID thisGuid, otherGuid; if (m_module == NULL) { memset(&thisGuid, 0, sizeof(GUID)); } else { m_module->GetFile()->GetMVID(&thisGuid); } if (other.m_module == NULL) { memset(&otherGuid, 0, sizeof(GUID)); } else { other.m_module->GetFile()->GetMVID(&otherGuid); } return memcmp(&thisGuid, &otherGuid, sizeof(GUID)) < 0; } else { return nameCmpResult < 0; } } } bool MethodInModule::operator ==(const MethodInModule& other) const { LIMITED_METHOD_DAC_CONTRACT; return m_methodDef == other.m_methodDef && m_module == other.m_module; } bool MethodInModule::operator !=(const MethodInModule& other) const { LIMITED_METHOD_DAC_CONTRACT; return m_methodDef != other.m_methodDef || m_module != other.m_module; } void InlineTrackingEntry::SortAndDeduplicate() { STANDARD_VM_CONTRACT; //Sort MethodInModule *begin = &m_inliners[0]; MethodInModule *end = begin + m_inliners.GetCount(); util::sort(begin, end); //Deduplicate MethodInModule *left = begin; MethodInModule *right = left + 1; while (right < end) { auto rvalue = *right; if (*left != rvalue) { left++; if (left != right) { *left = rvalue; } } right++; } //Shrink int newCount = (int)(left - begin + 1); m_inliners.SetCount(newCount); } InlineTrackingEntry::InlineTrackingEntry(const InlineTrackingEntry& other) :m_inlinee(other.m_inlinee) { STANDARD_VM_CONTRACT; m_inliners.Set(other.m_inliners); } InlineTrackingEntry & InlineTrackingEntry::operator = (const InlineTrackingEntry &other) { STANDARD_VM_CONTRACT; m_inlinee = other.m_inlinee; m_inliners.Set(other.m_inliners); return *this; } void InlineTrackingEntry::Add(PTR_MethodDesc inliner) { STANDARD_VM_CONTRACT; MethodInModule method(inliner->GetModule(), inliner->GetMemberDef()); // Going through last 10 inliners to check if a given inliner has recently been registered. // It allows to filter out most duplicates without having to scan through hundreds of inliners // for methods like Object.ctor or Monitor.Enter. // We are OK to keep occasional duplicates in m_inliners, we'll get rid of them // in SortAndDeduplicate() anyway. int count = static_cast<int>(m_inliners.GetCount()); int start = max(0, count - 10); for (int i = count - 1; i >= start; i--) { if (m_inliners[i] == method) return; } //look like we see this inliner for the first time, add it to the collection m_inliners.Append(method); } InlineTrackingMap::InlineTrackingMap() : m_mapCrst(CrstInlineTrackingMap) { STANDARD_VM_CONTRACT; } void InlineTrackingMap::AddInlining(MethodDesc *inliner, MethodDesc *inlinee) { STANDARD_VM_CONTRACT; _ASSERTE(inliner != NULL); _ASSERTE(inlinee != NULL); MethodInModule inlineeMnM(inlinee->GetModule(), inlinee->GetMemberDef()); if (RidFromToken(inlineeMnM.m_methodDef) == 0 || RidFromToken(inliner->GetMemberDef()) == 0) { // Sometimes we do see methods that don't have valid tokens (stubs etc) // we just ignore them. return; } CrstHolder lock(&m_mapCrst); InlineTrackingEntry *existingEntry = const_cast<InlineTrackingEntry *>(LookupPtr(inlineeMnM)); if (existingEntry) { // We saw this inlinee before, just add one more inliner existingEntry->Add(inliner); } else { // We haven't seen this inlinee before, create a new record in the hashtable // and add a first inliner to it. InlineTrackingEntry newEntry; newEntry.m_inlinee = inlineeMnM; newEntry.Add(inliner); Add(newEntry); } } #endif //!DACCESS_COMPILE void ZapInlineeRecord::InitForNGen(RID rid, LPCUTF8 simpleName) { LIMITED_METHOD_CONTRACT; //XOR of up to first 24 bytes in module name DWORD hash = 0; for (int i = 0; simpleName[i] && i < 24; i++) hash ^= (BYTE)simpleName[i]; // This key contains 24 bits of RID and 8 bits from module name. // Since RID can't be longer than 24 bits, we can't have method RID collistions, // that's why PersistentInlineTrackingMap::GetInliners only deals with module collisions. m_key = (hash << 24) | rid; } COUNT_T PersistentInlineTrackingMapNGen::GetInliners(PTR_Module inlineeOwnerMod, mdMethodDef inlineeTkn, COUNT_T inlinersSize, MethodInModule inliners[], BOOL *incompleteData) { CONTRACTL { THROWS; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; _ASSERTE(inlineeOwnerMod); _ASSERTE(inliners); if (incompleteData) { *incompleteData = FALSE; } if (m_inlineeIndex == NULL || m_inlinersBuffer == NULL) { //No inlines saved in this image. return 0; } // Binary search to find all records matching (inlineeTkn/inlineeOwnerMod) ZapInlineeRecord probeRecord; probeRecord.InitForNGen(RidFromToken(inlineeTkn), inlineeOwnerMod->GetSimpleName()); ZapInlineeRecord *begin = m_inlineeIndex; ZapInlineeRecord *end = m_inlineeIndex + m_inlineeIndexSize; ZapInlineeRecord *foundRecord = util::lower_bound(begin, end, probeRecord); DWORD result = 0; DWORD outputIndex = 0; // Go through all matching records for (; foundRecord < end && *foundRecord == probeRecord; foundRecord++) { DWORD offset = foundRecord->m_offset; NibbleReader stream(m_inlinersBuffer + offset, m_inlinersBufferSize - offset); DWORD inlineeModuleZapIndex = stream.ReadEncodedU32(); Module *decodedInlineeModule = GetModuleByIndex(inlineeModuleZapIndex); // Check if this is just token/method name hash collision if (decodedInlineeModule == inlineeOwnerMod) { // We found the token and the module we were looking for! DWORD inlinerModuleZapIndex = stream.ReadEncodedU32(); //read inliner module, it is same for all inliners Module *inlinerModule = GetModuleByIndex(inlinerModuleZapIndex); if (inlinerModule != NULL) { DWORD inlinersCount = stream.ReadEncodedU32(); _ASSERTE(inlinersCount > 0); RID inlinerRid = 0; // Reading inliner RIDs one by one, each RID is represented as an adjustment (diff) to the previous one. // Adding inliners module and coping to the output buffer for (DWORD i = 0; i < inlinersCount && outputIndex < inlinersSize; i++) { inlinerRid += stream.ReadEncodedU32(); mdMethodDef inlinerTkn = TokenFromRid(inlinerRid, mdtMethodDef); inliners[outputIndex++] = MethodInModule(inlinerModule, inlinerTkn); } result += inlinersCount; } else { // We can't find module for this inlineeModuleZapIndex, it means it hasn't been loaded yet // (maybe it never will be), we just report it to the profiler. // Profiler might want to try later when more modules are loaded. if (incompleteData) { *incompleteData = TRUE; } } } } return result; } Module *PersistentInlineTrackingMapNGen::GetModuleByIndex(DWORD index) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; // This "black magic spell" has in fact nothing to do with GenericInstantiationCompare per se, but just sets a thread flag // that later activates more thorough search inside Module::GetAssemblyIfLoaded, which is indirectly called from GetModuleFromIndexIfLoaded. // This is useful when ngen image was compiler against a different assembly version than the one loaded now. ClrFlsThreadTypeSwitch genericInstantionCompareHolder(ThreadType_GenericInstantiationCompare); return m_module->GetModuleFromIndexIfLoaded(index); } #ifndef DACCESS_COMPILE #ifdef FEATURE_NATIVE_IMAGE_GENERATION // This is a shared serialization routine used for both NGEN and R2R formats. If image != NULL the NGEN format is generated, otherwise the R2R format void SerializeInlineTrackingEntry(DataImage* image, SBuffer *inlinersBuffer, SArray<ZapInlineeRecord> *inlineeIndex, InlineTrackingEntry *entry) { STANDARD_VM_CONTRACT; // This call removes duplicates from inliners and makes sure they are sorted by module entry->SortAndDeduplicate(); MethodInModule inlinee = entry->m_inlinee; DWORD inlineeModuleZapIndex = 0; if (image != NULL) { inlineeModuleZapIndex = image->GetModuleImportIndex(inlinee.m_module); } InlineSArray<MethodInModule, 3> &inliners = entry->m_inliners; COUNT_T totalInlinersCount = inliners.GetCount(); _ASSERTE(totalInlinersCount > 0); COUNT_T sameModuleCount; // Going through all inliners and grouping them by their module, for each module we'll create // an ZapInlineeRecord and encode inliners as bytes in inlinersBuffer. for (COUNT_T thisModuleBegin = 0; thisModuleBegin < totalInlinersCount; thisModuleBegin += sameModuleCount) { Module *lastInlinerModule = inliners[thisModuleBegin].m_module; DWORD lastInlinerModuleZapIndex = 0; if (image != NULL) { lastInlinerModuleZapIndex = image->GetModuleImportIndex(lastInlinerModule); } // Counting how many inliners belong to this module sameModuleCount = 1; while (thisModuleBegin + sameModuleCount < totalInlinersCount && inliners[thisModuleBegin + sameModuleCount].m_module == lastInlinerModule) { sameModuleCount++; } // Saving module indexes and number of inliners NibbleWriter inlinersStream; if (image != NULL) { inlinersStream.WriteEncodedU32(inlineeModuleZapIndex); inlinersStream.WriteEncodedU32(lastInlinerModuleZapIndex); } inlinersStream.WriteEncodedU32(sameModuleCount); // Saving inliners RIDs, each new RID is represented as an adjustment (diff) to the previous one RID prevMethodRid = 0; for (COUNT_T i = thisModuleBegin; i < thisModuleBegin + sameModuleCount; i++) { RID methodRid = RidFromToken(inliners[i].m_methodDef); _ASSERTE(methodRid >= prevMethodRid); inlinersStream.WriteEncodedU32(methodRid - prevMethodRid); prevMethodRid = methodRid; } inlinersStream.Flush(); // Copy output of NibbleWriter into a big buffer (inlinersBuffer) for inliners from the same module // and create an InlineeRecord with correct offset DWORD inlinersStreamSize; const BYTE *inlinersStreamPtr = (const BYTE *)inlinersStream.GetBlob(&inlinersStreamSize); ZapInlineeRecord record; if (image != NULL) { record.InitForNGen(RidFromToken(inlinee.m_methodDef), inlinee.m_module->GetSimpleName()); } else { record.InitForR2R(RidFromToken(inlinee.m_methodDef)); } record.m_offset = inlinersBuffer->GetSize(); inlinersBuffer->Insert(inlinersBuffer->End(), SBuffer(SBuffer::Immutable, inlinersStreamPtr, inlinersStreamSize)); inlineeIndex->Append(record); } } bool compare_entry(const InlineTrackingEntry* first, const InlineTrackingEntry* second) { return first->m_inlinee < second->m_inlinee; } // This is a shared serialization routine used for both NGEN and R2R formats. If image != NULL the NGEN format is generated, otherwise the R2R format void SerializeTrackingMapBuffers(ZapHeap* heap, DataImage *image, SBuffer *inlinersBuffer, SArray<ZapInlineeRecord> *inlineeIndex, InlineTrackingMap* runtimeMap) { STANDARD_VM_CONTRACT; _ASSERTE(runtimeMap != NULL); // Sort records from runtimeMap, because we need to make sure // we save everything in deterministic order. Hashtable iteration is not deterministic. COUNT_T runtimeMapCount = runtimeMap->GetCount(); InlineTrackingEntry **inlinees = new (heap) InlineTrackingEntry *[runtimeMapCount]; int index = 0; for (auto iter = runtimeMap->Begin(), end = runtimeMap->End(); iter != end; ++iter) { inlinees[index++] = const_cast<InlineTrackingEntry *>(&*iter); } util::sort(inlinees, inlinees + runtimeMapCount, compare_entry); // Iterate throught each inlinee record from the InlineTrackingMap // and write corresponding records into inlineeIndex and inlinersBuffer for (COUNT_T i = 0; i < runtimeMapCount; i++) { SerializeInlineTrackingEntry(image, inlinersBuffer, inlineeIndex, inlinees[i]); } } void PersistentInlineTrackingMapNGen::Save(DataImage *image, InlineTrackingMap* runtimeMap) { STANDARD_VM_CONTRACT; _ASSERTE(image != NULL); _ASSERTE(runtimeMap != NULL); SArray<ZapInlineeRecord> inlineeIndex; SBuffer inlinersBuffer; SerializeTrackingMapBuffers(image->GetHeap(), image, &inlinersBuffer, &inlineeIndex, runtimeMap); m_inlineeIndexSize = inlineeIndex.GetCount(); m_inlinersBufferSize = inlinersBuffer.GetSize(); _ASSERTE((m_inlineeIndexSize == 0) == (m_inlinersBufferSize == 0)); if (m_inlineeIndexSize != 0 && m_inlinersBufferSize != 0) { // Copy everything to the class fields, we didn't use the class fields for addition // because we want to make sure we don't waste memory for buffer's amortized growth m_inlineeIndex = new (image->GetHeap()) ZapInlineeRecord[m_inlineeIndexSize]; inlineeIndex.Copy(m_inlineeIndex, inlineeIndex.Begin(), m_inlineeIndexSize); m_inlinersBuffer = new (image->GetHeap()) BYTE[m_inlinersBufferSize]; inlinersBuffer.Copy(m_inlinersBuffer, inlinersBuffer.Begin(), m_inlinersBufferSize); //Sort m_inlineeIndex so we can later use binary search util::sort(m_inlineeIndex, m_inlineeIndex + m_inlineeIndexSize); //Making sure all this memory actually gets saved into NGEN image image->StoreStructure(m_inlineeIndex, m_inlineeIndexSize * sizeof(m_inlineeIndex[0]), DataImage::ITEM_INLINING_DATA); image->StoreStructure(m_inlinersBuffer, m_inlinersBufferSize, DataImage::ITEM_INLINING_DATA); } image->StoreStructure(this, sizeof(*this), DataImage::ITEM_INLINING_DATA); LOG((LF_ZAP, LL_INFO100000, "PersistentInlineTrackingMap saved. InlineeIndexSize: %d bytes, InlinersBufferSize: %d bytes\n", m_inlineeIndexSize * sizeof(m_inlineeIndex[0]), m_inlinersBufferSize)); } void PersistentInlineTrackingMapNGen::Fixup(DataImage *image) { STANDARD_VM_CONTRACT; image->FixupPointerField(this, offsetof(PersistentInlineTrackingMapNGen, m_module)); image->FixupPointerField(this, offsetof(PersistentInlineTrackingMapNGen, m_inlineeIndex)); image->FixupPointerField(this, offsetof(PersistentInlineTrackingMapNGen, m_inlinersBuffer)); } #endif //FEATURE_NATIVE_IMAGE_GENERATION #endif //!DACCESS_COMPILE #ifdef FEATURE_READYTORUN struct InliningHeader { int SizeOfInlineeIndex; }; #ifndef DACCESS_COMPILE #ifdef FEATURE_NATIVE_IMAGE_GENERATION void PersistentInlineTrackingMapR2R::Save(ZapHeap* pHeap, SBuffer* pSaveTarget, InlineTrackingMap* runtimeMap) { STANDARD_VM_CONTRACT; _ASSERTE(pSaveTarget != NULL); _ASSERTE(runtimeMap != NULL); SArray<ZapInlineeRecord> inlineeIndex; SBuffer inlinersBuffer; SerializeTrackingMapBuffers(pHeap, NULL, &inlinersBuffer, &inlineeIndex, runtimeMap); InliningHeader header; header.SizeOfInlineeIndex = inlineeIndex.GetCount() * sizeof(ZapInlineeRecord); pSaveTarget->Insert(pSaveTarget->End(), SBuffer(SBuffer::Immutable, (const BYTE*) &header, sizeof(header))); DWORD unused = 0; pSaveTarget->Insert(pSaveTarget->End(), SBuffer(SBuffer::Immutable, (const BYTE*) inlineeIndex.GetElements(), header.SizeOfInlineeIndex)); pSaveTarget->Insert(pSaveTarget->End(), SBuffer(SBuffer::Immutable, (const BYTE*) inlinersBuffer, inlinersBuffer.GetSize())); LOG((LF_ZAP, LL_INFO100000, "PersistentInlineTrackingMap saved. InlineeIndexSize: %d bytes, InlinersBufferSize: %d bytes\n", header.SizeOfInlineeIndex, inlinersBuffer.GetSize())); } #endif //FEATURE_NATIVE_IMAGE_GENERATION BOOL PersistentInlineTrackingMapR2R::TryLoad(Module* pModule, const BYTE* pBuffer, DWORD cbBuffer, AllocMemTracker *pamTracker, PersistentInlineTrackingMapR2R** ppLoadedMap) { InliningHeader* pHeader = (InliningHeader*)pBuffer; if (pHeader->SizeOfInlineeIndex > (int)(cbBuffer - sizeof(InliningHeader))) { //invalid serialized data, the index can't be larger the entire block _ASSERTE(!"R2R image is invalid or there is a bug in the R2R parser"); return FALSE; } //NOTE: Error checking on the format is very limited at this point. //We trust the image format is valid and this initial check is a cheap //verification that may help catch simple bugs. It does not secure against //a deliberately maliciously formed binary. LoaderHeap *pHeap = pModule->GetLoaderAllocator()->GetHighFrequencyHeap(); void * pMemory = pamTracker->Track(pHeap->AllocMem((S_SIZE_T)sizeof(PersistentInlineTrackingMapR2R))); PersistentInlineTrackingMapR2R* pMap = new (pMemory) PersistentInlineTrackingMapR2R(); pMap->m_module = pModule; pMap->m_inlineeIndex = (PTR_ZapInlineeRecord)(pHeader + 1); pMap->m_inlineeIndexSize = pHeader->SizeOfInlineeIndex / sizeof(ZapInlineeRecord); pMap->m_inlinersBuffer = ((PTR_BYTE)(pHeader+1)) + pHeader->SizeOfInlineeIndex; pMap->m_inlinersBufferSize = cbBuffer - sizeof(InliningHeader) - pMap->m_inlineeIndexSize; *ppLoadedMap = pMap; return TRUE; } #endif //!DACCESS_COMPILE COUNT_T PersistentInlineTrackingMapR2R::GetInliners(PTR_Module inlineeOwnerMod, mdMethodDef inlineeTkn, COUNT_T inlinersSize, MethodInModule inliners[], BOOL *incompleteData) { CONTRACTL { THROWS; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; _ASSERTE(inlineeOwnerMod); _ASSERTE(inliners != NULL || inlinersSize == 0); if (incompleteData) { *incompleteData = FALSE; } if (m_inlineeIndex == NULL || m_inlinersBuffer == NULL) { //No inlines saved in this image. return 0; } if(inlineeOwnerMod != m_module) { // no cross module inlining (yet?) return 0; } // Binary search to find all records matching (inlineeTkn) ZapInlineeRecord probeRecord; probeRecord.InitForR2R(RidFromToken(inlineeTkn)); ZapInlineeRecord *begin = m_inlineeIndex; ZapInlineeRecord *end = m_inlineeIndex + m_inlineeIndexSize; ZapInlineeRecord *foundRecord = util::lower_bound(begin, end, probeRecord); DWORD result = 0; DWORD outputIndex = 0; // Go through all matching records for (; foundRecord < end && *foundRecord == probeRecord; foundRecord++) { DWORD offset = foundRecord->m_offset; NibbleReader stream(m_inlinersBuffer + offset, m_inlinersBufferSize - offset); Module *inlinerModule = m_module; DWORD inlinersCount = stream.ReadEncodedU32(); _ASSERTE(inlinersCount > 0); RID inlinerRid = 0; // Reading inliner RIDs one by one, each RID is represented as an adjustment (diff) to the previous one. // Adding inliners module and coping to the output buffer for (DWORD i = 0; i < inlinersCount && outputIndex < inlinersSize; i++) { inlinerRid += stream.ReadEncodedU32(); mdMethodDef inlinerTkn = TokenFromRid(inlinerRid, mdtMethodDef); inliners[outputIndex++] = MethodInModule(inlinerModule, inlinerTkn); } result += inlinersCount; } return result; } #ifndef DACCESS_COMPILE BOOL PersistentInlineTrackingMapR2R2::TryLoad(Module* pModule, const BYTE* pBuffer, DWORD cbBuffer, AllocMemTracker* pamTracker, PersistentInlineTrackingMapR2R2** ppLoadedMap) { LoaderHeap* pHeap = pModule->GetLoaderAllocator()->GetHighFrequencyHeap(); void* pMemory = pamTracker->Track(pHeap->AllocMem((S_SIZE_T)sizeof(PersistentInlineTrackingMapR2R2))); PersistentInlineTrackingMapR2R2* pMap = new (pMemory) PersistentInlineTrackingMapR2R2(); pMap->m_module = pModule; pMap->m_reader = NativeReader(pBuffer, cbBuffer); NativeParser parser = NativeParser(&pMap->m_reader, 0); pMap->m_hashtable = NativeHashtable(parser); *ppLoadedMap = pMap; return TRUE; } COUNT_T PersistentInlineTrackingMapR2R2::GetInliners(PTR_Module inlineeOwnerMod, mdMethodDef inlineeTkn, COUNT_T inlinersSize, MethodInModule inliners[], BOOL* incompleteData) { CONTRACTL { THROWS; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; _ASSERTE(inlineeOwnerMod); _ASSERTE(inliners); if (incompleteData) { *incompleteData = FALSE; } DWORD result = 0; int hashCode = GetVersionResilientModuleHashCode(inlineeOwnerMod); hashCode ^= inlineeTkn; NativeHashtable::Enumerator lookup = m_hashtable.Lookup(hashCode); NativeParser entryParser; while (lookup.GetNext(entryParser)) { DWORD streamSize = entryParser.GetUnsigned(); _ASSERTE(streamSize > 1); // First make sure this is the right inlinee and not just a hash collision DWORD inlineeRidAndFlag = entryParser.GetUnsigned(); streamSize--; mdMethodDef inlineeToken = TokenFromRid(inlineeRidAndFlag >> 1, mdtMethodDef); if (inlineeToken != inlineeTkn) { continue; } Module* inlineeModule; if ((inlineeRidAndFlag & 1) != 0) { inlineeModule = GetModuleByIndex(entryParser.GetUnsigned()); streamSize--; _ASSERTE(streamSize > 0); } else { inlineeModule = m_module; } if (inlineeModule != inlineeOwnerMod) { continue; } // We have the right inlinee, let's look at the inliners DWORD currentInlinerRid = 0; do { DWORD inlinerRidDeltaAndFlag = entryParser.GetUnsigned(); streamSize--; currentInlinerRid += inlinerRidDeltaAndFlag >> 1; Module* inlinerModule; if ((inlinerRidDeltaAndFlag & 1) != 0) { _ASSERTE(streamSize > 0); inlinerModule = GetModuleByIndex(entryParser.GetUnsigned()); streamSize--; if (inlinerModule == nullptr && incompleteData) { // We can't find module for this inlineeModuleZapIndex, it means it hasn't been loaded yet // (maybe it never will be), we just report it to the profiler. // Profiler might want to try later when more modules are loaded. *incompleteData = TRUE; continue; } } else { inlinerModule = m_module; } if (result < inlinersSize) { inliners[result].m_methodDef = TokenFromRid(currentInlinerRid, mdtMethodDef); inliners[result].m_module = inlinerModule; } result++; } while (streamSize > 0); } return result; } Module* PersistentInlineTrackingMapR2R2::GetModuleByIndex(DWORD index) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; // This "black magic spell" has in fact nothing to do with GenericInstantiationCompare per se, but just sets a thread flag // that later activates more thorough search inside Module::GetAssemblyIfLoaded, which is indirectly called from GetModuleFromIndexIfLoaded. // This is useful when ngen image was compiler against a different assembly version than the one loaded now. ClrFlsThreadTypeSwitch genericInstantionCompareHolder(ThreadType_GenericInstantiationCompare); return m_module->GetModuleFromIndexIfLoaded(index); } #endif //!DACCESS_COMPILE #endif //FEATURE_READYTORUN #if !defined(DACCESS_COMPILE) && !defined(CROSSGEN_COMPILE) JITInlineTrackingMap::JITInlineTrackingMap(LoaderAllocator *pAssociatedLoaderAllocator) : m_mapCrst(CrstJitInlineTrackingMap), m_map() { LIMITED_METHOD_CONTRACT; m_map.Init(pAssociatedLoaderAllocator); } BOOL JITInlineTrackingMap::InliningExistsDontTakeLock(MethodDesc *inliner, MethodDesc *inlinee) { LIMITED_METHOD_CONTRACT; _ASSERTE(m_mapCrst.OwnedByCurrentThread()); _ASSERTE(inliner != NULL); _ASSERTE(inlinee != NULL); BOOL found = FALSE; auto lambda = [&](OBJECTREF obj, MethodDesc *lambdaInlinee, MethodDesc *lambdaInliner) { _ASSERTE(inlinee == lambdaInlinee); if (lambdaInliner == inliner) { found = TRUE; return false; } return true; }; m_map.VisitValuesOfKey(inlinee, lambda); return found; } void JITInlineTrackingMap::AddInlining(MethodDesc *inliner, MethodDesc *inlinee) { LIMITED_METHOD_CONTRACT; inlinee = inlinee->LoadTypicalMethodDefinition(); CrstHolder holder(&m_mapCrst); AddInliningDontTakeLock(inliner, inlinee); } void JITInlineTrackingMap::AddInliningDontTakeLock(MethodDesc *inliner, MethodDesc *inlinee) { LIMITED_METHOD_CONTRACT; _ASSERTE(m_mapCrst.OwnedByCurrentThread()); _ASSERTE(inliner != NULL); _ASSERTE(inlinee != NULL); GCX_COOP(); if (!InliningExistsDontTakeLock(inliner, inlinee)) { LoaderAllocator *loaderAllocatorOfInliner = inliner->GetLoaderAllocator(); m_map.Add(inlinee, inliner, loaderAllocatorOfInliner); } } #endif // !defined(DACCESS_COMPILE) && !defined(CROSSGEN_COMPILE)
34.930607
175
0.670971
patricksadowski
4f85560d8ad56dc3a326ee07f360374566820569
3,928
cpp
C++
nano/lib/locks.cpp
Srayman/nano-node
d5fd87c1f73d8e5edac33e7969c1b3d5a04d90f4
[ "BSD-2-Clause" ]
3
2020-12-24T06:32:59.000Z
2021-01-13T17:50:51.000Z
nano/lib/locks.cpp
Ifarukcolak/nano-node
14454a234eaef6bd7e702ce252eebd3cf7cf3181
[ "BSD-2-Clause" ]
null
null
null
nano/lib/locks.cpp
Ifarukcolak/nano-node
14454a234eaef6bd7e702ce252eebd3cf7cf3181
[ "BSD-2-Clause" ]
1
2021-09-21T10:57:56.000Z
2021-09-21T10:57:56.000Z
#include <nano/lib/locks.hpp> #include <nano/lib/utility.hpp> #if NANO_TIMED_LOCKS > 0 namespace { template <typename Mutex> void output (const char * str, std::chrono::milliseconds time, Mutex & mutex) { static std::mutex cout_mutex; auto stacktrace = nano::generate_stacktrace (); // Guard standard out to keep the output from being interleaved std::lock_guard<std::mutex> guard (cout_mutex); std::cout << std::addressof (mutex) << " Mutex " << str << " for: " << time.count () << "ms\n" << stacktrace << std::endl; } template <typename Mutex> void output_if_held_long_enough (nano::timer<std::chrono::milliseconds> & timer, Mutex & mutex) { auto time_held = timer.since_start (); if (time_held >= std::chrono::milliseconds (NANO_TIMED_LOCKS)) { output ("held", time_held, mutex); } timer.stop (); } template <typename Mutex> void output_if_blocked_long_enough (nano::timer<std::chrono::milliseconds> & timer, Mutex & mutex) { auto time_blocked = timer.since_start (); if (time_blocked >= std::chrono::milliseconds (NANO_TIMED_LOCKS)) { output ("blocked", time_blocked, mutex); } } } namespace nano { lock_guard<std::mutex>::lock_guard (std::mutex & mutex) : mut (mutex) { timer.start (); mut.lock (); output_if_blocked_long_enough (timer, mut); } lock_guard<std::mutex>::~lock_guard () noexcept { mut.unlock (); output_if_held_long_enough (timer, mut); } // Explicit instantiations for allowed types template class lock_guard<std::mutex>; template <typename Mutex, typename U> unique_lock<Mutex, U>::unique_lock (Mutex & mutex) : mut (std::addressof (mutex)) { lock_impl (); } template <typename Mutex, typename U> void unique_lock<Mutex, U>::lock_impl () { timer.start (); mut->lock (); owns = true; output_if_blocked_long_enough (timer, *mut); } template <typename Mutex, typename U> unique_lock<Mutex, U> & unique_lock<Mutex, U>::operator= (unique_lock<Mutex, U> && other) noexcept { if (this != std::addressof (other)) { if (owns) { mut->unlock (); owns = false; output_if_held_long_enough (timer, *mut); } mut = other.mut; owns = other.owns; timer = other.timer; other.mut = nullptr; other.owns = false; } return *this; } template <typename Mutex, typename U> unique_lock<Mutex, U>::~unique_lock () noexcept { if (owns) { mut->unlock (); owns = false; output_if_held_long_enough (timer, *mut); } } template <typename Mutex, typename U> void unique_lock<Mutex, U>::lock () { validate (); lock_impl (); } template <typename Mutex, typename U> bool unique_lock<Mutex, U>::try_lock () { validate (); owns = mut->try_lock (); if (owns) { timer.start (); } return owns; } template <typename Mutex, typename U> void unique_lock<Mutex, U>::unlock () { if (!mut || !owns) { throw (std::system_error (std::make_error_code (std::errc::operation_not_permitted))); } mut->unlock (); owns = false; output_if_held_long_enough (timer, *mut); } template <typename Mutex, typename U> bool unique_lock<Mutex, U>::owns_lock () const noexcept { return owns; } template <typename Mutex, typename U> unique_lock<Mutex, U>::operator bool () const noexcept { return owns; } template <typename Mutex, typename U> Mutex * unique_lock<Mutex, U>::mutex () const noexcept { return mut; } template <typename Mutex, typename U> void unique_lock<Mutex, U>::validate () const { if (!mut) { throw (std::system_error (std::make_error_code (std::errc::operation_not_permitted))); } if (owns) { throw (std::system_error (std::make_error_code (std::errc::resource_deadlock_would_occur))); } } // Explicit instantiations for allowed types template class unique_lock<std::mutex>; void condition_variable::notify_one () noexcept { cnd.notify_one (); } void condition_variable::notify_all () noexcept { cnd.notify_all (); } void condition_variable::wait (nano::unique_lock<std::mutex> & lk) { cnd.wait (lk); } } #endif
19.738693
98
0.691446
Srayman
4f863fd5b046a7c6bb13b874cc6924a29f7280ea
442
cpp
C++
template/Add.cpp
jdh8/dragonite
af727ab5a1366efea917f2cb7e9b8797fa01d952
[ "MIT" ]
null
null
null
template/Add.cpp
jdh8/dragonite
af727ab5a1366efea917f2cb7e9b8797fa01d952
[ "MIT" ]
null
null
null
template/Add.cpp
jdh8/dragonite
af727ab5a1366efea917f2cb7e9b8797fa01d952
[ "MIT" ]
null
null
null
#include "common.hpp" {% from "mod/batch.cpp" import batch -%} {% from "mod/binary.cpp" import inner, outer -%} {% call(name, shape) batch() -%} {% call(x, y) outer("Add", name, shape) -%} {% set a = numpy.random.standard_cauchy(x).astype(numpy.float32) -%} {% set b = numpy.random.standard_cauchy(y).astype(numpy.float32) -%} {{ inner(a + b, a, b) }} {% endcall -%} {% endcall -%} {# vim: set ft=liquid: #}
31.571429
76
0.565611
jdh8
4f8902a93982b124df08d91dbf39706c491eb85c
64,990
cpp
C++
lib/AST/Builtins.cpp
gottesmm/swift
ac57b66c99f9e5f8dd023245a28447613f74d08d
[ "Apache-2.0" ]
2
2016-11-03T04:30:53.000Z
2016-12-07T08:17:10.000Z
lib/AST/Builtins.cpp
gottesmm/swift
ac57b66c99f9e5f8dd023245a28447613f74d08d
[ "Apache-2.0" ]
1
2016-08-16T17:02:01.000Z
2016-12-14T23:46:57.000Z
lib/AST/Builtins.cpp
gottesmm/swift
ac57b66c99f9e5f8dd023245a28447613f74d08d
[ "Apache-2.0" ]
null
null
null
//===--- Builtins.cpp - Swift Language Builtin ASTs -----------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file implements the interface to the Builtin APIs. // //===----------------------------------------------------------------------===// #include "swift/AST/AST.h" #include "swift/AST/ArchetypeBuilder.h" #include "swift/Basic/LLVMContext.h" #include "swift/AST/Builtins.h" #include "swift/AST/GenericEnvironment.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/IR/Attributes.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/Intrinsics.h" #include "llvm/IR/LLVMContext.h" #include <tuple> using namespace swift; struct BuiltinExtraInfoTy { const char *Attributes; }; static const BuiltinExtraInfoTy BuiltinExtraInfo[] = { {nullptr}, #define BUILTIN(Id, Name, Attrs) {Attrs}, #include "swift/AST/Builtins.def" }; bool BuiltinInfo::isReadNone() const { return strchr(BuiltinExtraInfo[(unsigned)ID].Attributes, 'n') != nullptr; } bool IntrinsicInfo::hasAttribute(llvm::Attribute::AttrKind Kind) const { // FIXME: We should not be relying on the global LLVM context. llvm::AttributeSet attrs = llvm::Intrinsic::getAttributes(getGlobalLLVMContext(), ID); return (attrs.hasAttribute(llvm::AttributeSet::FunctionIndex, Kind)); } Type swift::getBuiltinType(ASTContext &Context, StringRef Name) { // Vectors are VecNxT, where "N" is the number of elements and // T is the element type. if (Name.startswith("Vec")) { Name = Name.substr(3); StringRef::size_type xPos = Name.find('x'); if (xPos == StringRef::npos) return Type(); unsigned numElements; if (Name.substr(0, xPos).getAsInteger(10, numElements) || numElements == 0 || numElements > 1024) return Type(); Type elementType = getBuiltinType(Context, Name.substr(xPos + 1)); if (!elementType) return Type(); return BuiltinVectorType::get(Context, elementType, numElements); } if (Name == "RawPointer") return Context.TheRawPointerType; if (Name == "NativeObject") return Context.TheNativeObjectType; if (Name == "UnknownObject") return Context.TheUnknownObjectType; if (Name == "BridgeObject") return Context.TheBridgeObjectType; if (Name == "UnsafeValueBuffer") return Context.TheUnsafeValueBufferType; if (Name == "FPIEEE32") return Context.TheIEEE32Type; if (Name == "FPIEEE64") return Context.TheIEEE64Type; if (Name == "Word") return BuiltinIntegerType::getWordType(Context); // Handle 'int8' and friends. if (Name.substr(0, 3) == "Int") { unsigned BitWidth; if (!Name.substr(3).getAsInteger(10, BitWidth) && BitWidth <= 2048 && BitWidth != 0) // Cap to prevent insane things. return BuiltinIntegerType::get(BitWidth, Context); } // Target specific FP types. if (Name == "FPIEEE16") return Context.TheIEEE16Type; if (Name == "FPIEEE80") return Context.TheIEEE80Type; if (Name == "FPIEEE128") return Context.TheIEEE128Type; if (Name == "FPPPC128") return Context.ThePPC128Type; return Type(); } /// getBuiltinBaseName - Decode the type list of a builtin (e.g. mul_Int32) and /// return the base name (e.g. "mul"). StringRef swift::getBuiltinBaseName(ASTContext &C, StringRef Name, SmallVectorImpl<Type> &Types) { // builtin-id ::= operation-id ('_' type-id)* for (StringRef::size_type Underscore = Name.find_last_of('_'); Underscore != StringRef::npos; Underscore = Name.find_last_of('_')) { // Check that the type parameter is well-formed and set it up for returning. // This allows operations with underscores in them, like "icmp_eq". Type Ty = getBuiltinType(C, Name.substr(Underscore + 1)); if (Ty.isNull()) break; Types.push_back(Ty); Name = Name.substr(0, Underscore); } std::reverse(Types.begin(), Types.end()); return Name; } /// Build a builtin function declaration. static FuncDecl * getBuiltinFunction(Identifier Id, ArrayRef<Type> argTypes, Type ResType, FunctionType::ExtInfo Info = FunctionType::ExtInfo()) { auto &Context = ResType->getASTContext(); SmallVector<TupleTypeElt, 4> tupleElts; for (Type argType : argTypes) tupleElts.push_back(argType); Type ArgType = TupleType::get(tupleElts, Context); Type FnType = FunctionType::get(ArgType, ResType, Info); ModuleDecl *M = Context.TheBuiltinModule; DeclContext *DC = &M->getMainFile(FileUnitKind::Builtin); SmallVector<ParamDecl*, 4> params; for (Type argType : argTypes) { auto PD = new (Context) ParamDecl(/*IsLet*/true, SourceLoc(), SourceLoc(), Identifier(), SourceLoc(), Identifier(), argType, DC); PD->setInterfaceType(argType); PD->setImplicit(); params.push_back(PD); } auto *paramList = ParameterList::create(Context, params); DeclName Name(Context, Id, paramList); auto FD = FuncDecl::create(Context, /*StaticLoc=*/SourceLoc(), StaticSpellingKind::None, /*FuncLoc=*/SourceLoc(), Name, /*NameLoc=*/SourceLoc(), /*Throws=*/false, /*ThrowsLoc=*/SourceLoc(), /*AccessorKeywordLoc=*/SourceLoc(), /*GenericParams=*/nullptr, paramList, TypeLoc::withoutLoc(ResType), DC); FD->setInterfaceType(FnType); FD->setImplicit(); FD->setAccessibility(Accessibility::Public); return FD; } /// Build a builtin function declaration. static FuncDecl * getBuiltinGenericFunction(Identifier Id, ArrayRef<TupleTypeElt> ArgParamTypes, ArrayRef<Type> ArgBodyTypes, Type ResType, Type ResBodyType, GenericParamList *GenericParams, GenericEnvironment *Env) { assert(GenericParams && "Missing generic parameters"); auto &Context = ResType->getASTContext(); Type ArgParamType = TupleType::get(ArgParamTypes, Context); // Compute the interface type. SmallVector<GenericTypeParamType *, 1> GenericParamTypes; for (auto gp : *GenericParams) { GenericParamTypes.push_back(gp->getDeclaredInterfaceType() ->castTo<GenericTypeParamType>()); } GenericSignature *Sig = Env->getGenericSignature(); Type InterfaceType = GenericFunctionType::get(Sig, ArgParamType, ResType, AnyFunctionType::ExtInfo()); ModuleDecl *M = Context.TheBuiltinModule; DeclContext *DC = &M->getMainFile(FileUnitKind::Builtin); SmallVector<ParamDecl*, 4> params; for (unsigned i = 0, e = ArgParamTypes.size(); i < e; i++) { auto paramType = ArgBodyTypes[i]; auto paramIfaceType = ArgParamTypes[i].getType(); auto PD = new (Context) ParamDecl(/*IsLet*/true, SourceLoc(), SourceLoc(), Identifier(), SourceLoc(), Identifier(), paramType, DC); PD->setInterfaceType(paramIfaceType); PD->setImplicit(); params.push_back(PD); } auto *paramList = ParameterList::create(Context, params); DeclName Name(Context, Id, paramList); auto func = FuncDecl::create(Context, /*StaticLoc=*/SourceLoc(), StaticSpellingKind::None, /*FuncLoc=*/SourceLoc(), Name, /*NameLoc=*/SourceLoc(), /*Throws=*/false, /*ThrowsLoc=*/SourceLoc(), /*AccessorKeywordLoc=*/SourceLoc(), GenericParams, paramList, TypeLoc::withoutLoc(ResBodyType), DC); func->setInterfaceType(InterfaceType); func->setGenericEnvironment(Env); func->setImplicit(); func->setAccessibility(Accessibility::Public); return func; } /// Build a getelementptr operation declaration. static ValueDecl *getGepRawOperation(Identifier Id, Type ArgType) { auto &Context = ArgType->getASTContext(); // This is always "(i8*, IntTy) -> i8*" Type ArgElts[] = { Context.TheRawPointerType, ArgType }; Type ResultTy = Context.TheRawPointerType; return getBuiltinFunction(Id, ArgElts, ResultTy); } /// Build a binary operation declaration. static ValueDecl *getBinaryOperation(Identifier Id, Type ArgType) { return getBuiltinFunction(Id, { ArgType, ArgType }, ArgType); } /// Build a declaration for a binary operation with overflow. static ValueDecl *getBinaryOperationWithOverflow(Identifier Id, Type ArgType) { auto &Context = ArgType->getASTContext(); Type ShouldCheckForOverflowTy = BuiltinIntegerType::get(1, Context); Type ArgElts[] = { ArgType, ArgType, ShouldCheckForOverflowTy }; Type OverflowBitTy = BuiltinIntegerType::get(1, Context); TupleTypeElt ResultElts[] = { ArgType, OverflowBitTy }; Type ResultTy = TupleType::get(ResultElts, Context); return getBuiltinFunction(Id, ArgElts, ResultTy); } static ValueDecl *getUnaryOperation(Identifier Id, Type ArgType) { return getBuiltinFunction(Id, { ArgType }, ArgType); } /// Build a binary predicate declaration. static ValueDecl *getBinaryPredicate(Identifier Id, Type ArgType) { auto &Context = ArgType->getASTContext(); Type ArgElts[] = { ArgType, ArgType }; Type ResultTy = BuiltinIntegerType::get(1, Context); if (auto VecTy = ArgType->getAs<BuiltinVectorType>()) { ResultTy = BuiltinVectorType::get(Context, ResultTy, VecTy->getNumElements()); } return getBuiltinFunction(Id, ArgElts, ResultTy); } /// Build a cast. There is some custom type checking here. static ValueDecl *getCastOperation(ASTContext &Context, Identifier Id, BuiltinValueKind VK, ArrayRef<Type> Types) { if (Types.size() == 0 || Types.size() > 2) return nullptr; Type Input = Types[0]; Type Output = Types.size() == 2 ? Types[1] : Type(); // If both types are vectors, look through the vectors. Type CheckInput = Input; Type CheckOutput = Output; bool UnwrappedVector = false; auto InputVec = Input->getAs<BuiltinVectorType>(); auto OutputVec = Output.isNull()? nullptr :Output->getAs<BuiltinVectorType>(); if (InputVec && OutputVec && InputVec->getNumElements() == OutputVec->getNumElements()) { UnwrappedVector = true; CheckInput = InputVec->getElementType(); CheckOutput = OutputVec->getElementType(); } // Custom type checking. We know the one or two types have been subjected to // the "isBuiltinTypeOverloaded" predicate successfully. switch (VK) { default: llvm_unreachable("Not a cast operation"); case BuiltinValueKind::Trunc: if (CheckOutput.isNull() || !CheckInput->is<BuiltinIntegerType>() || !CheckOutput->is<BuiltinIntegerType>() || CheckInput->castTo<BuiltinIntegerType>()->getLeastWidth() <= CheckOutput->castTo<BuiltinIntegerType>()->getGreatestWidth()) return nullptr; break; case BuiltinValueKind::TruncOrBitCast: if (CheckOutput.isNull() || !CheckInput->is<BuiltinIntegerType>() || !CheckOutput->is<BuiltinIntegerType>() || CheckInput->castTo<BuiltinIntegerType>()->getLeastWidth() < CheckOutput->castTo<BuiltinIntegerType>()->getGreatestWidth()) return nullptr; break; case BuiltinValueKind::ZExt: case BuiltinValueKind::SExt: { if (CheckOutput.isNull() || !CheckInput->is<BuiltinIntegerType>() || !CheckOutput->is<BuiltinIntegerType>() || CheckInput->castTo<BuiltinIntegerType>()->getGreatestWidth() >= CheckOutput->castTo<BuiltinIntegerType>()->getLeastWidth()) return nullptr; break; } case BuiltinValueKind::ZExtOrBitCast: case BuiltinValueKind::SExtOrBitCast: { if (CheckOutput.isNull() || !CheckInput->is<BuiltinIntegerType>() || !CheckOutput->is<BuiltinIntegerType>() || CheckInput->castTo<BuiltinIntegerType>()->getGreatestWidth() > CheckOutput->castTo<BuiltinIntegerType>()->getLeastWidth()) return nullptr; break; } case BuiltinValueKind::FPToUI: case BuiltinValueKind::FPToSI: if (CheckOutput.isNull() || !CheckInput->is<BuiltinFloatType>() || !CheckOutput->is<BuiltinIntegerType>()) return nullptr; break; case BuiltinValueKind::UIToFP: case BuiltinValueKind::SIToFP: if (CheckOutput.isNull() || !CheckInput->is<BuiltinIntegerType>() || !CheckOutput->is<BuiltinFloatType>()) return nullptr; break; case BuiltinValueKind::FPTrunc: if (CheckOutput.isNull() || !CheckInput->is<BuiltinFloatType>() || !CheckOutput->is<BuiltinFloatType>() || CheckInput->castTo<BuiltinFloatType>()->getFPKind() <= CheckOutput->castTo<BuiltinFloatType>()->getFPKind()) return nullptr; break; case BuiltinValueKind::FPExt: if (CheckOutput.isNull() || !CheckInput->is<BuiltinFloatType>() || !CheckOutput->is<BuiltinFloatType>() || CheckInput->castTo<BuiltinFloatType>()->getFPKind() >= CheckOutput->castTo<BuiltinFloatType>()->getFPKind()) return nullptr; break; case BuiltinValueKind::PtrToInt: // FIXME: Do we care about vectors of pointers? if (!CheckOutput.isNull() || !CheckInput->is<BuiltinIntegerType>() || UnwrappedVector) return nullptr; Output = Input; Input = Context.TheRawPointerType; break; case BuiltinValueKind::IntToPtr: // FIXME: Do we care about vectors of pointers? if (!CheckOutput.isNull() || !CheckInput->is<BuiltinIntegerType>() || UnwrappedVector) return nullptr; Output = Context.TheRawPointerType; break; case BuiltinValueKind::BitCast: if (CheckOutput.isNull()) return nullptr; // Support float <-> int bitcast where the types are the same widths. if (auto *BIT = CheckInput->getAs<BuiltinIntegerType>()) if (auto *BFT = CheckOutput->getAs<BuiltinFloatType>()) if (BIT->isFixedWidth() && BIT->getFixedWidth() == BFT->getBitWidth()) break; if (auto *BFT = CheckInput->getAs<BuiltinFloatType>()) if (auto *BIT = CheckOutput->getAs<BuiltinIntegerType>()) if (BIT->isFixedWidth() && BIT->getFixedWidth() == BFT->getBitWidth()) break; // FIXME: Implement bitcast typechecking. llvm_unreachable("Bitcast not supported yet!"); return nullptr; } return getBuiltinFunction(Id, { Input }, Output); } static const char * const GenericParamNames[] = { "T", "U", "V", "W", "X", "Y", "Z" }; static GenericTypeParamDecl* createGenericParam(ASTContext &ctx, const char *name, unsigned index) { ModuleDecl *M = ctx.TheBuiltinModule; Identifier ident = ctx.getIdentifier(name); SmallVector<ProtocolDecl *, 1> protos; auto genericParam = new (ctx) GenericTypeParamDecl(&M->getMainFile(FileUnitKind::Builtin), ident, SourceLoc(), 0, index); return genericParam; } /// Create a generic parameter list with multiple generic parameters. static GenericParamList *getGenericParams(ASTContext &ctx, unsigned numParameters, SmallVectorImpl<GenericTypeParamDecl*> &genericParams) { assert(numParameters <= llvm::array_lengthof(GenericParamNames)); assert(genericParams.empty()); for (unsigned i = 0; i != numParameters; ++i) genericParams.push_back(createGenericParam(ctx, GenericParamNames[i], i)); auto paramList = GenericParamList::create(ctx, SourceLoc(), genericParams, SourceLoc()); return paramList; } namespace { class BuiltinGenericSignatureBuilder { public: ASTContext &Context; private: GenericParamList *TheGenericParamList; SmallVector<GenericTypeParamDecl*, 2> GenericTypeParams; GenericEnvironment *GenericEnv = nullptr; SmallVector<TupleTypeElt, 4> InterfaceParams; SmallVector<Type, 4> BodyParams; Type InterfaceResult; Type BodyResult; public: BuiltinGenericSignatureBuilder(ASTContext &ctx, unsigned numGenericParams = 1) : Context(ctx) { TheGenericParamList = getGenericParams(ctx, numGenericParams, GenericTypeParams); ArchetypeBuilder Builder(ctx, LookUpConformanceInModule(ctx.TheBuiltinModule)); for (auto gp : GenericTypeParams) Builder.addGenericParameter(gp); Builder.finalize(SourceLoc()); auto sig = Builder.getGenericSignature(); GenericEnv = Builder.getGenericEnvironment(sig); } template <class G> void addParameter(const G &generator) { InterfaceParams.push_back(generator.build(*this, false)); BodyParams.push_back(generator.build(*this, true)); } template <class G> void setResult(const G &generator) { InterfaceResult = generator.build(*this, false); BodyResult = generator.build(*this, true); } ValueDecl *build(Identifier name) { return getBuiltinGenericFunction(name, InterfaceParams, BodyParams, InterfaceResult, BodyResult, TheGenericParamList, GenericEnv); } // Don't use these generator classes directly; call the make{...} // functions which follow this class. struct ConcreteGenerator { Type TheType; Type build(BuiltinGenericSignatureBuilder &builder, bool forBody) const { return TheType; } }; struct ParameterGenerator { unsigned Index; Type build(BuiltinGenericSignatureBuilder &builder, bool forBody) const { auto gpType = builder.GenericTypeParams[Index]->getDeclaredInterfaceType(); if (forBody) { return builder.GenericEnv->mapTypeIntoContext( gpType->castTo<GenericTypeParamType>()); } return gpType; } }; struct LambdaGenerator { std::function<Type(BuiltinGenericSignatureBuilder &,bool)> TheFunction; Type build(BuiltinGenericSignatureBuilder &builder, bool forBody) const { return TheFunction(builder, forBody); } }; template <class T, class U> struct FunctionGenerator { T Arg; U Result; FunctionType::ExtInfo ExtInfo; Type build(BuiltinGenericSignatureBuilder &builder, bool forBody) const { return FunctionType::get(Arg.build(builder, forBody), Result.build(builder, forBody), ExtInfo); } }; template <class T> struct InOutGenerator { T Object; Type build(BuiltinGenericSignatureBuilder &builder, bool forBody) const { return InOutType::get(Object.build(builder, forBody)); } }; template <class T> struct MetatypeGenerator { T Object; Optional<MetatypeRepresentation> Repr; Type build(BuiltinGenericSignatureBuilder &builder, bool forBody) const { return MetatypeType::get(Object.build(builder, forBody), Repr); } }; }; } // end anonymous namespace static BuiltinGenericSignatureBuilder::ConcreteGenerator makeConcrete(Type type) { return { type }; } static BuiltinGenericSignatureBuilder::ParameterGenerator makeGenericParam(unsigned index = 0) { return { index }; } template <class... Gs> static BuiltinGenericSignatureBuilder::LambdaGenerator makeTuple(const Gs & ...elementGenerators) { return { [=](BuiltinGenericSignatureBuilder &builder, bool forBody) -> Type { TupleTypeElt elts[] = { elementGenerators.build(builder, forBody)... }; return TupleType::get(elts, builder.Context); } }; } template <class T, class U> static BuiltinGenericSignatureBuilder::FunctionGenerator<T,U> makeFunction(const T &arg, const U &result, FunctionType::ExtInfo extInfo = FunctionType::ExtInfo()) { return { arg, result, extInfo }; } template <class T> static BuiltinGenericSignatureBuilder::InOutGenerator<T> makeInOut(const T &object) { return { object }; } template <class T> static BuiltinGenericSignatureBuilder::MetatypeGenerator<T> makeMetatype(const T &object, Optional<MetatypeRepresentation> repr = None) { return { object, repr }; } /// Create a function with type <T> T -> (). static ValueDecl *getRefCountingOperation(ASTContext &Context, Identifier Id) { BuiltinGenericSignatureBuilder builder(Context); builder.addParameter(makeGenericParam()); builder.setResult(makeConcrete(TupleType::getEmpty(Context))); return builder.build(Id); } static ValueDecl *getLoadOperation(ASTContext &Context, Identifier Id) { BuiltinGenericSignatureBuilder builder(Context); builder.addParameter(makeConcrete(Context.TheRawPointerType)); builder.setResult(makeGenericParam()); return builder.build(Id); } static ValueDecl *getStoreOperation(ASTContext &Context, Identifier Id) { BuiltinGenericSignatureBuilder builder(Context); builder.addParameter(makeGenericParam()); builder.addParameter(makeConcrete(Context.TheRawPointerType)); builder.setResult(makeConcrete(TupleType::getEmpty(Context))); return builder.build(Id); } static ValueDecl *getDestroyOperation(ASTContext &Context, Identifier Id) { BuiltinGenericSignatureBuilder builder(Context); builder.addParameter(makeMetatype(makeGenericParam())); builder.addParameter(makeConcrete(Context.TheRawPointerType)); builder.setResult(makeConcrete(TupleType::getEmpty(Context))); return builder.build(Id); } static ValueDecl *getDestroyArrayOperation(ASTContext &Context, Identifier Id) { auto wordType = BuiltinIntegerType::get(BuiltinIntegerWidth::pointer(), Context); BuiltinGenericSignatureBuilder builder(Context); builder.addParameter(makeMetatype(makeGenericParam())); builder.addParameter(makeConcrete(Context.TheRawPointerType)); builder.addParameter(makeConcrete(wordType)); builder.setResult(makeConcrete(TupleType::getEmpty(Context))); return builder.build(Id); } static ValueDecl *getTransferArrayOperation(ASTContext &Context, Identifier Id){ auto wordType = BuiltinIntegerType::get(BuiltinIntegerWidth::pointer(), Context); BuiltinGenericSignatureBuilder builder(Context); builder.addParameter(makeMetatype(makeGenericParam())); builder.addParameter(makeConcrete(Context.TheRawPointerType)); builder.addParameter(makeConcrete(Context.TheRawPointerType)); builder.addParameter(makeConcrete(wordType)); builder.setResult(makeConcrete(TupleType::getEmpty(Context))); return builder.build(Id); } static ValueDecl *getIsUniqueOperation(ASTContext &Context, Identifier Id) { // <T> (@inout T) -> Int1 Type Int1Ty = BuiltinIntegerType::get(1, Context); BuiltinGenericSignatureBuilder builder(Context); builder.addParameter(makeInOut(makeGenericParam())); builder.setResult(makeConcrete(Int1Ty)); return builder.build(Id); } static ValueDecl *getBindMemoryOperation(ASTContext &Context, Identifier Id) { BuiltinGenericSignatureBuilder builder(Context); builder.addParameter(makeConcrete(Context.TheRawPointerType)); builder.addParameter(makeConcrete(BuiltinIntegerType::getWordType(Context))); builder.addParameter(makeMetatype(makeGenericParam())); builder.setResult(makeConcrete(TupleType::getEmpty(Context))); return builder.build(Id); } static ValueDecl *getAllocWithTailElemsOperation(ASTContext &Context, Identifier Id, int NumTailTypes) { if (NumTailTypes < 1 || 1 + NumTailTypes > (int)llvm::array_lengthof(GenericParamNames)) return nullptr; BuiltinGenericSignatureBuilder builder(Context, 1 + NumTailTypes); builder.addParameter(makeMetatype(makeGenericParam(0))); for (int Idx = 0; Idx < NumTailTypes; ++Idx) { builder.addParameter(makeConcrete(BuiltinIntegerType::getWordType(Context))); builder.addParameter(makeMetatype(makeGenericParam(Idx + 1))); } builder.setResult(makeGenericParam(0)); return builder.build(Id); } static ValueDecl *getProjectTailElemsOperation(ASTContext &Context, Identifier Id) { BuiltinGenericSignatureBuilder builder(Context, 2); builder.addParameter(makeGenericParam(0)); builder.addParameter(makeMetatype(makeGenericParam(1))); builder.setResult(makeConcrete(Context.TheRawPointerType)); return builder.build(Id); } /// Build a getelementptr operation declaration. static ValueDecl *getGepOperation(ASTContext &Context, Identifier Id, Type ArgType) { BuiltinGenericSignatureBuilder builder(Context, 1); builder.addParameter(makeConcrete(Context.TheRawPointerType)); builder.addParameter(makeConcrete(ArgType)); builder.addParameter(makeMetatype(makeGenericParam(0))); builder.setResult(makeConcrete(Context.TheRawPointerType)); return builder.build(Id); } static ValueDecl *getGetTailAddrOperation(ASTContext &Context, Identifier Id, Type ArgType) { BuiltinGenericSignatureBuilder builder(Context, 2); builder.addParameter(makeConcrete(Context.TheRawPointerType)); builder.addParameter(makeConcrete(ArgType)); builder.addParameter(makeMetatype(makeGenericParam(0))); builder.addParameter(makeMetatype(makeGenericParam(1))); builder.setResult(makeConcrete(Context.TheRawPointerType)); return builder.build(Id); } static ValueDecl *getSizeOrAlignOfOperation(ASTContext &Context, Identifier Id) { BuiltinGenericSignatureBuilder builder(Context); builder.addParameter(makeMetatype(makeGenericParam())); builder.setResult(makeConcrete(BuiltinIntegerType::getWordType(Context))); return builder.build(Id); } static ValueDecl *getIsPODOperation(ASTContext &Context, Identifier Id) { BuiltinGenericSignatureBuilder builder(Context); builder.addParameter(makeMetatype(makeGenericParam())); builder.setResult(makeConcrete(BuiltinIntegerType::get(1,Context))); return builder.build(Id); } static ValueDecl *getIsOptionalOperation(ASTContext &Context, Identifier Id) { BuiltinGenericSignatureBuilder builder(Context); builder.addParameter(makeMetatype(makeGenericParam())); builder.setResult(makeConcrete(BuiltinIntegerType::get(1,Context))); return builder.build(Id); } static ValueDecl *getAllocOperation(ASTContext &Context, Identifier Id) { Type PtrSizeTy = BuiltinIntegerType::getWordType(Context); Type ResultTy = Context.TheRawPointerType; return getBuiltinFunction(Id, { PtrSizeTy, PtrSizeTy }, ResultTy); } static ValueDecl *getDeallocOperation(ASTContext &Context, Identifier Id) { auto PtrSizeTy = BuiltinIntegerType::getWordType(Context); Type ArgElts[] = { Context.TheRawPointerType, PtrSizeTy, PtrSizeTy }; Type ResultTy = TupleType::getEmpty(Context); return getBuiltinFunction(Id, ArgElts, ResultTy); } static ValueDecl *getFenceOperation(ASTContext &Context, Identifier Id) { return getBuiltinFunction(Id, {}, TupleType::getEmpty(Context)); } static ValueDecl *getVoidErrorOperation(ASTContext &Context, Identifier Id) { return getBuiltinFunction(Id, {Context.getExceptionType()}, TupleType::getEmpty(Context)); } static ValueDecl *getUnexpectedErrorOperation(ASTContext &Context, Identifier Id) { return getBuiltinFunction(Id, {Context.getExceptionType()}, Context.getNeverType()); } static ValueDecl *getCmpXChgOperation(ASTContext &Context, Identifier Id, Type T) { Type ArgElts[] = { Context.TheRawPointerType, T, T }; Type BoolTy = BuiltinIntegerType::get(1, Context); Type ResultTy = TupleType::get({ T, BoolTy }, Context); return getBuiltinFunction(Id, ArgElts, ResultTy); } static ValueDecl *getAtomicRMWOperation(ASTContext &Context, Identifier Id, Type T) { return getBuiltinFunction(Id, { Context.TheRawPointerType, T }, T); } static ValueDecl *getAtomicLoadOperation(ASTContext &Context, Identifier Id, Type T) { return getBuiltinFunction(Id, { Type(Context.TheRawPointerType) }, T); } static ValueDecl *getAtomicStoreOperation(ASTContext &Context, Identifier Id, Type T) { return getBuiltinFunction(Id, { Context.TheRawPointerType, T }, Context.TheEmptyTupleType); } static ValueDecl *getNativeObjectCast(ASTContext &Context, Identifier Id, BuiltinValueKind BV) { Type BuiltinTy; if (BV == BuiltinValueKind::BridgeToRawPointer || BV == BuiltinValueKind::BridgeFromRawPointer) BuiltinTy = Context.TheRawPointerType; else if (BV == BuiltinValueKind::CastToUnknownObject || BV == BuiltinValueKind::CastFromUnknownObject) BuiltinTy = Context.TheUnknownObjectType; else BuiltinTy = Context.TheNativeObjectType; BuiltinGenericSignatureBuilder builder(Context); if (BV == BuiltinValueKind::CastToNativeObject || BV == BuiltinValueKind::CastToUnknownObject || BV == BuiltinValueKind::BridgeToRawPointer) { builder.addParameter(makeGenericParam()); builder.setResult(makeConcrete(BuiltinTy)); } else { builder.addParameter(makeConcrete(BuiltinTy)); builder.setResult(makeGenericParam()); } return builder.build(Id); } static ValueDecl *getCastToBridgeObjectOperation(ASTContext &C, Identifier Id) { auto wordType = BuiltinIntegerType::get(BuiltinIntegerWidth::pointer(), C); BuiltinGenericSignatureBuilder builder(C); builder.addParameter(makeGenericParam()); builder.addParameter(makeConcrete(wordType)); builder.setResult(makeConcrete(C.TheBridgeObjectType)); return builder.build(Id); } static ValueDecl *getCastFromBridgeObjectOperation(ASTContext &C, Identifier Id, BuiltinValueKind BV) { Type BridgeTy = C.TheBridgeObjectType; switch (BV) { case BuiltinValueKind::CastReferenceFromBridgeObject: { BuiltinGenericSignatureBuilder builder(C); builder.addParameter(makeConcrete(BridgeTy)); builder.setResult(makeGenericParam()); return builder.build(Id); } case BuiltinValueKind::CastBitPatternFromBridgeObject: { Type WordTy = BuiltinIntegerType::get(BuiltinIntegerWidth::pointer(), C); return getBuiltinFunction(Id, { BridgeTy }, WordTy); } default: llvm_unreachable("not a cast from bridge object op"); } } static ValueDecl *getUnsafeGuaranteed(ASTContext &C, Identifier Id) { // <T : AnyObject> T -> (T, Int8Ty) // BuiltinGenericSignatureBuilder builder(C); auto T = makeGenericParam(); builder.addParameter(T); Type Int8Ty = BuiltinIntegerType::get(8, C); builder.setResult(makeTuple(T, makeConcrete(Int8Ty))); return builder.build(Id); } static ValueDecl *getUnsafeGuaranteedEnd(ASTContext &C, Identifier Id) { // Int8Ty -> () Type Int8Ty = BuiltinIntegerType::get(8, C); return getBuiltinFunction(Id, { Int8Ty }, TupleType::getEmpty(C)); } static ValueDecl *getOnFastPath(ASTContext &Context, Identifier Id) { return getBuiltinFunction(Id, {}, TupleType::getEmpty(Context)); } static ValueDecl *getCastReferenceOperation(ASTContext &ctx, Identifier name) { // <T, U> T -> U // SILGen and IRGen check additional constraints during lowering. BuiltinGenericSignatureBuilder builder(ctx, 2); builder.addParameter(makeGenericParam(0)); builder.setResult(makeGenericParam(1)); return builder.build(name); } static ValueDecl *getReinterpretCastOperation(ASTContext &ctx, Identifier name) { // <T, U> T -> U // SILGen and IRGen check additional constraints during lowering. BuiltinGenericSignatureBuilder builder(ctx, 2); builder.addParameter(makeGenericParam(0)); builder.setResult(makeGenericParam(1)); return builder.build(name); } static ValueDecl *getZeroInitializerOperation(ASTContext &Context, Identifier Id) { // <T> () -> T BuiltinGenericSignatureBuilder builder(Context); builder.setResult(makeGenericParam()); return builder.build(Id); } static ValueDecl *getGetObjCTypeEncodingOperation(ASTContext &Context, Identifier Id) { // <T> T.Type -> RawPointer BuiltinGenericSignatureBuilder builder(Context); builder.addParameter(makeMetatype(makeGenericParam())); builder.setResult(makeConcrete(Context.TheRawPointerType)); return builder.build(Id); } static ValueDecl *getAddressOfOperation(ASTContext &Context, Identifier Id) { // <T> (@inout T) -> RawPointer BuiltinGenericSignatureBuilder builder(Context); builder.addParameter(makeInOut(makeGenericParam())); builder.setResult(makeConcrete(Context.TheRawPointerType)); return builder.build(Id); } static ValueDecl *getCanBeObjCClassOperation(ASTContext &Context, Identifier Id) { // <T> T.Type -> Builtin.Int8 BuiltinGenericSignatureBuilder builder(Context); builder.addParameter(makeMetatype(makeGenericParam())); builder.setResult(makeConcrete(BuiltinIntegerType::get(8, Context))); return builder.build(Id); } static ValueDecl *getCondFailOperation(ASTContext &C, Identifier Id) { // Int1 -> () auto CondTy = BuiltinIntegerType::get(1, C); auto VoidTy = TupleType::getEmpty(C); return getBuiltinFunction(Id, {CondTy}, VoidTy); } static ValueDecl *getAssertConfOperation(ASTContext &C, Identifier Id) { // () -> Int32 auto Int32Ty = BuiltinIntegerType::get(32, C); return getBuiltinFunction(Id, {}, Int32Ty); } static ValueDecl *getFixLifetimeOperation(ASTContext &C, Identifier Id) { // <T> T -> () BuiltinGenericSignatureBuilder builder(C); builder.addParameter(makeGenericParam()); builder.setResult(makeConcrete(TupleType::getEmpty(C))); return builder.build(Id); } static ValueDecl *getExtractElementOperation(ASTContext &Context, Identifier Id, Type FirstTy, Type SecondTy) { // (Vector<N, T>, Int32) -> T auto VecTy = FirstTy->getAs<BuiltinVectorType>(); if (!VecTy) return nullptr; auto IndexTy = SecondTy->getAs<BuiltinIntegerType>(); if (!IndexTy || !IndexTy->isFixedWidth() || IndexTy->getFixedWidth() != 32) return nullptr; Type ResultTy = VecTy->getElementType(); return getBuiltinFunction(Id, { VecTy, IndexTy }, ResultTy); } static ValueDecl *getInsertElementOperation(ASTContext &Context, Identifier Id, Type FirstTy, Type SecondTy, Type ThirdTy) { // (Vector<N, T>, T, Int32) -> Vector<N, T> auto VecTy = FirstTy->getAs<BuiltinVectorType>(); if (!VecTy) return nullptr; auto ElementTy = VecTy->getElementType(); if (!SecondTy->isEqual(ElementTy)) return nullptr; auto IndexTy = ThirdTy->getAs<BuiltinIntegerType>(); if (!IndexTy || !IndexTy->isFixedWidth() || IndexTy->getFixedWidth() != 32) return nullptr; Type ArgElts[] = { VecTy, ElementTy, IndexTy }; return getBuiltinFunction(Id, ArgElts, VecTy); } static ValueDecl *getStaticReportOperation(ASTContext &Context, Identifier Id) { auto BoolTy = BuiltinIntegerType::get(1, Context); auto MessageTy = Context.TheRawPointerType; Type ArgElts[] = { BoolTy, BoolTy, MessageTy }; Type ResultTy = TupleType::getEmpty(Context); return getBuiltinFunction(Id, ArgElts, ResultTy); } static ValueDecl *getCheckedTruncOperation(ASTContext &Context, Identifier Id, Type InputTy, Type OutputTy) { auto InTy = InputTy->getAs<BuiltinIntegerType>(); auto OutTy = OutputTy->getAs<BuiltinIntegerType>(); if (!InTy || !OutTy) return nullptr; if (InTy->getLeastWidth() < OutTy->getGreatestWidth()) return nullptr; Type OverflowBitTy = BuiltinIntegerType::get(1, Context); TupleTypeElt ResultElts[] = { OutTy, OverflowBitTy }; Type ResultTy = TupleType::get(ResultElts, Context); return getBuiltinFunction(Id, { InTy }, ResultTy); } static ValueDecl *getCheckedConversionOperation(ASTContext &Context, Identifier Id, Type Ty) { auto BuiltinTy = Ty->getAs<BuiltinIntegerType>(); if (!BuiltinTy) return nullptr; Type SignErrorBitTy = BuiltinIntegerType::get(1, Context); TupleTypeElt ResultElts[] = { BuiltinTy, SignErrorBitTy }; Type ResultTy = TupleType::get(ResultElts, Context); return getBuiltinFunction(Id, { BuiltinTy }, ResultTy); } static ValueDecl *getIntToFPWithOverflowOperation(ASTContext &Context, Identifier Id, Type InputTy, Type OutputTy) { auto InTy = InputTy->getAs<BuiltinIntegerType>(); auto OutTy = OutputTy->getAs<BuiltinFloatType>(); if (!InTy || !OutTy) return nullptr; return getBuiltinFunction(Id, { InTy }, OutTy); } static ValueDecl *getUnreachableOperation(ASTContext &Context, Identifier Id) { // () -> Never return getBuiltinFunction(Id, {}, Context.getNeverType()); } static ValueDecl *getOnceOperation(ASTContext &Context, Identifier Id) { // (RawPointer, @convention(thin) () -> ()) -> () auto HandleTy = Context.TheRawPointerType; auto VoidTy = Context.TheEmptyTupleType; auto Thin = FunctionType::ExtInfo(FunctionTypeRepresentation::Thin, /*throws*/ false); auto BlockTy = FunctionType::get(VoidTy, VoidTy, Thin); return getBuiltinFunction(Id, {HandleTy, BlockTy}, VoidTy); } static ValueDecl *getTryPinOperation(ASTContext &ctx, Identifier name) { // <T> NativeObject -> T // (T must actually be NativeObject?) BuiltinGenericSignatureBuilder builder(ctx); builder.addParameter(makeConcrete(ctx.TheNativeObjectType)); builder.setResult(makeGenericParam()); return builder.build(name); } /// An array of the overloaded builtin kinds. static const OverloadedBuiltinKind OverloadedBuiltinKinds[] = { OverloadedBuiltinKind::None, // There's deliberately no BUILTIN clause here so that we'll blow up // if new builtin categories are added there and not here. #define BUILTIN_CAST_OPERATION(id, attrs, name) \ OverloadedBuiltinKind::Special, #define BUILTIN_CAST_OR_BITCAST_OPERATION(id, attrs, name) \ OverloadedBuiltinKind::Special, #define BUILTIN_BINARY_OPERATION(id, name, attrs, overload) \ OverloadedBuiltinKind::overload, #define BUILTIN_BINARY_OPERATION_WITH_OVERFLOW(id, name, _, attrs, overload) \ OverloadedBuiltinKind::overload, #define BUILTIN_BINARY_PREDICATE(id, name, attrs, overload) \ OverloadedBuiltinKind::overload, #define BUILTIN_UNARY_OPERATION(id, name, attrs, overload) \ OverloadedBuiltinKind::overload, #define BUILTIN_SIL_OPERATION(id, name, overload) \ OverloadedBuiltinKind::overload, #define BUILTIN_MISC_OPERATION(id, name, attrs, overload) \ OverloadedBuiltinKind::overload, #define BUILTIN_TYPE_TRAIT_OPERATION(id, name) \ OverloadedBuiltinKind::Special, #define BUILTIN_RUNTIME_CALL(id, attrs, name) \ OverloadedBuiltinKind::Special, #include "swift/AST/Builtins.def" }; /// Determines if a builtin type falls within the given category. inline bool isBuiltinTypeOverloaded(Type T, OverloadedBuiltinKind OK) { switch (OK) { case OverloadedBuiltinKind::None: return false; // always fail. case OverloadedBuiltinKind::Integer: return T->is<BuiltinIntegerType>(); case OverloadedBuiltinKind::IntegerOrVector: return T->is<BuiltinIntegerType>() || (T->is<BuiltinVectorType>() && T->castTo<BuiltinVectorType>()->getElementType() ->is<BuiltinIntegerType>()); case OverloadedBuiltinKind::IntegerOrRawPointer: return T->is<BuiltinIntegerType>() || T->is<BuiltinRawPointerType>(); case OverloadedBuiltinKind::IntegerOrRawPointerOrVector: return T->is<BuiltinIntegerType>() || T->is<BuiltinRawPointerType>() || (T->is<BuiltinVectorType>() && T->castTo<BuiltinVectorType>()->getElementType() ->is<BuiltinIntegerType>()); case OverloadedBuiltinKind::Float: return T->is<BuiltinFloatType>(); case OverloadedBuiltinKind::FloatOrVector: return T->is<BuiltinFloatType>() || (T->is<BuiltinVectorType>() && T->castTo<BuiltinVectorType>()->getElementType() ->is<BuiltinFloatType>()); case OverloadedBuiltinKind::Special: return true; } llvm_unreachable("bad overloaded builtin kind"); } /// Table of string intrinsic names indexed by enum value. static const char *const IntrinsicNameTable[] = { "not_intrinsic", #define GET_INTRINSIC_NAME_TABLE #include "llvm/IR/Intrinsics.gen" #undef GET_INTRINSIC_NAME_TABLE }; #define GET_INTRINSIC_TARGET_DATA #include "llvm/IR/Intrinsics.gen" #undef GET_INTRINSIC_TARGET_DATA /// getLLVMIntrinsicID - Given an LLVM IR intrinsic name with argument types /// removed (e.g. like "bswap") return the LLVM IR IntrinsicID for the intrinsic /// or 0 if the intrinsic name doesn't match anything. unsigned swift::getLLVMIntrinsicID(StringRef InName) { using namespace llvm; // Swift intrinsic names start with int_. if (!InName.startswith("int_")) return llvm::Intrinsic::not_intrinsic; InName = InName.drop_front(strlen("int_")); // Prepend "llvm." and change _ to . in name. SmallString<128> NameS; NameS.append("llvm."); for (char C : InName) NameS.push_back(C == '_' ? '.' : C); const char *Name = NameS.c_str(); ArrayRef<const char *> NameTable(&IntrinsicNameTable[1], TargetInfos[1].Offset); int Idx = Intrinsic::lookupLLVMIntrinsicByName(NameTable, Name); return static_cast<Intrinsic::ID>(Idx + 1); } llvm::Intrinsic::ID swift::getLLVMIntrinsicIDForBuiltinWithOverflow(BuiltinValueKind ID) { switch (ID) { default: break; case BuiltinValueKind::SAddOver: return llvm::Intrinsic::sadd_with_overflow; case BuiltinValueKind::UAddOver: return llvm::Intrinsic::uadd_with_overflow; case BuiltinValueKind::SSubOver: return llvm::Intrinsic::ssub_with_overflow; case BuiltinValueKind::USubOver: return llvm::Intrinsic::usub_with_overflow; case BuiltinValueKind::SMulOver: return llvm::Intrinsic::smul_with_overflow; case BuiltinValueKind::UMulOver: return llvm::Intrinsic::umul_with_overflow; } llvm_unreachable("Cannot convert the overflow builtin to llvm intrinsic."); } static Type DecodeIntrinsicType(ArrayRef<llvm::Intrinsic::IITDescriptor> &Table, ArrayRef<Type> Tys, ASTContext &Context) { typedef llvm::Intrinsic::IITDescriptor IITDescriptor; IITDescriptor D = Table.front(); Table = Table.slice(1); switch (D.Kind) { default: llvm_unreachable("Unhandled case"); case IITDescriptor::Half: case IITDescriptor::MMX: case IITDescriptor::Metadata: case IITDescriptor::Vector: case IITDescriptor::ExtendArgument: case IITDescriptor::TruncArgument: case IITDescriptor::VarArg: // These types cannot be expressed in swift yet. return Type(); case IITDescriptor::Void: return TupleType::getEmpty(Context); case IITDescriptor::Float: return Context.TheIEEE32Type; case IITDescriptor::Double: return Context.TheIEEE64Type; case IITDescriptor::Integer: return BuiltinIntegerType::get(D.Integer_Width, Context); case IITDescriptor::Pointer: if (D.Pointer_AddressSpace) return Type(); // Reject non-default address space pointers. // Decode but ignore the pointee. Just decode all IR pointers to unsafe // pointer type. (void)DecodeIntrinsicType(Table, Tys, Context); return Context.TheRawPointerType; case IITDescriptor::Argument: if (D.getArgumentNumber() >= Tys.size()) return Type(); return Tys[D.getArgumentNumber()]; case IITDescriptor::Struct: { SmallVector<TupleTypeElt, 5> Elts; for (unsigned i = 0; i != D.Struct_NumElements; ++i) { Type T = DecodeIntrinsicType(Table, Tys, Context); if (!T) return Type(); Elts.push_back(T); } return TupleType::get(Elts, Context); } } llvm_unreachable("unhandled"); } /// \returns true on success, false on failure. static bool getSwiftFunctionTypeForIntrinsic(unsigned iid, ArrayRef<Type> TypeArgs, ASTContext &Context, SmallVectorImpl<Type> &ArgElts, Type &ResultTy, FunctionType::ExtInfo &Info) { llvm::Intrinsic::ID ID = (llvm::Intrinsic::ID)iid; typedef llvm::Intrinsic::IITDescriptor IITDescriptor; SmallVector<IITDescriptor, 8> Table; getIntrinsicInfoTableEntries(ID, Table); ArrayRef<IITDescriptor> TableRef = Table; // Decode the intrinsic's LLVM IR type, and map it to swift builtin types. ResultTy = DecodeIntrinsicType(TableRef, TypeArgs, Context); if (!ResultTy) return false; while (!TableRef.empty()) { Type ArgTy = DecodeIntrinsicType(TableRef, TypeArgs, Context); if (!ArgTy) return false; ArgElts.push_back(ArgTy); } // Translate LLVM function attributes to Swift function attributes. llvm::AttributeSet attrs = llvm::Intrinsic::getAttributes(getGlobalLLVMContext(), ID); Info = FunctionType::ExtInfo(); if (attrs.hasAttribute(llvm::AttributeSet::FunctionIndex, llvm::Attribute::NoReturn)) ResultTy = Context.getNeverType(); return true; } static bool isValidFenceOrdering(StringRef Ordering) { return Ordering == "acquire" || Ordering == "release" || Ordering == "acqrel" || Ordering == "seqcst"; } static bool isValidRMWOrdering(StringRef Ordering) { return Ordering == "unordered" || Ordering == "monotonic" || Ordering == "acquire" || Ordering == "release" || Ordering == "acqrel" || Ordering == "seqcst"; } static bool isValidLoadOrdering(StringRef Ordering) { return Ordering == "unordered" || Ordering == "monotonic" || Ordering == "acquire" || Ordering == "seqcst"; } static bool isValidStoreOrdering(StringRef Ordering) { return Ordering == "unordered" || Ordering == "monotonic" || Ordering == "release" || Ordering == "seqcst"; } llvm::AtomicOrdering swift::decodeLLVMAtomicOrdering(StringRef O) { using namespace llvm; return StringSwitch<AtomicOrdering>(O) .Case("unordered", AtomicOrdering::Unordered) .Case("monotonic", AtomicOrdering::Monotonic) .Case("acquire", AtomicOrdering::Acquire) .Case("release", AtomicOrdering::Release) .Case("acqrel", AtomicOrdering::AcquireRelease) .Case("seqcst", AtomicOrdering::SequentiallyConsistent) .Default(AtomicOrdering::NotAtomic); } static bool isUnknownOrUnordered(llvm::AtomicOrdering ordering) { using namespace llvm; switch (ordering) { case AtomicOrdering::NotAtomic: case AtomicOrdering::Unordered: return true; case AtomicOrdering::Monotonic: case AtomicOrdering::Acquire: case AtomicOrdering::Release: case AtomicOrdering::AcquireRelease: case AtomicOrdering::SequentiallyConsistent: return false; } llvm_unreachable("Unhandled AtomicOrdering in switch."); } static bool isValidCmpXChgOrdering(StringRef SuccessString, StringRef FailureString) { using namespace llvm; AtomicOrdering SuccessOrdering = decodeLLVMAtomicOrdering(SuccessString); AtomicOrdering FailureOrdering = decodeLLVMAtomicOrdering(FailureString); // Unordered and unknown values are not allowed. if (isUnknownOrUnordered(SuccessOrdering) || isUnknownOrUnordered(FailureOrdering)) return false; // Success must be at least as strong as failure. if (!isAtLeastOrStrongerThan(SuccessOrdering, FailureOrdering)) return false; // Failure may not release because no store occurred. if (FailureOrdering == AtomicOrdering::Release || FailureOrdering == AtomicOrdering::AcquireRelease) return false; return true; } ValueDecl *swift::getBuiltinValueDecl(ASTContext &Context, Identifier Id) { SmallVector<Type, 4> Types; StringRef OperationName = getBuiltinBaseName(Context, Id.str(), Types); // If this is the name of an LLVM intrinsic, cons up a swift function with a // type that matches the IR types. if (unsigned ID = getLLVMIntrinsicID(OperationName)) { SmallVector<Type, 8> ArgElts; Type ResultTy; FunctionType::ExtInfo Info; if (getSwiftFunctionTypeForIntrinsic(ID, Types, Context, ArgElts, ResultTy, Info)) return getBuiltinFunction(Id, ArgElts, ResultTy, Info); } // If this starts with fence, we have special suffixes to handle. if (OperationName.startswith("fence_")) { OperationName = OperationName.drop_front(strlen("fence_")); // Verify we have a single integer, floating point, or pointer type. if (!Types.empty()) return nullptr; // Get and validate the ordering argument, which is required. auto Underscore = OperationName.find('_'); if (!isValidFenceOrdering(OperationName.substr(0, Underscore))) return nullptr; OperationName = OperationName.substr(Underscore); // Accept singlethread if present. if (OperationName.startswith("_singlethread")) OperationName = OperationName.drop_front(strlen("_singlethread")); // Nothing else is allowed in the name. if (!OperationName.empty()) return nullptr; return getFenceOperation(Context, Id); } // If this starts with cmpxchg, we have special suffixes to handle. if (OperationName.startswith("cmpxchg_")) { OperationName = OperationName.drop_front(strlen("cmpxchg_")); // Verify we have a single integer, floating point, or pointer type. if (Types.size() != 1) return nullptr; Type T = Types[0]; if (!T->is<BuiltinIntegerType>() && !T->is<BuiltinRawPointerType>() && !T->is<BuiltinFloatType>()) return nullptr; // Get and validate the ordering arguments, which are both required. SmallVector<StringRef, 4> Parts; OperationName.split(Parts, "_"); if (Parts.size() < 2) return nullptr; if (!isValidCmpXChgOrdering(Parts[0], Parts[1])) return nullptr; auto NextPart = Parts.begin() + 2; // Accept weak, volatile, and singlethread if present. if (NextPart != Parts.end() && *NextPart == "weak") NextPart++; if (NextPart != Parts.end() && *NextPart == "volatile") NextPart++; if (NextPart != Parts.end() && *NextPart == "singlethread") NextPart++; // Nothing else is allowed in the name. if (NextPart != Parts.end()) return nullptr; return getCmpXChgOperation(Context, Id, T); } // If this starts with atomicrmw, we have special suffixes to handle. if (OperationName.startswith("atomicrmw_")) { OperationName = OperationName.drop_front(strlen("atomicrmw_")); // Verify we have a single integer or pointer type. if (Types.size() != 1) return nullptr; Type Ty = Types[0]; if (!Ty->is<BuiltinIntegerType>() && !Ty->is<BuiltinRawPointerType>()) return nullptr; // Get and validate the suboperation name, which is required. auto Underscore = OperationName.find('_'); if (Underscore == StringRef::npos) return nullptr; StringRef SubOp = OperationName.substr(0, Underscore); if (SubOp != "xchg" && SubOp != "add" && SubOp != "sub" && SubOp != "and" && SubOp != "nand" && SubOp != "or" && SubOp != "xor" && SubOp != "max" && SubOp != "min" && SubOp != "umax" && SubOp != "umin") return nullptr; OperationName = OperationName.drop_front(Underscore+1); // Get and validate the ordering argument, which is required. Underscore = OperationName.find('_'); if (!isValidRMWOrdering(OperationName.substr(0, Underscore))) return nullptr; OperationName = OperationName.substr(Underscore); // Accept volatile and singlethread if present. if (OperationName.startswith("_volatile")) OperationName = OperationName.drop_front(strlen("_volatile")); if (OperationName.startswith("_singlethread")) OperationName = OperationName.drop_front(strlen("_singlethread")); // Nothing else is allowed in the name. if (!OperationName.empty()) return nullptr; return getAtomicRMWOperation(Context, Id, Ty); } // If this starts with atomicload or atomicstore, we have special suffixes to // handle. if (OperationName.startswith("atomicload_")) { OperationName = OperationName.drop_front(strlen("atomicload_")); // Verify we have a single integer, floating point, or pointer type. if (Types.size() != 1) return nullptr; Type T = Types[0]; if (!T->is<BuiltinIntegerType>() && !T->is<BuiltinRawPointerType>() && !T->is<BuiltinFloatType>()) return nullptr; // Get and validate the ordering argument, which is required. auto Underscore = OperationName.find('_'); if (!isValidLoadOrdering(OperationName.substr(0, Underscore))) return nullptr; OperationName = OperationName.substr(Underscore); // Accept volatile and singlethread if present. if (OperationName.startswith("_volatile")) OperationName = OperationName.drop_front(strlen("_volatile")); if (OperationName.startswith("_singlethread")) OperationName = OperationName.drop_front(strlen("_singlethread")); // Nothing else is allowed in the name. if (!OperationName.empty()) return nullptr; return getAtomicLoadOperation(Context, Id, T); } if (OperationName.startswith("atomicstore_")) { OperationName = OperationName.drop_front(strlen("atomicstore_")); // Verify we have a single integer, floating point, or pointer type. if (Types.size() != 1) return nullptr; Type T = Types[0]; if (!T->is<BuiltinIntegerType>() && !T->is<BuiltinRawPointerType>() && !T->is<BuiltinFloatType>()) return nullptr; // Get and validate the ordering argument, which is required. auto Underscore = OperationName.find('_'); if (!isValidStoreOrdering(OperationName.substr(0, Underscore))) return nullptr; OperationName = OperationName.substr(Underscore); // Accept volatile and singlethread if present. if (OperationName.startswith("_volatile")) OperationName = OperationName.drop_front(strlen("_volatile")); if (OperationName.startswith("_singlethread")) OperationName = OperationName.drop_front(strlen("_singlethread")); // Nothing else is allowed in the name. if (!OperationName.empty()) return nullptr; return getAtomicStoreOperation(Context, Id, T); } if (OperationName.startswith("allocWithTailElems_")) { OperationName = OperationName.drop_front(strlen("allocWithTailElems_")); int NumTailTypes = 0; if (OperationName.getAsInteger(10, NumTailTypes)) return nullptr; return getAllocWithTailElemsOperation(Context, Id, NumTailTypes); } BuiltinValueKind BV = llvm::StringSwitch<BuiltinValueKind>(OperationName) #define BUILTIN(id, name, Attrs) \ .Case(name, BuiltinValueKind::id) #include "swift/AST/Builtins.def" .Default(BuiltinValueKind::None); // Filter out inappropriate overloads. OverloadedBuiltinKind OBK = OverloadedBuiltinKinds[unsigned(BV)]; // Verify that all types match the overload filter. for (Type T : Types) if (!isBuiltinTypeOverloaded(T, OBK)) return nullptr; switch (BV) { case BuiltinValueKind::Fence: case BuiltinValueKind::CmpXChg: case BuiltinValueKind::AtomicRMW: case BuiltinValueKind::AtomicLoad: case BuiltinValueKind::AtomicStore: case BuiltinValueKind::AllocWithTailElems: llvm_unreachable("Handled above"); case BuiltinValueKind::None: return nullptr; case BuiltinValueKind::GepRaw: if (Types.size() != 1) return nullptr; return getGepRawOperation(Id, Types[0]); case BuiltinValueKind::Gep: if (Types.size() != 1) return nullptr; return getGepOperation(Context, Id, Types[0]); case BuiltinValueKind::GetTailAddr: if (Types.size() != 1) return nullptr; return getGetTailAddrOperation(Context, Id, Types[0]); #define BUILTIN(id, name, Attrs) #define BUILTIN_BINARY_OPERATION(id, name, attrs, overload) case BuiltinValueKind::id: #include "swift/AST/Builtins.def" if (Types.size() != 1) return nullptr; return getBinaryOperation(Id, Types[0]); #define BUILTIN(id, name, Attrs) #define BUILTIN_BINARY_OPERATION_WITH_OVERFLOW(id, name, _, attrs, overload) case BuiltinValueKind::id: #include "swift/AST/Builtins.def" if (Types.size() != 1) return nullptr; return getBinaryOperationWithOverflow(Id, Types[0]); #define BUILTIN(id, name, Attrs) #define BUILTIN_BINARY_PREDICATE(id, name, attrs, overload) case BuiltinValueKind::id: #include "swift/AST/Builtins.def" if (Types.size() != 1) return nullptr; return getBinaryPredicate(Id, Types[0]); #define BUILTIN(id, name, Attrs) #define BUILTIN_UNARY_OPERATION(id, name, attrs, overload) case BuiltinValueKind::id: #include "swift/AST/Builtins.def" if (Types.size() != 1) return nullptr; return getUnaryOperation(Id, Types[0]); #define BUILTIN(id, name, Attrs) #define BUILTIN_CAST_OPERATION(id, name, attrs) case BuiltinValueKind::id: #define BUILTIN_CAST_OR_BITCAST_OPERATION(id, name, attrs) case BuiltinValueKind::id: #include "swift/AST/Builtins.def" return getCastOperation(Context, Id, BV, Types); case BuiltinValueKind::TryPin: return getTryPinOperation(Context, Id); case BuiltinValueKind::Retain: case BuiltinValueKind::Release: case BuiltinValueKind::Autorelease: case BuiltinValueKind::Unpin: if (!Types.empty()) return nullptr; return getRefCountingOperation(Context, Id); case BuiltinValueKind::Load: case BuiltinValueKind::LoadRaw: case BuiltinValueKind::Take: if (!Types.empty()) return nullptr; return getLoadOperation(Context, Id); case BuiltinValueKind::Destroy: if (!Types.empty()) return nullptr; return getDestroyOperation(Context, Id); case BuiltinValueKind::Assign: case BuiltinValueKind::Init: if (!Types.empty()) return nullptr; return getStoreOperation(Context, Id); case BuiltinValueKind::DestroyArray: if (!Types.empty()) return nullptr; return getDestroyArrayOperation(Context, Id); case BuiltinValueKind::CopyArray: case BuiltinValueKind::TakeArrayFrontToBack: case BuiltinValueKind::TakeArrayBackToFront: if (!Types.empty()) return nullptr; return getTransferArrayOperation(Context, Id); case BuiltinValueKind::IsUnique: case BuiltinValueKind::IsUniqueOrPinned: case BuiltinValueKind::IsUnique_native: case BuiltinValueKind::IsUniqueOrPinned_native: if (!Types.empty()) return nullptr; return getIsUniqueOperation(Context, Id); case BuiltinValueKind::BindMemory: if (!Types.empty()) return nullptr; return getBindMemoryOperation(Context, Id); case BuiltinValueKind::ProjectTailElems: if (!Types.empty()) return nullptr; return getProjectTailElemsOperation(Context, Id); case BuiltinValueKind::Sizeof: case BuiltinValueKind::Strideof: case BuiltinValueKind::Alignof: return getSizeOrAlignOfOperation(Context, Id); case BuiltinValueKind::IsPOD: return getIsPODOperation(Context, Id); case BuiltinValueKind::IsOptionalType: return getIsOptionalOperation(Context, Id); case BuiltinValueKind::AllocRaw: return getAllocOperation(Context, Id); case BuiltinValueKind::DeallocRaw: return getDeallocOperation(Context, Id); case BuiltinValueKind::CastToNativeObject: case BuiltinValueKind::CastFromNativeObject: case BuiltinValueKind::CastToUnknownObject: case BuiltinValueKind::CastFromUnknownObject: case BuiltinValueKind::BridgeToRawPointer: case BuiltinValueKind::BridgeFromRawPointer: if (!Types.empty()) return nullptr; return getNativeObjectCast(Context, Id, BV); case BuiltinValueKind::CastToBridgeObject: if (!Types.empty()) return nullptr; return getCastToBridgeObjectOperation(Context, Id); case BuiltinValueKind::CastReferenceFromBridgeObject: case BuiltinValueKind::CastBitPatternFromBridgeObject: if (!Types.empty()) return nullptr; return getCastFromBridgeObjectOperation(Context, Id, BV); case BuiltinValueKind::CastReference: if (!Types.empty()) return nullptr; return getCastReferenceOperation(Context, Id); case BuiltinValueKind::ReinterpretCast: if (!Types.empty()) return nullptr; return getReinterpretCastOperation(Context, Id); case BuiltinValueKind::AddressOf: if (!Types.empty()) return nullptr; return getAddressOfOperation(Context, Id); case BuiltinValueKind::CondFail: return getCondFailOperation(Context, Id); case BuiltinValueKind::AssertConf: return getAssertConfOperation(Context, Id); case BuiltinValueKind::FixLifetime: return getFixLifetimeOperation(Context, Id); case BuiltinValueKind::CanBeObjCClass: return getCanBeObjCClassOperation(Context, Id); case BuiltinValueKind::CondUnreachable: case BuiltinValueKind::Unreachable: return getUnreachableOperation(Context, Id); case BuiltinValueKind::ZeroInitializer: return getZeroInitializerOperation(Context, Id); case BuiltinValueKind::Once: return getOnceOperation(Context, Id); case BuiltinValueKind::WillThrow: case BuiltinValueKind::ErrorInMain: return getVoidErrorOperation(Context, Id); case BuiltinValueKind::UnexpectedError: return getUnexpectedErrorOperation(Context, Id); case BuiltinValueKind::ExtractElement: if (Types.size() != 2) return nullptr; return getExtractElementOperation(Context, Id, Types[0], Types[1]); case BuiltinValueKind::InsertElement: if (Types.size() != 3) return nullptr; return getInsertElementOperation(Context, Id, Types[0], Types[1], Types[2]); case BuiltinValueKind::StaticReport: if (!Types.empty()) return nullptr; return getStaticReportOperation(Context, Id); case BuiltinValueKind::UToSCheckedTrunc: case BuiltinValueKind::SToSCheckedTrunc: case BuiltinValueKind::SToUCheckedTrunc: case BuiltinValueKind::UToUCheckedTrunc: if (Types.size() != 2) return nullptr; return getCheckedTruncOperation(Context, Id, Types[0], Types[1]); case BuiltinValueKind::SUCheckedConversion: case BuiltinValueKind::USCheckedConversion: if (Types.size() != 1) return nullptr; return getCheckedConversionOperation(Context, Id, Types[0]); case BuiltinValueKind::UnsafeGuaranteed: return getUnsafeGuaranteed(Context, Id); case BuiltinValueKind::UnsafeGuaranteedEnd: return getUnsafeGuaranteedEnd(Context, Id); case BuiltinValueKind::OnFastPath: return getOnFastPath(Context, Id); case BuiltinValueKind::IntToFPWithOverflow: if (Types.size() != 2) return nullptr; return getIntToFPWithOverflowOperation(Context, Id, Types[0], Types[1]); case BuiltinValueKind::GetObjCTypeEncoding: return getGetObjCTypeEncodingOperation(Context, Id); } llvm_unreachable("bad builtin value!"); } StringRef swift::getBuiltinName(BuiltinValueKind ID) { switch (ID) { case BuiltinValueKind::None: llvm_unreachable("no builtin kind"); #define BUILTIN(Id, Name, Attrs) \ case BuiltinValueKind::Id: \ return Name; #include "swift/AST/Builtins.def" } llvm_unreachable("bad BuiltinValueKind"); }
36.926136
104
0.685105
gottesmm
4f8c2a7a899054765b8968b25847d31b8cc63716
1,026
hpp
C++
src/cpp/include/nodegui/QtWidgets/QSystemTrayIcon/nsystemtrayicon.hpp
NeryHenrique/nodegui
254b6a910928f512e57bc4bfab7dfadcd2073c84
[ "MIT" ]
1
2020-07-30T15:02:17.000Z
2020-07-30T15:02:17.000Z
src/cpp/include/nodegui/QtWidgets/QSystemTrayIcon/nsystemtrayicon.hpp
NeryHenrique/nodegui
254b6a910928f512e57bc4bfab7dfadcd2073c84
[ "MIT" ]
5
2021-06-28T20:44:38.000Z
2022-02-27T11:34:26.000Z
src/cpp/include/nodegui/QtWidgets/QSystemTrayIcon/nsystemtrayicon.hpp
NeryHenrique/nodegui
254b6a910928f512e57bc4bfab7dfadcd2073c84
[ "MIT" ]
1
2020-07-29T15:00:18.000Z
2020-07-29T15:00:18.000Z
#pragma once #include <QSystemTrayIcon> #include "Extras/Export/export.h" #include "QtCore/QObject/qobject_macro.h" #include "core/NodeWidget/nodewidget.h" #include "napi.h" class DLL_EXPORT NSystemTrayIcon : public QSystemTrayIcon, public EventWidget { Q_OBJECT EVENTWIDGET_IMPLEMENTATIONS(QSystemTrayIcon) public: // inherit all constructors of QSystemTrayIcon using QSystemTrayIcon::QSystemTrayIcon; void connectSignalsToEventEmitter() { QOBJECT_SIGNALS QObject::connect(this, &QSystemTrayIcon::activated, [=](int reason) { Napi::Env env = this->emitOnNode.Env(); Napi::HandleScope scope(env); this->emitOnNode.Call({ Napi::String::New(env, "activated"), Napi::Value::From(env, reason), }); }); QObject::connect(this, &QSystemTrayIcon::messageClicked, [=]() { Napi::Env env = this->emitOnNode.Env(); Napi::HandleScope scope(env); this->emitOnNode.Call({ Napi::String::New(env, "messageClicked"), }); }); } };
29.314286
79
0.674464
NeryHenrique
4f8fce46adcef976365d83a5a60359ac879cc6af
341
cpp
C++
src/core.initialization/Initializable.cpp
toeb/sine
96bcde571218f89a2b0b3cc51c19ad2b7be89c13
[ "MIT" ]
null
null
null
src/core.initialization/Initializable.cpp
toeb/sine
96bcde571218f89a2b0b3cc51c19ad2b7be89c13
[ "MIT" ]
null
null
null
src/core.initialization/Initializable.cpp
toeb/sine
96bcde571218f89a2b0b3cc51c19ad2b7be89c13
[ "MIT" ]
null
null
null
#include "Initializable.h" using namespace nspace; bool Initializable::initialize(){ if(_initialized){ return true; } _initialized = initializeObject(); if(_initialized)onObjectInitialized(); return _initialized; }; bool Initializable::cleanup(){ cleanupObject(); _initialized = false; return true; };
18.944444
41
0.68915
toeb
4f91c8e832a0b4364c360d0c57f7f065ff4ff6ba
974
cpp
C++
dmengine/core/private/dmliveobject_p.cpp
damao1222/dmengine
09ab62c043a520f8f6b15eb8790c7ee56c006931
[ "Apache-2.0" ]
null
null
null
dmengine/core/private/dmliveobject_p.cpp
damao1222/dmengine
09ab62c043a520f8f6b15eb8790c7ee56c006931
[ "Apache-2.0" ]
null
null
null
dmengine/core/private/dmliveobject_p.cpp
damao1222/dmengine
09ab62c043a520f8f6b15eb8790c7ee56c006931
[ "Apache-2.0" ]
null
null
null
/* Copyright (C) 2012-2014 Xiongfa Li, <damao1222@live.com> All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "dmliveobject_p.h" #include "dmcoreapplication.h" #include "dmevent.h" #include "dmutilstring.h" DM_BEGIN_NAMESPACE BasicAtomicInt TimerProxy::g_id = DM_BASIC_ATOMIC_INITIALIZER(0); duint TimerProxy::generateId() { g_id.ref(); return g_id; } LiveObjectPrivate::~LiveObjectPrivate() { } DM_END_NAMESPACE
24.35
75
0.743326
damao1222